Files
InvoiceShelf/resources/scripts/features/company/ai/components/AiChatDrawer.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

141 lines
3.8 KiB
Vue

<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import { useAiChatStore } from '../stores/ai-chat.store'
import AiChatMessage from './AiChatMessage.vue'
import AiChatMessageInput from './AiChatMessageInput.vue'
import AiChatConversationList from './AiChatConversationList.vue'
const store = useAiChatStore()
const messagesEl = ref<HTMLDivElement | null>(null)
// Auto-scroll to the bottom whenever the message list grows.
watch(
() => store.messages.length,
async () => {
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
},
)
async function onSend(message: string): Promise<void> {
await store.sendMessage(message)
await nextTick()
if (messagesEl.value) {
messagesEl.value.scrollTop = messagesEl.value.scrollHeight
}
}
</script>
<template>
<!-- Backdrop -->
<Teleport to="body">
<transition name="ai-drawer-fade">
<div
v-if="store.isOpen"
class="fixed inset-0 bg-black/20 z-40"
@click="store.close()"
/>
</transition>
<!-- Drawer panel -->
<transition name="ai-drawer-slide">
<aside
v-if="store.isOpen"
class="
fixed top-0 right-0 bottom-0 z-50
w-full sm:w-[480px] lg:w-[640px]
bg-surface shadow-2xl
flex
"
>
<!-- Conversation list sidebar -->
<div class="hidden sm:block w-48 border-r border-line-default bg-surface-secondary">
<AiChatConversationList />
</div>
<!-- Messages + input -->
<div class="flex-1 flex flex-col">
<div class="flex items-center justify-between p-3 border-b border-line-default">
<div class="flex items-center gap-2">
<BaseIcon name="SparklesIcon" class="w-5 h-5 text-primary-500" />
<h2 class="text-sm font-semibold text-heading">
{{ $t('ai.chat.title') }}
</h2>
</div>
<button
type="button"
class="text-muted hover:text-heading"
@click="store.close()"
>
<BaseIcon name="XMarkIcon" class="w-5 h-5" />
</button>
</div>
<div
ref="messagesEl"
class="flex-1 overflow-y-auto p-4 space-y-3"
>
<div
v-if="store.messages.length === 0"
class="text-center text-sm text-muted mt-12"
>
<BaseIcon name="SparklesIcon" class="w-10 h-10 mx-auto mb-2 text-subtle" />
<p>{{ $t('ai.chat.empty_state') }}</p>
</div>
<AiChatMessage
v-for="msg in store.messages"
:key="msg.id"
:message="msg"
/>
<div
v-if="store.isSending"
class="flex justify-start"
>
<div class="bg-surface-tertiary rounded-lg px-4 py-2 text-sm text-muted italic">
{{ $t('ai.chat.thinking') }}
</div>
</div>
<div
v-if="store.lastError"
class="p-3 text-xs text-alert-error-text bg-alert-error-bg rounded"
>
{{ store.lastError }}
</div>
</div>
<AiChatMessageInput
:is-sending="store.isSending"
@send="onSend"
/>
</div>
</aside>
</transition>
</Teleport>
</template>
<style scoped>
.ai-drawer-fade-enter-active,
.ai-drawer-fade-leave-active {
transition: opacity 0.2s ease;
}
.ai-drawer-fade-enter-from,
.ai-drawer-fade-leave-to {
opacity: 0;
}
.ai-drawer-slide-enter-active,
.ai-drawer-slide-leave-active {
transition: transform 0.25s ease;
}
.ai-drawer-slide-enter-from,
.ai-drawer-slide-leave-to {
transform: translateX(100%);
}
</style>