mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-16 22:05:20 +00:00
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.
94 lines
3.3 KiB
PHP
94 lines
3.3 KiB
PHP
<?php
|
|
|
|
use App\Models\Company;
|
|
use App\Models\Customer;
|
|
use App\Models\Invoice;
|
|
use App\Services\Ai\Tools\SearchInvoicesTool;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
|
|
beforeEach(function () {
|
|
Artisan::call('db:seed', ['--class' => 'DatabaseSeeder', '--force' => true]);
|
|
Artisan::call('db:seed', ['--class' => 'DemoSeeder', '--force' => true]);
|
|
});
|
|
|
|
test('search_invoices scopes strictly to the passed company id', function () {
|
|
$companyA = Company::first();
|
|
$companyB = Company::factory()->create();
|
|
|
|
$customerA = Customer::factory()->create(['company_id' => $companyA->id]);
|
|
$customerB = Customer::factory()->create(['company_id' => $companyB->id]);
|
|
|
|
$invoiceA = Invoice::factory()->create([
|
|
'company_id' => $companyA->id,
|
|
'customer_id' => $customerA->id,
|
|
'invoice_number' => 'AAA-001',
|
|
]);
|
|
$invoiceB = Invoice::factory()->create([
|
|
'company_id' => $companyB->id,
|
|
'customer_id' => $customerB->id,
|
|
'invoice_number' => 'BBB-001',
|
|
]);
|
|
|
|
$tool = new SearchInvoicesTool;
|
|
|
|
// Call with companyA — should ONLY see invoiceA
|
|
$resultA = $tool->execute([], $companyA->id, 1);
|
|
$numbersA = collect($resultA['invoices'])->pluck('invoice_number');
|
|
expect($numbersA)->toContain('AAA-001')->not->toContain('BBB-001');
|
|
|
|
// Call with companyB — should ONLY see invoiceB
|
|
$resultB = $tool->execute([], $companyB->id, 1);
|
|
$numbersB = collect($resultB['invoices'])->pluck('invoice_number');
|
|
expect($numbersB)->toContain('BBB-001')->not->toContain('AAA-001');
|
|
});
|
|
|
|
test('search_invoices ignores any company_id the caller tries to pass in arguments', function () {
|
|
$companyA = Company::first();
|
|
$companyB = Company::factory()->create();
|
|
|
|
$customerB = Customer::factory()->create(['company_id' => $companyB->id]);
|
|
Invoice::factory()->create([
|
|
'company_id' => $companyB->id,
|
|
'customer_id' => $customerB->id,
|
|
'invoice_number' => 'BBB-LEAK',
|
|
]);
|
|
|
|
$tool = new SearchInvoicesTool;
|
|
|
|
// Simulate an LLM trying to pass company_id as an argument — even if present,
|
|
// the tool must ignore it because the schema doesn't include that field and
|
|
// the execute() method uses the injected $companyId.
|
|
$result = $tool->execute(
|
|
['company_id' => $companyB->id, 'query' => 'BBB'],
|
|
$companyA->id,
|
|
1,
|
|
);
|
|
|
|
expect(collect($result['invoices'])->pluck('invoice_number'))
|
|
->not->toContain('BBB-LEAK');
|
|
});
|
|
|
|
test('search_invoices respects the limit parameter with a hard cap', function () {
|
|
$company = Company::first();
|
|
$customer = Customer::factory()->create(['company_id' => $company->id]);
|
|
|
|
// Create 60 invoices — more than the max limit of 50
|
|
for ($i = 0; $i < 60; $i++) {
|
|
Invoice::factory()->create([
|
|
'company_id' => $company->id,
|
|
'customer_id' => $customer->id,
|
|
'invoice_number' => 'SCAN-'.str_pad((string) $i, 3, '0', STR_PAD_LEFT),
|
|
]);
|
|
}
|
|
|
|
$tool = new SearchInvoicesTool;
|
|
|
|
// Passing limit=99 should be capped to 50
|
|
$result = $tool->execute(['limit' => 99], $company->id, 1);
|
|
expect($result['invoices'])->toHaveCount(50);
|
|
|
|
// Default limit is 10
|
|
$result = $tool->execute([], $company->id, 1);
|
|
expect($result['invoices'])->toHaveCount(10);
|
|
});
|