80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
import { defineStore } from 'pinia'
|
|
import { computed, ref } from 'vue'
|
|
import { notify } from '@/utils/notify'
|
|
|
|
export const useAppStore = defineStore('app', () => {
|
|
const apiBase = ref(localStorage.getItem('financeAiApiBase') || 'http://127.0.0.1:8775')
|
|
const token = ref(localStorage.getItem('financeAiToken') || '')
|
|
const currentUser = ref(null)
|
|
const healthy = ref(false)
|
|
|
|
const permissions = computed(() => new Set(currentUser.value?.permissions || []))
|
|
function hasPermission(code) {
|
|
if (!currentUser.value) return false
|
|
if (!code) return true
|
|
if (currentUser.value.is_superuser) return true
|
|
return permissions.value.has(code)
|
|
}
|
|
|
|
function setApiBase(value) {
|
|
apiBase.value = (value || '').trim() || 'http://127.0.0.1:8775'
|
|
localStorage.setItem('financeAiApiBase', apiBase.value)
|
|
}
|
|
|
|
function setToken(value) {
|
|
token.value = value || ''
|
|
if (value) localStorage.setItem('financeAiToken', value)
|
|
else localStorage.removeItem('financeAiToken')
|
|
}
|
|
|
|
function setCurrentUser(user) {
|
|
currentUser.value = user || null
|
|
}
|
|
|
|
async function checkHealth() {
|
|
try {
|
|
const url = `${apiBase.value.replace(/\/$/, '')}/health`
|
|
const res = await fetch(url)
|
|
healthy.value = res.ok
|
|
} catch {
|
|
healthy.value = false
|
|
}
|
|
}
|
|
|
|
async function loadCurrentUser() {
|
|
if (!token.value) {
|
|
currentUser.value = null
|
|
return
|
|
}
|
|
try {
|
|
const { request } = await import('@/api/client')
|
|
currentUser.value = await request('/api/auth/me')
|
|
} catch {
|
|
currentUser.value = null
|
|
setToken('')
|
|
}
|
|
}
|
|
|
|
async function logout() {
|
|
if (token.value) {
|
|
try {
|
|
const { request } = await import('@/api/client')
|
|
await request('/api/auth/logout', { method: 'POST' })
|
|
} catch (err) {
|
|
console.warn(err)
|
|
}
|
|
}
|
|
setToken('')
|
|
currentUser.value = null
|
|
}
|
|
|
|
function toast(message, type = 'info') {
|
|
notify[type] ? notify[type](message) : notify.info(message)
|
|
}
|
|
|
|
return {
|
|
apiBase, token, currentUser, healthy, permissions,
|
|
setApiBase, setToken, setCurrentUser, checkHealth, loadCurrentUser, logout, toast, hasPermission,
|
|
}
|
|
})
|