import {ref, computed, watch} from 'vue' import { defineStore } from 'pinia' import axios from 'axios' import {usePage} from "@inertiajs/vue3"; export const useAuthStore = defineStore('authStore', () => { const page = usePage() const user = ref(page.props.user) const token = computed(() => user.value?.token) const role = computed(() => user.value?.role) const permissions = computed(() => user.value?.permissions) const availableDepartments = computed(() => user.value?.available_departments) const availableRoles = computed(() => user.value?.available_roles) watch( () => page.props.user, (newUser) => { user.value = newUser }, { deep: true, immediate: true }) // Инициализация axios с токеном if (token?.value) { axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}` } // Вычисляемые свойства const isAuthenticated = computed(() => !!user.value && !!token.value) const userDepartment = computed(() => user.value?.current_department || '') // Проверка роли по слагу const hasRole = (slug) => role.value?.slug === slug const isAdmin = computed(() => hasRole('admin')) const isChiefDoctor = computed(() => hasRole('gv')) const isDeputyChief = computed(() => hasRole('zam')) const isHeadOfDepartment = computed(() => hasRole('zav')) const isDoctor = computed(() => hasRole('dej')) const isNurse = computed(() => hasRole('nurse')) const isSeniorStaff = computed(() => isAdmin.value || isChiefDoctor.value || isDeputyChief.value || isHeadOfDepartment.value) // Проверка права (permissions — массив строк от Spatie) const hasPermission = (permission) => { return permissions.value?.includes(permission) ?? false } const canAccessDepartment = (department) => { if (isSeniorStaff.value) return true return availableDepartments.value.includes(department) } const clearAuthData = () => { user.value = null delete axios.defaults.headers.common['Authorization'] } const logout = async () => { try { await axios.post('/api/auth/logout') } catch (error) { console.error('Ошибка при выходе:', error) } finally { clearAuthData() } } return { user, token, permissions, availableDepartments, availableRoles, isAuthenticated, isAdmin, isChiefDoctor, isDeputyChief, isHeadOfDepartment, isDoctor, isNurse, isSeniorStaff, userDepartment, hasRole, hasPermission, canAccessDepartment, clearAuthData, logout, } })