This commit is contained in:
parent
2f0b55cfa7
commit
1924f21659
|
|
@ -0,0 +1,12 @@
|
|||
.git
|
||||
.agents
|
||||
.codex
|
||||
.nuxt
|
||||
.output
|
||||
node_modules
|
||||
coverage
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
npm-debug.log*
|
||||
*.local
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
FROM docker.io/library/node:20-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM docker.io/library/node:20-bookworm-slim AS runtime
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
NITRO_HOST=0.0.0.0 \
|
||||
NITRO_PORT=3000
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=build --chown=node:node /app/.output ./.output
|
||||
|
||||
USER node
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:3000/').then(response => { if (!response.ok) process.exit(1) }).catch(() => process.exit(1))"
|
||||
|
||||
CMD ["node", ".output/server/index.mjs"]
|
||||
33
README.md
33
README.md
|
|
@ -10,7 +10,7 @@ Incidents, SLA, Configuration items, Device и System.
|
|||
## Возможности
|
||||
|
||||
- аутентификация Knox Token;
|
||||
- загрузка текущего пользователя и эффективных разрешений через `/me/` и `/me/permissions/`;
|
||||
- загрузка текущего пользователя, эффективных разрешений и доступной навигации через `/me/`, `/me/permissions/` и `/me/capabilities/`;
|
||||
- мгновенное применение языка, светлой/тёмной темы и основного цвета;
|
||||
- форма управления профилем и ролевое ограничение меню/CRUD-действий;
|
||||
- навигация по модулям и сущностям;
|
||||
|
|
@ -37,6 +37,35 @@ npm run dev
|
|||
По умолчанию API доступен по адресу `http://localhost:10000/api/v1`. Другой
|
||||
адрес задаётся переменной `NUXT_PUBLIC_API_BASE`.
|
||||
|
||||
## Запуск в Podman
|
||||
|
||||
Соберите production-образ из корня проекта:
|
||||
|
||||
```bash
|
||||
podman build -t wanitil-main-web -f Containerfile .
|
||||
```
|
||||
|
||||
Запустите контейнер, передав доступный браузеру адрес API:
|
||||
|
||||
```bash
|
||||
podman run --rm --name wanitil-main-web \
|
||||
-p 3000:3000 \
|
||||
-e NUXT_PUBLIC_API_BASE=http://localhost:10000/api/v1 \
|
||||
wanitil-main-web
|
||||
```
|
||||
|
||||
Интерфейс будет доступен по адресу `http://localhost:3000`. Значение
|
||||
`NUXT_PUBLIC_API_BASE` — публичный URL: его должен видеть браузер пользователя,
|
||||
поэтому имя контейнера API обычно указывать здесь не следует.
|
||||
|
||||
Для фонового запуска добавьте параметр `-d`. Проверить состояние контейнера и
|
||||
его healthcheck можно командами:
|
||||
|
||||
```bash
|
||||
podman ps
|
||||
podman healthcheck run wanitil-main-web
|
||||
```
|
||||
|
||||
## Проверки
|
||||
|
||||
```bash
|
||||
|
|
@ -57,4 +86,4 @@ npm run build
|
|||
`/api/v1/main/*`.
|
||||
|
||||
|
||||
OpenAPI: `http://localhost:10000/api/v1/docs/`, основные методы:
|
||||
OpenAPI: `http://localhost:10000/api/v1/docs/`, основные методы:
|
||||
|
|
|
|||
|
|
@ -172,6 +172,14 @@ h1, h2, h3, h4, h5, h6,
|
|||
box-shadow: 0 18px 38px rgb(0 0 0 / 12%) !important;
|
||||
}
|
||||
|
||||
/* Keep dialogs anchored to the viewport top when their tab content changes height. */
|
||||
.v-dialog > .v-overlay__content {
|
||||
align-self: flex-start;
|
||||
margin-top: 32px;
|
||||
margin-bottom: 32px;
|
||||
max-height: calc(100vh - 64px);
|
||||
}
|
||||
|
||||
.resource-editor-card { max-height: 90vh; }
|
||||
.resource-editor-header {
|
||||
flex: 0 0 auto;
|
||||
|
|
@ -278,6 +286,12 @@ h1, h2, h3, h4, h5, h6,
|
|||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.v-dialog > .v-overlay__content {
|
||||
margin-top: 12px;
|
||||
margin-bottom: 12px;
|
||||
max-height: calc(100vh - 24px);
|
||||
}
|
||||
|
||||
.soft-app-bar {
|
||||
margin: 8px 10px 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,410 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
import { accessIds, accessModule, accessOption, belongsToModule } from '~/utils/access'
|
||||
|
||||
type ProfileForm = {
|
||||
module: string
|
||||
code: string
|
||||
name: string
|
||||
description: string
|
||||
scope: 'own' | 'team' | 'all'
|
||||
permissions: string[]
|
||||
navigations: string[]
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const access = usePermissions()
|
||||
const canCreate = computed(() => access.canCreate('system', 'sys', 'employee-access'))
|
||||
const canEdit = computed(() => access.canEdit('system', 'sys', 'employee-access'))
|
||||
const canDelete = computed(() => access.canDelete('system', 'sys', 'employee-access'))
|
||||
const profileReadonly = computed(() => Boolean(editingProfile.value?.is_system)
|
||||
|| (editingProfile.value ? !canEdit.value : !canCreate.value))
|
||||
|
||||
const tab = ref<'profiles' | 'employees'>('profiles')
|
||||
const profiles = ref<ApiRecord[]>([])
|
||||
const employees = ref<ApiRecord[]>([])
|
||||
const permissionOptions = ref<{ title: string; value: string }[]>([])
|
||||
const navigationOptions = ref<{ title: string; value: string }[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const noticeOpen = computed({
|
||||
get: () => Boolean(notice.value),
|
||||
set: value => { if (!value) notice.value = '' },
|
||||
})
|
||||
const profileSearch = ref('')
|
||||
const moduleFilter = ref<string | null>(null)
|
||||
const editorOpen = ref(false)
|
||||
const editingProfile = ref<ApiRecord | null>(null)
|
||||
const assignmentOpen = ref(false)
|
||||
const assignmentProfile = ref<ApiRecord | null>(null)
|
||||
const assignmentEmployeeIds = ref<(string | number)[]>([])
|
||||
const replaceProfiles = ref(false)
|
||||
const employeeId = ref<string | number | null>(null)
|
||||
const employee = ref<ApiRecord | null>(null)
|
||||
const employeeLoading = ref(false)
|
||||
const form = reactive<ProfileForm>(emptyProfile())
|
||||
|
||||
function emptyProfile(): ProfileForm {
|
||||
return {
|
||||
module: '', code: '', name: '', description: '', scope: 'all',
|
||||
permissions: [], navigations: [], is_active: true,
|
||||
}
|
||||
}
|
||||
|
||||
function listItems(result: any): ApiRecord[] {
|
||||
return normalizeList<ApiRecord>(result).items
|
||||
}
|
||||
|
||||
function normalizedOptions(result: any) {
|
||||
return listItems(result).map(accessOption).filter((item): item is { title: string; value: string } => Boolean(item))
|
||||
}
|
||||
|
||||
const modules = computed(() => [...new Set([
|
||||
...permissionOptions.value.map(item => accessModule(item.value)),
|
||||
...navigationOptions.value.map(item => accessModule(item.value)),
|
||||
...profiles.value.map(item => String(item.module || '')),
|
||||
].filter(Boolean))].sort())
|
||||
|
||||
const displayedProfiles = computed(() => profiles.value.filter(profile => {
|
||||
if (moduleFilter.value && String(profile.module) !== moduleFilter.value) return false
|
||||
const query = profileSearch.value.trim().toLowerCase()
|
||||
return !query || [profile.name, profile.code, profile.description, profile.module]
|
||||
.some(value => String(value || '').toLowerCase().includes(query))
|
||||
}))
|
||||
|
||||
const modulePermissions = computed(() => permissionOptions.value
|
||||
.filter(item => belongsToModule(item.value, form.module)))
|
||||
const moduleNavigations = computed(() => navigationOptions.value
|
||||
.filter(item => belongsToModule(item.value, form.module)))
|
||||
const employeePermissions = computed(() => permissionOptions.value)
|
||||
const employeeNavigations = computed(() => navigationOptions.value)
|
||||
const employeeOptions = computed(() => employees.value
|
||||
.filter(item => item.id !== undefined)
|
||||
.map(item => ({
|
||||
value: item.id!,
|
||||
title: String(item.name || item.fullname || item.username || `Сотрудник #${item.id}`),
|
||||
})))
|
||||
|
||||
const profileHeaders = [
|
||||
{ title: 'Название', key: 'name' },
|
||||
{ title: 'Код', key: 'code' },
|
||||
{ title: 'Модуль', key: 'module' },
|
||||
{ title: 'Область', key: 'scope' },
|
||||
{ title: 'Права', key: 'permissions' },
|
||||
{ title: 'Состояние', key: 'is_active' },
|
||||
{ title: '', key: 'actions', sortable: false, align: 'end' as const },
|
||||
]
|
||||
const scopeLabels: Record<string, string> = { own: 'Свои записи', team: 'Своя команда', all: 'Все записи' }
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [profileResult, permissionResult, navigationResult, employeeResult] = await Promise.all([
|
||||
request<any>('/main/sys/sysprofiles/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/permissions/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/navigations/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/employees/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
profiles.value = listItems(profileResult)
|
||||
permissionOptions.value = normalizedOptions(permissionResult)
|
||||
navigationOptions.value = normalizedOptions(navigationResult)
|
||||
employees.value = listItems(employeeResult)
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function createProfile() {
|
||||
editingProfile.value = null
|
||||
Object.assign(form, emptyProfile())
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function editProfile(profile: ApiRecord) {
|
||||
editingProfile.value = profile
|
||||
Object.assign(form, {
|
||||
module: String(profile.module || ''),
|
||||
code: String(profile.code || ''),
|
||||
name: String(profile.name || ''),
|
||||
description: String(profile.description || ''),
|
||||
scope: (['own', 'team', 'all'].includes(String(profile.scope)) ? profile.scope : 'all') as ProfileForm['scope'],
|
||||
permissions: accessIds(profile.permissions),
|
||||
navigations: accessIds(profile.navigations),
|
||||
is_active: profile.is_active !== false,
|
||||
})
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
watch(() => form.module, (module, previous) => {
|
||||
if (!editorOpen.value || !previous || module === previous) return
|
||||
form.permissions = form.permissions.filter(id => belongsToModule(id, module))
|
||||
form.navigations = form.navigations.filter(id => belongsToModule(id, module))
|
||||
})
|
||||
|
||||
async function saveProfile() {
|
||||
if (!form.module || !form.code.trim() || !form.name.trim()) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const payload = {
|
||||
module: form.module,
|
||||
code: form.code.trim(),
|
||||
name: form.name.trim(),
|
||||
description: form.description,
|
||||
scope: form.scope,
|
||||
permissions: form.permissions.filter(id => belongsToModule(id, form.module)),
|
||||
navigations: form.navigations.filter(id => belongsToModule(id, form.module)),
|
||||
is_active: form.is_active,
|
||||
}
|
||||
if (editingProfile.value?.id !== undefined) {
|
||||
await request(`/main/sys/sysprofiles/${editingProfile.value.id}/`, { method: 'PATCH', body: payload })
|
||||
notice.value = 'Профиль обновлён. Изменения синхронизированы с назначенными сотрудниками.'
|
||||
} else {
|
||||
await request('/main/sys/sysprofiles/', { method: 'POST', body: payload })
|
||||
notice.value = 'Профиль создан'
|
||||
}
|
||||
editorOpen.value = false
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteProfile(profile: ApiRecord) {
|
||||
if (profile.id === undefined || profile.is_system || !window.confirm(`Удалить профиль «${profile.name || profile.code}»?`)) return
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/sysprofiles/${profile.id}/`, { method: 'DELETE' })
|
||||
notice.value = 'Профиль удалён'
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
}
|
||||
}
|
||||
|
||||
function assignProfile(profile: ApiRecord) {
|
||||
assignmentProfile.value = profile
|
||||
assignmentEmployeeIds.value = []
|
||||
replaceProfiles.value = false
|
||||
assignmentOpen.value = true
|
||||
}
|
||||
|
||||
async function changeAssignment(action: 'apply' | 'revoke') {
|
||||
if (assignmentProfile.value?.id === undefined || !assignmentEmployeeIds.value.length) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/sysprofiles/${assignmentProfile.value.id}/${action}/`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
employee_ids: assignmentEmployeeIds.value.map(Number),
|
||||
...(action === 'apply' ? { replace: replaceProfiles.value } : {}),
|
||||
},
|
||||
})
|
||||
assignmentOpen.value = false
|
||||
notice.value = action === 'apply' ? 'Профиль назначен сотрудникам' : 'Профиль отозван у сотрудников'
|
||||
if (employeeId.value) await loadEmployee()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEmployee() {
|
||||
if (employeeId.value === null) {
|
||||
employee.value = null
|
||||
return
|
||||
}
|
||||
employeeLoading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
employee.value = await request<ApiRecord>(`/main/sys/employees/${employeeId.value}/`)
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
employeeLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEmployeeAccess() {
|
||||
if (!employee.value?.id) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const updated = await request<ApiRecord>(`/main/sys/employees/${employee.value.id}/`, {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
permissions: accessIds(employee.value.permissions),
|
||||
navigations: accessIds(employee.value.navigations),
|
||||
},
|
||||
})
|
||||
employee.value = updated
|
||||
notice.value = 'Прямые права и навигация сотрудника сохранены'
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell">
|
||||
<div class="d-flex flex-wrap align-center ga-3 mb-5">
|
||||
<div>
|
||||
<h1 class="text-h4 font-weight-bold">Профили и доступы</h1>
|
||||
<p class="text-medium-emphasis mt-1">Шаблоны доступа и фактические права сотрудников</p>
|
||||
</div>
|
||||
<v-spacer />
|
||||
<v-btn v-if="tab === 'profiles' && canCreate" color="primary" prepend-icon="mdi-plus" @click="createProfile">
|
||||
Добавить профиль
|
||||
</v-btn>
|
||||
</div>
|
||||
|
||||
<v-alert v-if="error" type="error" closable class="mb-4" @click:close="error = ''">{{ error }}</v-alert>
|
||||
<v-snackbar v-model="noticeOpen" color="success">{{ notice }}</v-snackbar>
|
||||
<v-alert type="info" variant="tonal" class="mb-4">
|
||||
Permissions разрешают операции API. Navigation управляет только видимостью пунктов меню и не предоставляет права на действия.
|
||||
</v-alert>
|
||||
|
||||
<v-tabs v-model="tab" class="mb-4">
|
||||
<v-tab value="profiles">Профили</v-tab>
|
||||
<v-tab value="employees">Доступ сотрудников</v-tab>
|
||||
</v-tabs>
|
||||
|
||||
<v-window v-model="tab">
|
||||
<v-window-item value="profiles">
|
||||
<v-card>
|
||||
<v-card-text class="d-flex flex-wrap ga-3">
|
||||
<v-text-field v-model="profileSearch" label="Поиск" prepend-inner-icon="mdi-magnify"
|
||||
clearable hide-details class="access-search" />
|
||||
<v-select v-model="moduleFilter" :items="modules" label="Модуль" clearable hide-details class="access-module" />
|
||||
</v-card-text>
|
||||
<v-data-table :headers="profileHeaders" :items="displayedProfiles" :loading="loading" item-value="id">
|
||||
<template #item.scope="{ item }">{{ scopeLabels[String(item.scope)] || item.scope }}</template>
|
||||
<template #item.permissions="{ item }">
|
||||
{{ accessIds(item.permissions).length }} / навигация: {{ accessIds(item.navigations).length }}
|
||||
</template>
|
||||
<template #item.is_active="{ item }">
|
||||
<v-chip :color="item.is_active === false ? 'default' : 'success'" size="small">
|
||||
{{ item.is_active === false ? 'Неактивен' : 'Активен' }}
|
||||
</v-chip>
|
||||
<v-chip v-if="item.is_system" class="ml-2" size="small">Системный</v-chip>
|
||||
</template>
|
||||
<template #item.actions="{ item }">
|
||||
<v-btn v-if="canEdit" icon="mdi-account-multiple-plus-outline" variant="text" size="small"
|
||||
title="Назначить или отозвать" @click="assignProfile(item)" />
|
||||
<v-btn :icon="item.is_system || !canEdit ? 'mdi-eye-outline' : 'mdi-pencil-outline'" variant="text" size="small"
|
||||
:title="item.is_system || !canEdit ? 'Просмотреть' : 'Редактировать'" @click="editProfile(item)" />
|
||||
<v-btn v-if="canDelete && !item.is_system" icon="mdi-delete-outline" color="error" variant="text"
|
||||
size="small" title="Удалить" @click="deleteProfile(item)" />
|
||||
</template>
|
||||
</v-data-table>
|
||||
</v-card>
|
||||
</v-window-item>
|
||||
|
||||
<v-window-item value="employees">
|
||||
<v-card>
|
||||
<v-card-text>
|
||||
<v-autocomplete v-model="employeeId" :items="employeeOptions" label="Сотрудник"
|
||||
prepend-inner-icon="mdi-account-search-outline" clearable :loading="loading"
|
||||
@update:model-value="loadEmployee" />
|
||||
<v-progress-linear v-if="employeeLoading" indeterminate class="mb-4" />
|
||||
<template v-if="employee">
|
||||
<div class="text-h6 mb-4">{{ employee.name || employee.fullname || `Сотрудник #${employee.id}` }}</div>
|
||||
<AccessSelectionList :permissions="accessIds(employee.permissions)"
|
||||
:navigations="accessIds(employee.navigations)"
|
||||
:permission-options="employeePermissions" :navigation-options="employeeNavigations"
|
||||
:readonly="!canEdit"
|
||||
@update:permissions="employee = { ...employee!, permissions: $event }"
|
||||
@update:navigations="employee = { ...employee!, navigations: $event }" />
|
||||
<div class="d-flex justify-end">
|
||||
<v-btn v-if="canEdit" color="primary" :loading="saving" @click="saveEmployeeAccess">
|
||||
Сохранить доступ
|
||||
</v-btn>
|
||||
</div>
|
||||
</template>
|
||||
<v-alert v-else-if="!employeeLoading" type="info" variant="tonal">
|
||||
Выберите сотрудника для просмотра и изменения его фактического доступа.
|
||||
</v-alert>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
</v-window-item>
|
||||
</v-window>
|
||||
|
||||
<v-dialog v-model="editorOpen" max-width="900">
|
||||
<v-card>
|
||||
<v-card-title>{{ editingProfile ? 'Редактирование профиля' : 'Новый профиль' }}</v-card-title>
|
||||
<v-card-text>
|
||||
<v-alert v-if="editingProfile?.is_system" type="warning" variant="tonal" class="mb-4">
|
||||
Системный профиль доступен только для просмотра.
|
||||
</v-alert>
|
||||
<div class="access-form-grid">
|
||||
<v-select v-model="form.module" :items="modules" label="Модуль *"
|
||||
:readonly="Boolean(editingProfile) || profileReadonly" />
|
||||
<v-text-field v-model="form.code" label="Код *" :readonly="profileReadonly" />
|
||||
<v-text-field v-model="form.name" label="Название *" :readonly="profileReadonly" />
|
||||
<v-select v-model="form.scope" :items="[
|
||||
{ title: 'Только собственные записи', value: 'own' },
|
||||
{ title: 'Записи своей команды', value: 'team' },
|
||||
{ title: 'Все записи', value: 'all' },
|
||||
]" label="Область действия" :readonly="profileReadonly" />
|
||||
</div>
|
||||
<v-textarea v-model="form.description" label="Описание" rows="2" :readonly="profileReadonly" />
|
||||
<AccessSelectionList v-if="form.module"
|
||||
v-model:permissions="form.permissions" v-model:navigations="form.navigations"
|
||||
:permission-options="modulePermissions" :navigation-options="moduleNavigations"
|
||||
:readonly="profileReadonly" />
|
||||
<v-alert v-else type="info" variant="tonal" class="mb-4">
|
||||
Выберите модуль, чтобы настроить права и навигацию.
|
||||
</v-alert>
|
||||
<v-switch v-model="form.is_active" label="Профиль активен" color="primary"
|
||||
:readonly="profileReadonly" />
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn variant="text" @click="editorOpen = false">Закрыть</v-btn>
|
||||
<v-btn v-if="!profileReadonly" color="primary" :loading="saving"
|
||||
:disabled="!form.module || !form.code.trim() || !form.name.trim()" @click="saveProfile">Сохранить</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
|
||||
<v-dialog v-model="assignmentOpen" max-width="650">
|
||||
<v-card>
|
||||
<v-card-title>Назначение профиля «{{ assignmentProfile?.name }}»</v-card-title>
|
||||
<v-card-text>
|
||||
<v-autocomplete v-model="assignmentEmployeeIds" :items="employeeOptions" label="Сотрудники"
|
||||
multiple chips closable-chips />
|
||||
<v-checkbox v-model="replaceProfiles" label="Заменить другие профили сотрудников в этом модуле" hide-details />
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-btn variant="text" @click="assignmentOpen = false">Отмена</v-btn>
|
||||
<v-spacer />
|
||||
<v-btn color="error" variant="tonal" :loading="saving" :disabled="!assignmentEmployeeIds.length"
|
||||
@click="changeAssignment('revoke')">Отозвать</v-btn>
|
||||
<v-btn color="primary" :loading="saving" :disabled="!assignmentEmployeeIds.length"
|
||||
@click="changeAssignment('apply')">Назначить</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.access-search { flex: 1 1 320px; }
|
||||
.access-module { flex: 0 1 260px; }
|
||||
.access-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 16px; }
|
||||
@media (max-width: 700px) { .access-form-grid { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
<script setup lang="ts">
|
||||
import { modules as moduleDefinitions } from '~/config/modules'
|
||||
import { accessModule } from '~/utils/access'
|
||||
|
||||
type AccessOption = { title: string; value: string }
|
||||
|
||||
const props = defineProps<{
|
||||
permissions: string[]
|
||||
navigations: string[]
|
||||
permissionOptions: AccessOption[]
|
||||
navigationOptions: AccessOption[]
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
'update:permissions': [value: string[]]
|
||||
'update:navigations': [value: string[]]
|
||||
}>()
|
||||
|
||||
const moduleTitles = new Map(moduleDefinitions.flatMap(module => [
|
||||
[module.key, module.title],
|
||||
[module.apiPrefix, module.title],
|
||||
] as [string, string][]))
|
||||
|
||||
const groups = computed(() => {
|
||||
const keys = [...new Set([
|
||||
...props.permissionOptions.map(option => accessModule(option.value)),
|
||||
...props.navigationOptions.map(option => accessModule(option.value)),
|
||||
].filter(Boolean))]
|
||||
return keys.map(key => ({
|
||||
key,
|
||||
title: moduleTitles.get(key) || key.toUpperCase(),
|
||||
permissions: props.permissionOptions.filter(option => accessModule(option.value) === key),
|
||||
navigations: props.navigationOptions.filter(option => accessModule(option.value) === key),
|
||||
})).sort((left, right) => left.title.localeCompare(right.title, 'ru'))
|
||||
})
|
||||
|
||||
function toggle(kind: 'permissions' | 'navigations', value: string, selected: boolean | null) {
|
||||
const current = props[kind]
|
||||
const next = selected
|
||||
? [...new Set([...current, value])]
|
||||
: current.filter(item => item !== value)
|
||||
if (kind === 'permissions') emit('update:permissions', next)
|
||||
else emit('update:navigations', next)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="access-selection-list">
|
||||
<v-alert v-if="!groups.length" type="info" variant="tonal">
|
||||
Для выбранной области нет доступных прав.
|
||||
</v-alert>
|
||||
<v-expansion-panels v-else multiple variant="accordion">
|
||||
<v-expansion-panel v-for="group in groups" :key="group.key">
|
||||
<v-expansion-panel-title>
|
||||
<div class="d-flex align-center ga-2">
|
||||
<span class="font-weight-medium">{{ group.title }}</span>
|
||||
<v-chip size="x-small" variant="tonal">{{ group.key }}</v-chip>
|
||||
<span class="text-caption text-medium-emphasis">
|
||||
{{ group.permissions.length }} прав · {{ group.navigations.length }} пунктов
|
||||
</span>
|
||||
</div>
|
||||
</v-expansion-panel-title>
|
||||
<v-expansion-panel-text>
|
||||
<div class="access-columns">
|
||||
<section>
|
||||
<h4 class="text-subtitle-2 mb-2">Permissions — операции API</h4>
|
||||
<v-checkbox-btn v-for="option in group.permissions" :key="option.value"
|
||||
:model-value="permissions.includes(option.value)" :label="option.title"
|
||||
:disabled="readonly" density="compact"
|
||||
@update:model-value="toggle('permissions', option.value, $event)" />
|
||||
<p v-if="!group.permissions.length" class="text-caption text-medium-emphasis">
|
||||
Нет доступных операций
|
||||
</p>
|
||||
</section>
|
||||
<section>
|
||||
<h4 class="text-subtitle-2 mb-2">Navigation — пункты меню</h4>
|
||||
<v-checkbox-btn v-for="option in group.navigations" :key="option.value"
|
||||
:model-value="navigations.includes(option.value)" :label="option.title"
|
||||
:disabled="readonly" density="compact"
|
||||
@update:model-value="toggle('navigations', option.value, $event)" />
|
||||
<p v-if="!group.navigations.length" class="text-caption text-medium-emphasis">
|
||||
Нет доступных пунктов
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</v-expansion-panel-text>
|
||||
</v-expansion-panel>
|
||||
</v-expansion-panels>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.access-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.access-columns { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
|
|
@ -5,6 +5,7 @@ const props = defineProps<{
|
|||
modelValue: unknown
|
||||
readonly?: boolean
|
||||
smart?: boolean
|
||||
label?: string
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string | number | null]
|
||||
|
|
@ -62,7 +63,7 @@ async function searchTowns(search = '') {
|
|||
loading.value = true
|
||||
try {
|
||||
const data = await request<any>('/main/adr/towns/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { name__icontains: search.trim() } : {}) },
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
})
|
||||
towns.value = options(normalizeList(data).items, 'Населённый пункт')
|
||||
} finally { loading.value = false }
|
||||
|
|
@ -79,7 +80,7 @@ async function searchStreets(search = '') {
|
|||
query: {
|
||||
page_size: 50,
|
||||
adr_town__id__exact: townId.value,
|
||||
...(search.trim() ? { name__icontains: search.trim() } : {}),
|
||||
...(search.trim() ? { searchstr: search.trim() } : {}),
|
||||
},
|
||||
})
|
||||
streets.value = options(normalizeList(data).items, 'Улица')
|
||||
|
|
@ -98,7 +99,7 @@ async function searchHouses(search = '') {
|
|||
query: {
|
||||
page_size: 50,
|
||||
adr_street__id__exact: streetId.value,
|
||||
...(search.trim() ? { name__icontains: search.trim() } : {}),
|
||||
...(search.trim() ? { searchstr: search.trim() } : {}),
|
||||
},
|
||||
})
|
||||
houseRecords.value = normalizeList(data).items
|
||||
|
|
@ -242,7 +243,7 @@ watch(() => props.modelValue, (value, previous) => {
|
|||
|
||||
<template>
|
||||
<v-autocomplete v-if="smart" :model-value="null" v-model:search="searchText"
|
||||
:items="smartItems" :label="smartLabel" :placeholder="smartPlaceholder"
|
||||
:items="smartItems" :label="label || smartLabel" :placeholder="smartPlaceholder"
|
||||
persistent-placeholder
|
||||
no-data-text="Ничего не найдено" :loading="loading"
|
||||
:readonly="readonly || (modelValue !== null && modelValue !== undefined)"
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ const loading = ref(false)
|
|||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const options = computed(() => available.value
|
||||
.filter(zone => zone.id !== undefined
|
||||
|
|
@ -41,6 +42,24 @@ async function load() {
|
|||
}
|
||||
}
|
||||
|
||||
function searchAvailable(search: string) {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<any>('/main/adr/zones/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
})
|
||||
available.value = normalizeList(result).items
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
|
||||
async function add() {
|
||||
if (selectedZoneId.value === null) return
|
||||
saving.value = true
|
||||
|
|
@ -75,6 +94,7 @@ async function remove(zone: ApiRecord) {
|
|||
}
|
||||
|
||||
watch(() => [props.resourcePath, props.objectId], load, { immediate: true })
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -97,7 +117,8 @@ watch(() => [props.resourcePath, props.objectId], load, { immediate: true })
|
|||
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить</h4>
|
||||
<div class="d-flex flex-column flex-sm-row ga-3 align-sm-start">
|
||||
<v-autocomplete v-model="selectedZoneId" :items="options"
|
||||
label="Добавить зону" clearable no-data-text="Нет доступных зон" hide-details />
|
||||
label="Добавить зону" clearable no-data-text="Нет доступных зон" hide-details
|
||||
@update:search="searchAvailable($event || '')" />
|
||||
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
|
||||
:disabled="selectedZoneId === null" @click="add">Добавить</v-btn>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ function isUnread(item: ApiRecord) {
|
|||
|
||||
async function loadUnreadCount() {
|
||||
try {
|
||||
const result = await request<ApiRecord | number>('/main/con/appsends/unread-count/')
|
||||
const result = await request<ApiRecord | number>('/main/con/app-deliveries/unread-count/')
|
||||
unreadCount.value = typeof result === 'number'
|
||||
? result
|
||||
: Number(result.unread_count ?? result.count ?? result.unread ?? 0)
|
||||
|
|
@ -71,7 +71,7 @@ async function loadMessages() {
|
|||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<any>('/main/con/appsends/', {
|
||||
const result = await request<any>('/main/con/app-deliveries/', {
|
||||
query: { page: 1, page_size: 50, ordering: '-id' },
|
||||
})
|
||||
messages.value = normalizeList(result).items
|
||||
|
|
@ -93,9 +93,9 @@ async function openMessage(item: ApiRecord) {
|
|||
detailLoading.value = true
|
||||
selectedMessage.value = item
|
||||
try {
|
||||
selectedMessage.value = await request<ApiRecord>(`/main/con/appsends/${item.id}/`)
|
||||
selectedMessage.value = await request<ApiRecord>(`/main/con/app-deliveries/${item.id}/`)
|
||||
if (isUnread(item)) {
|
||||
await request(`/main/con/appsends/${item.id}/mark-read/`, { method: 'POST' })
|
||||
await request(`/main/con/app-deliveries/${item.id}/mark-read/`, { method: 'POST' })
|
||||
item.status = 1
|
||||
if (selectedMessage.value) selectedMessage.value.status = 1
|
||||
unreadCount.value = Math.max(0, unreadCount.value - 1)
|
||||
|
|
@ -109,7 +109,7 @@ async function openMessage(item: ApiRecord) {
|
|||
|
||||
async function markAllRead() {
|
||||
try {
|
||||
await request('/main/con/appsends/mark-all-read/', { method: 'POST' })
|
||||
await request('/main/con/app-deliveries/mark-all-read/', { method: 'POST' })
|
||||
messages.value.forEach(message => { message.status = 1 })
|
||||
unreadCount.value = 0
|
||||
} catch (caught: any) {
|
||||
|
|
@ -161,7 +161,7 @@ async function sendMessage() {
|
|||
error.value = ''
|
||||
try {
|
||||
if (!idempotencyKey.value) idempotencyKey.value = crypto.randomUUID()
|
||||
await request('/main/con/appsends/messages/', {
|
||||
await request('/main/con/app-deliveries/messages/', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
idempotency_key: idempotencyKey.value,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,148 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
import { formatDateValue } from '~/utils/date'
|
||||
|
||||
interface DskFile extends ApiRecord {
|
||||
id: string | number
|
||||
original_name?: string
|
||||
name?: string
|
||||
size?: number | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
attachments?: { id: string | number; target_type: string; target_id: string | number }[]
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
targetType?: string
|
||||
kind?: 'req' | 'inc'
|
||||
recordId?: string | number
|
||||
readonly?: boolean
|
||||
active?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const files = ref<DskFile[]>([])
|
||||
const selectedFiles = ref<File[]>([])
|
||||
const loading = ref(false)
|
||||
const uploading = ref(false)
|
||||
const downloadingId = ref<string | number | null>(null)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const loadedKey = ref('')
|
||||
const error = ref('')
|
||||
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}`)
|
||||
|
||||
function formatSize(value?: number | null) {
|
||||
if (value === undefined || value === null) return 'Размер неизвестен'
|
||||
if (value < 1024) return `${value} Б`
|
||||
if (value < 1024 ** 2) return `${(value / 1024).toFixed(1)} КБ`
|
||||
return `${(value / 1024 ** 2).toFixed(1)} МБ`
|
||||
}
|
||||
function normalizeFiles(value: File[] | File | null) {
|
||||
selectedFiles.value = value === null ? [] : Array.isArray(value) ? value : [value]
|
||||
}
|
||||
async function loadFiles(force = false) {
|
||||
if (!targetKey.value || (!force && loadedKey.value === targetKey.value)) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await request<any>('/main/dsk/files/', {
|
||||
query: { page_size: 1000, target_type: resolvedTargetType.value, target_id: props.recordId },
|
||||
})
|
||||
files.value = normalizeList<DskFile>(data).items
|
||||
loadedKey.value = targetKey.value
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось загрузить вложения'
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
async function uploadFiles() {
|
||||
if (!targetKey.value || !selectedFiles.value.length) return
|
||||
uploading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
for (const file of selectedFiles.value) {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
body.append('target_type', resolvedTargetType.value)
|
||||
body.append('target_id', String(props.recordId))
|
||||
await request('/main/dsk/files/', { method: 'POST', body })
|
||||
}
|
||||
selectedFiles.value = []
|
||||
await loadFiles(true)
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось загрузить вложения'
|
||||
} finally { uploading.value = false }
|
||||
}
|
||||
async function downloadFile(file: DskFile) {
|
||||
downloadingId.value = file.id
|
||||
error.value = ''
|
||||
try {
|
||||
const blob = await request<Blob>(`/main/dsk/files/${file.id}/download/`, { responseType: 'blob' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = String(file.original_name || file.name || 'attachment')
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось скачать вложение'
|
||||
} finally { downloadingId.value = null }
|
||||
}
|
||||
async function detachFile(file: DskFile) {
|
||||
const name = String(file.original_name || file.name || `#${file.id}`)
|
||||
if (!window.confirm(`Отвязать вложение «${name}»?`)) return
|
||||
const attachment = file.attachments?.find(item => item.target_type === resolvedTargetType.value
|
||||
&& String(item.target_id) === String(props.recordId))
|
||||
deletingId.value = file.id
|
||||
error.value = ''
|
||||
try {
|
||||
if (attachment) {
|
||||
await request(`/main/dsk/files/${file.id}/attachments/${attachment.id}/`, { method: 'DELETE' })
|
||||
} else {
|
||||
await request(`/main/dsk/files/${file.id}/`, { method: 'DELETE' })
|
||||
}
|
||||
files.value = files.value.filter(item => String(item.id) !== String(file.id))
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось отвязать вложение'
|
||||
} finally { deletingId.value = null }
|
||||
}
|
||||
|
||||
watch(() => [targetKey.value, props.active], () => {
|
||||
if (props.active === false) return
|
||||
loadFiles()
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-alert v-if="!targetKey" type="info" variant="tonal">Сначала сохраните объект, затем можно будет добавлять вложения.</v-alert>
|
||||
<template v-else>
|
||||
<v-card v-if="!readonly" variant="outlined" class="mb-4">
|
||||
<v-card-title class="text-subtitle-1">Добавить вложения</v-card-title>
|
||||
<v-card-text>
|
||||
<v-file-input :model-value="selectedFiles" label="Выберите файлы" multiple chips show-size
|
||||
prepend-icon="mdi-paperclip" :disabled="uploading" @update:model-value="normalizeFiles" />
|
||||
<div class="d-flex justify-end"><v-btn type="button" color="primary" prepend-icon="mdi-upload"
|
||||
:loading="uploading" :disabled="!selectedFiles.length" @click="uploadFiles">Загрузить</v-btn></div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<div v-if="loading" class="d-flex justify-center py-8"><v-progress-circular indeterminate color="primary" /></div>
|
||||
<v-alert v-else-if="!files.length" type="info" variant="tonal">Вложений пока нет.</v-alert>
|
||||
<v-list v-else lines="two" border rounded>
|
||||
<v-list-item v-for="file in files" :key="String(file.id)" prepend-icon="mdi-file-outline"
|
||||
:title="String(file.original_name || file.name || `Файл #${file.id}`)">
|
||||
<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-download" variant="text" color="primary"
|
||||
:loading="downloadingId === file.id" title="Скачать" @click="downloadFile(file)" />
|
||||
<v-btn v-if="!readonly" type="button" icon="mdi-link-off" variant="text" color="error"
|
||||
:loading="deletingId === file.id" title="Отвязать" @click="detachFile(file)" />
|
||||
</div></template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</template>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const items = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const decision = ref<{ change: ApiRecord; action: 'approve' | 'reject' } | null>(null)
|
||||
const comment = ref('')
|
||||
const saving = ref(false)
|
||||
|
||||
function relationTitle(value: unknown, fallback: string) {
|
||||
if (value && typeof value === 'object') {
|
||||
const record = value as ApiRecord
|
||||
return String(record.name || record.title || `${fallback} #${record.id}`)
|
||||
}
|
||||
return value ? `${fallback} #${value}` : '—'
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await request<any>('/main/chn/changes/pending-approval/', {
|
||||
query: { page_size: 1000 },
|
||||
})
|
||||
items.value = normalizeList(response).items
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось загрузить изменения на согласование'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openDecision(change: ApiRecord, action: 'approve' | 'reject') {
|
||||
decision.value = { change, action }
|
||||
comment.value = ''
|
||||
}
|
||||
|
||||
async function submitDecision() {
|
||||
if (!decision.value?.change.id) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/chn/changes/${decision.value.change.id}/${decision.value.action}/`, {
|
||||
method: 'POST', body: { comment: comment.value.trim() },
|
||||
})
|
||||
items.value = items.value.filter(item => item.id !== decision.value?.change.id)
|
||||
decision.value = null
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось сохранить решение'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="d-flex align-center justify-space-between mb-6">
|
||||
<div>
|
||||
<h1 class="text-h4">Изменения на согласование</h1>
|
||||
<p class="text-medium-emphasis mt-1">Изменения, ожидающие вашего решения</p>
|
||||
</div>
|
||||
<v-btn icon="mdi-refresh" variant="text" :loading="loading" @click="load" />
|
||||
</div>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-skeleton-loader v-if="loading && !items.length" type="list-item-three-line@3" />
|
||||
<v-card v-else-if="items.length" variant="outlined">
|
||||
<v-list lines="three">
|
||||
<template v-for="(change, index) in items" :key="change.id">
|
||||
<v-divider v-if="index" />
|
||||
<v-list-item>
|
||||
<template #title>{{ change.title || `Изменение #${change.id}` }}</template>
|
||||
<template #subtitle>
|
||||
{{ relationTitle(change.change_type, 'Тип') }} · {{ relationTitle(change.status, 'Статус') }}
|
||||
<div v-if="change.description" class="mt-1">{{ change.description }}</div>
|
||||
</template>
|
||||
<template #append>
|
||||
<div class="d-flex ga-2 ml-4">
|
||||
<v-btn color="success" variant="tonal" @click="openDecision(change, 'approve')">Согласовать</v-btn>
|
||||
<v-btn color="error" variant="tonal" @click="openDecision(change, 'reject')">Отклонить</v-btn>
|
||||
</div>
|
||||
</template>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</v-list>
|
||||
</v-card>
|
||||
<v-alert v-else type="info" variant="tonal">Нет изменений, ожидающих вашего согласования.</v-alert>
|
||||
|
||||
<v-dialog :model-value="Boolean(decision)" max-width="520" @update:model-value="!$event && (decision = null)">
|
||||
<v-card v-if="decision" class="pa-4">
|
||||
<v-card-title>{{ decision.action === 'approve' ? 'Согласовать изменение' : 'Отклонить изменение' }}</v-card-title>
|
||||
<v-card-text>
|
||||
<div class="mb-3">{{ decision.change.title }}</div>
|
||||
<v-textarea v-model="comment" label="Комментарий" rows="3" autofocus />
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn @click="decision = null">Отмена</v-btn>
|
||||
<v-btn :color="decision.action === 'approve' ? 'success' : 'error'" :loading="saving"
|
||||
@click="submitDecision">Подтвердить</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,122 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
change: ApiRecord
|
||||
section: 'tasks' | 'approvals' | 'workflow'
|
||||
active?: boolean
|
||||
}>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const items = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const loadedKey = ref('')
|
||||
|
||||
const decisionTitles: Record<string, string> = {
|
||||
pending: 'Ожидает решения',
|
||||
approved: 'Согласовано',
|
||||
rejected: 'Отклонено',
|
||||
}
|
||||
const stateTitles: Record<string, string> = {
|
||||
pending: 'Ожидает',
|
||||
active: 'Выполняется',
|
||||
succeeded: 'Выполнено',
|
||||
failed: 'Не выполнено',
|
||||
}
|
||||
|
||||
function relationTitle(value: unknown, fallback: string) {
|
||||
if (value && typeof value === 'object') {
|
||||
const record = value as ApiRecord
|
||||
return String(record.employee_name || record.name || record.title || record.fullname
|
||||
|| record.username || `${fallback} #${record.id}`)
|
||||
}
|
||||
return value === null || value === undefined ? '—' : `${fallback} #${value}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!props.active || props.change.id === undefined) return
|
||||
const key = `${props.section}:${props.change.id}`
|
||||
if (loadedKey.value === key) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
if (props.section === 'tasks') {
|
||||
const data = await request<any>('/main/chn/tasks/', {
|
||||
query: { page_size: 1000, parent_change__id__exact: props.change.id },
|
||||
})
|
||||
items.value = normalizeList(data).items
|
||||
} else if (props.section === 'workflow') {
|
||||
const data = await request<any>('/main/chn/workflow-runs/', {
|
||||
query: { page_size: 1000, change: props.change.id },
|
||||
})
|
||||
const runs = normalizeList(data).items
|
||||
items.value = await Promise.all(runs.map(async run => {
|
||||
if (run.node && typeof run.node === 'object') return run
|
||||
try {
|
||||
const node = await request<ApiRecord>(`/main/chn/workflow-nodes/${run.node}/`)
|
||||
return { ...run, node }
|
||||
} catch {
|
||||
return run
|
||||
}
|
||||
}))
|
||||
} else {
|
||||
const approvals = Array.isArray(props.change.approvals) ? props.change.approvals : []
|
||||
items.value = approvals.map(approval => approval && typeof approval === 'object'
|
||||
? approval as ApiRecord
|
||||
: { id: approval as string | number })
|
||||
}
|
||||
loadedKey.value = key
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось загрузить связанные данные'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.active, props.change.id, props.change.approvals], () => {
|
||||
if (props.section === 'approvals') loadedKey.value = ''
|
||||
load()
|
||||
}, { immediate: true, deep: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="change-related-data">
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
|
||||
<v-list v-if="items.length" class="border rounded-lg" lines="two">
|
||||
<template v-if="section === 'tasks'">
|
||||
<v-list-item v-for="task in items" :key="task.id"
|
||||
prepend-icon="mdi-checkbox-marked-circle-outline"
|
||||
:title="String(task.title || `Задача #${task.id}`)"
|
||||
:subtitle="[
|
||||
relationTitle(task.status, 'Статус'),
|
||||
task.progress !== undefined ? `Прогресс: ${task.progress}%` : '',
|
||||
].filter(Boolean).join(' · ')" />
|
||||
</template>
|
||||
<template v-else-if="section === 'approvals'">
|
||||
<v-list-item v-for="approval in items" :key="approval.id"
|
||||
prepend-icon="mdi-account-check-outline"
|
||||
:title="relationTitle(approval.employee, 'Согласование')"
|
||||
:subtitle="decisionTitles[String(approval.decision)] || `Запись #${approval.id}`" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<v-list-item v-for="run in items" :key="run.id"
|
||||
prepend-icon="mdi-source-branch"
|
||||
:title="relationTitle(run.node, 'Блок')"
|
||||
:subtitle="[
|
||||
stateTitles[String(run.state)] || String(run.state || 'Состояние не указано'),
|
||||
run.task ? relationTitle(run.task, 'Задача') : '',
|
||||
run.child_change ? relationTitle(run.child_change, 'Изменение') : '',
|
||||
].filter(Boolean).join(' · ')" />
|
||||
</template>
|
||||
</v-list>
|
||||
<v-alert v-else-if="!loading && !error" type="info" variant="tonal">
|
||||
{{ section === 'tasks'
|
||||
? 'Связанных задач нет.'
|
||||
: section === 'approvals'
|
||||
? 'Согласования не требуются.'
|
||||
: 'Бизнес-процесс ещё не запущен.' }}
|
||||
</v-alert>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
change: ApiRecord
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ changed: [] }>()
|
||||
const { request } = useApi()
|
||||
const transitioning = ref(false)
|
||||
const cancelling = ref(false)
|
||||
const error = ref('')
|
||||
const resolvedStatus = ref<ApiRecord | null>(null)
|
||||
const fixedStatusTitles: Record<string, string> = {
|
||||
new: 'Создан',
|
||||
assessment: 'На оценке',
|
||||
assessment_completed: 'Оценка предоставлена',
|
||||
pending_approval: 'На согласовании',
|
||||
approved: 'Авторизован / запланирован',
|
||||
in_progress: 'В работе',
|
||||
review: 'Проверка',
|
||||
review_completed: 'Проверка проведена',
|
||||
closed: 'Закрыт',
|
||||
rejected: 'Отклонён',
|
||||
cancelled: 'Отменён',
|
||||
}
|
||||
const automaticTransitionStatuses = new Set([
|
||||
'new', 'assessment', 'assessment_completed', 'approved', 'review', 'review_completed',
|
||||
])
|
||||
|
||||
const statusRecord = computed(() => {
|
||||
const status = props.change.status
|
||||
return status && typeof status === 'object' ? status as ApiRecord : resolvedStatus.value
|
||||
})
|
||||
const statusCode = computed(() => String(statusRecord.value?.code || ''))
|
||||
|
||||
const statusTitle = computed(() => {
|
||||
const record = statusRecord.value
|
||||
if (record) return String(record.name || record.title
|
||||
|| fixedStatusTitles[String(record.code)] || `Статус #${record.id}`)
|
||||
const status = props.change.status
|
||||
if (status === null || status === undefined) return 'Не назначен'
|
||||
return fixedStatusTitles[String(status)] || `Статус #${status}`
|
||||
})
|
||||
const canAdvance = computed(() => automaticTransitionStatuses.has(statusCode.value))
|
||||
const canCancel = computed(() => statusCode.value !== 'cancelled')
|
||||
const statusHint = computed(() => ({
|
||||
pending_approval: 'Дальнейший переход выполнится после решений всех согласующих.',
|
||||
in_progress: 'Статус изменится автоматически после завершения бизнес-процесса.',
|
||||
closed: 'Изменение закрыто.',
|
||||
rejected: 'Изменение отклонено.',
|
||||
cancelled: 'Изменение отменено.',
|
||||
}[statusCode.value] || ''))
|
||||
|
||||
async function resolveStatus() {
|
||||
const status = props.change.status
|
||||
resolvedStatus.value = status && typeof status === 'object' ? status as ApiRecord : null
|
||||
if ((typeof status !== 'string' && typeof status !== 'number') || fixedStatusTitles[String(status)]) return
|
||||
try {
|
||||
resolvedStatus.value = await request<ApiRecord>(`/main/chn/change-statuses/${status}/`)
|
||||
} catch {
|
||||
// The form remains usable even when the reference endpoint is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.change.status, resolveStatus, { immediate: true })
|
||||
|
||||
async function transition(target?: 'cancelled') {
|
||||
if (props.change.id === undefined) return
|
||||
if (target === 'cancelled'
|
||||
&& !window.confirm('Отменить изменение? Это действие переведёт его в статус «Отменено».')) return
|
||||
const progress = target === 'cancelled' ? cancelling : transitioning
|
||||
progress.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/chn/changes/${props.change.id}/transition/`, {
|
||||
method: 'POST',
|
||||
body: target ? { target } : {},
|
||||
})
|
||||
emit('changed')
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось изменить статус'
|
||||
} finally {
|
||||
progress.value = false
|
||||
}
|
||||
}
|
||||
</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(statusRecord?.color || '') || undefined" variant="tonal">
|
||||
{{ statusTitle }}
|
||||
</v-chip>
|
||||
</div>
|
||||
<template v-if="!readonly">
|
||||
<v-btn v-if="canAdvance" color="primary" prepend-icon="mdi-arrow-right-circle-outline"
|
||||
:loading="transitioning" :disabled="cancelling" @click="transition()">
|
||||
Следующий статус
|
||||
</v-btn>
|
||||
<v-btn v-if="canCancel" color="error" variant="tonal" prepend-icon="mdi-cancel"
|
||||
:loading="cancelling" :disabled="transitioning" @click="transition('cancelled')">
|
||||
Отменить изменение
|
||||
</v-btn>
|
||||
</template>
|
||||
</div>
|
||||
<v-alert v-if="statusHint" type="info" variant="tonal" class="mt-4">
|
||||
{{ statusHint }}
|
||||
</v-alert>
|
||||
<v-alert v-if="error" type="error" variant="tonal" closable class="mt-4"
|
||||
@click:close="error = ''">{{ error }}</v-alert>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<script setup lang="ts">
|
||||
const statuses = [
|
||||
{ code: 'created', name: 'Создан', color: '#607d8b' },
|
||||
{ code: 'assessment', name: 'На оценке', color: '#f9a825' },
|
||||
{ code: 'assessment_completed', name: 'Оценка предоставлена', color: '#7cb342' },
|
||||
{ code: 'approval', name: 'На согласовании', color: '#8e24aa' },
|
||||
{ code: 'planned', name: 'Запланирован', color: '#1e88e5' },
|
||||
{ code: 'in_progress', name: 'В работе', color: '#00897b' },
|
||||
{ code: 'review', name: 'Проверка', color: '#3949ab' },
|
||||
{ code: 'review_completed', name: 'Проверка проведена', color: '#43a047' },
|
||||
{ code: 'completed', name: 'Закрыт', color: '#2e7d32' },
|
||||
{ code: 'rejected', name: 'Отклонён', color: '#e53935' },
|
||||
{ code: 'cancelled', name: 'Отменён', color: '#757575' },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="mb-6">
|
||||
<div class="mb-3">
|
||||
<h3 class="text-subtitle-1 font-weight-bold">Статусы процесса</h3>
|
||||
<p class="text-caption text-medium-emphasis">
|
||||
Фиксированная последовательность статусов изменения
|
||||
</p>
|
||||
</div>
|
||||
<v-list class="border rounded-lg" lines="two">
|
||||
<v-list-item v-for="(status, index) in statuses" :key="status.code"
|
||||
:title="status.name" :subtitle="status.code">
|
||||
<template #prepend>
|
||||
<span class="status-color" :style="{ backgroundColor: status.color }" />
|
||||
</template>
|
||||
<template #append>
|
||||
<span class="text-caption text-medium-emphasis">{{ index + 1 }}</span>
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.status-color {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid rgba(var(--v-theme-on-surface), .2);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,309 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{ changeTypeId: string | number; readonly?: boolean }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const nodes = ref<ApiRecord[]>([])
|
||||
const edges = ref<ApiRecord[]>([])
|
||||
const taskTypes = ref<ApiRecord[]>([])
|
||||
const changeTypes = ref<ApiRecord[]>([])
|
||||
const priorities = ref<ApiRecord[]>([])
|
||||
const departments = ref<ApiRecord[]>([])
|
||||
const employees = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const nodeDialog = ref(false)
|
||||
const editingNodeId = ref<string | number | null>(null)
|
||||
const nodeForm = reactive<ApiRecord>({})
|
||||
const dragging = ref<{ id: string | number; offsetX: number; offsetY: number } | null>(null)
|
||||
const connectionDrag = ref<{
|
||||
source: string | number
|
||||
decision: 'always' | 'positive' | 'negative'
|
||||
startX: number
|
||||
startY: number
|
||||
currentX: number
|
||||
currentY: number
|
||||
} | null>(null)
|
||||
const board = ref<HTMLElement | null>(null)
|
||||
const systemKinds = new Set(['input', 'positive_output', 'negative_output'])
|
||||
|
||||
function isSystemNode(node?: ApiRecord) {
|
||||
return Boolean(node && systemKinds.has(String(node.kind)))
|
||||
}
|
||||
|
||||
function nodeIcon(node: ApiRecord) {
|
||||
if (node.kind === 'input') return 'mdi-play-circle-outline'
|
||||
if (node.kind === 'positive_output') return 'mdi-check-circle-outline'
|
||||
if (node.kind === 'negative_output') return 'mdi-close-circle-outline'
|
||||
return node.kind === 'task' ? 'mdi-checkbox-marked-circle-outline' : 'mdi-swap-horizontal-bold'
|
||||
}
|
||||
|
||||
function nodeKindTitle(node: ApiRecord) {
|
||||
if (node.kind === 'input') return 'Начало процесса'
|
||||
if (node.kind === 'positive_output') return 'Положительный выход'
|
||||
if (node.kind === 'negative_output') return 'Отрицательный выход'
|
||||
return node.kind === 'task' ? 'Задача' : 'Изменение'
|
||||
}
|
||||
|
||||
const option = (item: ApiRecord) => ({ title: String(item.name || item.title || `#${item.id}`), value: item.id! })
|
||||
const nodeById = computed(() => new Map(nodes.value.map(node => [String(node.id), node])))
|
||||
const paths = computed(() => edges.value.flatMap(edge => {
|
||||
const source = nodeById.value.get(String(edge.source))
|
||||
const target = nodeById.value.get(String(edge.target))
|
||||
if (!source || !target) return []
|
||||
const x1 = Number(source.x || 0) + 220
|
||||
const decision = String(edge.decision || 'positive')
|
||||
const y1 = Number(source.y || 0) + (decision === 'always' ? 60 : decision === 'positive' ? 38 : 82)
|
||||
const x2 = Number(target.x || 0)
|
||||
const y2 = Number(target.y || 0) + 60
|
||||
const middle = x1 + Math.max(35, (x2 - x1) / 2)
|
||||
return [{ ...edge, decision, path: `M ${x1} ${y1} C ${middle} ${y1}, ${middle} ${y2}, ${x2} ${y2}` }]
|
||||
}))
|
||||
function edgeColor(decision: unknown) {
|
||||
if (decision === 'always') return '#546e7a'
|
||||
return decision === 'positive' ? '#2e7d32' : '#c62828'
|
||||
}
|
||||
const connectionPreviewPath = computed(() => {
|
||||
const connection = connectionDrag.value
|
||||
if (!connection) return ''
|
||||
const middle = connection.startX + (connection.currentX - connection.startX) / 2
|
||||
return `M ${connection.startX} ${connection.startY} C ${middle} ${connection.startY}, ${middle} ${connection.currentY}, ${connection.currentX} ${connection.currentY}`
|
||||
})
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [nodeData, edgeData, taskTypeData, changeTypeData, priorityData, departmentData, employeeData] = await Promise.all([
|
||||
request<any>('/main/chn/workflow-nodes/', { query: { page_size: 1000, change_type: props.changeTypeId } }),
|
||||
request<any>('/main/chn/workflow-edges/', { query: { page_size: 1000, change_type: props.changeTypeId } }),
|
||||
request<any>('/main/chn/task-types/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/chn/change-types/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/chn/task-priorities/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/departments/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/employees/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
nodes.value = normalizeList(nodeData).items
|
||||
edges.value = normalizeList(edgeData).items
|
||||
taskTypes.value = normalizeList(taskTypeData).items
|
||||
changeTypes.value = normalizeList(changeTypeData).items.filter(item => String(item.id) !== String(props.changeTypeId))
|
||||
priorities.value = normalizeList(priorityData).items
|
||||
departments.value = normalizeList(departmentData).items
|
||||
employees.value = normalizeList(employeeData).items
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось загрузить схему процесса'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openNode(node?: ApiRecord) {
|
||||
if (isSystemNode(node)) return
|
||||
editingNodeId.value = node?.id ?? null
|
||||
Object.assign(nodeForm, {
|
||||
kind: node?.kind || 'task', title: node?.title || '', description: node?.description || '',
|
||||
x: Number(node?.x ?? 40), y: Number(node?.y ?? 40), task_type: node?.task_type ?? null,
|
||||
child_change_type: node?.child_change_type ?? null, priority: node?.priority ?? null,
|
||||
department: node?.department ?? null, assignees: Array.isArray(node?.assignees) ? [...node.assignees] : [],
|
||||
})
|
||||
nodeDialog.value = true
|
||||
}
|
||||
|
||||
async function saveNode() {
|
||||
const id = editingNodeId.value
|
||||
const existingNode = nodes.value.find(node => String(node.id) === String(id))
|
||||
if (isSystemNode(existingNode)) return
|
||||
const body = {
|
||||
...nodeForm, change_type: props.changeTypeId,
|
||||
task_type: nodeForm.kind === 'task' ? nodeForm.task_type : null,
|
||||
child_change_type: nodeForm.kind === 'change' ? nodeForm.child_change_type : null,
|
||||
}
|
||||
try {
|
||||
const saved = await request<ApiRecord>(id === null ? '/main/chn/workflow-nodes/' : `/main/chn/workflow-nodes/${id}/`, {
|
||||
method: id === null ? 'POST' : 'PATCH', body,
|
||||
})
|
||||
const index = nodes.value.findIndex(node => String(node.id) === String(saved.id))
|
||||
if (index < 0) nodes.value.push(saved); else nodes.value[index] = saved
|
||||
nodeDialog.value = false
|
||||
} catch (caught: any) { error.value = caught.message || 'Не удалось сохранить блок' }
|
||||
}
|
||||
|
||||
function connectionError(source: ApiRecord, target: ApiRecord, decision: 'always' | 'positive' | 'negative') {
|
||||
if (String(source.id) === String(target.id)) return 'Нельзя соединить блок с самим собой'
|
||||
if (['positive_output', 'negative_output'].includes(String(source.kind))) {
|
||||
return 'Связь должна начинаться с выхода блока'
|
||||
}
|
||||
if (target.kind === 'input') return 'Блок «Начало» не может принимать входящие связи'
|
||||
if (target.kind === 'positive_output' && decision !== 'positive') {
|
||||
return 'Блок «Выполнено» принимает только положительный выход'
|
||||
}
|
||||
if (target.kind === 'negative_output' && decision !== 'negative') {
|
||||
return 'Блок «Не выполнено» принимает только отрицательный выход'
|
||||
}
|
||||
if (edges.value.some(edge => String(edge.source) === String(source.id)
|
||||
&& String(edge.decision || 'positive') === decision)) {
|
||||
if (decision === 'always') return 'Выход блока «Начало» уже связан'
|
||||
return decision === 'positive'
|
||||
? 'Положительный выход этого блока уже связан'
|
||||
: 'Отрицательный выход этого блока уже связан'
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
async function saveEdge(source: ApiRecord, target: ApiRecord, decision: 'always' | 'positive' | 'negative') {
|
||||
const validationError = connectionError(source, target, decision)
|
||||
if (validationError) {
|
||||
error.value = validationError
|
||||
return
|
||||
}
|
||||
try {
|
||||
const saved = await request<ApiRecord>('/main/chn/workflow-edges/', {
|
||||
method: 'POST',
|
||||
body: { source: source.id, target: target.id, decision },
|
||||
})
|
||||
edges.value.push(saved)
|
||||
error.value = ''
|
||||
} catch (caught: any) { error.value = caught.message || 'Не удалось сохранить связь' }
|
||||
}
|
||||
|
||||
function boardPoint(event: PointerEvent) {
|
||||
const rect = board.value?.getBoundingClientRect()
|
||||
if (!rect || !board.value) return null
|
||||
return {
|
||||
x: event.clientX - rect.left + board.value.scrollLeft,
|
||||
y: event.clientY - rect.top + board.value.scrollTop,
|
||||
}
|
||||
}
|
||||
|
||||
function startConnection(event: PointerEvent, node: ApiRecord, decision: 'positive' | 'negative') {
|
||||
if (props.readonly || node.id === undefined
|
||||
|| ['positive_output', 'negative_output'].includes(String(node.kind))) return
|
||||
event.stopPropagation()
|
||||
const apiDecision = node.kind === 'input' ? 'always' : decision
|
||||
const startX = Number(node.x || 0) + 220
|
||||
const startY = Number(node.y || 0) + (apiDecision === 'always' ? 60 : decision === 'positive' ? 38 : 82)
|
||||
connectionDrag.value = { source: node.id, decision: apiDecision, startX, startY, currentX: startX, currentY: startY }
|
||||
window.addEventListener('pointermove', moveConnection)
|
||||
window.addEventListener('pointerup', finishConnection, { once: true })
|
||||
}
|
||||
|
||||
function moveConnection(event: PointerEvent) {
|
||||
const point = boardPoint(event)
|
||||
if (!connectionDrag.value || !point) return
|
||||
connectionDrag.value.currentX = point.x
|
||||
connectionDrag.value.currentY = point.y
|
||||
}
|
||||
|
||||
async function finishConnection(event: PointerEvent) {
|
||||
window.removeEventListener('pointermove', moveConnection)
|
||||
const connection = connectionDrag.value
|
||||
connectionDrag.value = null
|
||||
if (!connection) return
|
||||
const input = document.elementFromPoint(event.clientX, event.clientY)
|
||||
?.closest<HTMLElement>('[data-workflow-input]')
|
||||
if (!input?.dataset.workflowInput) {
|
||||
error.value = 'Перетащите связь на вход другого блока'
|
||||
return
|
||||
}
|
||||
const source = nodes.value.find(node => String(node.id) === String(connection.source))
|
||||
const target = nodes.value.find(node => String(node.id) === input.dataset.workflowInput)
|
||||
if (source && target) await saveEdge(source, target, connection.decision)
|
||||
}
|
||||
|
||||
async function removeNode(node: ApiRecord) {
|
||||
if (!node.id || isSystemNode(node)
|
||||
|| !window.confirm(`Удалить блок «${node.title}» и его связи?`)) return
|
||||
await request(`/main/chn/workflow-nodes/${node.id}/`, { method: 'DELETE' })
|
||||
nodes.value = nodes.value.filter(item => item.id !== node.id)
|
||||
edges.value = edges.value.filter(edge => edge.source !== node.id && edge.target !== node.id)
|
||||
}
|
||||
|
||||
async function removeEdge(edge: ApiRecord) {
|
||||
if (!edge.id) return
|
||||
await request(`/main/chn/workflow-edges/${edge.id}/`, { method: 'DELETE' })
|
||||
edges.value = edges.value.filter(item => item.id !== edge.id)
|
||||
}
|
||||
|
||||
function startDrag(event: PointerEvent, node: ApiRecord) {
|
||||
if (props.readonly || node.id === undefined) return
|
||||
const rect = board.value?.getBoundingClientRect()
|
||||
if (!rect) return
|
||||
dragging.value = { id: node.id, offsetX: event.clientX - rect.left - Number(node.x || 0), offsetY: event.clientY - rect.top - Number(node.y || 0) }
|
||||
window.addEventListener('pointermove', drag)
|
||||
window.addEventListener('pointerup', finishDrag, { once: true })
|
||||
}
|
||||
function drag(event: PointerEvent) {
|
||||
const active = dragging.value
|
||||
const rect = board.value?.getBoundingClientRect()
|
||||
const node = nodes.value.find(item => item.id === active?.id)
|
||||
if (!active || !rect || !node) return
|
||||
node.x = Math.max(0, event.clientX - rect.left - active.offsetX)
|
||||
node.y = Math.max(0, event.clientY - rect.top - active.offsetY)
|
||||
}
|
||||
async function finishDrag() {
|
||||
window.removeEventListener('pointermove', drag)
|
||||
const active = dragging.value
|
||||
dragging.value = null
|
||||
const node = nodes.value.find(item => item.id === active?.id)
|
||||
if (node?.id) await request(`/main/chn/workflow-nodes/${node.id}/`, { method: 'PATCH', body: { x: node.x, y: node.y } })
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="d-flex align-center justify-space-between mb-3">
|
||||
<div><h3 class="text-h6">Бизнес-процесс</h3><p class="text-caption text-medium-emphasis">Перетаскивайте блоки и соединяйте положительные и отрицательные выходы</p></div>
|
||||
<v-btn v-if="!readonly" prepend-icon="mdi-plus-box" @click="openNode()">Блок</v-btn>
|
||||
</div>
|
||||
<v-alert v-if="error" type="error" variant="tonal" closable class="mb-3" @click:close="error = ''">{{ error }}</v-alert>
|
||||
<div ref="board" class="workflow-board">
|
||||
<svg class="workflow-lines" width="1600" height="900">
|
||||
<path v-for="edge in paths" :key="edge.id" :d="edge.path" fill="none"
|
||||
:stroke="edgeColor(edge.decision)" stroke-width="3"
|
||||
@dblclick="!readonly && removeEdge(edge)" />
|
||||
<path v-if="connectionPreviewPath" :d="connectionPreviewPath" fill="none"
|
||||
:stroke="edgeColor(connectionDrag?.decision)"
|
||||
stroke-width="3" stroke-dasharray="7 5" />
|
||||
</svg>
|
||||
<v-card v-for="node in nodes" :key="node.id" class="workflow-node"
|
||||
:class="{ 'workflow-node--system': isSystemNode(node) }"
|
||||
:style="{ left: `${node.x || 0}px`, top: `${node.y || 0}px` }"
|
||||
variant="outlined" @pointerdown="startDrag($event, node)">
|
||||
<v-card-text class="pa-3">
|
||||
<div class="d-flex align-center">
|
||||
<v-icon class="mr-2">{{ nodeIcon(node) }}</v-icon>
|
||||
<strong class="text-truncate">{{ node.title }}</strong>
|
||||
<v-spacer />
|
||||
<v-btn v-if="!readonly && !isSystemNode(node)" icon="mdi-pencil" size="x-small"
|
||||
variant="text" @pointerdown.stop @click="openNode(node)" />
|
||||
</div>
|
||||
<div class="text-caption mt-2">{{ nodeKindTitle(node) }}</div>
|
||||
</v-card-text>
|
||||
<span v-if="node.kind !== 'input'" class="port port-in" title="Вход"
|
||||
:data-workflow-input="node.id" />
|
||||
<span v-if="!['positive_output', 'negative_output'].includes(String(node.kind))"
|
||||
class="port port-positive" :class="{ 'port-single': node.kind === 'input' }"
|
||||
:title="node.kind === 'input' ? 'Выход процесса' : 'Положительный выход'"
|
||||
@pointerdown="startConnection($event, node, 'positive')">{{ node.kind === 'input' ? '→' : '+' }}</span>
|
||||
<span v-if="!['input', 'positive_output', 'negative_output'].includes(String(node.kind))"
|
||||
class="port port-negative" title="Отрицательный выход"
|
||||
@pointerdown="startConnection($event, node, 'negative')">−</span>
|
||||
</v-card>
|
||||
<div v-if="!loading && !nodes.length" class="workflow-empty">Добавьте первый блок процесса</div>
|
||||
</div>
|
||||
|
||||
<v-dialog v-model="nodeDialog" max-width="620"><v-card class="pa-4"><v-card-title>{{ editingNodeId === null ? 'Новый блок' : 'Изменить блок' }}</v-card-title><v-card-text>
|
||||
<v-select v-model="nodeForm.kind" :items="[{ title: 'Задача', value: 'task' }, { title: 'Изменение', value: 'change' }]" label="Вид блока" />
|
||||
<v-text-field v-model="nodeForm.title" label="Название" required />
|
||||
<v-textarea v-model="nodeForm.description" label="Описание" rows="2" />
|
||||
<template v-if="nodeForm.kind === 'task'"><v-select v-model="nodeForm.task_type" :items="taskTypes.map(option)" label="Тип задачи" required /><v-select v-model="nodeForm.priority" :items="priorities.map(option)" label="Приоритет" clearable /><v-select v-model="nodeForm.department" :items="departments.map(option)" label="Подразделение" clearable /><v-autocomplete v-model="nodeForm.assignees" :items="employees.map(option)" label="Исполнители" multiple chips clearable /></template>
|
||||
<v-select v-else v-model="nodeForm.child_change_type" :items="changeTypes.map(option)" label="Тип дочернего изменения" required />
|
||||
</v-card-text><v-card-actions><v-btn v-if="editingNodeId !== null" color="error" variant="text" @click="removeNode(nodes.find(n => n.id === editingNodeId)!); nodeDialog = false">Удалить</v-btn><v-spacer /><v-btn @click="nodeDialog = false">Отмена</v-btn><v-btn color="primary" @click="saveNode">Сохранить</v-btn></v-card-actions></v-card></v-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.workflow-board{position:relative;box-sizing:border-box;width:100%;min-width:400px;height:600px;min-height:400px;max-width:100%;overflow:auto;resize:both;background:radial-gradient(circle,rgba(var(--v-theme-on-surface),.12) 1px,transparent 1px);background-size:20px 20px;border:1px solid rgba(var(--v-border-color),var(--v-border-opacity));border-radius:12px}.workflow-lines{position:absolute;inset:0;pointer-events:stroke}.workflow-node{position:absolute;width:220px;height:120px;cursor:move;user-select:none;z-index:2;background:rgb(var(--v-theme-surface))!important;box-shadow:0 3px 10px rgba(0,0,0,.18)}.workflow-node--system{border-color:rgb(var(--v-theme-primary))!important;box-shadow:0 3px 10px rgba(0,0,0,.18),0 0 0 1px rgb(var(--v-theme-primary))}.port{position:absolute;width:22px;height:22px;border-radius:50%;display:grid;place-items:center;color:white;font-weight:700;touch-action:none}.port-in{left:-11px;top:49px;background:#546e7a}.port-positive{right:-11px;top:27px;background:#2e7d32;cursor:crosshair}.port-positive.port-single{top:49px}.port-negative{right:-11px;top:71px;background:#c62828;cursor:crosshair}.workflow-empty{position:absolute;inset:0;display:grid;place-items:center;color:rgba(var(--v-theme-on-surface),.55)}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
<script setup lang="ts">
|
||||
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 error = ref('')
|
||||
const loadedKey = ref('')
|
||||
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}`)
|
||||
return value === null || value === undefined ? '—' : `${fallback} #${value}`
|
||||
}
|
||||
async function load(force = false) {
|
||||
if (!key.value || (!force && loadedKey.value === key.value)) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const query = props.parentKind === 'task'
|
||||
? { page_size: 1000, parent_task__id__exact: props.parentId }
|
||||
: { page_size: 1000, parent_change__id__exact: props.parentId }
|
||||
const data = await request<any>('/main/chn/tasks/', { query })
|
||||
items.value = normalizeList(data).items
|
||||
loadedKey.value = key.value
|
||||
} catch (caught: any) { error.value = caught?.message || 'Не удалось загрузить дочерние задачи' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function create() {
|
||||
if (!key.value || !title.value.trim()) 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 },
|
||||
})
|
||||
title.value = ''
|
||||
description.value = ''
|
||||
await load(true)
|
||||
} catch (caught: any) { error.value = caught?.message || 'Не удалось создать дочернюю задачу' }
|
||||
finally { creating.value = false }
|
||||
}
|
||||
watch(() => [key.value, props.active], () => { if (props.active !== false) load() }, { immediate: true })
|
||||
</script>
|
||||
|
||||
<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>
|
||||
<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-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>
|
||||
</template>
|
||||
</template>
|
||||
|
|
@ -6,20 +6,26 @@ const props = defineProps<{
|
|||
kind: 'req' | 'inc'
|
||||
recordId?: string | number
|
||||
readonly?: boolean
|
||||
active?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const comments = ref<ApiRecord[]>([])
|
||||
const text = ref('')
|
||||
const selectedFiles = ref<File[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const downloadingAttachment = ref('')
|
||||
const deletingAttachment = ref('')
|
||||
const loaded = ref(false)
|
||||
const error = ref('')
|
||||
const bottomAnchor = ref<HTMLElement | null>(null)
|
||||
|
||||
const endpoint = computed(() => `/main/${props.kind}/comments/`)
|
||||
const relationField = computed(() => props.kind === 'req' ? 'req_request' : 'inc_incident')
|
||||
const filterField = computed(() => `${relationField.value}__id__exact`)
|
||||
const entityName = computed(() => props.kind === 'req' ? 'обращения' : 'инцидента')
|
||||
const attachmentField = computed(() => props.kind === 'req' ? 'req_comment_file' : 'inc_comment_file')
|
||||
|
||||
function commentDate(comment: ApiRecord) {
|
||||
return comment.sysdatecreate || comment.created_at || comment.created || comment.datecreate
|
||||
|
|
@ -29,6 +35,61 @@ function commentAuthor(comment: ApiRecord) {
|
|||
return String(comment.author || 'Неизвестный автор')
|
||||
}
|
||||
|
||||
function normalizeFiles(value: File[] | File | null) {
|
||||
selectedFiles.value = value === null ? [] : Array.isArray(value) ? value : [value]
|
||||
}
|
||||
|
||||
function commentAttachments(comment: ApiRecord) {
|
||||
const value = comment[attachmentField.value]
|
||||
return Array.isArray(value) ? value as ApiRecord[] : []
|
||||
}
|
||||
|
||||
function attachmentKey(comment: ApiRecord, attachment: ApiRecord) {
|
||||
return `${comment.id}:${attachment.id}`
|
||||
}
|
||||
|
||||
function attachmentEndpoint(comment: ApiRecord, attachment: ApiRecord) {
|
||||
return `/main/${props.kind}/comments/${comment.id}/attachments/${attachment.id}/`
|
||||
}
|
||||
|
||||
async function downloadCommentAttachment(comment: ApiRecord, attachment: ApiRecord) {
|
||||
const key = attachmentKey(comment, attachment)
|
||||
downloadingAttachment.value = key
|
||||
error.value = ''
|
||||
try {
|
||||
const blob = await request<Blob>(attachmentEndpoint(comment, attachment), { responseType: 'blob' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = String(attachment.name || 'attachment')
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось скачать вложение комментария'
|
||||
} finally {
|
||||
downloadingAttachment.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteCommentAttachment(comment: ApiRecord, attachment: ApiRecord) {
|
||||
if (!window.confirm(`Удалить вложение «${String(attachment.name || '')}»?`)) return
|
||||
const key = attachmentKey(comment, attachment)
|
||||
deletingAttachment.value = key
|
||||
error.value = ''
|
||||
try {
|
||||
await request(attachmentEndpoint(comment, attachment), { method: 'DELETE' })
|
||||
const files = commentAttachments(comment)
|
||||
.filter(item => String(item.id) !== String(attachment.id))
|
||||
comment[attachmentField.value] = files
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось удалить вложение комментария'
|
||||
} finally {
|
||||
deletingAttachment.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function loadComments(force = false) {
|
||||
if ((!force && loaded.value) || props.recordId === undefined || props.recordId === null) return
|
||||
loading.value = true
|
||||
|
|
@ -47,13 +108,20 @@ async function loadComments(force = false) {
|
|||
}
|
||||
}
|
||||
|
||||
async function scrollToBottom() {
|
||||
await nextTick()
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => {
|
||||
bottomAnchor.value?.scrollIntoView({ block: 'end' })
|
||||
}))
|
||||
}
|
||||
|
||||
async function addComment() {
|
||||
const value = text.value.trim()
|
||||
if (!value || props.recordId === undefined || props.recordId === null) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request<ApiRecord>(endpoint.value, {
|
||||
const comment = await request<ApiRecord>(endpoint.value, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
[relationField.value]: { id: props.recordId },
|
||||
|
|
@ -61,7 +129,23 @@ async function addComment() {
|
|||
},
|
||||
})
|
||||
text.value = ''
|
||||
if (selectedFiles.value.length && (comment.id === undefined || comment.id === null)) {
|
||||
error.value = 'Комментарий добавлен, но API не вернул его идентификатор для загрузки вложений.'
|
||||
} else if (selectedFiles.value.length) {
|
||||
const body = new FormData()
|
||||
selectedFiles.value.forEach(file => body.append('files', file))
|
||||
try {
|
||||
await request(`/main/${props.kind}/comments/${comment.id}/attachments/`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
})
|
||||
selectedFiles.value = []
|
||||
} catch (caught: any) {
|
||||
error.value = `Комментарий добавлен, но вложения загрузить не удалось: ${caught?.message || 'неизвестная ошибка'}`
|
||||
}
|
||||
}
|
||||
await loadComments(true)
|
||||
await scrollToBottom()
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось добавить комментарий'
|
||||
} finally {
|
||||
|
|
@ -71,10 +155,17 @@ async function addComment() {
|
|||
|
||||
watch(() => props.recordId, () => {
|
||||
comments.value = []
|
||||
selectedFiles.value = []
|
||||
loaded.value = false
|
||||
error.value = ''
|
||||
loadComments()
|
||||
}, { immediate: true })
|
||||
|
||||
watch(() => props.active, async active => {
|
||||
if (!active) return
|
||||
await loadComments()
|
||||
await scrollToBottom()
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -82,20 +173,6 @@ watch(() => props.recordId, () => {
|
|||
Сначала сохраните {{ entityName }}, затем можно будет добавлять комментарии.
|
||||
</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-textarea v-model="text" label="Текст комментария" rows="3" auto-grow
|
||||
:disabled="saving" @keydown.ctrl.enter.prevent="addComment" />
|
||||
<div class="d-flex justify-end">
|
||||
<v-btn type="button" color="primary" prepend-icon="mdi-comment-plus-outline"
|
||||
:disabled="!text.trim()" :loading="saving" @click="addComment">
|
||||
Добавить
|
||||
</v-btn>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<div v-if="loading" class="d-flex justify-center py-8">
|
||||
<v-progress-circular indeterminate color="primary" />
|
||||
|
|
@ -112,7 +189,45 @@ watch(() => props.recordId, () => {
|
|||
</span>
|
||||
</div>
|
||||
<div class="text-body-1" style="white-space: pre-wrap">{{ comment.text }}</div>
|
||||
<div v-if="commentAttachments(comment).length" class="mt-4">
|
||||
<div class="text-caption text-medium-emphasis mb-1">Вложения</div>
|
||||
<v-list density="compact" variant="tonal" rounded>
|
||||
<v-list-item v-for="attachment in commentAttachments(comment)" :key="String(attachment.id)"
|
||||
prepend-icon="mdi-file-outline" :title="String(attachment.name || 'Файл')">
|
||||
<template #append>
|
||||
<div class="d-flex ga-1">
|
||||
<v-btn type="button" icon="mdi-download" size="small" variant="text" color="primary"
|
||||
:loading="downloadingAttachment === attachmentKey(comment, attachment)"
|
||||
aria-label="Скачать вложение" title="Скачать"
|
||||
@click="downloadCommentAttachment(comment, attachment)" />
|
||||
<v-btn v-if="!readonly" type="button" icon="mdi-delete-outline" size="small"
|
||||
variant="text" color="error"
|
||||
:loading="deletingAttachment === attachmentKey(comment, attachment)"
|
||||
aria-label="Удалить вложение" title="Удалить"
|
||||
@click="deleteCommentAttachment(comment, attachment)" />
|
||||
</div>
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
|
||||
<v-card v-if="!readonly" variant="outlined" class="mt-4">
|
||||
<v-card-title class="text-subtitle-1">Новый комментарий</v-card-title>
|
||||
<v-card-text>
|
||||
<v-textarea v-model="text" label="Текст комментария" rows="3" auto-grow
|
||||
:disabled="saving" @keydown.ctrl.enter.prevent="addComment" />
|
||||
<v-file-input :model-value="selectedFiles" label="Вложения" multiple chips show-size
|
||||
prepend-icon="mdi-paperclip" :disabled="saving" @update:model-value="normalizeFiles" />
|
||||
<div class="d-flex justify-end">
|
||||
<v-btn type="button" color="primary" prepend-icon="mdi-comment-plus-outline"
|
||||
:disabled="!text.trim()" :loading="saving" @click="addComment">
|
||||
Добавить
|
||||
</v-btn>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
<div ref="bottomAnchor" />
|
||||
</template>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,309 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
type Id = string | number
|
||||
type ContactDraft = {
|
||||
type: 'phone' | 'email' | 'telegram'
|
||||
purpose: 'personal' | 'work' | 'notification' | 'billing' | 'emergency'
|
||||
value: string
|
||||
label: string
|
||||
is_primary: boolean
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: ApiRecord
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: ApiRecord] }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
|
||||
const persons = ref<ApiRecord[]>([])
|
||||
const contacts = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const personDialog = ref(false)
|
||||
const selectDialog = ref(false)
|
||||
const savingPerson = ref(false)
|
||||
const selectedExistingPersonId = ref<Id | null>(null)
|
||||
let personSearchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const personDialogError = ref('')
|
||||
const newPerson = reactive({ name: '', is_active: true })
|
||||
const newContacts = ref<ContactDraft[]>([])
|
||||
|
||||
function ids(value: unknown): Id[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.flatMap(item => {
|
||||
if (typeof item === 'string' || typeof item === 'number') return [item]
|
||||
const id = (item as ApiRecord)?.id
|
||||
return typeof id === 'string' || typeof id === 'number' ? [id] : []
|
||||
})
|
||||
}
|
||||
const selectedPersonIds = computed(() => ids(props.modelValue.con_person))
|
||||
const selectedPersonRecords = computed(() => selectedPersonIds.value.map(id =>
|
||||
persons.value.find(person => String(person.id) === String(id)) || { id, name: `Контактное лицо #${id}` }))
|
||||
const availablePersonOptions = computed(() => {
|
||||
const selected = new Set(selectedPersonIds.value.map(String))
|
||||
return persons.value.flatMap(person => person.id === undefined || selected.has(String(person.id)) ? [] : [{
|
||||
title: String(person.name || `Контактное лицо #${person.id}`),
|
||||
value: person.id,
|
||||
}])
|
||||
})
|
||||
const typeOptions = [
|
||||
{ title: 'Телефон', value: 'phone' },
|
||||
{ title: 'Email', value: 'email' },
|
||||
{ title: 'Telegram', value: 'telegram' },
|
||||
]
|
||||
const purposeOptions = [
|
||||
{ title: 'Личный', value: 'personal' },
|
||||
{ title: 'Рабочий', value: 'work' },
|
||||
{ title: 'Для уведомлений', value: 'notification' },
|
||||
{ title: 'Для расчётов', value: 'billing' },
|
||||
{ title: 'Экстренный', value: 'emergency' },
|
||||
]
|
||||
const typeNames = Object.fromEntries(typeOptions.map(option => [option.value, option.title]))
|
||||
const purposeNames = Object.fromEntries(purposeOptions.map(option => [option.value, option.title]))
|
||||
|
||||
function contactPersonId(contact: ApiRecord) {
|
||||
const person = contact.con_person
|
||||
if (typeof person === 'string' || typeof person === 'number') return person
|
||||
return (person as ApiRecord | null)?.id
|
||||
}
|
||||
function personContacts(personId: unknown) {
|
||||
return contacts.value.filter(contact => contact.id !== undefined
|
||||
&& String(contactPersonId(contact)) === String(personId))
|
||||
}
|
||||
function removePerson(personId: unknown) {
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
con_person: selectedPersonIds.value.filter(id => String(id) !== String(personId)),
|
||||
})
|
||||
}
|
||||
function openSelectDialog() {
|
||||
selectDialog.value = true
|
||||
}
|
||||
function selectExistingPerson(personId: Id) {
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
con_person: [...new Set([...selectedPersonIds.value, personId])],
|
||||
})
|
||||
selectedExistingPersonId.value = null
|
||||
}
|
||||
|
||||
function searchPersons(search: string) {
|
||||
if (personSearchTimer) clearTimeout(personSearchTimer)
|
||||
personSearchTimer = setTimeout(async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<any>('/main/con/persons/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
})
|
||||
persons.value = mergeRecords(
|
||||
persons.value.filter(person => selectedPersonIds.value.some(id => String(id) === String(person.id))),
|
||||
normalizeList(result).items,
|
||||
)
|
||||
} catch (e: any) {
|
||||
error.value = e.message || 'Не удалось найти контактные лица'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
|
||||
function mergeRecords(current: ApiRecord[], incoming: ApiRecord[]) {
|
||||
const merged = new Map<Id, ApiRecord>()
|
||||
for (const record of [...current, ...incoming]) if (record.id !== undefined) merged.set(record.id, record)
|
||||
return [...merged.values()]
|
||||
}
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
const [personResult] = await Promise.allSettled([
|
||||
request<any>('/main/con/persons/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
if (personResult.status === 'fulfilled') {
|
||||
persons.value = mergeRecords(persons.value, normalizeList(personResult.value).items)
|
||||
}
|
||||
const failed = [personResult].find(result => result.status === 'rejected')
|
||||
if (failed?.status === 'rejected') error.value = failed.reason?.message || 'Не удалось загрузить контактные данные'
|
||||
loading.value = false
|
||||
await loadSelectedRecords()
|
||||
}
|
||||
async function loadSelectedRecords() {
|
||||
const knownPersons = new Set(persons.value.map(person => String(person.id)))
|
||||
const personIds = selectedPersonIds.value.filter(id => !knownPersons.has(String(id)))
|
||||
const [personResults, contactResults] = await Promise.all([
|
||||
Promise.allSettled(personIds.map(id => request<ApiRecord>(`/main/con/persons/${id}/`))),
|
||||
Promise.allSettled(selectedPersonIds.value.map(id => request<any>('/main/con/contacts/', {
|
||||
query: { page_size: 1000, con_person__id__exact: id },
|
||||
}))),
|
||||
])
|
||||
persons.value = mergeRecords(persons.value,
|
||||
personResults.flatMap(result => result.status === 'fulfilled' ? [result.value] : []))
|
||||
contacts.value = mergeRecords(contacts.value,
|
||||
contactResults.flatMap(result => result.status === 'fulfilled'
|
||||
? normalizeList(result.value).items : []))
|
||||
}
|
||||
function emptyContact(): ContactDraft {
|
||||
return { type: 'phone', purpose: 'work', value: '', label: '', is_primary: false, is_active: true }
|
||||
}
|
||||
function openPersonDialog() {
|
||||
newPerson.name = ''
|
||||
newPerson.is_active = true
|
||||
newContacts.value = []
|
||||
personDialogError.value = ''
|
||||
personDialog.value = true
|
||||
}
|
||||
function addContact() {
|
||||
newContacts.value.push(emptyContact())
|
||||
}
|
||||
function normalizedContactValue(type: string, value: string) {
|
||||
const trimmed = value.trim()
|
||||
if (type === 'email') return trimmed.toLowerCase()
|
||||
if (type === 'telegram') return trimmed.replace(/^@/, '').toLowerCase()
|
||||
return trimmed.replace(/[^\d+]/g, '')
|
||||
}
|
||||
async function createPerson() {
|
||||
if (!newPerson.name.trim() || newContacts.value.some(contact => !contact.value.trim())) return
|
||||
savingPerson.value = true
|
||||
personDialogError.value = ''
|
||||
try {
|
||||
const created = await request<ApiRecord>('/main/con/persons/', {
|
||||
method: 'POST', body: { ...newPerson, name: newPerson.name.trim() },
|
||||
})
|
||||
persons.value = mergeRecords(persons.value, [created])
|
||||
const results = created.id === undefined ? [] : await Promise.allSettled(newContacts.value.map(contact =>
|
||||
request<ApiRecord>('/main/con/contacts/', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
...contact,
|
||||
con_person: created.id,
|
||||
value: contact.value.trim(),
|
||||
normalized_value: normalizedContactValue(contact.type, contact.value),
|
||||
},
|
||||
})))
|
||||
const createdContacts = results.flatMap(result => result.status === 'fulfilled' ? [result.value] : [])
|
||||
contacts.value = mergeRecords(contacts.value, createdContacts)
|
||||
emit('update:modelValue', {
|
||||
...props.modelValue,
|
||||
con_person: [...new Set([
|
||||
...selectedPersonIds.value,
|
||||
...(created.id === undefined ? [] : [created.id]),
|
||||
])],
|
||||
})
|
||||
personDialog.value = false
|
||||
const failedCount = results.filter(result => result.status === 'rejected').length
|
||||
if (failedCount) error.value = `Контактное лицо создано, но не удалось добавить контактов: ${failedCount}`
|
||||
} catch (e: any) { personDialogError.value = e.message }
|
||||
finally { savingPerson.value = false }
|
||||
}
|
||||
|
||||
watch(
|
||||
() => selectedPersonIds.value.map(String).join(','),
|
||||
loadSelectedRecords,
|
||||
)
|
||||
onMounted(load)
|
||||
onBeforeUnmount(() => { if (personSearchTimer) clearTimeout(personSearchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-card class="mt-4" variant="outlined">
|
||||
<v-card-title class="text-subtitle-1">Контактные данные</v-card-title>
|
||||
<v-card-text>
|
||||
<v-alert v-if="error" class="mb-4" type="error" variant="tonal" closable @click:close="error = ''">{{ error }}</v-alert>
|
||||
<div v-if="loading" class="d-flex justify-center py-5">
|
||||
<v-progress-circular indeterminate color="primary" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<v-card v-for="person in selectedPersonRecords" :key="String(person.id)"
|
||||
variant="outlined" class="pa-4 mb-3">
|
||||
<div class="d-flex align-center ga-3 mb-2">
|
||||
<v-icon color="primary">mdi-account-outline</v-icon>
|
||||
<div class="text-subtitle-1 font-weight-medium">{{ person.name }}</div>
|
||||
<v-spacer />
|
||||
<v-btn v-if="!readonly" size="small" variant="text" color="error"
|
||||
@click="removePerson(person.id)">Убрать из списка</v-btn>
|
||||
</div>
|
||||
<v-list v-if="personContacts(person.id).length" density="compact" class="pa-0">
|
||||
<v-list-item v-for="contact in personContacts(person.id)" :key="String(contact.id)"
|
||||
:prepend-icon="contact.type === 'phone' ? 'mdi-phone-outline'
|
||||
: contact.type === 'email' ? 'mdi-email-outline' : 'mdi-send-outline'"
|
||||
:title="String(contact.value || contact.label || `Контакт #${contact.id}`)"
|
||||
:subtitle="[typeNames[String(contact.type)] || contact.type,
|
||||
purposeNames[String(contact.purpose)] || contact.purpose,
|
||||
contact.label].filter(Boolean).join(' · ')" />
|
||||
</v-list>
|
||||
<div v-else class="text-body-2 text-medium-emphasis">Контакты не добавлены</div>
|
||||
</v-card>
|
||||
<div v-if="!selectedPersonRecords.length" class="text-body-2 text-medium-emphasis mb-3">
|
||||
Контактные лица не добавлены.
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="!readonly" class="d-flex justify-end mt-3">
|
||||
<v-btn variant="text" prepend-icon="mdi-account-search-outline"
|
||||
@click="openSelectDialog">Подобрать из списка</v-btn>
|
||||
<v-btn class="ml-2" color="primary" variant="tonal" prepend-icon="mdi-plus"
|
||||
@click="openPersonDialog">Создать контактное лицо</v-btn>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
|
||||
<v-dialog v-model="selectDialog" max-width="620">
|
||||
<v-card title="Подбор контактных лиц">
|
||||
<v-card-text>
|
||||
<v-autocomplete v-model="selectedExistingPersonId" :items="availablePersonOptions"
|
||||
label="Контактное лицо" clearable autofocus :loading="loading"
|
||||
no-data-text="Контактные лица не найдены"
|
||||
@update:search="searchPersons($event || '')"
|
||||
@update:model-value="$event !== null && selectExistingPerson($event)" />
|
||||
<v-list v-if="availablePersonOptions.length" class="border rounded-lg">
|
||||
<v-list-item v-for="person in availablePersonOptions" :key="String(person.value)"
|
||||
prepend-icon="mdi-account-plus-outline" :title="person.title"
|
||||
subtitle="Нажмите, чтобы добавить" @click="selectExistingPerson(person.value)" />
|
||||
</v-list>
|
||||
<div v-else class="text-body-2 text-medium-emphasis py-4 text-center">
|
||||
Все контактные лица уже добавлены.
|
||||
</div>
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn @click="selectDialog = false">Закрыть</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
|
||||
<v-dialog v-model="personDialog" max-width="760">
|
||||
<v-card title="Новое контактное лицо">
|
||||
<v-card-text>
|
||||
<v-alert v-if="personDialogError" type="error" variant="tonal" class="mb-4">{{ personDialogError }}</v-alert>
|
||||
<v-text-field v-model="newPerson.name" label="Имя" autofocus @keyup.enter="createPerson" />
|
||||
<v-switch v-model="newPerson.is_active" label="Активно" color="primary" hide-details />
|
||||
<div class="d-flex align-center mt-6 mb-3">
|
||||
<div class="text-subtitle-1">Контакты контактного лица</div>
|
||||
<v-spacer />
|
||||
<v-btn size="small" variant="tonal" prepend-icon="mdi-plus" @click="addContact">Добавить контакт</v-btn>
|
||||
</div>
|
||||
<v-card v-for="(contact, index) in newContacts" :key="index" variant="outlined" class="pa-4 mb-3">
|
||||
<div class="d-flex align-center mb-2">
|
||||
<span class="text-subtitle-2">Контакт {{ index + 1 }}</span>
|
||||
<v-spacer />
|
||||
<v-btn size="small" variant="text" color="error" @click="newContacts.splice(index, 1)">Убрать</v-btn>
|
||||
</div>
|
||||
<v-row>
|
||||
<v-col cols="12" sm="6"><v-select v-model="contact.type" :items="typeOptions" label="Канал" /></v-col>
|
||||
<v-col cols="12" sm="6"><v-select v-model="contact.purpose" :items="purposeOptions" label="Назначение" /></v-col>
|
||||
</v-row>
|
||||
<v-text-field v-model="contact.value" label="Значение" :type="contact.type === 'email' ? 'email' : 'text'" required />
|
||||
<v-text-field v-model="contact.label" label="Метка" />
|
||||
<v-row>
|
||||
<v-col><v-switch v-model="contact.is_primary" label="Основной" color="primary" hide-details /></v-col>
|
||||
<v-col><v-switch v-model="contact.is_active" label="Активен" color="primary" hide-details /></v-col>
|
||||
</v-row>
|
||||
</v-card>
|
||||
<div v-if="!newContacts.length" class="text-body-2 text-medium-emphasis">Контакты можно добавить сразу или позже.</div>
|
||||
</v-card-text>
|
||||
<v-card-actions><v-spacer /><v-btn @click="personDialog = false">Отмена</v-btn><v-btn color="primary" :loading="savingPerson" :disabled="!newPerson.name.trim() || newContacts.some(contact => !contact.value.trim())" @click="createPerson">Создать</v-btn></v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
|
@ -130,13 +130,8 @@ onBeforeUnmount(() => {
|
|||
</script>
|
||||
|
||||
<template>
|
||||
<div class="coordinate-picker mb-4">
|
||||
<div class="coordinate-picker">
|
||||
<div class="coordinate-trigger">
|
||||
<div>
|
||||
<div class="text-caption text-medium-emphasis">Координаты</div>
|
||||
<div v-if="hasCoordinates">{{ latitude }}, {{ longitude }}</div>
|
||||
<div v-else class="text-medium-emphasis">Не выбраны</div>
|
||||
</div>
|
||||
<v-btn
|
||||
icon="mdi-map-marker"
|
||||
color="primary"
|
||||
|
|
@ -191,12 +186,8 @@ onBeforeUnmount(() => {
|
|||
<style scoped>
|
||||
.coordinate-trigger {
|
||||
display: flex;
|
||||
min-height: 64px;
|
||||
padding: 8px 10px 8px 16px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
|
||||
border-radius: 8px;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.coordinate-inputs {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,334 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord, CrmActivityTaskRequest } from '~/types/api'
|
||||
import { formatDateValue } from '~/utils/date'
|
||||
|
||||
const props = defineProps<{
|
||||
subjectType: 'client' | 'lead'
|
||||
subjectId?: string | number
|
||||
active?: boolean
|
||||
canCreate?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const activities = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const loaded = ref(false)
|
||||
const error = ref('')
|
||||
const createDialog = ref(false)
|
||||
const createLoading = ref(false)
|
||||
const createError = ref('')
|
||||
const createMode = ref<'comment' | 'task' | 'reminder'>('comment')
|
||||
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 taskTypes = ref<{ title: string; value: number }[]>([])
|
||||
const taskStatuses = ref<{ title: string; value: number }[]>([])
|
||||
const taskPriorities = ref<{ title: string; value: number }[]>([])
|
||||
const taskCategories = ref<{ title: string; value: number }[]>([])
|
||||
const departments = ref<{ title: string; value: number }[]>([])
|
||||
const employees = ref<{ title: string; value: number }[]>([])
|
||||
|
||||
const typePresentation: Record<string, { title: string; icon: string; color: string }> = {
|
||||
task: { title: 'Задача', icon: 'mdi-checkbox-marked-circle-outline', color: 'primary' },
|
||||
comment: { title: 'Комментарий', icon: 'mdi-comment-text-outline', color: 'grey' },
|
||||
note: { title: 'Заметка', icon: 'mdi-note-text-outline', color: 'grey' },
|
||||
call: { title: 'Звонок', icon: 'mdi-phone-outline', color: 'success' },
|
||||
messenger_message: { title: 'Сообщение', icon: 'mdi-message-text-outline', color: 'info' },
|
||||
email: { title: 'Email', icon: 'mdi-email-outline', color: 'warning' },
|
||||
reminder: { title: 'Напоминание', icon: 'mdi-bell-outline', color: 'warning' },
|
||||
}
|
||||
|
||||
function presentation(activity: ApiRecord) {
|
||||
const type = String(activity.type || '')
|
||||
return typePresentation[type] || { title: type || 'Активность', icon: 'mdi-circle-outline', color: 'grey' }
|
||||
}
|
||||
|
||||
function localDateTimeValue() {
|
||||
const now = new Date()
|
||||
return new Date(now.getTime() - now.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 => ({
|
||||
title: String(item.name || item.fullname || item.username || `${fallback} #${item.id}`),
|
||||
value: Number(item.id),
|
||||
}))
|
||||
}
|
||||
|
||||
function employeeOption(employee: ApiRecord) {
|
||||
if (typeof employee.id !== 'number') return null
|
||||
return {
|
||||
title: String(employee.employee_name || employee.name || employee.fullname
|
||||
|| [employee.surname, employee.firstname, employee.secondname].filter(Boolean).join(' ')
|
||||
|| employee.username || `Сотрудник #${employee.id}`),
|
||||
value: Number(employee.id),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEmployeeOptions(departmentId: number | null) {
|
||||
const employeeResponse = await request<any>('/main/sys/employees/', {
|
||||
query: {
|
||||
page_size: 1000,
|
||||
...(departmentId !== null ? { departments__id__exact: departmentId } : {}),
|
||||
},
|
||||
})
|
||||
const options = normalizeList(employeeResponse).items
|
||||
.map(employeeOption)
|
||||
.filter((option): option is { title: string; value: number } => Boolean(option))
|
||||
if (departmentId === null) return options
|
||||
|
||||
const department = await request<ApiRecord>(`/main/sys/departments/${departmentId}/`)
|
||||
let manager = department.manager_details || department.manager
|
||||
if (typeof manager === 'number') {
|
||||
manager = await request<ApiRecord>(`/main/sys/employees/${manager}/`)
|
||||
}
|
||||
const managerOption = manager && typeof manager === 'object'
|
||||
? employeeOption(manager as ApiRecord)
|
||||
: null
|
||||
if (managerOption && !options.some(option => option.value === managerOption.value)) {
|
||||
options.unshift(managerOption)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
watch(() => newTask.department, async departmentId => {
|
||||
try {
|
||||
employees.value = await loadEmployeeOptions(departmentId)
|
||||
const allowedIds = new Set(employees.value.map(employee => employee.value))
|
||||
newTask.assignees = newTask.assignees.filter(id => allowedIds.has(id))
|
||||
} catch (caught: any) {
|
||||
createError.value = caught?.message || 'Не удалось загрузить исполнителей подразделения'
|
||||
}
|
||||
})
|
||||
|
||||
async function openCreate(mode: 'comment' | 'task' | 'reminder') {
|
||||
createMode.value = mode
|
||||
newActivity.title = ''
|
||||
newActivity.text = ''
|
||||
newActivity.occurredAt = localDateTimeValue()
|
||||
newTask.taskType = null
|
||||
newTask.status = null
|
||||
newTask.priority = null
|
||||
newTask.category = null
|
||||
newTask.department = null
|
||||
newTask.assignees = []
|
||||
newTask.plannedStartAt = ''
|
||||
newTask.plannedFinishAt = ''
|
||||
newReminder.remindAt = new Date(Date.now() + 24 * 60 * 60_000
|
||||
- new Date().getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
|
||||
createError.value = ''
|
||||
createDialog.value = true
|
||||
if (mode === 'task' && (!taskTypes.value.length || !taskPriorities.value.length)) {
|
||||
createLoading.value = true
|
||||
try {
|
||||
const [types, statuses, priorities, categories, departmentOptions, employeeOptions] = await Promise.all([
|
||||
loadOptions('/main/chn/task-types/', 'Тип'),
|
||||
loadOptions('/main/chn/task-statuses/', 'Статус'),
|
||||
loadOptions('/main/chn/task-priorities/', 'Приоритет'),
|
||||
loadOptions('/main/chn/task-categories/', 'Категория'),
|
||||
loadOptions('/main/sys/departments/', 'Подразделение'),
|
||||
loadEmployeeOptions(null),
|
||||
])
|
||||
taskTypes.value = types
|
||||
taskStatuses.value = statuses
|
||||
taskPriorities.value = priorities
|
||||
taskCategories.value = categories
|
||||
departments.value = departmentOptions
|
||||
employees.value = employeeOptions
|
||||
} 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()) {
|
||||
createError.value = 'Укажите заголовок или текст активности'
|
||||
return
|
||||
}
|
||||
if (createMode.value !== 'comment' && !newActivity.title.trim()) {
|
||||
createError.value = createMode.value === 'task'
|
||||
? 'Укажите заголовок задачи'
|
||||
: 'Укажите заголовок напоминания'
|
||||
return
|
||||
}
|
||||
if (createMode.value === 'task'
|
||||
&& !newTask.taskType && !newTask.department && !newTask.assignees.length) {
|
||||
createError.value = 'Укажите хотя бы одно поле: тип задачи, подразделение или исполнитель'
|
||||
return
|
||||
}
|
||||
if (createMode.value === 'task' && newTask.plannedStartAt && newTask.plannedFinishAt
|
||||
&& new Date(newTask.plannedFinishAt) < new Date(newTask.plannedStartAt)) {
|
||||
createError.value = 'Плановое завершение не может быть раньше планового начала'
|
||||
return
|
||||
}
|
||||
if (createMode.value === 'reminder' && !newReminder.remindAt) {
|
||||
createError.value = 'Укажите дату и время напоминания'
|
||||
return
|
||||
}
|
||||
if (!newActivity.occurredAt) {
|
||||
createError.value = 'Укажите дату и время активности'
|
||||
return
|
||||
}
|
||||
createLoading.value = true
|
||||
createError.value = ''
|
||||
try {
|
||||
let created = await request<ApiRecord>('/main/crm/activities/', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'comment',
|
||||
subject_type: props.subjectType,
|
||||
subject_id: props.subjectId,
|
||||
title: newActivity.title.trim(),
|
||||
text: newActivity.text.trim(),
|
||||
occurred_at: new Date(newActivity.occurredAt).toISOString(),
|
||||
},
|
||||
})
|
||||
if (createMode.value === 'task') {
|
||||
const taskPayload: CrmActivityTaskRequest = {
|
||||
title: newActivity.title.trim(), description: newActivity.text.trim(),
|
||||
...(newTask.priority !== null ? { priority: newTask.priority } : {}),
|
||||
...(newTask.taskType !== null ? { task_type: newTask.taskType } : {}),
|
||||
category: newTask.category ?? undefined,
|
||||
department: newTask.department ?? undefined,
|
||||
assignees: newTask.assignees,
|
||||
...(newTask.plannedStartAt
|
||||
? { planned_start_at: new Date(newTask.plannedStartAt).toISOString() }
|
||||
: {}),
|
||||
...(newTask.plannedFinishAt
|
||||
? { planned_finish_at: new Date(newTask.plannedFinishAt).toISOString() }
|
||||
: {}),
|
||||
...(newTask.status !== null ? { status: newTask.status } : {}),
|
||||
}
|
||||
const task = await request<ApiRecord>(`/main/crm/activities/${created.id}/create-task/`, {
|
||||
method: 'POST',
|
||||
body: taskPayload,
|
||||
})
|
||||
created = { ...created, type: 'task', reference_type: 'task', reference_id: task.id }
|
||||
} else if (createMode.value === 'reminder') {
|
||||
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() },
|
||||
})
|
||||
created = { ...created, type: 'reminder', reference_type: 'reminder', reference_id: reminder.id }
|
||||
}
|
||||
activities.value = [created, ...activities.value]
|
||||
loaded.value = true
|
||||
createDialog.value = false
|
||||
} catch (caught: any) {
|
||||
createError.value = caught?.message || 'Не удалось добавить активность'
|
||||
} finally {
|
||||
createLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!props.active || loaded.value || props.subjectId === undefined || props.subjectId === null) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await request<any>('/main/crm/activities/', {
|
||||
query: {
|
||||
page_size: 1000,
|
||||
subject_type__exact: props.subjectType,
|
||||
subject_id__exact: props.subjectId,
|
||||
ordering: '-occurred_at,-id',
|
||||
},
|
||||
})
|
||||
activities.value = normalizeList(data).items
|
||||
loaded.value = true
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось загрузить активности'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch([() => props.subjectType, () => props.subjectId], () => {
|
||||
activities.value = []
|
||||
loaded.value = false
|
||||
error.value = ''
|
||||
load()
|
||||
})
|
||||
watch(() => props.active, load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<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>
|
||||
</div>
|
||||
<v-alert v-if="subjectId === undefined || subjectId === null" type="info" variant="tonal">
|
||||
Сохраните объект, чтобы управлять его активностями.
|
||||
</v-alert>
|
||||
<div v-else-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="!activities.length" type="info" variant="tonal">
|
||||
Активности отсутствуют.
|
||||
</v-alert>
|
||||
<v-timeline v-else side="end" density="compact" align="start">
|
||||
<v-timeline-item v-for="activity in activities" :key="String(activity.id)"
|
||||
:dot-color="presentation(activity).color" :icon="presentation(activity).icon" size="small">
|
||||
<v-card variant="outlined">
|
||||
<v-card-title class="text-body-1 d-flex align-center ga-2">
|
||||
<span>{{ activity.title || presentation(activity).title }}</span>
|
||||
<v-chip size="x-small" variant="tonal" :color="presentation(activity).color">
|
||||
{{ presentation(activity).title }}
|
||||
</v-chip>
|
||||
</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>
|
||||
</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-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" />
|
||||
<v-textarea v-model="newActivity.text" label="Комментарий" rows="4" autofocus />
|
||||
<template v-if="createMode === 'task'">
|
||||
<v-select v-model="newTask.taskType" :items="taskTypes" label="Тип задачи" clearable />
|
||||
<v-select v-model="newTask.status" :items="taskStatuses" label="Статус" clearable />
|
||||
<v-select v-model="newTask.priority" :items="taskPriorities" label="Приоритет" clearable />
|
||||
<v-select v-model="newTask.category" :items="taskCategories" label="Категория" clearable />
|
||||
<v-select v-model="newTask.department" :items="departments" label="Подразделение" clearable />
|
||||
<v-autocomplete v-model="newTask.assignees" :items="employees" label="Исполнители"
|
||||
multiple chips closable-chips clearable
|
||||
hint="Можно выбрать исполнителей, подразделение или использовать подразделение типа задачи"
|
||||
persistent-hint />
|
||||
<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 />
|
||||
<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' ? 'Создать напоминание' : 'Добавить' }}
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.activity-text {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<script setup lang="ts">
|
||||
import { getModule, getResource } from '~/config/modules'
|
||||
|
||||
const crmModule = getModule('crm')!
|
||||
const typesResource = getResource('crm', 'types')!
|
||||
const categoriesResource = getResource('crm', 'categories')!
|
||||
const permissions = usePermissions()
|
||||
const canViewTypes = computed(() => permissions.canView('crm', 'crm', 'types'))
|
||||
const canViewCategories = computed(() => permissions.canView('crm', 'crm', 'categories'))
|
||||
const activeTab = ref(canViewTypes.value ? 'types' : 'categories')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell">
|
||||
<div class="mb-6">
|
||||
<h1 class="text-h4">Настройки CRM</h1>
|
||||
<p class="text-medium-emphasis mt-1">Типы и категории клиентов</p>
|
||||
</div>
|
||||
<v-tabs v-model="activeTab" color="primary" class="mb-5">
|
||||
<v-tab v-if="canViewTypes" value="types">Типы клиентов</v-tab>
|
||||
<v-tab v-if="canViewCategories" value="categories">Категории клиентов</v-tab>
|
||||
</v-tabs>
|
||||
<v-window v-model="activeTab">
|
||||
<v-window-item v-if="canViewTypes" value="types">
|
||||
<ResourceCrud :module="crmModule" :resource="typesResource" embedded />
|
||||
</v-window-item>
|
||||
<v-window-item v-if="canViewCategories" value="categories">
|
||||
<ResourceCrud :module="crmModule" :resource="categoriesResource" embedded />
|
||||
</v-window-item>
|
||||
</v-window>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
departmentId: string | number
|
||||
managerId?: string | number | null
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const employees = ref<ApiRecord[]>([])
|
||||
const selectedEmployeeId = ref<string | number | null>(null)
|
||||
const loading = ref(false)
|
||||
const updatingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const departmentIds = (employee: ApiRecord) => Array.isArray(employee.departments)
|
||||
? employee.departments.flatMap(value => {
|
||||
if (typeof value === 'string' || typeof value === 'number') return [value]
|
||||
const id = (value as ApiRecord)?.id
|
||||
return id === undefined ? [] : [id]
|
||||
})
|
||||
: []
|
||||
const belongsToDepartment = (employee: ApiRecord) => departmentIds(employee)
|
||||
.some(id => String(id) === String(props.departmentId))
|
||||
const members = computed(() => employees.value.filter(belongsToDepartment))
|
||||
const candidates = computed(() => employees.value
|
||||
.filter(employee => employee.id !== undefined && !belongsToDepartment(employee))
|
||||
.map(employee => ({ title: employeeName(employee), value: employee.id! })))
|
||||
const employeeName = (employee: ApiRecord) => String(employee.name
|
||||
|| [employee.surname, employee.firstname, employee.secondname].filter(Boolean).join(' ')
|
||||
|| employee.username || `Сотрудник #${employee.id}`)
|
||||
|
||||
async function load(search = '') {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [response, memberResponse] = await Promise.all([
|
||||
request<any>('/main/sys/employees/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
}),
|
||||
request<any>('/main/sys/employees/', {
|
||||
query: { page_size: 1000, departments__id__exact: props.departmentId },
|
||||
}),
|
||||
])
|
||||
const merged = [...normalizeList(memberResponse).items, ...normalizeList(response).items]
|
||||
employees.value = [...new Map(merged
|
||||
.filter(employee => employee.id !== undefined)
|
||||
.map(employee => [String(employee.id), employee])).values()]
|
||||
} catch (reason: any) {
|
||||
error.value = reason.message || 'Не удалось загрузить сотрудников'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchEmployees(search: string) {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => load(search), 300)
|
||||
}
|
||||
|
||||
async function updateMembership(employee: ApiRecord, add: boolean) {
|
||||
if (employee.id === undefined) return
|
||||
updatingId.value = employee.id
|
||||
error.value = ''
|
||||
try {
|
||||
const currentIds = departmentIds(employee)
|
||||
const departments = add
|
||||
? [...new Set([...currentIds.map(String), String(props.departmentId)])]
|
||||
: currentIds.filter(id => String(id) !== String(props.departmentId))
|
||||
const updated = await request<ApiRecord>(`/main/sys/employees/${employee.id}/`, {
|
||||
method: 'PATCH',
|
||||
body: { departments },
|
||||
})
|
||||
const index = employees.value.findIndex(item => String(item.id) === String(employee.id))
|
||||
if (index >= 0) employees.value[index] = updated
|
||||
} catch (reason: any) {
|
||||
error.value = reason.message || 'Не удалось изменить состав подразделения'
|
||||
} finally {
|
||||
if (add) selectedEmployeeId.value = null
|
||||
updatingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function addEmployee(employeeId: string | number | null) {
|
||||
if (employeeId === null) return
|
||||
const employee = employees.value.find(item => String(item.id) === String(employeeId))
|
||||
if (employee) await updateMembership(employee, true)
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-6" />
|
||||
<div class="d-flex align-center ga-3 mb-4">
|
||||
<div>
|
||||
<h3 class="text-subtitle-1 font-weight-bold">Сотрудники подразделения</h3>
|
||||
<p class="text-caption text-medium-emphasis">Сотрудник может входить в несколько подразделений</p>
|
||||
</div>
|
||||
<v-spacer />
|
||||
<v-chip size="small" variant="tonal">{{ members.length }}</v-chip>
|
||||
</div>
|
||||
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<div v-if="!readonly" class="mb-4">
|
||||
<v-autocomplete v-model="selectedEmployeeId" :items="candidates" label="Добавить сотрудника"
|
||||
no-data-text="Нет доступных сотрудников" clearable hide-details
|
||||
:readonly="updatingId !== null" :loading="updatingId !== null"
|
||||
@update:search="searchEmployees($event || '')"
|
||||
@update:model-value="addEmployee" />
|
||||
</div>
|
||||
|
||||
<v-skeleton-loader v-if="loading" type="list-item-two-line, list-item-two-line" />
|
||||
<v-list v-else-if="members.length" class="border rounded-lg" lines="two">
|
||||
<v-list-item v-for="employee in members" :key="String(employee.id)"
|
||||
:title="employeeName(employee)"
|
||||
:subtitle="String(employee.username || employee.description || '')">
|
||||
<template #prepend>
|
||||
<v-avatar color="primary" variant="tonal"><v-icon icon="mdi-account-outline" /></v-avatar>
|
||||
</template>
|
||||
<template #append>
|
||||
<v-chip v-if="String(employee.id) === String(managerId)" size="small"
|
||||
prepend-icon="mdi-account-tie-outline" color="primary" variant="tonal">
|
||||
Руководитель
|
||||
</v-chip>
|
||||
<v-btn v-if="!readonly && String(employee.id) !== String(managerId)" icon="mdi-account-minus-outline"
|
||||
variant="text" color="error" title="Исключить из подразделения"
|
||||
:loading="String(updatingId) === String(employee.id)"
|
||||
@click="updateMembership(employee, false)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
<v-alert v-else type="info" variant="tonal">В подразделении пока нет сотрудников.</v-alert>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,334 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const router = useRouter()
|
||||
const departments = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const permissions = usePermissions()
|
||||
const canEdit = computed(() => permissions.canEdit('system', 'sys', 'departments'))
|
||||
const savingIds = ref(new Set<string>())
|
||||
type DiagramNode = {
|
||||
department: ApiRecord
|
||||
parentId: string | number | null
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
type DiagramInteraction = {
|
||||
mode: 'move' | 'resize'
|
||||
id: string
|
||||
startClientX: number
|
||||
startClientY: number
|
||||
startX: number
|
||||
startY: number
|
||||
startWidth: number
|
||||
startHeight: number
|
||||
saveAll: boolean
|
||||
moved: boolean
|
||||
}
|
||||
const interaction = ref<DiagramInteraction | null>(null)
|
||||
const suppressCardClick = ref(false)
|
||||
|
||||
const numberOr = (value: unknown, fallback: number) => {
|
||||
const number = Number(value)
|
||||
return Number.isFinite(number) ? number : fallback
|
||||
}
|
||||
const rawNodes = computed(() => {
|
||||
const result: Array<{ department: ApiRecord; parentId: string | number | null; depth: number }> = []
|
||||
const visit = (items: ApiRecord[], parentId: string | number | null, depth: number) => {
|
||||
items.forEach(item => {
|
||||
result.push({ department: item, parentId, depth })
|
||||
visit(Array.isArray(item.children) ? item.children as ApiRecord[] : [], item.id ?? null, depth + 1)
|
||||
})
|
||||
}
|
||||
visit(departments.value, null, 0)
|
||||
return result
|
||||
})
|
||||
const usesSavedLayout = computed(() => rawNodes.value.some(({ department }) =>
|
||||
numberOr(department.diagram_x, 0) !== 0 || numberOr(department.diagram_y, 0) !== 0))
|
||||
const nodes = computed<DiagramNode[]>(() => {
|
||||
let row = 0
|
||||
return rawNodes.value.map(({ department, parentId, depth }) => {
|
||||
const width = Math.max(180, numberOr(department.diagram_width, 240))
|
||||
const height = Math.max(100, numberOr(department.diagram_height, 120))
|
||||
const x = usesSavedLayout.value ? numberOr(department.diagram_x, 0) : depth * 320
|
||||
const y = usesSavedLayout.value ? numberOr(department.diagram_y, 0) : row++ * 160
|
||||
return { department, parentId, x, y, width, height }
|
||||
})
|
||||
})
|
||||
const diagramOffset = 32
|
||||
const minX = computed(() => Math.min(0, ...nodes.value.map(node => node.x)))
|
||||
const minY = computed(() => Math.min(0, ...nodes.value.map(node => node.y)))
|
||||
const nodeLeft = (node: DiagramNode) => node.x - minX.value + diagramOffset
|
||||
const nodeTop = (node: DiagramNode) => node.y - minY.value + diagramOffset
|
||||
const canvasWidth = computed(() => Math.max(640, ...nodes.value.map(node => nodeLeft(node) + node.width + diagramOffset)))
|
||||
const canvasHeight = computed(() => Math.max(320, ...nodes.value.map(node => nodeTop(node) + node.height + diagramOffset)))
|
||||
const nodeById = computed(() => new Map(nodes.value.map(node => [String(node.department.id), node])))
|
||||
const connections = computed(() => nodes.value.flatMap(node => {
|
||||
if (node.parentId === null) return []
|
||||
const parent = nodeById.value.get(String(node.parentId))
|
||||
if (!parent) return []
|
||||
const x1 = nodeLeft(parent) + parent.width / 2
|
||||
const y1 = nodeTop(parent) + parent.height
|
||||
const x2 = nodeLeft(node) + node.width / 2
|
||||
const y2 = nodeTop(node)
|
||||
const middleY = y1 + (y2 - y1) / 2
|
||||
return [{ id: `${parent.department.id}-${node.department.id}`, path: `M ${x1} ${y1} V ${middleY} H ${x2} V ${y2}` }]
|
||||
}))
|
||||
|
||||
function updateDepartment(id: string, values: Record<string, number>) {
|
||||
const entry = rawNodes.value.find(node => String(node.department.id) === id)
|
||||
if (entry) Object.assign(entry.department, values)
|
||||
}
|
||||
|
||||
function materializeAutomaticLayout() {
|
||||
const layout = nodes.value.map(node => ({
|
||||
id: String(node.department.id),
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
width: node.width,
|
||||
height: node.height,
|
||||
}))
|
||||
layout.forEach(node => updateDepartment(node.id, {
|
||||
diagram_x: node.x,
|
||||
diagram_y: node.y,
|
||||
diagram_width: node.width,
|
||||
diagram_height: node.height,
|
||||
}))
|
||||
}
|
||||
|
||||
function startInteraction(event: PointerEvent, node: DiagramNode, mode: DiagramInteraction['mode']) {
|
||||
if (!canEdit.value || event.button !== 0 || node.department.id === undefined) return
|
||||
event.preventDefault()
|
||||
const saveAll = !usesSavedLayout.value
|
||||
interaction.value = {
|
||||
mode,
|
||||
id: String(node.department.id),
|
||||
startClientX: event.clientX,
|
||||
startClientY: event.clientY,
|
||||
startX: node.x,
|
||||
startY: node.y,
|
||||
startWidth: node.width,
|
||||
startHeight: node.height,
|
||||
saveAll,
|
||||
moved: false,
|
||||
}
|
||||
window.addEventListener('pointermove', moveInteraction)
|
||||
window.addEventListener('pointerup', finishInteraction, { once: true })
|
||||
}
|
||||
|
||||
function moveInteraction(event: PointerEvent) {
|
||||
const active = interaction.value
|
||||
if (!active) return
|
||||
const dx = event.clientX - active.startClientX
|
||||
const dy = event.clientY - active.startClientY
|
||||
if (!active.moved && (Math.abs(dx) > 3 || Math.abs(dy) > 3)) {
|
||||
active.moved = true
|
||||
if (active.saveAll) materializeAutomaticLayout()
|
||||
}
|
||||
if (!active.moved) return
|
||||
if (active.mode === 'move') {
|
||||
updateDepartment(active.id, {
|
||||
diagram_x: Math.max(0, active.startX + dx),
|
||||
diagram_y: Math.max(0, active.startY + dy),
|
||||
})
|
||||
} else {
|
||||
updateDepartment(active.id, {
|
||||
diagram_width: Math.max(180, active.startWidth + dx),
|
||||
diagram_height: Math.max(100, active.startHeight + dy),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function saveNodeLayout(node: DiagramNode) {
|
||||
if (node.department.id === undefined) return
|
||||
const id = String(node.department.id)
|
||||
savingIds.value = new Set([...savingIds.value, id])
|
||||
try {
|
||||
await request(`/main/sys/departments/${node.department.id}/`, {
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
diagram_x: node.x,
|
||||
diagram_y: node.y,
|
||||
diagram_width: node.width,
|
||||
diagram_height: node.height,
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
const next = new Set(savingIds.value)
|
||||
next.delete(id)
|
||||
savingIds.value = next
|
||||
}
|
||||
}
|
||||
|
||||
async function finishInteraction() {
|
||||
window.removeEventListener('pointermove', moveInteraction)
|
||||
const active = interaction.value
|
||||
interaction.value = null
|
||||
if (!active) return
|
||||
if (!active.moved) return
|
||||
suppressCardClick.value = true
|
||||
window.setTimeout(() => { suppressCardClick.value = false }, 0)
|
||||
error.value = ''
|
||||
try {
|
||||
const changedNode = nodes.value.find(node => String(node.department.id) === active.id)
|
||||
if (active.saveAll) await Promise.all(nodes.value.map(saveNodeLayout))
|
||||
else if (changedNode) await saveNodeLayout(changedNode)
|
||||
} catch (reason: any) {
|
||||
error.value = reason.message || 'Не удалось сохранить расположение подразделений'
|
||||
}
|
||||
}
|
||||
|
||||
function openDepartment(node: DiagramNode) {
|
||||
if (suppressCardClick.value || node.department.id === undefined) return
|
||||
router.push({ path: '/system/departments', query: { edit: String(node.department.id) } })
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await request<any>('/main/sys/departments/tree/')
|
||||
departments.value = Array.isArray(response) ? response : normalizeList(response).items
|
||||
} catch (reason: any) {
|
||||
error.value = reason.message || 'Не удалось загрузить структуру подразделений'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('pointermove', moveInteraction)
|
||||
window.removeEventListener('pointerup', finishInteraction)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell">
|
||||
<div class="d-flex align-center flex-wrap ga-3 mb-6">
|
||||
<div>
|
||||
<h1 class="text-h4">Структура подразделений</h1>
|
||||
<p class="text-medium-emphasis mt-1">Иерархия подразделений, руководителей и сотрудников</p>
|
||||
</div>
|
||||
<v-spacer />
|
||||
<v-chip v-if="canEdit" prepend-icon="mdi-cursor-move" variant="tonal" color="primary">
|
||||
Перетаскивайте блоки и маркер в правом нижнем углу
|
||||
</v-chip>
|
||||
<v-btn prepend-icon="mdi-refresh" variant="tonal" :loading="loading" @click="load">
|
||||
Обновить
|
||||
</v-btn>
|
||||
</div>
|
||||
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-5">{{ error }}</v-alert>
|
||||
<v-skeleton-loader v-if="loading && !departments.length" type="article, article" />
|
||||
<v-alert v-else-if="!departments.length && !error" type="info" variant="tonal">
|
||||
Подразделения пока не созданы.
|
||||
</v-alert>
|
||||
<div v-else class="department-diagram-scroll">
|
||||
<div class="department-diagram" :style="{ width: `${canvasWidth}px`, height: `${canvasHeight}px` }">
|
||||
<svg class="department-connectors" :width="canvasWidth" :height="canvasHeight" aria-hidden="true">
|
||||
<path v-for="connection in connections" :key="connection.id" :d="connection.path" />
|
||||
</svg>
|
||||
<div v-for="node in nodes" :key="String(node.department.id)" class="department-position"
|
||||
:class="{
|
||||
'department-position--editable': canEdit,
|
||||
'department-position--active': interaction?.id === String(node.department.id),
|
||||
}"
|
||||
:style="{
|
||||
left: `${nodeLeft(node)}px`, top: `${nodeTop(node)}px`,
|
||||
width: `${node.width}px`, height: `${node.height}px`,
|
||||
}"
|
||||
@pointerdown="startInteraction($event, node, 'move')"
|
||||
@click="openDepartment(node)">
|
||||
<DepartmentTreeNode :department="node.department" />
|
||||
<div v-if="savingIds.has(String(node.department.id))" class="department-saving">
|
||||
<v-progress-circular indeterminate size="22" width="2" />
|
||||
</div>
|
||||
<button v-if="canEdit" type="button" class="department-resize-handle"
|
||||
title="Изменить размер" aria-label="Изменить размер блока"
|
||||
@click.stop
|
||||
@pointerdown.stop="startInteraction($event, node, 'resize')">
|
||||
<v-icon icon="mdi-resize-bottom-right" size="18" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.department-diagram-scroll {
|
||||
overflow-x: auto;
|
||||
min-height: 320px;
|
||||
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
|
||||
border-radius: 16px;
|
||||
background-color: rgb(var(--v-theme-surface));
|
||||
background-image: radial-gradient(rgba(var(--v-theme-primary), 0.16) 1px, transparent 1px);
|
||||
background-size: 20px 20px;
|
||||
}
|
||||
|
||||
.department-diagram {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.department-connectors {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.department-connectors path {
|
||||
fill: none;
|
||||
stroke: rgb(var(--v-theme-primary));
|
||||
stroke-width: 2;
|
||||
stroke-linejoin: round;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.department-position {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.department-position--editable {
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.department-position--active {
|
||||
cursor: grabbing;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.department-saving {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 4px;
|
||||
border-radius: 50%;
|
||||
color: rgb(var(--v-theme-primary));
|
||||
background: rgb(var(--v-theme-surface));
|
||||
}
|
||||
|
||||
.department-resize-handle {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
bottom: 2px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 0;
|
||||
color: rgb(var(--v-theme-primary));
|
||||
background: transparent;
|
||||
cursor: nwse-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{ department: ApiRecord }>()
|
||||
const manager = computed(() => props.department.manager_details
|
||||
&& typeof props.department.manager_details === 'object'
|
||||
? props.department.manager_details as ApiRecord
|
||||
: null)
|
||||
const employeeCount = computed(() => Array.isArray(props.department.employee_ids)
|
||||
? props.department.employee_ids.length
|
||||
: 0)
|
||||
const managerName = (manager: ApiRecord) => String(
|
||||
manager.name
|
||||
|| [manager.surname, manager.firstname, manager.secondname].filter(Boolean).join(' ')
|
||||
|| `Сотрудник #${manager.id}`,
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-card class="department-node h-100" variant="outlined"
|
||||
:class="{ 'department-node--inactive': department.is_active === false }">
|
||||
<v-card-text>
|
||||
<div class="d-flex align-start ga-3">
|
||||
<v-avatar color="primary" variant="tonal" rounded="lg" size="42">
|
||||
<v-icon icon="mdi-office-building-outline" />
|
||||
</v-avatar>
|
||||
<div class="min-width-0 flex-grow-1">
|
||||
<div class="d-flex align-center flex-wrap ga-2">
|
||||
<div class="text-subtitle-1 font-weight-bold text-wrap">{{ department.name }}</div>
|
||||
<v-chip v-if="department.code" size="x-small" variant="tonal">{{ department.code }}</v-chip>
|
||||
<v-chip v-if="department.is_active === false" size="x-small" color="grey">Неактивно</v-chip>
|
||||
</div>
|
||||
<div v-if="department.description" class="text-body-2 text-medium-emphasis mt-1">
|
||||
{{ department.description }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<v-divider class="my-3" />
|
||||
<div class="d-flex flex-wrap ga-2">
|
||||
<v-chip size="small" prepend-icon="mdi-account-group-outline" variant="text">
|
||||
Сотрудников: {{ employeeCount }}
|
||||
</v-chip>
|
||||
<v-chip v-if="manager" size="small" prepend-icon="mdi-account-tie-outline" variant="text">
|
||||
{{ managerName(manager) }}
|
||||
</v-chip>
|
||||
<span v-else class="text-caption text-medium-emphasis align-self-center">
|
||||
Руководитель не назначен
|
||||
</span>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.department-node {
|
||||
border-color: rgba(var(--v-theme-primary), 0.28);
|
||||
background: rgb(var(--v-theme-surface));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.department-node--inactive {
|
||||
opacity: 0.68;
|
||||
}
|
||||
|
||||
.min-width-0 {
|
||||
min-width: 0;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
<script setup lang="ts">
|
||||
import type { AccessOption } from '~/types/api'
|
||||
import { accessIds } from '~/utils/access'
|
||||
|
||||
const props = defineProps<{
|
||||
permissions?: unknown
|
||||
navigations?: unknown
|
||||
permissionOptions: AccessOption[]
|
||||
navigationOptions: AccessOption[]
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
'update:permissions': [value: string[]]
|
||||
'update:navigations': [value: string[]]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<AccessSelectionList
|
||||
:permissions="accessIds(permissions)" :navigations="accessIds(navigations)"
|
||||
:permission-options="permissionOptions" :navigation-options="navigationOptions"
|
||||
:readonly="readonly"
|
||||
@update:permissions="emit('update:permissions', $event)"
|
||||
@update:navigations="emit('update:navigations', $event)" />
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue?: unknown
|
||||
employeeId?: string | number | null
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: Array<string | number>] }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const departments = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const selectedIds = computed<Array<string | number>>(() => Array.isArray(props.modelValue)
|
||||
? props.modelValue.flatMap(value => {
|
||||
if (typeof value === 'string' || typeof value === 'number') return [value]
|
||||
const id = (value as ApiRecord)?.id
|
||||
return id === undefined ? [] : [id]
|
||||
})
|
||||
: [])
|
||||
const options = computed(() => departments.value
|
||||
.filter(department => department.id !== undefined)
|
||||
.map(department => ({ title: departmentTitle(department), value: department.id! })))
|
||||
const selectedDepartments = computed(() => departments.value.filter(department =>
|
||||
selectedIds.value.some(id => sameId(id, department.id))))
|
||||
const managedDepartments = computed(() => {
|
||||
if (props.employeeId === null || props.employeeId === undefined) return []
|
||||
return departments.value.filter(department => {
|
||||
const manager = department.manager
|
||||
const managerId = manager && typeof manager === 'object' ? (manager as ApiRecord).id : manager
|
||||
return sameId(managerId, props.employeeId)
|
||||
})
|
||||
})
|
||||
|
||||
function sameId(left: unknown, right: unknown) {
|
||||
return left !== null && left !== undefined && String(left) === String(right)
|
||||
}
|
||||
function departmentTitle(department: ApiRecord) {
|
||||
return String(department.name || '')
|
||||
}
|
||||
function departmentSubtitle(department: ApiRecord) {
|
||||
return department.parent_name ? `В составе: ${department.parent_name}` : 'Корневое подразделение'
|
||||
}
|
||||
|
||||
async function load(search = '') {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const ids = selectedIds.value
|
||||
const [response, selectedResponse] = await Promise.all([
|
||||
request<any>('/main/sys/departments/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
}),
|
||||
ids.length
|
||||
? request<any>('/main/sys/departments/', { query: { page_size: 1000, id__in: ids.join(',') } })
|
||||
: Promise.resolve([]),
|
||||
])
|
||||
const merged = [...normalizeList(selectedResponse).items, ...normalizeList(response).items]
|
||||
departments.value = [...new Map(merged
|
||||
.filter(department => department.id !== undefined)
|
||||
.map(department => [String(department.id), department])).values()]
|
||||
} catch (reason: any) {
|
||||
error.value = reason.message || 'Не удалось загрузить подразделения'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchDepartments(search: string) {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => load(search), 300)
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="pt-4">
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-1">Подразделения сотрудника</h3>
|
||||
<p class="text-caption text-medium-emphasis mb-4">Сотрудник может состоять в нескольких подразделениях</p>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-autocomplete v-if="!readonly" :model-value="selectedIds" :items="options"
|
||||
label="Подразделения" multiple chips closable-chips clearable :loading="loading"
|
||||
no-data-text="Подразделения не найдены"
|
||||
@update:search="searchDepartments($event || '')"
|
||||
@update:model-value="emit('update:modelValue', $event)" />
|
||||
<v-skeleton-loader v-else-if="loading" type="list-item-two-line" />
|
||||
<v-list v-else-if="selectedDepartments.length" class="border rounded-lg" density="compact">
|
||||
<v-list-item v-for="department in selectedDepartments" :key="String(department.id)"
|
||||
:title="departmentTitle(department)" :subtitle="departmentSubtitle(department)"
|
||||
prepend-icon="mdi-office-building-outline" />
|
||||
</v-list>
|
||||
<p v-else-if="readonly" class="text-body-2 text-medium-emphasis">Не состоит в подразделениях</p>
|
||||
</section>
|
||||
|
||||
<section v-if="employeeId !== null && employeeId !== undefined" class="mt-6">
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-3">Руководит подразделениями</h3>
|
||||
<v-skeleton-loader v-if="loading" type="list-item-two-line" />
|
||||
<v-list v-else-if="managedDepartments.length" class="border rounded-lg" density="compact">
|
||||
<v-list-item v-for="department in managedDepartments" :key="String(department.id)"
|
||||
:title="departmentTitle(department)" :subtitle="departmentSubtitle(department)"
|
||||
prepend-icon="mdi-account-tie-outline" />
|
||||
</v-list>
|
||||
<p v-else class="text-body-2 text-medium-emphasis">Не является руководителем подразделения</p>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -10,24 +10,29 @@ const props = defineProps<{
|
|||
const { request, normalizeList } = useApi()
|
||||
const assigned = ref<ApiRecord[]>([])
|
||||
const available = ref<ApiRecord[]>([])
|
||||
const selectedHolidayId = ref<string | number | null>(null)
|
||||
const selectedHolidayIds = ref<(string | number)[]>([])
|
||||
const candidateHolidayId = ref<string | number | null>(null)
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function holidayTitle(holiday: ApiRecord) {
|
||||
const period = [holiday.date_begin, holiday.date_end].filter(Boolean).map(formatDateValue).join(' — ')
|
||||
return [holiday.name || `Праздник #${holiday.id}`, period].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
const options = computed(() => available.value
|
||||
.filter(holiday => holiday.id !== undefined
|
||||
&& !assigned.value.some(item => String(item.id) === String(holiday.id)))
|
||||
const options = computed(() => [...new Map([...assigned.value, ...available.value]
|
||||
.filter(holiday => holiday.id !== undefined)
|
||||
.map(holiday => [String(holiday.id), holiday])).values()]
|
||||
.filter(holiday => !selectedHolidayIds.value.some(id => String(id) === String(holiday.id)))
|
||||
.map(holiday => ({
|
||||
title: holidayTitle(holiday),
|
||||
value: holiday.id!,
|
||||
})))
|
||||
const selectedHolidays = computed(() => selectedHolidayIds.value.map(id =>
|
||||
[...assigned.value, ...available.value].find(holiday => String(holiday.id) === String(id))
|
||||
|| { id, name: `Праздник #${id}` }))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
|
|
@ -37,12 +42,15 @@ async function load() {
|
|||
request<any>(`/main/sys/holiday-groups/${props.groupId}/holidays/`, {
|
||||
query: { page_size: 1000 },
|
||||
}),
|
||||
request<any>('/main/sys/holidayelements/', {
|
||||
request<any>('/main/sys/holidays/', {
|
||||
query: { page_size: 1000 },
|
||||
}),
|
||||
])
|
||||
assigned.value = normalizeList(assignedResult).items
|
||||
available.value = normalizeList(allResult).items
|
||||
selectedHolidayIds.value = assigned.value
|
||||
.filter(holiday => holiday.id !== undefined)
|
||||
.map(holiday => holiday.id!)
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
|
|
@ -50,40 +58,63 @@ async function load() {
|
|||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
if (selectedHolidayId.value === null) return
|
||||
function searchAvailable(search: string) {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<any>('/main/sys/holidays/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
})
|
||||
const selected = selectedHolidays.value
|
||||
available.value = [...new Map([...selected, ...normalizeList(result).items]
|
||||
.filter(holiday => holiday.id !== undefined)
|
||||
.map(holiday => [String(holiday.id), holiday])).values()]
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
|
||||
async function saveAssignments() {
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/holiday-groups/${props.groupId}/holidays/${selectedHolidayId.value}/`, {
|
||||
const result = await request<any>(`/main/sys/holiday-groups/${props.groupId}/holidays/`, {
|
||||
method: 'PUT',
|
||||
body: { holiday_ids: selectedHolidayIds.value.map(Number) },
|
||||
})
|
||||
selectedHolidayId.value = null
|
||||
await load()
|
||||
assigned.value = normalizeList(result).items
|
||||
selectedHolidayIds.value = assigned.value
|
||||
.filter(holiday => holiday.id !== undefined)
|
||||
.map(holiday => holiday.id!)
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
throw e
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(holiday: ApiRecord) {
|
||||
if (holiday.id === undefined || !window.confirm(`Убрать «${holidayTitle(holiday)}» из группы?`)) return
|
||||
deletingId.value = holiday.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/holiday-groups/${props.groupId}/holidays/${holiday.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
assigned.value = assigned.value.filter(item => String(item.id) !== String(holiday.id))
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
function remove(holiday: ApiRecord) {
|
||||
selectedHolidayIds.value = selectedHolidayIds.value
|
||||
.filter(id => String(id) !== String(holiday.id))
|
||||
}
|
||||
|
||||
function selectHoliday(holidayId: string | number | null) {
|
||||
if (holidayId === null) return
|
||||
if (!selectedHolidayIds.value.some(id => String(id) === String(holidayId))) {
|
||||
selectedHolidayIds.value = [...selectedHolidayIds.value, holidayId]
|
||||
}
|
||||
candidateHolidayId.value = null
|
||||
}
|
||||
|
||||
watch(() => props.groupId, load, { immediate: true })
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
defineExpose({ saveAssignments })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -91,26 +122,25 @@ watch(() => props.groupId, load, { immediate: true })
|
|||
<h3 class="text-subtitle-1 font-weight-bold mb-4">Праздники группы</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
|
||||
<v-list v-if="assigned.length" class="border rounded-lg mb-5" lines="two">
|
||||
<v-list-item v-for="holiday in assigned" :key="holiday.id"
|
||||
<v-list v-if="selectedHolidays.length" class="border rounded-lg mb-5" lines="two">
|
||||
<v-list-item v-for="holiday in selectedHolidays" :key="holiday.id"
|
||||
:title="String(holiday.name || `Праздник #${holiday.id}`)"
|
||||
:subtitle="[holiday.date_begin, holiday.date_end].filter(Boolean).map(formatDateValue).join(' — ')">
|
||||
<template #append>
|
||||
<v-btn v-if="!readonly" icon="mdi-link-off" variant="text" color="error"
|
||||
:loading="String(deletingId) === String(holiday.id)"
|
||||
aria-label="Убрать праздник из группы" @click="remove(holiday)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
<p v-else-if="!loading" class="text-medium-emphasis mb-5">В группе пока нет праздников</p>
|
||||
<template v-if="!readonly">
|
||||
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить</h4>
|
||||
<div class="d-flex flex-column flex-sm-row ga-3 align-sm-start">
|
||||
<v-autocomplete v-model="selectedHolidayId" :items="options"
|
||||
label="Добавить существующий праздник" no-data-text="Нет доступных праздников"
|
||||
clearable hide-details />
|
||||
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
|
||||
:disabled="selectedHolidayId === null" @click="add">Добавить</v-btn>
|
||||
</div>
|
||||
<v-autocomplete v-model="candidateHolidayId" :items="options"
|
||||
label="Праздники" no-data-text="Праздники не найдены"
|
||||
clearable :loading="saving"
|
||||
@update:search="searchAvailable($event || '')"
|
||||
@update:model-value="selectHoliday" />
|
||||
<p class="text-caption text-medium-emphasis mb-0">
|
||||
Изменения состава применятся после сохранения группы.
|
||||
</p>
|
||||
</template>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -1,88 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
employeeId: string | number
|
||||
readonly?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const groups = ref<ApiRecord[]>([])
|
||||
const selectedIds = ref<(string | number)[]>([])
|
||||
const loading = ref(false)
|
||||
const updatingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
|
||||
function relationIds(value: unknown) {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.flatMap(item => {
|
||||
const id = typeof item === 'object' && item !== null ? (item as ApiRecord).id : item
|
||||
return typeof id === 'string' || typeof id === 'number' ? [id] : []
|
||||
})
|
||||
}
|
||||
|
||||
function isSelected(id: string | number) {
|
||||
return selectedIds.value.some(selectedId => String(selectedId) === String(id))
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [groupsResult, membershipsResult] = await Promise.all([
|
||||
request<any>('/main/inc/groups/', { query: { page_size: 1000 } }),
|
||||
request<any>(`/main/inc/employees/${props.employeeId}/groups/`, { query: { page_size: 1000 } }),
|
||||
])
|
||||
groups.value = normalizeList(groupsResult).items.filter(group => group.id !== undefined)
|
||||
selectedIds.value = relationIds(normalizeList(membershipsResult).items)
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function updateMembership(groupId: string | number, enabled: boolean | null) {
|
||||
if (props.readonly || updatingId.value !== null) return
|
||||
const previous = [...selectedIds.value]
|
||||
selectedIds.value = enabled
|
||||
? [...new Set([...selectedIds.value, groupId])]
|
||||
: selectedIds.value.filter(id => String(id) !== String(groupId))
|
||||
updatingId.value = groupId
|
||||
error.value = ''
|
||||
try {
|
||||
const path = `/main/inc/employees/${props.employeeId}/groups/${groupId}/`
|
||||
await request(path, { method: enabled ? 'PUT' : 'DELETE' })
|
||||
const memberships = await request<any>(`/main/inc/employees/${props.employeeId}/groups/`, {
|
||||
query: { page_size: 1000 },
|
||||
})
|
||||
selectedIds.value = relationIds(normalizeList(memberships).items)
|
||||
} catch (e: any) {
|
||||
selectedIds.value = previous
|
||||
error.value = e.message
|
||||
} finally {
|
||||
updatingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.employeeId, load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-5" />
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-3">Группы сотрудника</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-3">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-3" />
|
||||
<v-list v-else class="border rounded-lg" density="compact">
|
||||
<v-list-item v-for="group in groups" :key="group.id" :title="String(group.name || `Группа #${group.id}`)"
|
||||
:subtitle="group.description ? String(group.description) : undefined">
|
||||
<template #prepend>
|
||||
<v-checkbox-btn :model-value="isSelected(group.id!)"
|
||||
:readonly="readonly || updatingId !== null"
|
||||
:loading="String(updatingId) === String(group.id)"
|
||||
@update:model-value="updateMembership(group.id!, $event)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
<v-list-item v-if="!groups.length" title="Группы не найдены" />
|
||||
</v-list>
|
||||
</template>
|
||||
|
|
@ -116,7 +116,7 @@ async function loadHistory() {
|
|||
historyLoading.value = true
|
||||
historyError.value = ''
|
||||
try {
|
||||
const data = await request<any>('/main/inc/incidenthistoricals/', {
|
||||
const data = await request<any>('/main/inc/incident-history/', {
|
||||
query: { page_size: 1000, id__exact: props.modelValue.id },
|
||||
})
|
||||
historyRecords.value = normalizeList(data).items
|
||||
|
|
@ -140,12 +140,15 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
|
|||
<v-tab value="main">Основное</v-tab>
|
||||
<v-tab value="request">Запрос/решение</v-tab>
|
||||
<v-tab value="comments">Комментарии</v-tab>
|
||||
<v-tab value="attachments">Вложения</v-tab>
|
||||
<v-tab value="sla">SLA</v-tab>
|
||||
<v-tab value="related">Связанные объекты</v-tab>
|
||||
<v-tab value="history">История</v-tab>
|
||||
</v-tabs>
|
||||
<v-window v-model="activeTab">
|
||||
<v-window-item value="main">
|
||||
<TagsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
|
||||
:readonly="readonly" :active="activeTab === 'main'" />
|
||||
<v-card variant="outlined" class="mb-4">
|
||||
<v-card-title class="text-subtitle-1">Данные инцидента</v-card-title>
|
||||
<v-card-text>
|
||||
|
|
@ -210,7 +213,12 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
|
|||
</v-card>
|
||||
</v-window-item>
|
||||
<v-window-item value="comments">
|
||||
<CommentsTab kind="inc" :record-id="modelValue.id as string | number | undefined" :readonly="readonly" />
|
||||
<CommentsTab kind="inc" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
|
||||
:active="activeTab === 'comments'" />
|
||||
</v-window-item>
|
||||
<v-window-item value="attachments">
|
||||
<AttachmentsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
|
||||
:readonly="readonly" :active="activeTab === 'attachments'" />
|
||||
</v-window-item>
|
||||
<v-window-item value="sla">
|
||||
<SlaCalculationHistory kind="incident"
|
||||
|
|
|
|||
|
|
@ -1,39 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{ groupId: string | number }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const employees = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<any>(`/main/inc/groups/${props.groupId}/employees/`, {
|
||||
query: { page_size: 1000 },
|
||||
})
|
||||
employees.value = normalizeList(result).items
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.groupId, load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-5" />
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-3">Сотрудники группы</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-3">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-3" />
|
||||
<v-list v-else class="border rounded-lg" density="compact">
|
||||
<v-list-item v-for="employee in employees" :key="employee.id"
|
||||
prepend-icon="mdi-account-outline"
|
||||
:title="String(employee.name || `Сотрудник #${employee.id}`)" />
|
||||
<v-list-item v-if="!employees.length" title="В группе нет сотрудников" />
|
||||
</v-list>
|
||||
</template>
|
||||
|
|
@ -21,7 +21,7 @@ type SettingSection = {
|
|||
}
|
||||
|
||||
const props = defineProps<{
|
||||
sectionKey: 'srv' | 'req' | 'inc' | 'con' | 'sys'
|
||||
sectionKey: 'srv' | 'req' | 'inc' | 'con' | 'chn' | 'sys'
|
||||
readonly?: boolean
|
||||
}>()
|
||||
const { request, normalizeList } = useApi()
|
||||
|
|
@ -68,6 +68,16 @@ const sections: SettingSection[] = [
|
|||
{ name: 'escalate_source_type', title: 'Источник эскалации', type: 'integer', optionsEndpoint: '/main/inc/source-types/' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'chn',
|
||||
title: 'Задачи',
|
||||
endpoint: '/main/chn/settings/1/',
|
||||
fields: [
|
||||
{ name: 'task_status_create', title: 'Статус «Создано»', type: 'integer', optionsEndpoint: '/main/chn/task-statuses/' },
|
||||
{ name: 'task_status_close', title: 'Статус «Выполнено успешно»', type: 'integer', optionsEndpoint: '/main/chn/task-statuses/' },
|
||||
{ name: 'task_status_not_done', title: 'Статус «Не выполнено»', type: 'integer', optionsEndpoint: '/main/chn/task-statuses/' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'con',
|
||||
title: 'Коммуникации',
|
||||
|
|
|
|||
|
|
@ -364,7 +364,7 @@ async function loadHistory() {
|
|||
historyLoading.value = true
|
||||
historyError.value = ''
|
||||
try {
|
||||
const data = await request<any>('/main/req/requesthistoricals/', {
|
||||
const data = await request<any>('/main/req/request-history/', {
|
||||
query: { page_size: 1000, id__exact: props.modelValue.id },
|
||||
})
|
||||
historyRecords.value = normalizeList(data).items
|
||||
|
|
@ -382,10 +382,10 @@ async function loadSla() {
|
|||
slaError.value = ''
|
||||
try {
|
||||
const [calculations, totals] = await Promise.all([
|
||||
request<any>('/main/sla/requesthistcalcs/', {
|
||||
request<any>('/main/sla/request-history-calculations/', {
|
||||
query: { page_size: 1000, sla_request_hist__request_id__exact: props.modelValue.id },
|
||||
}),
|
||||
request<any>('/main/sla/requesthistcalctotals/', {
|
||||
request<any>('/main/sla/request-history-calculations-total/', {
|
||||
query: { page_size: 1000, request_id__exact: props.modelValue.id },
|
||||
}),
|
||||
])
|
||||
|
|
@ -451,6 +451,7 @@ onMounted(async () => {
|
|||
<v-tab value="main">Основное</v-tab>
|
||||
<v-tab value="request">Запрос/решение</v-tab>
|
||||
<v-tab value="comments">Комментарии</v-tab>
|
||||
<v-tab value="attachments">Вложения</v-tab>
|
||||
<v-tab value="sla">SLA</v-tab>
|
||||
<v-tab value="related">Связанные объекты</v-tab>
|
||||
<v-tab value="history">История</v-tab>
|
||||
|
|
@ -458,6 +459,8 @@ onMounted(async () => {
|
|||
|
||||
<v-window v-model="activeTab">
|
||||
<v-window-item value="main">
|
||||
<TagsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
|
||||
:readonly="readonly" :active="activeTab === 'main'" />
|
||||
<v-card variant="outlined" class="mb-4">
|
||||
<v-card-title class="text-subtitle-1">Данные по обращению</v-card-title>
|
||||
<v-card-text>
|
||||
|
|
@ -552,7 +555,8 @@ onMounted(async () => {
|
|||
<v-card variant="outlined" class="mb-4">
|
||||
<v-card-title class="text-subtitle-1">Адрес</v-card-title>
|
||||
<v-card-text>
|
||||
<div :class="{ 'request-address-row': field('flat') }">
|
||||
<div class="request-address-row"
|
||||
:class="{ 'request-address-row--with-flat': field('flat') }">
|
||||
<AddressHousePicker :model-value="modelValue.house_id" smart :readonly="readonly"
|
||||
@update:model-value="set('house_id', $event)"
|
||||
@house-selected="selectHouseRecord"
|
||||
|
|
@ -560,11 +564,11 @@ onMounted(async () => {
|
|||
<ResourceField v-if="field('flat')" name="flat" :schema="field('flat')!"
|
||||
:model-value="modelValue.flat" :required="required('flat')" :readonly="readonly"
|
||||
@update:model-value="set('flat', $event)" />
|
||||
<CoordinatePicker v-if="field('lat') && field('lon')" :lat="modelValue.lat" :lon="modelValue.lon"
|
||||
:lat-schema="field('lat')!" :lon-schema="field('lon')!"
|
||||
:lat-required="required('lat')" :lon-required="required('lon')" :readonly="readonly"
|
||||
@change="setCoordinates" />
|
||||
</div>
|
||||
<CoordinatePicker v-if="field('lat') && field('lon')" :lat="modelValue.lat" :lon="modelValue.lon"
|
||||
:lat-schema="field('lat')!" :lon-schema="field('lon')!"
|
||||
:lat-required="required('lat')" :lon-required="required('lon')" :readonly="readonly"
|
||||
@change="setCoordinates" />
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
|
||||
|
|
@ -605,7 +609,12 @@ onMounted(async () => {
|
|||
|
||||
</v-window-item>
|
||||
<v-window-item value="comments">
|
||||
<CommentsTab kind="req" :record-id="modelValue.id as string | number | undefined" :readonly="readonly" />
|
||||
<CommentsTab kind="req" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
|
||||
:active="activeTab === 'comments'" />
|
||||
</v-window-item>
|
||||
<v-window-item value="attachments">
|
||||
<AttachmentsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
|
||||
:readonly="readonly" :active="activeTab === 'attachments'" />
|
||||
</v-window-item>
|
||||
<v-window-item value="sla">
|
||||
<SlaCalculationHistory kind="request"
|
||||
|
|
@ -659,8 +668,13 @@ onMounted(async () => {
|
|||
<style scoped>
|
||||
.request-address-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 17fr) minmax(0, 3fr);
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 12px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.request-address-row--with-flat {
|
||||
grid-template-columns: minmax(0, 17fr) minmax(0, 3fr) auto;
|
||||
}
|
||||
|
||||
.request-client-row {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -9,6 +9,8 @@ const props = defineProps<{
|
|||
schema: JsonSchema
|
||||
loading?: boolean
|
||||
readonly?: boolean
|
||||
readonlyFields?: string[]
|
||||
textFields?: string[]
|
||||
hiddenFields?: string[]
|
||||
fieldOptions?: Record<string, SelectOption[]>
|
||||
fieldLabels?: Record<string, string>
|
||||
|
|
@ -34,6 +36,28 @@ const fields = computed(() => Object.entries(props.schema.properties || {})
|
|||
const fieldTabs = computed(() => Object.fromEntries((props.tabs || []).flatMap(tab =>
|
||||
(tab.fields || []).map(field => [field, tab.value]))))
|
||||
const defaultTab = computed(() => props.tabs?.[0]?.value || '')
|
||||
function fieldReadonly(name: string) {
|
||||
return Boolean(props.readonly || props.readonlyFields?.includes(name))
|
||||
}
|
||||
function fieldLabel(name: string, field: JsonSchema) {
|
||||
return props.relationLabels?.[name] || props.fieldLabels?.[name]
|
||||
|| field.title || name.replaceAll('_', ' ')
|
||||
}
|
||||
function textFieldValue(name: string) {
|
||||
const value = props.modelValue[name]
|
||||
if (value === null || value === undefined || value === '') return '—'
|
||||
if (Array.isArray(value)) return value.map(item => {
|
||||
if (item && typeof item === 'object') return String((item as ApiRecord).name || (item as ApiRecord).title || (item as ApiRecord).id || '—')
|
||||
return String(item)
|
||||
}).join(', ')
|
||||
if (value && typeof value === 'object') {
|
||||
const record = value as ApiRecord
|
||||
return String(record.name || record.title || record.id || '—')
|
||||
}
|
||||
const option = [...(props.relationOptions?.[name] || []), ...(props.fieldOptions?.[name] || [])]
|
||||
.find(item => String(item.value) === String(value))
|
||||
return option?.title || String(value)
|
||||
}
|
||||
function tabForField(name: string) { return fieldTabs.value[name] || defaultTab.value }
|
||||
watch(() => props.tabs, tabs => {
|
||||
if (!tabs?.some(tab => tab.value === activeTab.value)) activeTab.value = tabs?.[0]?.value || ''
|
||||
|
|
@ -61,6 +85,21 @@ function relationRecord(name: string, value: string | number | null) {
|
|||
const option = props.relationOptions?.[name]?.find(item => String(item.value) === String(value))
|
||||
return { id: value, ...(option?.title ? { name: option.title } : {}), ...(option?.color ? { color: option.color } : {}) }
|
||||
}
|
||||
function fieldOption(name: string, value: unknown): SelectOption | null {
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
if (typeof value === 'object') return value as SelectOption
|
||||
return props.fieldOptions?.[name]?.find(option => String(option.value) === String(value))
|
||||
|| { title: String(value), value: value as string | number | boolean }
|
||||
}
|
||||
function fieldOptionValue(name: string) {
|
||||
const value = props.modelValue[name]
|
||||
return Array.isArray(value)
|
||||
? value.map(item => fieldOption(name, item)).filter(Boolean)
|
||||
: fieldOption(name, value)
|
||||
}
|
||||
function setOptionField(name: string, value: SelectOption | SelectOption[] | null) {
|
||||
setField(name, Array.isArray(value) ? value.map(option => option.value) : value?.value ?? null)
|
||||
}
|
||||
async function submit() { const result = await form.value?.validate(); if (result?.valid !== false) emit('submit') }
|
||||
</script>
|
||||
|
||||
|
|
@ -70,9 +109,16 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
<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>
|
||||
</v-tabs>
|
||||
<div v-if="$slots['tab-prepend']" class="tab-content">
|
||||
<slot name="tab-prepend" :active-tab="activeTab" />
|
||||
</div>
|
||||
<template v-for="[name, field] in fields" :key="name">
|
||||
<div v-show="!tabs?.length || tabForField(name) === activeTab" :class="fieldClasses?.[name]">
|
||||
<CoordinatePicker v-if="name === 'lat' && hasCoordinates"
|
||||
<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>
|
||||
<CoordinatePicker v-else-if="name === 'lat' && hasCoordinates"
|
||||
:lat="modelValue.lat"
|
||||
:lon="modelValue.lon"
|
||||
:lat-schema="schema.properties!.lat"
|
||||
|
|
@ -89,7 +135,7 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
? 'Начните вводить населённый пункт'
|
||||
: name === 'adr_street' ? 'Начните вводить улицу' : undefined"
|
||||
:persistent-placeholder="['adr_town', 'adr_street'].includes(name)"
|
||||
:readonly="readonly" clearable no-data-text="Ничего не найдено"
|
||||
:readonly="fieldReadonly(name)" clearable no-data-text="Ничего не найдено"
|
||||
@update:search="emit('relationSearch', name, $event || '')"
|
||||
:rules="Array.isArray(schema.required) && schema.required.includes(name)
|
||||
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
|
||||
|
|
@ -97,19 +143,20 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
:class="{ 'colored-object-field': relationColor(name) }"
|
||||
:style="relationColor(name) ? { '--field-accent': relationColor(name) } : undefined"
|
||||
@update:model-value="setField(name, relationRecord(name, $event))" />
|
||||
<v-autocomplete v-else-if="fieldOptions?.[name]" :model-value="modelValue[name]"
|
||||
<v-autocomplete v-else-if="fieldOptions?.[name]" :model-value="fieldOptionValue(name)"
|
||||
:items="fieldOptions[name]"
|
||||
:label="fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
|
||||
:readonly="readonly" clearable
|
||||
:readonly="fieldReadonly(name)" :multiple="field.type === 'array'" :chips="field.type === 'array'"
|
||||
return-object clearable
|
||||
:rules="Array.isArray(schema.required) && schema.required.includes(name)
|
||||
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
|
||||
: []"
|
||||
@update:search="emit('relationSearch', name, $event || '')"
|
||||
@update:model-value="setField(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="readonly"
|
||||
:readonly="fieldReadonly(name)"
|
||||
@update:model-value="setField(name, $event)" />
|
||||
</div>
|
||||
<div v-show="!tabs?.length || tabForField(name) === activeTab" class="field-slot">
|
||||
|
|
@ -155,6 +202,12 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
grid-column: span 18;
|
||||
}
|
||||
|
||||
.client-form-grid :deep(.address-flat-row) {
|
||||
grid-column: 1 / -1;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.contract-form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
|
@ -169,6 +222,20 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.holiday-form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
column-gap: 16px;
|
||||
}
|
||||
|
||||
.holiday-form-grid > :deep(*) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.holiday-form-grid > .holiday-date {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.service-form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
|
@ -234,6 +301,16 @@ async function submit() { const result = await form.value?.validate(); if (resul
|
|||
grid-column: span 1;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.holiday-form-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.holiday-form-grid > .holiday-date {
|
||||
grid-column: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.ci-form-grid :deep(.address-flat-row) {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ async function load() {
|
|||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const week = await request<ApiRecord>(`/main/sla/scheduleweeks/${props.scheduleWeekId}/`)
|
||||
const week = await request<ApiRecord>(`/main/sla/schedule-weeks/${props.scheduleWeekId}/`)
|
||||
periods.value = Array.isArray(week.sla_schedule_week_period)
|
||||
? week.sla_schedule_week_period as ApiRecord[]
|
||||
: []
|
||||
|
|
@ -74,7 +74,7 @@ async function add() {
|
|||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/scheduleweeks/${props.scheduleWeekId}/periods/`, {
|
||||
await request(`/main/sla/schedule-weeks/${props.scheduleWeekId}/periods/`, {
|
||||
method: 'POST',
|
||||
body: { day: day.value, time_begin: beginSeconds, time_end: endSeconds },
|
||||
})
|
||||
|
|
@ -94,7 +94,7 @@ async function remove(period: ApiRecord) {
|
|||
deletingId.value = period.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/scheduleweeks/${props.scheduleWeekId}/periods/${period.id}/`, {
|
||||
await request(`/main/sla/schedule-weeks/${props.scheduleWeekId}/periods/${period.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
periods.value = periods.value.filter(item => String(item.id) !== String(period.id))
|
||||
|
|
|
|||
|
|
@ -15,10 +15,11 @@ const loading = ref(false)
|
|||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const agreementPath = computed(() => props.agreementType === 'request'
|
||||
? '/main/sla/requestagreements/'
|
||||
: '/main/sla/incidentagreements/')
|
||||
? '/main/sla/request-agreements/'
|
||||
: '/main/sla/incident-agreements/')
|
||||
const availableGroups = computed(() => {
|
||||
const used = new Set(groups.value.map(group => String(group.id)))
|
||||
return groupOptions.value.filter(group => !used.has(String(group.value)))
|
||||
|
|
@ -30,7 +31,7 @@ async function load() {
|
|||
try {
|
||||
const [agreement, allGroups] = await Promise.all([
|
||||
request<ApiRecord>(`${agreementPath.value}${props.agreementId}/`),
|
||||
request<any>('/main/sys/holidaygroups/', { query: { page_size: 1000 } }),
|
||||
request<any>('/main/sys/holiday-groups/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
groups.value = Array.isArray(agreement.sys_holiday_group)
|
||||
? agreement.sys_holiday_group as ApiRecord[]
|
||||
|
|
@ -46,6 +47,22 @@ async function load() {
|
|||
} finally { loading.value = false }
|
||||
}
|
||||
|
||||
function searchGroups(search: string) {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(async () => {
|
||||
try {
|
||||
const result = await request<any>('/main/sys/holiday-groups/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { searchstr: search.trim() } : {}) },
|
||||
})
|
||||
groupOptions.value = normalizeList(result).items
|
||||
.filter(group => group.id !== undefined)
|
||||
.map(group => ({ title: String(group.name || `Группа #${group.id}`), value: group.id! }))
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось найти праздничные группы'
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
|
||||
async function add() {
|
||||
if (selectedGroupId.value === null) return
|
||||
saving.value = true
|
||||
|
|
@ -76,6 +93,7 @@ async function remove(group: ApiRecord) {
|
|||
}
|
||||
|
||||
watch([() => props.agreementId, () => props.agreementType], load, { immediate: true })
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -105,8 +123,9 @@ watch([() => props.agreementId, () => props.agreementType], load, { immediate: t
|
|||
<template v-if="!readonly">
|
||||
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить</h4>
|
||||
<v-form class="d-flex ga-3 align-start" @submit.prevent="add">
|
||||
<v-select v-model="selectedGroupId" :items="availableGroups"
|
||||
<v-autocomplete v-model="selectedGroupId" :items="availableGroups"
|
||||
label="Праздничная группа" clearable
|
||||
@update:search="searchGroups($event || '')"
|
||||
no-data-text="Все группы уже добавлены" />
|
||||
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving"
|
||||
:disabled="selectedGroupId === null">Добавить</v-btn>
|
||||
|
|
|
|||
|
|
@ -14,14 +14,14 @@ const loading = ref(false)
|
|||
const error = ref('')
|
||||
|
||||
const settings = computed(() => props.kind === 'request' ? {
|
||||
calculations: '/main/sla/requesthistcalcs/',
|
||||
totals: '/main/sla/requesthistcalctotals/',
|
||||
calculations: '/main/sla/request-history-calculations/',
|
||||
totals: '/main/sla/request-history-calculations-total/',
|
||||
calculationFilter: 'sla_request_hist__request_id__exact',
|
||||
totalFilter: 'request_id__exact',
|
||||
agreement: 'sla_request_agreement',
|
||||
} : {
|
||||
calculations: '/main/sla/incidenthistcalcs/',
|
||||
totals: '/main/sla/incidenthistcalctotals/',
|
||||
calculations: '/main/sla/incident-history-calculations/',
|
||||
totals: '/main/sla/incident-history-calculations-total/',
|
||||
calculationFilter: 'sla_incident_hist__incident_id__exact',
|
||||
totalFilter: 'incident_id__exact',
|
||||
agreement: 'sla_incident_agreement',
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ async function load() {
|
|||
error.value = ''
|
||||
try {
|
||||
const [agreement, statuses] = await Promise.all([
|
||||
request<ApiRecord>(`/main/sla/incidentagreements/${props.agreementId}/`),
|
||||
request<ApiRecord>(`/main/sla/incident-agreements/${props.agreementId}/`),
|
||||
request<any>('/main/inc/statuses/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
relations.value = Array.isArray(agreement.sla_incident_status)
|
||||
|
|
@ -60,7 +60,7 @@ async function add() {
|
|||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/incidentagreements/${props.agreementId}/statuses/`, {
|
||||
await request(`/main/sla/incident-agreements/${props.agreementId}/statuses/`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
status_id: Number(selectedStatusId.value),
|
||||
|
|
@ -81,7 +81,7 @@ async function remove(relation: ApiRecord) {
|
|||
deletingId.value = relation.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/incidentagreements/${props.agreementId}/statuses/${relation.id}/`, {
|
||||
await request(`/main/sla/incident-agreements/${props.agreementId}/statuses/${relation.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
relations.value = relations.value.filter(item => String(item.id) !== String(relation.id))
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ async function load() {
|
|||
error.value = ''
|
||||
try {
|
||||
const [agreement, statuses] = await Promise.all([
|
||||
request<ApiRecord>(`/main/sla/requestagreements/${props.agreementId}/`),
|
||||
request<ApiRecord>(`/main/sla/request-agreements/${props.agreementId}/`),
|
||||
request<any>('/main/req/statuses/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
relations.value = Array.isArray(agreement.sla_request_status)
|
||||
|
|
@ -60,7 +60,7 @@ async function add() {
|
|||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/requestagreements/${props.agreementId}/statuses/`, {
|
||||
await request(`/main/sla/request-agreements/${props.agreementId}/statuses/`, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
status_id: Number(selectedStatusId.value),
|
||||
|
|
@ -81,7 +81,7 @@ async function remove(relation: ApiRecord) {
|
|||
deletingId.value = relation.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sla/requestagreements/${props.agreementId}/statuses/${relation.id}/`, {
|
||||
await request(`/main/sla/request-agreements/${props.agreementId}/statuses/${relation.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
relations.value = relations.value.filter(item => String(item.id) !== String(relation.id))
|
||||
|
|
|
|||
|
|
@ -0,0 +1,220 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
interface Tag extends ApiRecord { id: string | number; name: string; color?: string; description?: string }
|
||||
const props = defineProps<{ targetType: string; recordId?: string | number; readonly?: boolean; active?: boolean }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const assigned = ref<Tag[]>([])
|
||||
const catalog = ref<Tag[]>([])
|
||||
const selectedId = ref<string | number | null>(null)
|
||||
const search = ref('')
|
||||
const enteredName = ref('')
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const error = ref('')
|
||||
const loadedKey = ref('')
|
||||
const detailsOpen = ref(false)
|
||||
const detailsTag = ref<Tag | null>(null)
|
||||
const detailsLoading = ref(false)
|
||||
const detailsError = ref('')
|
||||
const linkedObjects = ref<(ApiRecord & { target_type: string; target_id: string | number; display_title: string })[]>([])
|
||||
const targetKey = computed(() => props.recordId === undefined || props.recordId === null ? '' : `${props.targetType}:${props.recordId}`)
|
||||
const options = computed(() => catalog.value.filter(tag => !assigned.value.some(item => String(item.id) === String(tag.id)))
|
||||
.map(tag => ({ title: tag.name, value: tag.id })))
|
||||
const canAdd = computed(() => selectedId.value === null && Boolean(enteredName.value.trim()))
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const targetDefinitions: Record<string, { title: string; path: string }> = {
|
||||
'adr.country': { title: 'Страна', path: '/main/adr/countries/' },
|
||||
'adr.region': { title: 'Регион', path: '/main/adr/regions/' },
|
||||
'adr.area': { title: 'Район', path: '/main/adr/areas/' },
|
||||
'adr.town': { title: 'Населённый пункт', path: '/main/adr/towns/' },
|
||||
'adr.street': { title: 'Улица', path: '/main/adr/streets/' },
|
||||
'adr.house': { title: 'Дом', path: '/main/adr/houses/' },
|
||||
'adr.zone': { title: 'Зона', path: '/main/adr/zones/' },
|
||||
'req.request': { title: 'Обращение', path: '/main/req/requests/' },
|
||||
'inc.incident': { title: 'Инцидент', path: '/main/inc/incidents/' },
|
||||
'cim.ci': { title: 'CI', path: '/main/cim/cis/' },
|
||||
'dev.manufacturer': { title: 'Производитель', path: '/main/dev/manufacturers/' },
|
||||
'dev.model': { title: 'Модель устройства', path: '/main/dev/models/' },
|
||||
'dev.software-version': { title: 'Версия ПО', path: '/main/dev/software-versions/' },
|
||||
'dev.hardware-version': { title: 'Версия оборудования', path: '/main/dev/hardware-versions/' },
|
||||
'srv.service': { title: 'Сервис', path: '/main/srv/services/' },
|
||||
'crm.client': { title: 'Клиент', path: '/main/crm/clients/' },
|
||||
'crm.lead': { title: 'Лид', path: '/main/crm/leads/' },
|
||||
'crm.contract': { title: 'Договор', path: '/main/crm/contracts/' },
|
||||
'chn.task': { title: 'Задача', path: '/main/chn/tasks/' },
|
||||
'chn.change': { title: 'Изменение', path: '/main/chn/changes/' },
|
||||
}
|
||||
|
||||
function objectTitle(record: ApiRecord, definition: { title: string }, id: string | number) {
|
||||
return String(record.title || record.name || record.address || record.number
|
||||
|| record.request_text || record.fullname || `${definition.title} #${id}`)
|
||||
}
|
||||
|
||||
async function openTag(tag: Tag) {
|
||||
detailsTag.value = tag
|
||||
detailsOpen.value = true
|
||||
detailsLoading.value = true
|
||||
detailsError.value = ''
|
||||
linkedObjects.value = []
|
||||
try {
|
||||
const data = await request<any>(`/main/sys/tags/${tag.id}/assignments/`)
|
||||
const assignments = normalizeList<ApiRecord>(data).items
|
||||
linkedObjects.value = await Promise.all(assignments.map(async assignment => {
|
||||
const targetType = String(assignment.target_type || '')
|
||||
const targetId = assignment.target_id as string | number
|
||||
const definition = targetDefinitions[targetType] || { title: targetType || 'Объект', path: '' }
|
||||
if (!definition.path) return { ...assignment, target_type: targetType, target_id: targetId,
|
||||
display_title: `${definition.title} #${targetId}` }
|
||||
try {
|
||||
const record = await request<ApiRecord>(`${definition.path}${targetId}/`)
|
||||
return { ...assignment, ...record, target_type: targetType, target_id: targetId,
|
||||
display_title: objectTitle(record, definition, targetId) }
|
||||
} catch {
|
||||
return { ...assignment, target_type: targetType, target_id: targetId,
|
||||
display_title: `${definition.title} #${targetId}` }
|
||||
}
|
||||
}))
|
||||
} catch (caught: any) {
|
||||
detailsError.value = caught?.message || 'Не удалось загрузить связанные объекты'
|
||||
} finally { detailsLoading.value = false }
|
||||
}
|
||||
|
||||
async function load(force = false) {
|
||||
if (!targetKey.value || (!force && loadedKey.value === targetKey.value)) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [assignedData, catalogData] = await Promise.all([
|
||||
request<any>('/main/sys/tags/', { query: { page_size: 1000, target_type: props.targetType, target_id: props.recordId } }),
|
||||
request<any>('/main/sys/tags/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
assigned.value = normalizeList<Tag>(assignedData).items
|
||||
catalog.value = normalizeList<Tag>(catalogData).items
|
||||
loadedKey.value = targetKey.value
|
||||
} catch (caught: any) { error.value = caught?.message || 'Не удалось загрузить теги' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
async function addTag() {
|
||||
const selected = catalog.value.find(tag => String(tag.id) === String(selectedId.value))
|
||||
const name = (selected?.name || enteredName.value).trim()
|
||||
if (!name && selectedId.value === null) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const existing = selected || catalog.value.find(tag => tag.name.toLocaleLowerCase() === name.toLocaleLowerCase())
|
||||
const tag = existing || await request<Tag>('/main/sys/tags/', { method: 'POST', body: { name } })
|
||||
await request(`/main/sys/tags/${tag.id}/assignments/`, {
|
||||
method: 'POST', body: { target_type: props.targetType, target_id: props.recordId },
|
||||
})
|
||||
selectedId.value = null
|
||||
search.value = ''
|
||||
enteredName.value = ''
|
||||
await load(true)
|
||||
} catch (caught: any) { error.value = caught?.message || 'Не удалось создать тег' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
async function searchTags(value: string) {
|
||||
search.value = value
|
||||
if (value.trim()) enteredName.value = value
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(async () => {
|
||||
try {
|
||||
const term = enteredName.value.trim()
|
||||
const data = await request<any>('/main/sys/tags/', {
|
||||
query: { page_size: 50, ...(term ? { searchstr: term } : {}) },
|
||||
})
|
||||
const results = normalizeList<Tag>(data).items
|
||||
catalog.value = term
|
||||
? results.filter(tag => tag.name.toLocaleLowerCase().includes(term.toLocaleLowerCase()))
|
||||
: results
|
||||
} catch (caught: any) {
|
||||
error.value = caught?.message || 'Не удалось выполнить поиск тегов'
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
async function remove(tag: Tag) {
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await request<any>(`/main/sys/tags/${tag.id}/assignments/`)
|
||||
const assignments = normalizeList<ApiRecord>(data).items
|
||||
const assignment = assignments.find(item => item.target_type === props.targetType
|
||||
&& String(item.target_id) === String(props.recordId))
|
||||
if (assignment?.id !== undefined) await request(`/main/sys/tags/${tag.id}/assignments/${assignment.id}/`, { method: 'DELETE' })
|
||||
await load(true)
|
||||
} catch (caught: any) { error.value = caught?.message || 'Не удалось снять тег' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
watch(() => [targetKey.value, props.active], () => { if (props.active !== false) load() }, { immediate: true })
|
||||
watch(selectedId, value => {
|
||||
if (value !== null && !saving.value) addTag()
|
||||
})
|
||||
onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-alert v-if="!targetKey" type="info" variant="tonal">Сначала сохраните объект, затем можно будет назначать теги.</v-alert>
|
||||
<template v-else>
|
||||
<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" />
|
||||
<div class="tag-editor">
|
||||
<v-chip v-for="tag in assigned" :key="String(tag.id)" :color="tag.color || 'primary'"
|
||||
variant="tonal" :closable="!readonly" :disabled="saving" @click="openTag(tag)" @click:close.stop="remove(tag)">
|
||||
{{ tag.name }}
|
||||
</v-chip>
|
||||
<template v-if="!readonly">
|
||||
<v-autocomplete v-model="selectedId" v-model:search="search" :items="options"
|
||||
class="tag-editor__input" variant="underlined" density="compact" placeholder="Добавить тег"
|
||||
hide-details clearable :loading="saving" no-data-text="Будет создан новый тег"
|
||||
@update:search="searchTags"
|
||||
@keyup.enter="addTag" />
|
||||
<v-btn v-if="canAdd" type="button" icon="mdi-plus"
|
||||
size="small" variant="text" color="primary" :loading="saving"
|
||||
title="Добавить тег" @mousedown.prevent="addTag" />
|
||||
</template>
|
||||
<span v-else-if="!loading && !assigned.length" class="text-medium-emphasis">Теги не назначены.</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<v-dialog v-model="detailsOpen" max-width="720">
|
||||
<v-card>
|
||||
<v-card-title class="d-flex align-center ga-2">
|
||||
<v-icon :color="detailsTag?.color || 'primary'">mdi-tag-outline</v-icon>
|
||||
{{ detailsTag?.name || 'Тег' }}
|
||||
</v-card-title>
|
||||
<v-card-subtitle>Привязанные объекты</v-card-subtitle>
|
||||
<v-card-text>
|
||||
<v-progress-linear v-if="detailsLoading" indeterminate color="primary" class="mb-4" />
|
||||
<v-alert v-if="detailsError" type="error" variant="tonal">{{ detailsError }}</v-alert>
|
||||
<v-alert v-else-if="!detailsLoading && !linkedObjects.length" type="info" variant="tonal">
|
||||
К тегу не привязано ни одного объекта.
|
||||
</v-alert>
|
||||
<v-list v-else-if="!detailsLoading" border rounded lines="two">
|
||||
<v-list-item v-for="item in linkedObjects" :key="`${item.target_type}:${item.target_id}`"
|
||||
prepend-icon="mdi-link-variant" :title="item.display_title"
|
||||
:subtitle="`${targetDefinitions[item.target_type]?.title || item.target_type} · ID ${item.target_id}`" />
|
||||
</v-list>
|
||||
</v-card-text>
|
||||
<v-card-actions class="justify-end">
|
||||
<v-btn type="button" variant="text" @click="detailsOpen = false">Закрыть</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tag-editor {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.tag-editor__input {
|
||||
flex: 1 1 180px;
|
||||
min-width: 140px;
|
||||
max-width: 360px;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{ task: ApiRecord; readonly?: boolean }>()
|
||||
const emit = defineEmits<{ changed: [record: ApiRecord] }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
const status = ref<ApiRecord | null>(null)
|
||||
const statuses = ref<ApiRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const changingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
|
||||
const statusTitles: Record<string, string> = {
|
||||
new: 'Новая',
|
||||
in_progress: 'В работе',
|
||||
pending: 'Ожидание',
|
||||
resolved: 'Решена',
|
||||
closed: 'Закрыта',
|
||||
cancelled: 'Отменена',
|
||||
}
|
||||
const transitions: Record<string, string[]> = {
|
||||
new: ['in_progress', 'cancelled'],
|
||||
in_progress: ['pending', 'resolved', 'cancelled'],
|
||||
pending: ['in_progress', 'cancelled'],
|
||||
resolved: ['closed', 'cancelled'],
|
||||
closed: ['cancelled'],
|
||||
}
|
||||
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 options = computed(() => {
|
||||
const allowed = new Set(transitions[code.value] || [])
|
||||
return statuses.value.filter(item => allowed.has(String(item.code))).map(item => ({
|
||||
title: String(item.name || item.title || statusTitles[String(item.code)] || `Статус #${item.id}`),
|
||||
value: item.id!,
|
||||
code: String(item.code || ''),
|
||||
})).filter(item => item.value !== undefined)
|
||||
})
|
||||
|
||||
async function load() {
|
||||
const raw = props.task.status
|
||||
status.value = raw && typeof raw === 'object' ? raw as ApiRecord : null
|
||||
if (props.task.id === undefined) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await request<any>('/main/chn/task-statuses/', { query: { page_size: 1000 } })
|
||||
statuses.value = normalizeList(data).items
|
||||
if (!status.value && (typeof raw === 'string' || typeof raw === 'number')) {
|
||||
status.value = statuses.value.find(item => String(item.id) === String(raw)) || null
|
||||
}
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось загрузить статусы задачи'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function changeStatus(target: { value: string | number; code: string }) {
|
||||
if (props.task.id === undefined) return
|
||||
if (target.code === 'cancelled'
|
||||
&& !window.confirm('Отменить задачу?')) return
|
||||
changingId.value = target.value
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await request<ApiRecord>(`/main/chn/tasks/${props.task.id}/`, {
|
||||
method: 'PATCH', body: { status: target.value },
|
||||
})
|
||||
emit('changed', result)
|
||||
} catch (caught: any) {
|
||||
error.value = caught.message || 'Не удалось изменить статус задачи'
|
||||
} finally {
|
||||
changingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.task.id, props.task.status], load, { immediate: true, deep: true })
|
||||
</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>
|
||||
</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>
|
||||
<v-alert v-if="error" type="error" variant="tonal" density="compact" class="mt-4">
|
||||
{{ error }}
|
||||
</v-alert>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -22,13 +22,16 @@ export function useApi() {
|
|||
const config = useRuntimeConfig()
|
||||
const token = useCookie<string | null>('wanitil-token', { sameSite: 'lax' })
|
||||
|
||||
type RequestOptions<T> = Parameters<typeof $fetch<T>>[1] & { auth?: boolean }
|
||||
type RequestOptions<T> = Parameters<typeof $fetch<T>>[1] & {
|
||||
auth?: boolean
|
||||
preserveNulls?: boolean
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions<T> = {}) {
|
||||
const { auth = true, ...fetchOptions } = options
|
||||
const { auth = true, preserveNulls = false, ...fetchOptions } = options
|
||||
const sanitizedBody = fetchOptions.body === undefined
|
||||
? undefined
|
||||
: omitNullValues(fetchOptions.body)
|
||||
: preserveNulls ? fetchOptions.body : omitNullValues(fetchOptions.body)
|
||||
try {
|
||||
return await $fetch<T>(`${config.public.apiBase}${path}`, {
|
||||
...fetchOptions,
|
||||
|
|
|
|||
|
|
@ -22,6 +22,30 @@ export function usePermissions() {
|
|||
const isAdmin = computed(() => auth.roles.some(role => role.name.toUpperCase() === 'ROLE_ADMIN')
|
||||
|| roleNames.value.some(name => ADMIN_MARKERS.some(marker => name.includes(marker))))
|
||||
|
||||
const normalize = (value: string) => value.toLowerCase().replace(/^\/+|\/+$/g, '').replace(/[-_]/g, '')
|
||||
const variants = (value: string) => {
|
||||
const normalized = normalize(value)
|
||||
return new Set([
|
||||
normalized,
|
||||
normalized.replace(/ies$/, 'y'),
|
||||
normalized.replace(/es$/, ''),
|
||||
normalized.replace(/s$/, ''),
|
||||
])
|
||||
}
|
||||
const overlaps = (left: string, right: string) => [...variants(left)].some(value => variants(right).has(value))
|
||||
|
||||
function capabilityActions(apiPrefix: string, resourceKey?: string) {
|
||||
if (!auth.capabilities) return null
|
||||
const module = auth.capabilities.modules.find(item => overlaps(item.code || String(item.id), apiPrefix))
|
||||
if (!module || !resourceKey) return []
|
||||
const resource = module.objects.find(object => {
|
||||
const urlPart = object.url.split('?')[0]?.split('/').filter(Boolean).at(-1) || ''
|
||||
const objectId = object.code || String(object.id).split(/[.:/]/).filter(Boolean).at(-1) || ''
|
||||
return overlaps(objectId, resourceKey) || overlaps(urlPart, resourceKey)
|
||||
})
|
||||
return (resource?.actions || []).map(action => action.toLowerCase())
|
||||
}
|
||||
|
||||
function resourceScope(apiPrefix: string, resourceKey?: string): StructuredRole['scope'] {
|
||||
const key = resourceKey || ''
|
||||
if (apiPrefix === 'sys') {
|
||||
|
|
@ -57,15 +81,15 @@ export function usePermissions() {
|
|||
]
|
||||
const entry = Object.entries(auth.permissions).find(([key]) => {
|
||||
const normalized = key.toLowerCase().replace(/\/$/, '')
|
||||
const parts = normalized.split(/[:/.]/).filter(Boolean)
|
||||
return candidates.includes(normalized)
|
||||
|| normalized.endsWith(`.${resource}`)
|
||||
|| normalized.endsWith(`/${resource}`)
|
||||
|| (parts.some(part => overlaps(part, prefix)) && overlaps(parts.at(-1) || '', resource))
|
||||
})
|
||||
return (entry?.[1] || []).map(action => action.toLowerCase())
|
||||
}
|
||||
|
||||
function allows(actions: string[], markers: string[]) {
|
||||
return actions.some(action => markers.some(marker =>
|
||||
return actions.includes('*') || actions.some(action => markers.some(marker =>
|
||||
action === marker || action.endsWith(`_${marker}`) || action.includes(`.${marker}`)))
|
||||
}
|
||||
|
||||
|
|
@ -87,6 +111,8 @@ export function usePermissions() {
|
|||
}
|
||||
function canView(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const capabilityAccess = capabilityActions(apiPrefix, resourceKey)
|
||||
if (capabilityAccess !== null) return allows(capabilityAccess, ['view', 'list', 'retrieve', 'read'])
|
||||
const structuredAccess = structuredAllows(apiPrefix, resourceKey)
|
||||
if (structuredAccess !== null) return structuredAccess
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
|
|
@ -98,6 +124,8 @@ export function usePermissions() {
|
|||
}
|
||||
function canEdit(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const capabilityAccess = capabilityActions(apiPrefix, resourceKey)
|
||||
if (capabilityAccess !== null) return allows(capabilityAccess, ['change', 'update', 'partial_update', 'edit', 'write'])
|
||||
const structuredAccess = structuredAllows(apiPrefix, resourceKey, true)
|
||||
if (structuredAccess !== null) return structuredAccess
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
|
|
@ -112,6 +140,8 @@ export function usePermissions() {
|
|||
}
|
||||
function canCreate(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const capabilityAccess = capabilityActions(apiPrefix, resourceKey)
|
||||
if (capabilityAccess !== null) return allows(capabilityAccess, ['add', 'create'])
|
||||
const structuredAccess = structuredAllows(apiPrefix, resourceKey, true)
|
||||
if (structuredAccess !== null) return structuredAccess
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
|
|
@ -122,6 +152,8 @@ export function usePermissions() {
|
|||
}
|
||||
function canDelete(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const capabilityAccess = capabilityActions(apiPrefix, resourceKey)
|
||||
if (capabilityAccess !== null) return allows(capabilityAccess, ['delete', 'destroy', 'remove'])
|
||||
const structuredAccess = structuredAllows(apiPrefix, resourceKey, true)
|
||||
if (structuredAccess !== null) return structuredAccess
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
|
|
@ -130,5 +162,13 @@ export function usePermissions() {
|
|||
const matchingRoles = roleNames.value.filter(name => matchesModule(name, moduleKey, apiPrefix))
|
||||
return matchingRoles.some(name => DELETE_MARKERS.some(marker => name.includes(marker)))
|
||||
}
|
||||
return { isAdmin, canView, canCreate, canEdit, canDelete }
|
||||
function canNavigate(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value || !auth.navigations || !resourceKey) return true
|
||||
return auth.navigations.some(id => {
|
||||
const [navigationModule = '', navigationResource = ''] = id.toLowerCase().split(':')
|
||||
return (overlaps(navigationModule, moduleKey) || overlaps(navigationModule, apiPrefix))
|
||||
&& overlaps(navigationResource, resourceKey)
|
||||
})
|
||||
}
|
||||
return { isAdmin, canView, canNavigate, canCreate, canEdit, canDelete }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,16 @@
|
|||
export const menuGroups: Record<string, { title: string; icon: string }> = {
|
||||
staff: {
|
||||
title: 'Сотрудники/Подразделения',
|
||||
icon: 'mdi-account-group-outline',
|
||||
},
|
||||
holidays: {
|
||||
title: 'Праздники',
|
||||
icon: 'mdi-calendar-star',
|
||||
},
|
||||
parameters: {
|
||||
title: 'Параметры',
|
||||
icon: 'mdi-tune-variant',
|
||||
},
|
||||
requests: {
|
||||
title: 'Обращения',
|
||||
icon: 'mdi-inbox-arrow-down-outline',
|
||||
|
|
@ -15,4 +27,12 @@ export const menuGroups: Record<string, { title: string; icon: string }> = {
|
|||
title: 'Настройки',
|
||||
icon: 'mdi-cog-outline',
|
||||
},
|
||||
tasks: {
|
||||
title: 'Задачи',
|
||||
icon: 'mdi-clipboard-check-outline',
|
||||
},
|
||||
changes: {
|
||||
title: 'Изменения',
|
||||
icon: 'mdi-swap-horizontal-bold',
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { ModuleDefinition } from '~/types/api'
|
||||
|
||||
const resource = (key: string, title: string, readOnly = false, path = key, menuGroup?: string) =>
|
||||
({ key, title, path, readOnly, menuGroup })
|
||||
const resource = (key: string, title: string, readOnly = false, path = key, menuGroup?: string, accessKey?: string, hiddenInMenu = false, menuSubgroup?: string) =>
|
||||
({ key, title, path, readOnly, menuGroup, menuSubgroup, accessKey, hiddenInMenu })
|
||||
|
||||
export const modules: ModuleDefinition[] = [
|
||||
{ key: 'addresses', title: 'Адреса', icon: 'mdi-map-marker', apiPrefix: 'adr', resources: [
|
||||
|
|
@ -14,9 +14,11 @@ export const modules: ModuleDefinition[] = [
|
|||
resource('zonetypes', 'Типы зон', false, 'zone-types', 'settings'),
|
||||
] },
|
||||
{ key: 'crm', title: 'CRM', icon: 'mdi-account-group', apiPrefix: 'crm', resources: [
|
||||
resource('clients', 'Клиенты'), resource('contracts', 'Договора'),
|
||||
resource('categories', 'Категории', false, 'client-categories', 'settings'),
|
||||
resource('types', 'Типы', false, 'client-types', 'settings'),
|
||||
resource('clients', 'Клиенты'),
|
||||
resource('contracts', 'Договора'), resource('leads', 'Лиды'),
|
||||
resource('categories', 'Категории', false, 'client-categories', 'settings', undefined, true),
|
||||
resource('types', 'Типы', false, 'client-types', 'settings', undefined, true),
|
||||
{ ...resource('settings', 'Настройки', false, 'settings', 'settings'), accessKeys: ['categories', 'types'] },
|
||||
] },
|
||||
{ key: 'service', title: 'Сервисы', icon: 'mdi-room-service', apiPrefix: 'srv', resources: [
|
||||
resource('services', 'Сервисы'),
|
||||
|
|
@ -28,16 +30,14 @@ export const modules: ModuleDefinition[] = [
|
|||
] },
|
||||
{ key: 'requests', title: 'Обращения', icon: 'mdi-inbox-arrow-down', apiPrefix: 'req', resources: [
|
||||
resource('requests', 'Обращения'),
|
||||
resource('employees', 'Сотрудники', false, 'employees', 'employees'),
|
||||
resource('criticalities', 'Критичности', false, 'criticalities', 'settings'),
|
||||
resource('sourcetypes', 'Источники', false, 'source-types', 'settings'),
|
||||
resource('statuses', 'Статусы', false, 'statuses', 'settings'),
|
||||
resource('requestnotifies', 'Уведомления', false, 'requestnotifies', 'settings'),
|
||||
resource('requestnotifies', 'Уведомления', false, 'request-notifications', 'settings'),
|
||||
resource('settings', 'Настройки', false, 'settings', 'settings'),
|
||||
] },
|
||||
{ key: 'incidents', title: 'Инциденты', icon: 'mdi-alert-circle', apiPrefix: 'inc', resources: [
|
||||
resource('incidents', 'Инциденты'),
|
||||
resource('employees', 'Сотрудники', false, 'employees', 'employees'),
|
||||
resource('groups', 'Группы', false, 'groups', 'employees'),
|
||||
resource('categories', 'Категории', false, 'categories', 'settings'),
|
||||
resource('subcategories', 'Подкатегории', false, 'subcategories', 'settings'),
|
||||
|
|
@ -47,16 +47,29 @@ export const modules: ModuleDefinition[] = [
|
|||
resource('statuses', 'Статусы', false, 'statuses', 'settings'),
|
||||
resource('settings', 'Настройки', false, 'settings', 'settings'),
|
||||
] },
|
||||
{ key: 'tasks', title: 'Изменения/задачи', icon: 'mdi-clipboard-check-outline', apiPrefix: 'chn', resources: [
|
||||
resource('tasks', 'Задачи'),
|
||||
resource('changes', 'Изменения'),
|
||||
resource('approvals', 'На согласование', true, 'changes/pending-approval', undefined, 'changes'),
|
||||
resource('tasktransitions', 'Схема переходов', false, 'task-transitions', 'settings', undefined, false, 'changes'),
|
||||
resource('taskcategories', 'Категории задач', false, 'task-categories', 'settings', undefined, false, 'tasks'),
|
||||
resource('taskpriorities', 'Приоритеты задач', false, 'task-priorities', 'settings', undefined, false, 'tasks'),
|
||||
resource('taskstatuses', 'Статусы задач', true, 'task-statuses', 'settings', undefined, false, 'tasks'),
|
||||
resource('tasktypes', 'Типы задач', false, 'task-types', 'settings', undefined, false, 'tasks'),
|
||||
resource('changestatuses', 'Статусы изменений', true, 'change-statuses', 'settings', undefined, false, 'changes'),
|
||||
resource('changetypes', 'Типы изменений', false, 'change-types', 'settings', undefined, false, 'changes'),
|
||||
resource('settings', 'Общие параметры', false, 'settings', 'settings', undefined, true, 'tasks'),
|
||||
] },
|
||||
{ key: 'sla', title: 'SLA', icon: 'mdi-timer-outline', apiPrefix: 'sla', resources: [
|
||||
resource('requestagreements', 'SLA обращений', false, 'requestagreements', 'requests'),
|
||||
resource('incidentagreements', 'SLA инцидентов', false, 'incidentagreements', 'incidents'),
|
||||
resource('requeststatuses', 'Статусы обращений', true, 'requeststatuses', 'requests'),
|
||||
resource('incidentstatuses', 'Статусы инцидентов', true, 'incidentstatuses', 'incidents'),
|
||||
resource('scheduleweeks', 'Рабочие недели', false, 'scheduleweeks', 'settings'),
|
||||
resource('requestgraphs', 'Графики обращений', false, 'requestgraphs', 'requests'),
|
||||
resource('incidentgraphs', 'Графики инцидентов', false, 'incidentgraphs', 'incidents'),
|
||||
resource('requesthistcalcs', 'Расчёты обращений', true, 'requesthistcalcs', 'requests'),
|
||||
resource('incidenthistcalcs', 'Расчёты инцидентов', true, 'incidenthistcalcs', 'incidents'),
|
||||
resource('requestagreements', 'SLA обращений', false, 'request-agreements', 'requests'),
|
||||
resource('incidentagreements', 'SLA инцидентов', false, 'incident-agreements', 'incidents'),
|
||||
resource('requeststatuses', 'Статусы обращений', true, 'request-statuses', 'requests'),
|
||||
resource('incidentstatuses', 'Статусы инцидентов', true, 'incident-statuses', 'incidents'),
|
||||
resource('scheduleweeks', 'Рабочие недели', false, 'schedule-weeks', 'settings'),
|
||||
resource('requestgraphs', 'Графики обращений', false, 'request-graphs', 'requests'),
|
||||
resource('incidentgraphs', 'Графики инцидентов', false, 'incident-graphs', 'incidents'),
|
||||
resource('requesthistcalcs', 'Расчёты обращений', true, 'request-history-calculations', 'requests'),
|
||||
resource('incidenthistcalcs', 'Расчёты инцидентов', true, 'incident-history-calculations', 'incidents'),
|
||||
] },
|
||||
{ key: 'configuration-items', title: 'Configuration items', icon: 'mdi-vector-link', apiPrefix: 'cim', resources: [
|
||||
resource('cis', 'Конфигурационные единицы'),
|
||||
|
|
@ -66,13 +79,23 @@ export const modules: ModuleDefinition[] = [
|
|||
resource('manufacturers', 'Производители'), resource('models', 'Модели'),
|
||||
] },
|
||||
{ key: 'communications', title: 'Коммуникации', icon: 'mdi-message-processing-outline', apiPrefix: 'con', resources: [
|
||||
resource('parties', 'Контактные лица', false, 'persons'),
|
||||
resource('contactpoints', 'Контакты', false, 'contacts'),
|
||||
resource('settings', 'Настройки', false, 'settings', 'settings'),
|
||||
] },
|
||||
{ key: 'system', title: 'Система', icon: 'mdi-cog', apiPrefix: 'sys', resources: [
|
||||
resource('users', 'Пользователи'),
|
||||
resource('objects', 'Объекты'), resource('views', 'Представления'),
|
||||
resource('holidaygroups', 'Группы праздников', false, 'holiday-groups'), resource('holidayelements', 'Праздники'),
|
||||
resource('settings', 'Системные параметры'),
|
||||
resource('users', 'Пользователи', false, 'users', 'staff'),
|
||||
resource('employees', 'Сотрудники', false, 'employees', 'staff'),
|
||||
// Custom editor: generic ResourceCrud must not require a generated JSON schema for this resource.
|
||||
resource('accessprofiles', 'Профили и доступы', true, 'sysprofiles', 'staff', 'employee-access'),
|
||||
resource('departments', 'Подразделения', false, 'departments', 'staff'),
|
||||
resource('departmentstructure', 'Структура подразделений', true, 'departments/tree', 'staff', 'departments'),
|
||||
resource('objects', 'Объекты', false, 'objects', 'parameters'),
|
||||
resource('views', 'Представления', false, 'views', 'parameters'),
|
||||
resource('holidaygroups', 'Группы праздников', false, 'holiday-groups', 'holidays'),
|
||||
resource('holidays', 'Праздники', false, 'holidays', 'holidays'),
|
||||
resource('tags', 'Теги', false, 'tags', 'parameters'),
|
||||
resource('settings', 'Системные параметры', false, 'settings', 'parameters'),
|
||||
resource('module-settings', 'Настройки', false, 'module-settings', 'settings'),
|
||||
] },
|
||||
]
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -12,7 +12,10 @@ const permissions = usePermissions()
|
|||
const { t } = useUiText()
|
||||
const visibleModules = computed(() => modules.map(module => ({
|
||||
...module,
|
||||
resources: module.resources.filter(resource => permissions.canView(module.key, module.apiPrefix, resource.key)),
|
||||
resources: module.resources.filter(resource => !resource.hiddenInMenu
|
||||
&& (resource.accessKeys || [resource.accessKey || resource.key]).some(accessKey =>
|
||||
permissions.canView(module.key, module.apiPrefix, accessKey)
|
||||
&& permissions.canNavigate(module.key, module.apiPrefix, accessKey))),
|
||||
})).filter(module => module.resources.length > 0))
|
||||
const ungroupedResources = (resources: typeof modules[number]['resources']) =>
|
||||
resources.filter(resource => !resource.menuGroup)
|
||||
|
|
@ -21,6 +24,13 @@ const groupedResources = (resources: typeof modules[number]['resources']) =>
|
|||
resources.filter(resource => resource.menuGroup),
|
||||
resource => resource.menuGroup!,
|
||||
))
|
||||
const directGroupResources = (resources?: typeof modules[number]['resources']) =>
|
||||
(resources || []).filter(resource => !resource.menuSubgroup)
|
||||
const subgroupedResources = (resources?: typeof modules[number]['resources']) =>
|
||||
Object.entries(Object.groupBy(
|
||||
(resources || []).filter(resource => resource.menuSubgroup),
|
||||
resource => resource.menuSubgroup!,
|
||||
))
|
||||
|
||||
function toggleNavigation() {
|
||||
if (lgAndUp.value) rail.value = !rail.value
|
||||
|
|
@ -50,8 +60,18 @@ function toggleNavigation() {
|
|||
:prepend-icon="menuGroups[group]?.icon || 'mdi-folder-outline'"
|
||||
:title="menuGroups[group]?.title || group" />
|
||||
</template>
|
||||
<v-list-item v-for="item in items" :key="item.key"
|
||||
<v-list-item v-for="item in directGroupResources(items)" :key="item.key"
|
||||
:to="`/${module.key}/${item.key}`" :title="item.title" />
|
||||
<v-list-group v-for="[subgroup, subgroupItems] in subgroupedResources(items)"
|
||||
:key="subgroup" :value="`${module.key}-${group}-${subgroup}`">
|
||||
<template #activator="{ props }">
|
||||
<v-list-item v-bind="props"
|
||||
:prepend-icon="menuGroups[subgroup]?.icon || 'mdi-folder-outline'"
|
||||
:title="menuGroups[subgroup]?.title || subgroup" />
|
||||
</template>
|
||||
<v-list-item v-for="item in subgroupItems" :key="item.key"
|
||||
:to="`/${module.key}/${item.key}`" :title="item.title" />
|
||||
</v-list-group>
|
||||
</v-list-group>
|
||||
</v-list-group>
|
||||
</v-list>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
export default defineNuxtRouteMiddleware(async to => {
|
||||
const token = useCookie<string | null>('wanitil-token')
|
||||
if (!token.value && to.path !== '/login') return navigateTo('/login')
|
||||
if (token.value && to.path === '/login') return navigateTo('/')
|
||||
if (token.value) {
|
||||
try { await useAuthStore().restoreSession() }
|
||||
const auth = useAuthStore()
|
||||
try { await auth.restoreSession() }
|
||||
catch { if (to.path !== '/login') return navigateTo('/login') }
|
||||
if (auth.setupRequired && to.path !== '/login') return navigateTo('/login')
|
||||
if (!auth.setupRequired && to.path === '/login') return navigateTo('/')
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,7 +13,15 @@ export default defineNuxtConfig({
|
|||
},
|
||||
],
|
||||
build: { transpile: ['vuetify'] },
|
||||
vite: { vue: { template: { transformAssetUrls } } },
|
||||
vite: {
|
||||
vue: { template: { transformAssetUrls } },
|
||||
server: {
|
||||
watch: {
|
||||
usePolling: true,
|
||||
interval: 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
css: ['vuetify/styles', '@mdi/font/css/materialdesignicons.css', 'leaflet/dist/leaflet.css', '~/assets/main.css'],
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
|
|
@ -26,5 +34,7 @@ export default defineNuxtConfig({
|
|||
meta: [{ name: 'description', content: 'Система технической поддержки сотрудников' }],
|
||||
},
|
||||
},
|
||||
typescript: { strict: true, typeCheck: true },
|
||||
// vue-tsc is run explicitly via `npm run typecheck`; the bundled dev checker is
|
||||
// incompatible with the current Vue language-core versions and crashes the server.
|
||||
typescript: { strict: true, typeCheck: false },
|
||||
})
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@
|
|||
"nuxt": "3.12.4",
|
||||
"pinia": "2.1.7",
|
||||
"vite-plugin-vuetify": "2.0.3",
|
||||
"vue": "3.4.31",
|
||||
"vue": "3.5.40",
|
||||
"vuetify": "3.6.10",
|
||||
"yaml": "2.5.0"
|
||||
},
|
||||
|
|
@ -22,7 +22,7 @@
|
|||
"nuxi": "3.12.0",
|
||||
"typescript": "5.5.4",
|
||||
"vitest": "2.0.5",
|
||||
"vue-tsc": "2.0.29"
|
||||
"vue-tsc": "^2.1.10"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
|
@ -2435,27 +2435,27 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@volar/language-core": {
|
||||
"version": "2.4.28",
|
||||
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz",
|
||||
"integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==",
|
||||
"version": "2.4.15",
|
||||
"resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.15.tgz",
|
||||
"integrity": "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"@volar/source-map": "2.4.28"
|
||||
"@volar/source-map": "2.4.15"
|
||||
}
|
||||
},
|
||||
"node_modules/@volar/source-map": {
|
||||
"version": "2.4.28",
|
||||
"resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz",
|
||||
"integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==",
|
||||
"version": "2.4.15",
|
||||
"resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.15.tgz",
|
||||
"integrity": "sha512-CPbMWlUN6hVZJYGcU/GSoHu4EnCHiLaXI9n8c9la6RaI9W5JHX+NqG+GSQcB0JdC2FIBLdZJwGsfKyBB71VlTg==",
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/@volar/typescript": {
|
||||
"version": "2.4.28",
|
||||
"resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz",
|
||||
"integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==",
|
||||
"version": "2.4.15",
|
||||
"resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.15.tgz",
|
||||
"integrity": "sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"@volar/language-core": "2.4.28",
|
||||
"@volar/language-core": "2.4.15",
|
||||
"path-browserify": "^1.0.1",
|
||||
"vscode-uri": "^3.0.8"
|
||||
}
|
||||
|
|
@ -2668,16 +2668,16 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@vue/language-core": {
|
||||
"version": "2.0.29",
|
||||
"resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-2.0.29.tgz",
|
||||
"integrity": "sha512-o2qz9JPjhdoVj8D2+9bDXbaI4q2uZTHQA/dbyZT4Bj1FR9viZxDJnLcKVHfxdn6wsOzRgpqIzJEEmSSvgMvDTQ==",
|
||||
"version": "2.1.10",
|
||||
"resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-2.1.10.tgz",
|
||||
"integrity": "sha512-DAI289d0K3AB5TUG3xDp9OuQ71CnrujQwJrQnfuZDwo6eGNf0UoRlPuaVNO+Zrn65PC3j0oB2i7mNmVPggeGeQ==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"@volar/language-core": "~2.4.0-alpha.18",
|
||||
"@vue/compiler-dom": "^3.4.0",
|
||||
"@volar/language-core": "~2.4.8",
|
||||
"@vue/compiler-dom": "^3.5.0",
|
||||
"@vue/compiler-vue2": "^2.7.16",
|
||||
"@vue/shared": "^3.4.0",
|
||||
"computeds": "^0.0.1",
|
||||
"@vue/shared": "^3.5.0",
|
||||
"alien-signals": "^0.2.0",
|
||||
"minimatch": "^9.0.3",
|
||||
"muggle-string": "^0.4.1",
|
||||
"path-browserify": "^1.0.1"
|
||||
|
|
@ -2692,111 +2692,43 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@vue/reactivity": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.4.31.tgz",
|
||||
"integrity": "sha512-VGkTani8SOoVkZNds1PfJ/T1SlAIOf8E58PGAhIOUDYPC4GAmFA2u/E14TDAFcf3vVDKunc4QqCe/SHr8xC65Q==",
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.40.tgz",
|
||||
"integrity": "sha512-B7ot9UlUZOi1zbq61/LvE88ZLTV8IlajTdiZTAEiDQgrnIMIZoPr9kGw0Zw46ObW62O9+H/Be3kMbfb7kYPQZA==",
|
||||
"dependencies": {
|
||||
"@vue/shared": "3.4.31"
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/reactivity/node_modules/@vue/shared": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz",
|
||||
"integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA=="
|
||||
},
|
||||
"node_modules/@vue/runtime-core": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.4.31.tgz",
|
||||
"integrity": "sha512-LDkztxeUPazxG/p8c5JDDKPfkCDBkkiNLVNf7XZIUnJ+66GVGkP+TIh34+8LtPisZ+HMWl2zqhIw0xN5MwU1cw==",
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.40.tgz",
|
||||
"integrity": "sha512-KAZLweuZ6uUJPK1PMSQPgBU5gCjgrrfjUhSglmU9NhH+Zjepa8cnwSydPWDWHDwOgY4g3VcZ+PljbiHlURNCbw==",
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
"@vue/reactivity": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/runtime-core/node_modules/@vue/shared": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz",
|
||||
"integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA=="
|
||||
},
|
||||
"node_modules/@vue/runtime-dom": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.4.31.tgz",
|
||||
"integrity": "sha512-2Auws3mB7+lHhTFCg8E9ZWopA6Q6L455EcU7bzcQ4x6Dn4cCPuqj6S2oBZgN2a8vJRS/LSYYxwFFq2Hlx3Fsaw==",
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.40.tgz",
|
||||
"integrity": "sha512-ZfrX8ssZQds900L9pr8AuK05ddnMsR4MPMZr8cPN9GoqoPWcXLhjvvbIA2SMv+7a97sJ1vv9pj/zxK0Cq/eEFQ==",
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.4.31",
|
||||
"@vue/runtime-core": "3.4.31",
|
||||
"@vue/shared": "3.4.31",
|
||||
"csstype": "^3.1.3"
|
||||
"@vue/reactivity": "3.5.40",
|
||||
"@vue/runtime-core": "3.5.40",
|
||||
"@vue/shared": "3.5.40",
|
||||
"csstype": "^3.2.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/runtime-dom/node_modules/@vue/shared": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz",
|
||||
"integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA=="
|
||||
},
|
||||
"node_modules/@vue/server-renderer": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.4.31.tgz",
|
||||
"integrity": "sha512-D5BLbdvrlR9PE3by9GaUp1gQXlCNadIZytMIb8H2h3FMWJd4oUfkUTEH2wAr3qxoRz25uxbTcbqd3WKlm9EHQA==",
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.40.tgz",
|
||||
"integrity": "sha512-XNJym9WpevhTVt1HuwOrCRJ5Q+9z4BjTMrDtjTrvx74SmUll8spNTw6whWJa9mEkO4PKn5TihI/bm/8ds2QVJw==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-ssr": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "3.4.31"
|
||||
"@vue/compiler-ssr": "3.5.40",
|
||||
"@vue/runtime-dom": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/@vue/compiler-core": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.31.tgz",
|
||||
"integrity": "sha512-skOiodXWTV3DxfDhB4rOf3OGalpITLlgCeOwb+Y9GJpfQ8ErigdBUHomBzvG78JoVE8MJoQsb+qhZiHfKeNeEg==",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.24.7",
|
||||
"@vue/shared": "3.4.31",
|
||||
"entities": "^4.5.0",
|
||||
"estree-walker": "^2.0.2",
|
||||
"source-map-js": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/@vue/compiler-dom": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.31.tgz",
|
||||
"integrity": "sha512-wK424WMXsG1IGMyDGyLqB+TbmEBFM78hIsOJ9QwUVLGrcSk0ak6zYty7Pj8ftm7nEtdU/DGQxAXp0/lM/2cEpQ==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-core": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/@vue/compiler-ssr": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.31.tgz",
|
||||
"integrity": "sha512-RtefmITAje3fJ8FSg1gwgDhdKhZVntIVbwupdyZDSifZTRMiWxWehAOTCc8/KZDnBOcYQ4/9VWxsTbd3wT0hAA==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/@vue/shared": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz",
|
||||
"integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA=="
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/entities": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
|
||||
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@vue/server-renderer/node_modules/estree-walker": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="
|
||||
},
|
||||
"node_modules/@vue/shared": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.40.tgz",
|
||||
|
|
@ -2844,6 +2776,12 @@
|
|||
"acorn": "^8"
|
||||
}
|
||||
},
|
||||
"node_modules/alien-signals": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-0.2.2.tgz",
|
||||
"integrity": "sha512-cZIRkbERILsBOXTQmMrxc9hgpxglstn69zm+F1ARf4aPAzdAFYd6sBq87ErO0Fj3DV94tglcyHG5kQz9nDC/8A==",
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/ansi-colors": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz",
|
||||
|
|
@ -3579,12 +3517,6 @@
|
|||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/computeds": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/computeds/-/computeds-0.0.1.tgz",
|
||||
"integrity": "sha512-7CEBgcMjVmitjYo5q8JTJVra6X5mQ20uTThdK+0kR7UEaDrAWEQcRiBtWJzga4eRpP6afNwwLsX2SET2JhVB1Q==",
|
||||
"devOptional": true
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
|
|
@ -6588,44 +6520,6 @@
|
|||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/@vue/reactivity": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.40.tgz",
|
||||
"integrity": "sha512-B7ot9UlUZOi1zbq61/LvE88ZLTV8IlajTdiZTAEiDQgrnIMIZoPr9kGw0Zw46ObW62O9+H/Be3kMbfb7kYPQZA==",
|
||||
"dependencies": {
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/@vue/runtime-core": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.40.tgz",
|
||||
"integrity": "sha512-KAZLweuZ6uUJPK1PMSQPgBU5gCjgrrfjUhSglmU9NhH+Zjepa8cnwSydPWDWHDwOgY4g3VcZ+PljbiHlURNCbw==",
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/@vue/runtime-dom": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.40.tgz",
|
||||
"integrity": "sha512-ZfrX8ssZQds900L9pr8AuK05ddnMsR4MPMZr8cPN9GoqoPWcXLhjvvbIA2SMv+7a97sJ1vv9pj/zxK0Cq/eEFQ==",
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.5.40",
|
||||
"@vue/runtime-core": "3.5.40",
|
||||
"@vue/shared": "3.5.40",
|
||||
"csstype": "^3.2.3"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/@vue/server-renderer": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.40.tgz",
|
||||
"integrity": "sha512-XNJym9WpevhTVt1HuwOrCRJ5Q+9z4BjTMrDtjTrvx74SmUll8spNTw6whWJa9mEkO4PKn5TihI/bm/8ds2QVJw==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-ssr": "3.5.40",
|
||||
"@vue/runtime-dom": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/abbrev": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
|
||||
|
|
@ -7499,26 +7393,6 @@
|
|||
"node": ">=18.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/vue": {
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.40.tgz",
|
||||
"integrity": "sha512-+8PJ4SJXdn/cHGImF4CKdxlWHIN5Dkt7DoufRREM6h6uVCx2m7QxgcEQmmzyOK8A9mcafg7sFbJFYsdFVubTig==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.40",
|
||||
"@vue/compiler-sfc": "3.5.40",
|
||||
"@vue/runtime-dom": "3.5.40",
|
||||
"@vue/server-renderer": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/nuxt/node_modules/vue-router": {
|
||||
"version": "4.6.4",
|
||||
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz",
|
||||
|
|
@ -10474,15 +10348,15 @@
|
|||
"integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="
|
||||
},
|
||||
"node_modules/vue": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.4.31.tgz",
|
||||
"integrity": "sha512-njqRrOy7W3YLAlVqSKpBebtZpDVg21FPoaq1I7f/+qqBThK9ChAIjkRWgeP6Eat+8C+iia4P3OYqpATP21BCoQ==",
|
||||
"version": "3.5.40",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.40.tgz",
|
||||
"integrity": "sha512-+8PJ4SJXdn/cHGImF4CKdxlWHIN5Dkt7DoufRREM6h6uVCx2m7QxgcEQmmzyOK8A9mcafg7sFbJFYsdFVubTig==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.4.31",
|
||||
"@vue/compiler-sfc": "3.4.31",
|
||||
"@vue/runtime-dom": "3.4.31",
|
||||
"@vue/server-renderer": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
"@vue/compiler-dom": "3.5.40",
|
||||
"@vue/compiler-sfc": "3.5.40",
|
||||
"@vue/runtime-dom": "3.5.40",
|
||||
"@vue/server-renderer": "3.5.40",
|
||||
"@vue/shared": "3.5.40"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "*"
|
||||
|
|
@ -10507,13 +10381,13 @@
|
|||
"integrity": "sha512-RutnB7X8c5hjq39NceArgXg28WZtZpGc3+J16ljMiYnFhKvd8hITxSWQSQ5bvldxMDU6gG5mkxl1MTQLXckVSQ=="
|
||||
},
|
||||
"node_modules/vue-tsc": {
|
||||
"version": "2.0.29",
|
||||
"resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-2.0.29.tgz",
|
||||
"integrity": "sha512-MHhsfyxO3mYShZCGYNziSbc63x7cQ5g9kvijV7dRe1TTXBRLxXyL0FnXWpUF1xII2mJ86mwYpYsUmMwkmerq7Q==",
|
||||
"version": "2.1.10",
|
||||
"resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-2.1.10.tgz",
|
||||
"integrity": "sha512-RBNSfaaRHcN5uqVqJSZh++Gy/YUzryuv9u1aFWhsammDJXNtUiJMNoJ747lZcQ68wUQFx6E73y4FY3D8E7FGMA==",
|
||||
"devOptional": true,
|
||||
"dependencies": {
|
||||
"@volar/typescript": "~2.4.0-alpha.18",
|
||||
"@vue/language-core": "2.0.29",
|
||||
"@volar/typescript": "~2.4.8",
|
||||
"@vue/language-core": "2.1.10",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"bin": {
|
||||
|
|
@ -10523,73 +10397,6 @@
|
|||
"typescript": ">=5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/@vue/compiler-core": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.31.tgz",
|
||||
"integrity": "sha512-skOiodXWTV3DxfDhB4rOf3OGalpITLlgCeOwb+Y9GJpfQ8ErigdBUHomBzvG78JoVE8MJoQsb+qhZiHfKeNeEg==",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.24.7",
|
||||
"@vue/shared": "3.4.31",
|
||||
"entities": "^4.5.0",
|
||||
"estree-walker": "^2.0.2",
|
||||
"source-map-js": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/@vue/compiler-dom": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.31.tgz",
|
||||
"integrity": "sha512-wK424WMXsG1IGMyDGyLqB+TbmEBFM78hIsOJ9QwUVLGrcSk0ak6zYty7Pj8ftm7nEtdU/DGQxAXp0/lM/2cEpQ==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-core": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/@vue/compiler-sfc": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.31.tgz",
|
||||
"integrity": "sha512-einJxqEw8IIJxzmnxmJBuK2usI+lJonl53foq+9etB2HAzlPjAS/wa7r0uUpXw5ByX3/0uswVSrjNb17vJm1kQ==",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.24.7",
|
||||
"@vue/compiler-core": "3.4.31",
|
||||
"@vue/compiler-dom": "3.4.31",
|
||||
"@vue/compiler-ssr": "3.4.31",
|
||||
"@vue/shared": "3.4.31",
|
||||
"estree-walker": "^2.0.2",
|
||||
"magic-string": "^0.30.10",
|
||||
"postcss": "^8.4.38",
|
||||
"source-map-js": "^1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/@vue/compiler-ssr": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.31.tgz",
|
||||
"integrity": "sha512-RtefmITAje3fJ8FSg1gwgDhdKhZVntIVbwupdyZDSifZTRMiWxWehAOTCc8/KZDnBOcYQ4/9VWxsTbd3wT0hAA==",
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.4.31",
|
||||
"@vue/shared": "3.4.31"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/@vue/shared": {
|
||||
"version": "3.4.31",
|
||||
"resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.31.tgz",
|
||||
"integrity": "sha512-Yp3wtJk//8cO4NItOPpi3QkLExAr/aLBGZMmTtW9WpdwBCJpRM6zj9WgWktXAl8IDIozwNMByT45JP3tO3ACWA=="
|
||||
},
|
||||
"node_modules/vue/node_modules/entities": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
|
||||
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/vue/node_modules/estree-walker": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
|
||||
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="
|
||||
},
|
||||
"node_modules/vuetify": {
|
||||
"version": "3.6.10",
|
||||
"resolved": "https://registry.npmjs.org/vuetify/-/vuetify-3.6.10.tgz",
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nuxt dev",
|
||||
"dev": "CHOKIDAR_USEPOLLING=true nuxt dev",
|
||||
"build": "nuxt build",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
|
|
@ -18,7 +18,7 @@
|
|||
"nuxt": "3.12.4",
|
||||
"pinia": "2.1.7",
|
||||
"vite-plugin-vuetify": "2.0.3",
|
||||
"vue": "3.4.31",
|
||||
"vue": "3.5.40",
|
||||
"vuetify": "3.6.10",
|
||||
"yaml": "2.5.0"
|
||||
},
|
||||
|
|
@ -28,7 +28,7 @@
|
|||
"nuxi": "3.12.0",
|
||||
"typescript": "5.5.4",
|
||||
"vitest": "2.0.5",
|
||||
"vue-tsc": "2.0.29"
|
||||
"vue-tsc": "^2.1.10"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,10 @@ const moduleDefinition = computed(() => getModule(String(route.params.module)))
|
|||
const resourceDefinition = computed(() => getResource(String(route.params.module), String(route.params.resource)))
|
||||
const permissions = usePermissions()
|
||||
if (!moduleDefinition.value || !resourceDefinition.value) throw createError({ statusCode: 404, statusMessage: 'Раздел не найден' })
|
||||
if (!permissions.canView(moduleDefinition.value.key, moduleDefinition.value.apiPrefix, resourceDefinition.value.key)) throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
if (!(resourceDefinition.value.accessKeys || [resourceDefinition.value.accessKey || resourceDefinition.value.key])
|
||||
.some(accessKey => permissions.canView(
|
||||
moduleDefinition.value!.key, moduleDefinition.value!.apiPrefix, accessKey,
|
||||
))) throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
useHead({ title: `${resourceDefinition.value.title} · WANITIL` })
|
||||
const settingsSectionKey = computed(() => {
|
||||
if (resourceDefinition.value?.key === 'module-settings' && moduleDefinition.value?.key === 'system') return 'sys'
|
||||
|
|
@ -15,7 +18,8 @@ const settingsSectionKey = computed(() => {
|
|||
requests: 'req',
|
||||
incidents: 'inc',
|
||||
communications: 'con',
|
||||
} as const)[moduleDefinition.value?.key as 'service' | 'requests' | 'incidents' | 'communications'] || null
|
||||
tasks: 'chn',
|
||||
} as const)[moduleDefinition.value?.key as 'service' | 'requests' | 'incidents' | 'communications' | 'tasks'] || null
|
||||
})
|
||||
const settingsReadonly = computed(() =>
|
||||
!permissions.canEdit(
|
||||
|
|
@ -30,6 +34,10 @@ const settingsReadonly = computed(() =>
|
|||
Назад к разделам
|
||||
</v-btn>
|
||||
</div>
|
||||
<ModuleSettings v-if="settingsSectionKey" :section-key="settingsSectionKey" :readonly="settingsReadonly" />
|
||||
<DepartmentStructure v-if="resourceDefinition!.key === 'departmentstructure'" />
|
||||
<ChangeApprovals v-else-if="moduleDefinition!.key === 'tasks' && resourceDefinition!.key === 'approvals'" />
|
||||
<AccessManagement v-else-if="moduleDefinition!.key === 'system' && resourceDefinition!.key === 'accessprofiles'" />
|
||||
<CrmSettings v-else-if="moduleDefinition!.key === 'crm' && resourceDefinition!.key === 'settings'" />
|
||||
<ModuleSettings v-else-if="settingsSectionKey" :section-key="settingsSectionKey" :readonly="settingsReadonly" />
|
||||
<ResourceCrud v-else :module="moduleDefinition!" :resource="resourceDefinition!" />
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -6,11 +6,10 @@ const moduleDefinition = computed(() => getModule(String(route.params.module)))
|
|||
if (!moduleDefinition.value) throw createError({ statusCode: 404, statusMessage: 'Модуль не найден' })
|
||||
const permissions = usePermissions()
|
||||
const resources = computed(() => moduleDefinition.value!.resources
|
||||
.filter(resource => permissions.canView(
|
||||
moduleDefinition.value!.key,
|
||||
moduleDefinition.value!.apiPrefix,
|
||||
resource.key,
|
||||
)))
|
||||
.filter(resource => !resource.hiddenInMenu
|
||||
&& (resource.accessKeys || [resource.accessKey || resource.key]).some(accessKey =>
|
||||
permissions.canView(moduleDefinition.value!.key, moduleDefinition.value!.apiPrefix, accessKey)
|
||||
&& permissions.canNavigate(moduleDefinition.value!.key, moduleDefinition.value!.apiPrefix, accessKey))))
|
||||
if (!resources.value.length) throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
const mainResources = computed(() => resources.value.filter(resource => !resource.menuGroup))
|
||||
const groupedResources = computed(() => Object.entries(Object.groupBy(
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ const permissions = usePermissions()
|
|||
const { t } = useUiText()
|
||||
const visibleModules = computed(() => modules.map(module => ({
|
||||
...module,
|
||||
resources: module.resources.filter(resource => permissions.canView(module.key, module.apiPrefix, resource.key)),
|
||||
resources: module.resources.filter(resource => permissions.canView(
|
||||
module.key, module.apiPrefix, resource.accessKey || resource.key,
|
||||
) && permissions.canNavigate(module.key, module.apiPrefix, resource.accessKey || resource.key)),
|
||||
})).filter(module => module.resources.length > 0))
|
||||
</script>
|
||||
<template><div class="page-shell"><h1 class="text-h4 font-weight-bold mb-2">{{ t('workspace') }}</h1>
|
||||
|
|
|
|||
|
|
@ -5,17 +5,41 @@ const route = useRoute()
|
|||
const username = ref('')
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
const selectedSetupMode = ref<'empty' | 'basic' | 'demo'>('basic')
|
||||
const setupLoading = ref(false)
|
||||
|
||||
const setupModes = [
|
||||
{ value: 'empty' as const, title: 'Чистая установка', description: 'Без дополнительных справочников и демонстрационных данных' },
|
||||
{ value: 'basic' as const, title: 'Базовые справочники', description: 'Установка с базовым набором справочников' },
|
||||
{ value: 'demo' as const, title: 'Демонстрационные данные', description: 'Базовые справочники и демонстрационные данные' },
|
||||
]
|
||||
|
||||
async function redirectAfterLogin() {
|
||||
const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/')
|
||||
? route.query.redirect
|
||||
: '/'
|
||||
await navigateTo(redirect)
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
try {
|
||||
await auth.login(username.value, password.value)
|
||||
const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/')
|
||||
? route.query.redirect
|
||||
: '/'
|
||||
await navigateTo(redirect)
|
||||
const ready = await auth.login(username.value, password.value)
|
||||
if (ready) await redirectAfterLogin()
|
||||
}
|
||||
catch (e: any) { error.value = e.message || 'Не удалось войти' }
|
||||
}
|
||||
|
||||
async function finishSetup() {
|
||||
error.value = ''
|
||||
setupLoading.value = true
|
||||
try {
|
||||
await auth.completeSetup(selectedSetupMode.value)
|
||||
await redirectAfterLogin()
|
||||
}
|
||||
catch (e: any) { error.value = e.message || 'Не удалось завершить установку' }
|
||||
finally { setupLoading.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -29,4 +53,25 @@ async function submit() {
|
|||
<v-btn type="submit" color="primary" block size="large" :loading="auth.loading">Войти</v-btn>
|
||||
</v-form>
|
||||
</v-card>
|
||||
|
||||
<v-dialog :model-value="auth.setupRequired" persistent max-width="600">
|
||||
<v-card>
|
||||
<v-card-title class="pt-6 px-6">Завершение установки</v-card-title>
|
||||
<v-card-subtitle class="px-6">Выберите набор начальных данных</v-card-subtitle>
|
||||
<v-card-text>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-radio-group v-model="selectedSetupMode" hide-details>
|
||||
<v-radio v-for="mode in setupModes" :key="mode.value" :value="mode.value" class="mb-2">
|
||||
<template #label>
|
||||
<div><div class="font-weight-medium">{{ mode.title }}</div><div class="text-body-2 text-medium-emphasis">{{ mode.description }}</div></div>
|
||||
</template>
|
||||
</v-radio>
|
||||
</v-radio-group>
|
||||
</v-card-text>
|
||||
<v-card-actions class="px-6 pb-6">
|
||||
<v-spacer />
|
||||
<v-btn color="primary" variant="flat" :loading="setupLoading" @click="finishSetup">Завершить установку</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -7,7 +7,14 @@ const { language } = useUiPreferences()
|
|||
const saving = ref(false)
|
||||
const saved = ref(false)
|
||||
const error = ref('')
|
||||
const passwordError = ref('')
|
||||
const changingPassword = ref(false)
|
||||
const oldPassword = ref('')
|
||||
const newPassword = ref('')
|
||||
const passwordConfirmation = ref('')
|
||||
const passwordDialog = ref(false)
|
||||
const form = reactive<Partial<UserProfile>>({})
|
||||
const { request } = useApi()
|
||||
const isEnglish = computed(() => language.value === 'en')
|
||||
const themeColorOptions = computed(() => getThemeColorOptions(isEnglish.value ? 'en' : 'ru'))
|
||||
const languages = [
|
||||
|
|
@ -28,13 +35,36 @@ async function save() {
|
|||
saving.value = true; error.value = ''
|
||||
try {
|
||||
await auth.updateProfile({
|
||||
lang: form.lang, status: form.status, timezone: form.timezone,
|
||||
lang: form.lang, timezone: form.timezone,
|
||||
theme_is_light: form.theme_is_light, theme_color: form.theme_color,
|
||||
})
|
||||
saved.value = true
|
||||
} catch (e: any) { error.value = e.message || 'Не удалось сохранить профиль' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
async function changePassword() {
|
||||
if (!oldPassword.value || newPassword.value.length < 8
|
||||
|| newPassword.value !== passwordConfirmation.value) return
|
||||
changingPassword.value = true
|
||||
passwordError.value = ''
|
||||
try {
|
||||
await request('/main/sys/users/me/updatepassword/', {
|
||||
method: 'POST',
|
||||
body: { oldpassword: oldPassword.value, password: newPassword.value },
|
||||
})
|
||||
oldPassword.value = ''
|
||||
newPassword.value = ''
|
||||
passwordConfirmation.value = ''
|
||||
passwordDialog.value = false
|
||||
await auth.logout()
|
||||
} catch (e: any) {
|
||||
passwordError.value = e.message || (isEnglish.value
|
||||
? 'Failed to change password'
|
||||
: 'Не удалось изменить пароль')
|
||||
} finally {
|
||||
changingPassword.value = false
|
||||
}
|
||||
}
|
||||
function exitProfile() { return navigateTo('/') }
|
||||
</script>
|
||||
|
||||
|
|
@ -69,6 +99,10 @@ function exitProfile() { return navigateTo('/') }
|
|||
<h2 class="text-h6 mb-4">{{ isEnglish ? 'Account' : 'Учётная запись' }}</h2>
|
||||
<v-list density="compact"><v-list-item prepend-icon="mdi-account" :title="auth.user?.name || auth.user?.username" :subtitle="auth.user?.username" />
|
||||
<v-list-item prepend-icon="mdi-email-outline" :title="auth.user?.email || '—'" /></v-list>
|
||||
<v-btn block class="mt-4" color="primary" variant="tonal" prepend-icon="mdi-lock-reset"
|
||||
@click="passwordDialog = true">
|
||||
{{ isEnglish ? 'Change password' : 'Сменить пароль' }}
|
||||
</v-btn>
|
||||
</v-card><v-card class="pa-6"><h2 class="text-h6 mb-3">{{ isEnglish ? 'Session roles' : 'Роли сессии' }}</h2>
|
||||
<v-chip v-for="role in auth.roles" :key="role.id" class="ma-1" color="primary" variant="tonal">{{ role.name }}</v-chip>
|
||||
<p v-if="!auth.roles.length" class="text-medium-emphasis">{{ isEnglish ? 'No roles assigned' : 'Роли не назначены' }}</p>
|
||||
|
|
@ -77,5 +111,50 @@ function exitProfile() { return navigateTo('/') }
|
|||
<v-chip v-for="object in auth.allowedObjects" :key="object.id" class="ma-1" size="small" variant="outlined">{{ object.name }}</v-chip>
|
||||
</v-card></v-col>
|
||||
</v-row>
|
||||
<v-dialog v-model="passwordDialog" max-width="520">
|
||||
<v-card>
|
||||
<v-card-title class="d-flex align-center ga-2 px-6 py-4">
|
||||
<v-icon icon="mdi-lock-reset" />
|
||||
<span>{{ isEnglish ? 'Change password' : 'Смена пароля' }}</span>
|
||||
<v-spacer />
|
||||
<v-btn icon="mdi-close" variant="text" :disabled="changingPassword"
|
||||
:aria-label="isEnglish ? 'Close' : 'Закрыть'" @click="passwordDialog = false" />
|
||||
</v-card-title>
|
||||
<v-divider />
|
||||
<v-card-text class="px-6 pt-5">
|
||||
<v-alert v-if="passwordError" type="error" variant="tonal" class="mb-4">
|
||||
{{ passwordError }}
|
||||
</v-alert>
|
||||
<v-form @submit.prevent="changePassword">
|
||||
<v-text-field v-model="oldPassword"
|
||||
:label="isEnglish ? 'Current password' : 'Текущий пароль'"
|
||||
type="password" autocomplete="current-password" required />
|
||||
<v-text-field v-model="newPassword"
|
||||
:label="isEnglish ? 'New password' : 'Новый пароль'"
|
||||
type="password" autocomplete="new-password" required
|
||||
:rules="[value => value?.length >= 8 || (isEnglish ? 'At least 8 characters' : 'Минимум 8 символов')]" />
|
||||
<v-text-field v-model="passwordConfirmation"
|
||||
:label="isEnglish ? 'Confirm new password' : 'Подтверждение нового пароля'"
|
||||
type="password" autocomplete="new-password" required
|
||||
:rules="[value => value === newPassword || (isEnglish ? 'Passwords do not match' : 'Пароли не совпадают')]" />
|
||||
<p class="text-caption text-medium-emphasis mb-0">
|
||||
{{ isEnglish
|
||||
? 'After changing the password, sign in again.'
|
||||
: 'После смены пароля потребуется войти снова.' }}
|
||||
</p>
|
||||
<div class="d-flex justify-end ga-2 mt-5">
|
||||
<v-btn variant="text" :disabled="changingPassword" @click="passwordDialog = false">
|
||||
{{ isEnglish ? 'Cancel' : 'Отмена' }}
|
||||
</v-btn>
|
||||
<v-btn type="submit" color="primary" prepend-icon="mdi-lock-reset"
|
||||
:loading="changingPassword"
|
||||
:disabled="!oldPassword || newPassword.length < 8 || newPassword !== passwordConfirmation">
|
||||
{{ isEnglish ? 'Change password' : 'Изменить пароль' }}
|
||||
</v-btn>
|
||||
</div>
|
||||
</v-form>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
<script setup lang="ts">
|
||||
const permissions = usePermissions()
|
||||
|
||||
if (!permissions.canView('system', 'sys', 'employee-access')) {
|
||||
throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
}
|
||||
|
||||
useHead({ title: 'Профили и доступы · WANITIL' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell">
|
||||
<v-btn to="/system" prepend-icon="mdi-arrow-left" variant="text" class="mb-3">
|
||||
Назад к разделам
|
||||
</v-btn>
|
||||
</div>
|
||||
<AccessManagement />
|
||||
</template>
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
import type { ManagementObject, PermissionsResponse, SessionUser, UserManagement, UserProfile, UserRole } from '~/types/api'
|
||||
import type { CapabilitiesResponse, ManagementObject, PermissionsResponse, SessionUser, UserManagement, UserProfile, UserRole } from '~/types/api'
|
||||
import { normalizeThemeColor } from '~/config/theme-colors'
|
||||
|
||||
interface LoginResponse { token?: string; expiry?: string }
|
||||
interface SetupStatusResponse { status: 'waiting' | 'completed' }
|
||||
type SetupMode = 'empty' | 'basic' | 'demo'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const { request, token } = useApi()
|
||||
|
|
@ -10,13 +12,37 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
const roles = ref<UserRole[]>([])
|
||||
const allowedObjects = ref<ManagementObject[]>([])
|
||||
const permissions = ref<Record<string, string[]> | null>(null)
|
||||
const navigations = ref<string[] | null>(null)
|
||||
const capabilities = ref<CapabilitiesResponse | null>(null)
|
||||
const setupRequired = ref(false)
|
||||
const loading = ref(false)
|
||||
const initialized = ref(false)
|
||||
const authenticated = computed(() => Boolean(token.value))
|
||||
|
||||
async function checkSetupForAdmin(current: SessionUser) {
|
||||
if (current.username.toLowerCase() !== 'admin') return false
|
||||
|
||||
const setup = await request<SetupStatusResponse>('/main/sys/settings/setup-status/')
|
||||
return setup.status === 'waiting'
|
||||
}
|
||||
|
||||
async function completeSetup(mode: SetupMode) {
|
||||
if (!setupRequired.value || user.value?.username.toLowerCase() !== 'admin') {
|
||||
throw new Error('Завершение установки сейчас недоступно')
|
||||
}
|
||||
await request<SetupStatusResponse>('/main/sys/settings/complete-setup/', {
|
||||
method: 'POST',
|
||||
body: { mode, lang: 'ru' },
|
||||
})
|
||||
setupRequired.value = false
|
||||
await loadSession()
|
||||
}
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
loading.value = true
|
||||
token.value = null
|
||||
user.value = null
|
||||
setupRequired.value = false
|
||||
initialized.value = false
|
||||
try {
|
||||
const result = await request<LoginResponse>('/login/', {
|
||||
|
|
@ -26,34 +52,43 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
})
|
||||
if (!result.token) throw new Error('API не вернул токен авторизации')
|
||||
token.value = result.token
|
||||
try { await loadSession() }
|
||||
try { return await loadSession() }
|
||||
catch (error) { token.value = null; throw error }
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
|
||||
async function loadSession() {
|
||||
const [current, permissionResult] = await Promise.all([
|
||||
request<SessionUser>('/me/'),
|
||||
const current = await request<SessionUser>('/me/')
|
||||
user.value = current
|
||||
setupRequired.value = await checkSetupForAdmin(current)
|
||||
if (setupRequired.value) return false
|
||||
|
||||
const [permissionResult, capabilityResult, employeeResult] = await Promise.all([
|
||||
request<PermissionsResponse>('/me/permissions/').catch(() => null),
|
||||
request<CapabilitiesResponse>('/me/capabilities/').catch(() => null),
|
||||
request<UserProfile>('/main/sys/employees/me/').catch(() => current.sys_employee || current.sys_user_profile || null),
|
||||
])
|
||||
user.value = current
|
||||
roles.value = current.sys_role || []
|
||||
permissions.value = permissionResult?.resources || null
|
||||
capabilities.value = capabilityResult
|
||||
const managementIds = [...new Set(roles.value.map(role => role.sys_managment?.id).filter((id): id is number => typeof id === 'number'))]
|
||||
const managementResults = await Promise.allSettled(
|
||||
managementIds.map(id => request<UserManagement>(`/main/sys/managments/${id}/`)),
|
||||
managementIds.map(id => request<UserManagement>(`/main/sys/modules/${id}/`)),
|
||||
)
|
||||
const objects = managementResults.flatMap(result => result.status === 'fulfilled' ? result.value.sys_object || [] : [])
|
||||
allowedObjects.value = [...new Map(objects.map(object => [object.id, object])).values()]
|
||||
profile.value = current.sys_user_profile || null
|
||||
profile.value = employeeResult
|
||||
navigations.value = Array.isArray(capabilityResult?.navigations) ? capabilityResult.navigations : null
|
||||
initialized.value = true
|
||||
return true
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (!token.value || initialized.value) return
|
||||
loading.value = true
|
||||
try { await loadSession() }
|
||||
catch (error) { token.value = null; user.value = null; profile.value = null; roles.value = []; allowedObjects.value = []; permissions.value = null; throw error }
|
||||
catch (error) { token.value = null; user.value = null; profile.value = null; roles.value = []; allowedObjects.value = []; permissions.value = null; navigations.value = null; capabilities.value = null; setupRequired.value = false; throw error }
|
||||
finally { loading.value = false; initialized.value = true }
|
||||
}
|
||||
|
||||
|
|
@ -65,19 +100,19 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
? { theme_color: normalizeThemeColor(changes.theme_color) }
|
||||
: {}),
|
||||
}
|
||||
const result = await request<UserProfile | SessionUser>('/main/sys/users/me/updateprofile/', {
|
||||
method: 'POST',
|
||||
const result = await request<UserProfile | SessionUser>('/main/sys/employees/me/', {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
})
|
||||
const returnedUser = 'sys_user_profile' in result ? result : null
|
||||
const returnedProfile = returnedUser?.sys_user_profile || result as UserProfile
|
||||
const returnedUser = 'username' in result ? result as SessionUser : null
|
||||
const returnedProfile = returnedUser?.sys_employee || returnedUser?.sys_user_profile || result as UserProfile
|
||||
profile.value = {
|
||||
...returnedProfile,
|
||||
theme_color: normalizeThemeColor(returnedProfile.theme_color),
|
||||
}
|
||||
user.value = returnedUser
|
||||
? { ...user.value, ...returnedUser, sys_user_profile: profile.value }
|
||||
: { ...user.value, sys_user_profile: profile.value }
|
||||
? { ...user.value, ...returnedUser, sys_employee: profile.value }
|
||||
: { ...user.value, sys_employee: profile.value }
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
|
|
@ -88,10 +123,13 @@ export const useAuthStore = defineStore('auth', () => {
|
|||
roles.value = []
|
||||
allowedObjects.value = []
|
||||
permissions.value = null
|
||||
navigations.value = null
|
||||
capabilities.value = null
|
||||
setupRequired.value = false
|
||||
initialized.value = false
|
||||
await navigateTo('/login')
|
||||
}
|
||||
}
|
||||
|
||||
return { user, profile, roles, allowedObjects, permissions, loading, initialized, authenticated, login, logout, restoreSession, updateProfile }
|
||||
return { user, profile, roles, allowedObjects, permissions, navigations, capabilities, setupRequired, loading, initialized, authenticated, login, completeSetup, logout, restoreSession, updateProfile }
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,20 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { accessIds, accessModule, accessOption, belongsToModule } from '../utils/access'
|
||||
|
||||
describe('access helpers', () => {
|
||||
it('normalizes relation arrays returned as ids or objects', () => {
|
||||
expect(accessIds(['crm:client:view', { id: 'crm:lead:view' }, { code: 'crm:contract:view' }]))
|
||||
.toEqual(['crm:client:view', 'crm:lead:view', 'crm:contract:view'])
|
||||
})
|
||||
|
||||
it('validates that access identifiers belong to a module', () => {
|
||||
expect(accessModule('crm:client:view')).toBe('crm')
|
||||
expect(belongsToModule('crm:client', 'crm')).toBe(true)
|
||||
expect(belongsToModule('sys:employee', 'crm')).toBe(false)
|
||||
})
|
||||
|
||||
it('builds readable select options', () => {
|
||||
expect(accessOption({ id: 'crm:client:view', name: 'Просмотр клиентов' }))
|
||||
.toEqual({ value: 'crm:client:view', title: 'Просмотр клиентов (crm:client:view)' })
|
||||
})
|
||||
})
|
||||
|
|
@ -4,7 +4,7 @@ import { getModule, getResource, modules } from '../config/modules'
|
|||
describe('module registry', () => {
|
||||
it('contains every required support module', () => {
|
||||
expect(modules.map(module => module.key)).toEqual([
|
||||
'addresses', 'crm', 'service', 'requests', 'incidents', 'sla',
|
||||
'addresses', 'crm', 'service', 'requests', 'incidents', 'tasks', 'sla',
|
||||
'configuration-items', 'devices', 'communications', 'system',
|
||||
])
|
||||
})
|
||||
|
|
@ -21,7 +21,19 @@ describe('module registry', () => {
|
|||
expect(getModule('incidents')?.apiPrefix).toBe('inc')
|
||||
expect(getResource('requests', 'requests')?.title).toBe('Обращения')
|
||||
expect(getResource('system', 'holidaygroups')?.path).toBe('holiday-groups')
|
||||
expect(getResource('system', 'holidayelements')?.path).toBe('holidayelements')
|
||||
expect(getResource('system', 'employees')).toMatchObject({ path: 'employees', menuGroup: 'staff' })
|
||||
expect(getResource('system', 'accessprofiles')).toMatchObject({
|
||||
path: 'sysprofiles', accessKey: 'employee-access', title: 'Профили и доступы', menuGroup: 'staff',
|
||||
})
|
||||
expect(getResource('system', 'users')?.menuGroup).toBe('staff')
|
||||
expect(getResource('system', 'departments')).toMatchObject({ path: 'departments', menuGroup: 'staff' })
|
||||
expect(getResource('system', 'departmentstructure')).toMatchObject({
|
||||
path: 'departments/tree', accessKey: 'departments', readOnly: true, menuGroup: 'staff',
|
||||
})
|
||||
expect(getResource('system', 'holidaygroups')).toMatchObject({ path: 'holiday-groups', menuGroup: 'holidays' })
|
||||
expect(getResource('system', 'holidays')).toMatchObject({ path: 'holidays', menuGroup: 'holidays' })
|
||||
expect(getResource('system', 'objects')).toMatchObject({ path: 'objects', menuGroup: 'parameters' })
|
||||
expect(getResource('system', 'views')).toMatchObject({ path: 'views', menuGroup: 'parameters' })
|
||||
expect(getResource('configuration-items', 'types')?.path).toBe('ci-types')
|
||||
expect(getResource('configuration-items', 'relations')).toBeUndefined()
|
||||
expect(getResource('sla', 'scheduleweeks')?.menuGroup).toBe('settings')
|
||||
|
|
@ -31,15 +43,48 @@ describe('module registry', () => {
|
|||
expect(getResource('addresses', 'housetypes')?.path).toBe('house-types')
|
||||
expect(getResource('addresses', 'zonetypes')?.path).toBe('zone-types')
|
||||
expect(getResource('communications', 'settings')?.path).toBe('settings')
|
||||
expect(getResource('system', 'settings')?.path).toBe('settings')
|
||||
expect(getResource('system', 'settings')).toMatchObject({ path: 'settings', menuGroup: 'parameters' })
|
||||
expect(getResource('system', 'preferences')).toBeUndefined()
|
||||
expect(getResource('system', 'module-settings')?.path).toBe('module-settings')
|
||||
expect(getResource('crm', 'categories')?.path).toBe('client-categories')
|
||||
expect(getResource('crm', 'types')?.path).toBe('client-types')
|
||||
expect(getResource('crm', 'categories')?.hiddenInMenu).toBe(true)
|
||||
expect(getResource('crm', 'types')?.hiddenInMenu).toBe(true)
|
||||
expect(getResource('crm', 'settings')).toMatchObject({
|
||||
menuGroup: 'settings', accessKeys: ['categories', 'types'],
|
||||
})
|
||||
expect(getResource('service', 'requests')?.path).toBe('request-types')
|
||||
expect(getResource('requests', 'sourcetypes')?.path).toBe('source-types')
|
||||
expect(getResource('requests', 'statustransits')).toBeUndefined()
|
||||
expect(getResource('incidents', 'statustransits')).toBeUndefined()
|
||||
expect(getModule('tasks')?.apiPrefix).toBe('chn')
|
||||
expect(getModule('tasks')?.title).toBe('Изменения/задачи')
|
||||
expect(getResource('tasks', 'tasks')?.path).toBe('tasks')
|
||||
expect(getResource('tasks', 'changes')?.path).toBe('changes')
|
||||
expect(getResource('tasks', 'approvals')).toMatchObject({
|
||||
path: 'changes/pending-approval', accessKey: 'changes', readOnly: true,
|
||||
})
|
||||
expect(getResource('tasks', 'tasktransitions')).toMatchObject({
|
||||
path: 'task-transitions', menuGroup: 'settings', menuSubgroup: 'changes',
|
||||
})
|
||||
expect(getResource('tasks', 'taskcategories')?.path).toBe('task-categories')
|
||||
expect(getResource('tasks', 'taskcategories')?.title).toBe('Категории задач')
|
||||
expect(getResource('tasks', 'taskpriorities')).toMatchObject({
|
||||
title: 'Приоритеты задач', menuGroup: 'settings', menuSubgroup: 'tasks',
|
||||
})
|
||||
expect(getResource('tasks', 'taskstatuses')).toMatchObject({
|
||||
title: 'Статусы задач', path: 'task-statuses', readOnly: true,
|
||||
})
|
||||
expect(getResource('tasks', 'tasktypes')).toMatchObject({ title: 'Типы задач', path: 'task-types' })
|
||||
expect(getResource('tasks', 'changestatuses')).toMatchObject({
|
||||
path: 'change-statuses', menuSubgroup: 'changes', readOnly: true,
|
||||
})
|
||||
expect(getResource('tasks', 'changetypes')).toMatchObject({
|
||||
path: 'change-types', menuSubgroup: 'changes',
|
||||
})
|
||||
expect(getResource('tasks', 'settings')).toMatchObject({
|
||||
path: 'settings', title: 'Общие параметры', menuSubgroup: 'tasks', hiddenInMenu: true,
|
||||
})
|
||||
expect(getResource('missing', 'requests')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -45,4 +45,87 @@ describe('static resource form schemas', () => {
|
|||
expect(resourceSchemas).not.toHaveProperty(`/main/${prefix}/preferences/`)
|
||||
}
|
||||
})
|
||||
|
||||
it('describes change management resources and automatic task department', () => {
|
||||
expect(resourceSchemas['/main/chn/task-types/'].post.properties.department).toMatchObject({
|
||||
type: 'integer',
|
||||
nullable: true,
|
||||
})
|
||||
expect(resourceSchemas['/main/chn/tasks/'].post.required).not.toContain('department')
|
||||
expect(resourceSchemas['/main/chn/changes/'].post.required).toEqual([
|
||||
'change_type', 'title',
|
||||
])
|
||||
expect(resourceSchemas['/main/chn/changes/'].post.properties).not.toHaveProperty('initiator')
|
||||
expect(resourceSchemas['/main/chn/changes/'].post.properties.responsible)
|
||||
.toMatchObject({ type: 'integer', nullable: true })
|
||||
expect(resourceSchemas['/main/chn/task-transitions/'].post.properties.condition.enum)
|
||||
.toEqual(['success', 'not_done'])
|
||||
expect(Object.keys(resourceSchemas['/main/chn/settings/'].patch.properties)).toEqual([
|
||||
'task_status_create', 'task_status_close', 'task_status_not_done', 'change_status_on_check',
|
||||
])
|
||||
})
|
||||
|
||||
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' } })
|
||||
expect(changeType).toHaveProperty('status_created')
|
||||
expect(changeType).toHaveProperty('status_approval')
|
||||
expect(changeType).toHaveProperty('status_after_approval')
|
||||
expect(changeType).toHaveProperty('status_in_progress')
|
||||
expect(changeType).toHaveProperty('status_completed')
|
||||
expect(changeType).toHaveProperty('status_not_completed')
|
||||
expect(changeType).toMatchObject({
|
||||
requires_assessment: { type: 'boolean' },
|
||||
assessment_task_type: { type: 'integer', nullable: true },
|
||||
requires_approval: { type: 'boolean' },
|
||||
requires_planning: { type: 'boolean' },
|
||||
requires_testing: { type: 'boolean' },
|
||||
testing_task_type: { type: 'integer', nullable: true },
|
||||
})
|
||||
expect(resourceSchemas['/main/chn/change-statuses/'].post.properties.change_type)
|
||||
.toMatchObject({ type: 'integer', nullable: true })
|
||||
expect(resourceSchemas['/main/chn/workflow-nodes/'].post.properties.kind.enum)
|
||||
.toEqual(['task', 'change'])
|
||||
expect(resourceSchemas['/main/chn/workflow-edges/'].post.properties.decision.enum)
|
||||
.toEqual(['positive', 'negative'])
|
||||
})
|
||||
|
||||
it('contains the writable sysdepartment schema', () => {
|
||||
const schema = resourceSchemas['/main/sys/departments/'].post
|
||||
expect(schema.required).toContain('name')
|
||||
expect(schema.properties.parent).toMatchObject({ type: 'integer', nullable: true })
|
||||
expect(schema.properties.manager).toMatchObject({ type: 'integer', nullable: true })
|
||||
expect(schema.properties.diagram_x).toMatchObject({ type: 'number' })
|
||||
expect(schema.properties.diagram_y).toMatchObject({ type: 'number' })
|
||||
expect(schema.properties.diagram_width).toMatchObject({ type: 'number' })
|
||||
expect(schema.properties.diagram_height).toMatchObject({ type: 'number' })
|
||||
expect(schema.properties).not.toHaveProperty('manager_details')
|
||||
expect(schema.properties).not.toHaveProperty('employee_ids')
|
||||
expect(schema.properties).not.toHaveProperty('children')
|
||||
})
|
||||
|
||||
it('uses assigned_id for CRM client and lead responsibility', () => {
|
||||
for (const path of ['/main/crm/clients/', '/main/crm/leads/'] as const) {
|
||||
for (const schema of Object.values(resourceSchemas[path])) {
|
||||
expect(schema.properties.assigned_id).toMatchObject({
|
||||
type: 'integer',
|
||||
minimum: 1,
|
||||
writeOnly: true,
|
||||
nullable: true,
|
||||
})
|
||||
expect(schema.properties).not.toHaveProperty('responsible_id')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('contains colors for CRM client types and categories', () => {
|
||||
for (const path of ['/main/crm/client-types/', '/main/crm/client-categories/'] as const) {
|
||||
for (const schema of Object.values(resourceSchemas[path])) {
|
||||
expect(schema.properties.color).toMatchObject({
|
||||
type: 'string',
|
||||
maxLength: 60,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
93
types/api.ts
93
types/api.ts
|
|
@ -19,6 +19,10 @@ export interface ResourceDefinition {
|
|||
path: string
|
||||
readOnly?: boolean
|
||||
menuGroup?: string
|
||||
menuSubgroup?: string
|
||||
accessKey?: string
|
||||
accessKeys?: string[]
|
||||
hiddenInMenu?: boolean
|
||||
}
|
||||
|
||||
export interface ModuleDefinition {
|
||||
|
|
@ -30,16 +34,71 @@ export interface ModuleDefinition {
|
|||
}
|
||||
|
||||
export interface UserProfile {
|
||||
sys_user_id: number
|
||||
id: number
|
||||
sys_user: number
|
||||
lang?: string
|
||||
status?: number
|
||||
timezone?: number
|
||||
theme_is_light?: boolean
|
||||
theme_color?: string
|
||||
info?: string
|
||||
name?: string
|
||||
name: string
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
export interface SysEmployee extends UserProfile {
|
||||
username: string
|
||||
con_person: number[]
|
||||
con_contact: number[]
|
||||
description: string
|
||||
firstname: string
|
||||
secondname: string
|
||||
surname: string
|
||||
departments: number[]
|
||||
department_names: string[]
|
||||
phone_receiver_extid: string
|
||||
permissions: string[]
|
||||
navigations: string[]
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface SysPermission extends ApiRecord {
|
||||
id: string
|
||||
module?: string
|
||||
resource?: string
|
||||
action?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface SysNavigation extends ApiRecord {
|
||||
id: string
|
||||
description?: string
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
export interface AccessOption {
|
||||
title: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface TaskCreateRequest {
|
||||
title: string
|
||||
description?: string
|
||||
task_type?: number
|
||||
status?: number
|
||||
priority?: number
|
||||
category?: number
|
||||
change?: number
|
||||
department?: number
|
||||
assignees?: number[]
|
||||
initiator: number
|
||||
planned_start_at?: string
|
||||
planned_finish_at?: string
|
||||
progress?: number
|
||||
external_id?: string
|
||||
}
|
||||
|
||||
export type CrmActivityTaskRequest = Omit<TaskCreateRequest, 'initiator'>
|
||||
|
||||
export interface UserRole {
|
||||
id: number
|
||||
name: string
|
||||
|
|
@ -63,14 +122,40 @@ export interface UserManagement {
|
|||
}
|
||||
|
||||
export interface PermissionsResponse {
|
||||
codes: string[]
|
||||
resources: Record<string, string[]>
|
||||
}
|
||||
|
||||
export interface CapabilityObject {
|
||||
id: string | number
|
||||
code?: string
|
||||
name?: string
|
||||
description: string
|
||||
url: string
|
||||
actions: string[]
|
||||
}
|
||||
|
||||
export interface CapabilityModule {
|
||||
id: string | number
|
||||
code?: string
|
||||
name?: string
|
||||
description: string
|
||||
objects: CapabilityObject[]
|
||||
}
|
||||
|
||||
export interface CapabilitiesResponse {
|
||||
modules: CapabilityModule[]
|
||||
permissions: string[]
|
||||
navigations: string[]
|
||||
}
|
||||
|
||||
export interface SessionUser extends ApiRecord {
|
||||
id: number
|
||||
username: string
|
||||
email?: string
|
||||
name?: string
|
||||
sys_employee?: UserProfile
|
||||
/** @deprecated Старое имя профиля, оставлено для совместимости с предыдущим API. */
|
||||
sys_user_profile?: UserProfile
|
||||
sys_role?: UserRole[]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
export function accessIds(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.flatMap(item => {
|
||||
if (typeof item === 'string' || typeof item === 'number') return [String(item)]
|
||||
if (!item || typeof item !== 'object') return []
|
||||
const record = item as ApiRecord
|
||||
const id = record.id ?? record.code ?? record.value
|
||||
return typeof id === 'string' || typeof id === 'number' ? [String(id)] : []
|
||||
})
|
||||
}
|
||||
|
||||
export function accessModule(id: string): string {
|
||||
return id.split(':', 1)[0] || ''
|
||||
}
|
||||
|
||||
export function belongsToModule(id: string, module: string): boolean {
|
||||
return Boolean(module) && accessModule(id) === module
|
||||
}
|
||||
|
||||
export function accessOption(item: unknown): { title: string; value: string } | null {
|
||||
if (typeof item === 'string' || typeof item === 'number') {
|
||||
return { title: String(item), value: String(item) }
|
||||
}
|
||||
if (!item || typeof item !== 'object') return null
|
||||
const record = item as ApiRecord
|
||||
const value = record.id ?? record.code ?? record.value
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return null
|
||||
const label = record.name ?? record.title ?? record.description
|
||||
return {
|
||||
value: String(value),
|
||||
title: label ? `${String(label)} (${String(value)})` : String(value),
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue