Files
InvoiceShelf/resources/scripts/layouts/partials/SiteHeader.vue
Darko Gjorgjijoski e861fc1fc1 feat(ai): Phase 2 — chat assistant with tool-calling
Second phase of the AI feature. Users can now open a slide-in chat drawer from the SiteHeader and ask natural-language questions about their company's invoices, customers, payments, and expenses. The LLM invokes pre-defined read-only tool functions (scoped to the current company at execute time) to fetch data and synthesize answers.

**Database** — new ai_conversations and ai_messages tables. Messages are stored in OpenAI's chat format so AiAssistantService serializes a conversation into an API request with zero translation. Columns: role, content, tool_call_id, tool_calls JSON, model, tokens_in, tokens_out. Conversations are scoped (company_id, user_id) — one user's chats are invisible to everyone else, even inside the same company. Foreign-key cascade deletes.

**Tool infrastructure** — AiTool abstract base + AiToolRegistry singleton (registered in a new AiServiceProvider). The base class enforces the security rule: every tool's execute() receives companyId and userId as injected parameters; tools' JSON schemas NEVER include a company_id field. An LLM physically cannot pass a company_id and escape tenancy. Modules can register their own tools by resolving the registry from their own ServiceProvider::boot().

**Nine built-in tools**: search_invoices, get_invoice, search_customers, get_customer, list_recent_payments, list_overdue_invoices, get_company_stats (aggregates for named periods), search_items, list_expense_categories. All read-only; no mutations. Each returns JSON-encodable data the LLM can parse.

**AiAssistantService orchestration loop** — the heart of Phase 2. Flow: persist user message → build payload from system prompt + recent history (40-message window) + new user message → call driver.chatCompletion with tools → if tool_calls, execute each one via the registry (with injected scope), persist tool result, loop → if plain text, persist and return. Hard cap at 5 iterations to prevent runaway LLMs. System prompt pins the assistant to this company's data and forbids mutation.

**Controllers + policy + rate limit** — POST /api/v1/ai/chat runs the orchestration loop. GET/PATCH/DELETE /api/v1/ai/conversations for CRUD. AiConversationPolicy enforces user_id+company_id match on every action. A new 'ai' RateLimiter in RouteServiceProvider throttles to 30 req/min per (user, company). New 'use ai' Gate defined in AppServiceProvider returns true for any authenticated user — the per-company kill-switch still goes through AiConfigurationService::resolveForCompany.

**Frontend** — new features/company/ai/ folder with a Pinia store (ai-chat.store.ts) holding drawer state, current conversation, messages, and loading flags. AiChatDrawer.vue is a slide-in panel teleported to <body>, mounted globally in CompanyLayout.vue when bootstrap reports ai.enabled && ai.chat_enabled. Sub-components: AiChatMessage (user bubbles vs assistant bubbles), AiChatMessageInput (Enter submits, Shift+Enter newline), AiChatConversationList (sidebar with 'new chat' button, rename, delete). A SparklesIcon button in SiteHeader toggles the drawer.

**Driver test double** — tests use a ScriptedAiDriver registered via AiDriverFactory::register('scripted', ...) that returns pre-queued AiChatResponse objects. Feature tests cover: happy path (new conversation + message persistence), tool-call loop (multi-round-trip with search_invoices), runaway-loop cap, driver-throws path, ai_enabled=NO rejection, chat role disabled rejection, per-user conversation visibility, cross-user policy enforcement, cascade delete.

388 tests pass (was 372, +16 new). Pint clean. npm run build clean. Phase 3 (WYSIWYG text generation popup) is the remaining follow-up.
2026-04-12 08:00:00 +02:00

271 lines
8.4 KiB
Vue

<template>
<header
class="
fixed top-0 left-0 z-20 flex items-center justify-between w-full
px-4 py-3 md:h-16 md:px-8 bg-linear-to-r from-header-from to-header-to
"
>
<div class="flex items-center">
<router-link
:to="companyStore.isAdminMode ? '/admin/administration/dashboard' : '/admin/dashboard'"
class="
text-lg not-italic font-black tracking-wider text-white
brand-main font-base hidden md:block
"
>
<img v-if="adminLogo" :src="adminLogo" class="h-6" />
<MainLogo v-else class="h-6" light-color="white" dark-color="white" />
</router-link>
</div>
<!-- Mobile toggle button -->
<div
:class="{ 'is-active': globalStore.isSidebarOpen }"
class="
flex float-left p-1 overflow-visible text-sm ease-linear bg-surface
border-0 rounded cursor-pointer md:hidden md:ml-0 hover:bg-hover-strong
"
@click.prevent="onToggle"
>
<BaseIcon name="Bars3Icon" class="!w-6 !h-6 text-muted" />
</div>
<ul class="flex float-right h-8 m-0 list-none md:h-9">
<!-- Create dropdown -->
<li
v-if="hasCreateAbilities && !companyStore.isAdminMode"
class="relative hidden float-left m-0 md:block"
>
<BaseDropdown width-class="w-48">
<template #activator>
<div
class="
flex items-center justify-center w-8 h-8 ml-2 text-sm text-white
bg-white/20 rounded-lg hover:bg-white/30 md:h-9 md:w-9
"
>
<BaseIcon name="PlusIcon" class="w-5 h-5 text-white" />
</div>
</template>
<router-link to="/admin/invoices/create">
<BaseDropdownItem
v-if="userStore.hasAbilities(ABILITIES.CREATE_INVOICE)"
>
<BaseIcon
name="DocumentTextIcon"
class="w-5 h-5 mr-3 text-subtle group-hover:text-muted"
aria-hidden="true"
/>
{{ $t('invoices.new_invoice') }}
</BaseDropdownItem>
</router-link>
<router-link to="/admin/estimates/create">
<BaseDropdownItem
v-if="userStore.hasAbilities(ABILITIES.CREATE_ESTIMATE)"
>
<BaseIcon
name="DocumentIcon"
class="w-5 h-5 mr-3 text-subtle group-hover:text-muted"
aria-hidden="true"
/>
{{ $t('estimates.new_estimate') }}
</BaseDropdownItem>
</router-link>
<router-link to="/admin/customers/create">
<BaseDropdownItem
v-if="userStore.hasAbilities(ABILITIES.CREATE_CUSTOMER)"
>
<BaseIcon
name="UserIcon"
class="w-5 h-5 mr-3 text-subtle group-hover:text-muted"
aria-hidden="true"
/>
{{ $t('customers.new_customer') }}
</BaseDropdownItem>
</router-link>
</BaseDropdown>
</li>
<!-- Global search -->
<li v-if="!companyStore.isAdminMode" class="ml-2">
<GlobalSearchBar
v-if="
userStore.currentUser?.is_owner ||
userStore.hasAbilities(ABILITIES.VIEW_CUSTOMER)
"
/>
</li>
<!-- AI chat drawer trigger -->
<li
v-if="
!companyStore.isAdminMode &&
globalStore.ai?.enabled &&
globalStore.ai?.chat_enabled
"
class="ml-2"
>
<button
type="button"
class="
flex items-center justify-center w-8 h-8 md:w-9 md:h-9 rounded-lg
bg-white/20 hover:bg-white/30 text-white
"
:title="$t('ai.chat.title')"
@click="aiChatStore.toggle()"
>
<BaseIcon name="SparklesIcon" class="w-5 h-5" />
</button>
</li>
<!-- Company switcher -->
<li>
<CompanySwitcher />
</li>
<!-- User dropdown -->
<li class="relative block float-left ml-2">
<BaseDropdown width-class="w-48">
<template #activator>
<img
:src="previewAvatar"
class="block w-8 h-8 rounded-full ring-2 ring-white/30 md:h-9 md:w-9 object-cover"
/>
</template>
<!-- Theme Toggle -->
<div class="px-3 py-2">
<div class="flex items-center justify-between rounded-lg bg-surface-secondary p-1">
<button
v-for="opt in themeOptions"
:key="opt.value"
:class="[
'flex items-center justify-center rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors',
currentTheme === opt.value
? 'bg-surface text-heading shadow-sm'
: 'text-muted hover:text-body',
]"
@click.stop="setTheme(opt.value)"
>
<BaseIcon :name="opt.icon" class="w-3.5 h-3.5" />
</button>
</div>
</div>
<router-link to="/admin/settings/account-settings">
<BaseDropdownItem>
<BaseIcon
name="CogIcon"
class="w-5 h-5 mr-3 text-subtle group-hover:text-muted"
aria-hidden="true"
/>
{{ $t('navigation.settings') }}
</BaseDropdownItem>
</router-link>
<router-link
v-for="item in globalStore.userMenu"
:key="item.name"
:to="item.link"
>
<BaseDropdownItem>
<BaseIcon
:name="item.icon"
class="w-5 h-5 mr-3 text-subtle group-hover:text-muted"
aria-hidden="true"
/>
{{ item.title }}
</BaseDropdownItem>
</router-link>
<div class="my-1 border-t border-line-light" />
<BaseDropdownItem @click="logout">
<BaseIcon
name="ArrowRightOnRectangleIcon"
class="w-5 h-5 mr-3 text-red-400"
aria-hidden="true"
/>
<span class="text-red-600">{{ $t('navigation.logout') }}</span>
</BaseDropdownItem>
</BaseDropdown>
</li>
</ul>
</header>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/scripts/stores/auth.store'
import { useUserStore } from '@/scripts/stores/user.store'
import { useGlobalStore } from '@/scripts/stores/global.store'
import { useCompanyStore } from '@/scripts/stores/company.store'
import { useAiChatStore } from '@/scripts/features/company/ai/stores/ai-chat.store'
import { useTheme } from '@/scripts/composables/use-theme'
import { ABILITIES } from '@/scripts/config/abilities'
import { THEME } from '@/scripts/config/constants'
import type { Theme } from '@/scripts/config/constants'
import CompanySwitcher from './CompanySwitcher.vue'
import GlobalSearchBar from './GlobalSearchBar.vue'
import MainLogo from '@/scripts/components/icons/MainLogo.vue'
interface ThemeOption {
value: Theme
icon: string
}
const authStore = useAuthStore()
const userStore = useUserStore()
const globalStore = useGlobalStore()
const companyStore = useCompanyStore()
const aiChatStore = useAiChatStore()
const router = useRouter()
const { currentTheme, setTheme } = useTheme()
const previewAvatar = computed<string>(() => {
if (userStore.currentUser && userStore.currentUser.avatar !== 0) {
return userStore.currentUser.avatar as string
}
return getDefaultAvatar()
})
const adminLogo = computed<string | false>(() => {
if (globalStore.globalSettings?.admin_portal_logo) {
return '/storage/' + globalStore.globalSettings.admin_portal_logo
}
return false
})
const hasCreateAbilities = computed<boolean>(() => {
return userStore.hasAbilities([
ABILITIES.CREATE_INVOICE,
ABILITIES.CREATE_ESTIMATE,
ABILITIES.CREATE_CUSTOMER,
])
})
function getDefaultAvatar(): string {
const imgUrl = new URL('$images/default-avatar.jpg', import.meta.url)
return imgUrl.href
}
async function logout(): Promise<void> {
await authStore.logout()
router.push('/login')
}
function onToggle(): void {
globalStore.setSidebarVisibility(true)
}
const themeOptions: ThemeOption[] = [
{ value: THEME.LIGHT, icon: 'SunIcon' },
{ value: THEME.DARK, icon: 'MoonIcon' },
{ value: THEME.SYSTEM, icon: 'ComputerDesktopIcon' },
]
</script>