mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-16 13:55:21 +00:00
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.
This commit is contained in:
98
app/Http/Controllers/Company/Ai/ChatController.php
Normal file
98
app/Http/Controllers/Company/Ai/ChatController.php
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Company\Ai;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AiConversation;
|
||||
use App\Services\Ai\AiAssistantService;
|
||||
use App\Support\Ai\AiException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ChatController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AiAssistantService $assistant,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Send a message into a conversation and get the assistant's reply.
|
||||
*
|
||||
* If `conversation_id` is omitted (or belongs to a conversation the user
|
||||
* doesn't own), we start a fresh conversation scoped to the current
|
||||
* (company_id, user_id). This matches the "new chat" UX where the user
|
||||
* opens the drawer and starts typing immediately.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function __invoke(Request $request): JsonResponse
|
||||
{
|
||||
$this->authorize('use ai');
|
||||
|
||||
$validated = $this->validate($request, [
|
||||
'conversation_id' => 'nullable|integer',
|
||||
'message' => 'required|string|max:10000',
|
||||
]);
|
||||
|
||||
$companyId = (int) $request->header('company');
|
||||
$userId = (int) $request->user()->id;
|
||||
|
||||
$conversation = $this->resolveConversation(
|
||||
$validated['conversation_id'] ?? null,
|
||||
$companyId,
|
||||
$userId,
|
||||
$validated['message'],
|
||||
);
|
||||
|
||||
try {
|
||||
$assistantMessage = $this->assistant->chat($conversation, $validated['message']);
|
||||
} catch (AiException $e) {
|
||||
return response()->json([
|
||||
'error' => $e->errorKey,
|
||||
'message' => $e->getMessage(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
$conversation->refresh();
|
||||
|
||||
return response()->json([
|
||||
'conversation' => [
|
||||
'id' => $conversation->id,
|
||||
'title' => $conversation->title,
|
||||
'model' => $conversation->model,
|
||||
'updated_at' => $conversation->updated_at,
|
||||
],
|
||||
'message' => [
|
||||
'id' => $assistantMessage->id,
|
||||
'role' => $assistantMessage->role,
|
||||
'content' => $assistantMessage->content,
|
||||
'created_at' => $assistantMessage->created_at,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick an existing conversation the user owns, or create a new one.
|
||||
*/
|
||||
protected function resolveConversation(
|
||||
?int $conversationId,
|
||||
int $companyId,
|
||||
int $userId,
|
||||
string $firstMessage,
|
||||
): AiConversation {
|
||||
if ($conversationId !== null) {
|
||||
$existing = AiConversation::query()
|
||||
->where('id', $conversationId)
|
||||
->where('company_id', $companyId)
|
||||
->where('user_id', $userId)
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->assistant->startConversation($companyId, $userId, $firstMessage);
|
||||
}
|
||||
}
|
||||
103
app/Http/Controllers/Company/Ai/ConversationController.php
Normal file
103
app/Http/Controllers/Company/Ai/ConversationController.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Company\Ai;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AiConversation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ConversationController extends Controller
|
||||
{
|
||||
/**
|
||||
* List the current user's conversations for the current company.
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$this->authorize('use ai');
|
||||
|
||||
$conversations = AiConversation::query()
|
||||
->where('company_id', $request->header('company'))
|
||||
->where('user_id', $request->user()->id)
|
||||
->latest('updated_at')
|
||||
->limit(50)
|
||||
->get(['id', 'title', 'model', 'updated_at', 'created_at']);
|
||||
|
||||
return response()->json(['conversations' => $conversations]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a single conversation with its full message history.
|
||||
*/
|
||||
public function show(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$this->authorize('use ai');
|
||||
|
||||
$conversation = AiConversation::query()
|
||||
->where('id', $id)
|
||||
->where('company_id', $request->header('company'))
|
||||
->firstOrFail();
|
||||
|
||||
$this->authorize('view', $conversation);
|
||||
|
||||
$messages = $conversation->messages()
|
||||
->whereIn('role', ['user', 'assistant'])
|
||||
->get(['id', 'role', 'content', 'created_at']);
|
||||
|
||||
return response()->json([
|
||||
'conversation' => [
|
||||
'id' => $conversation->id,
|
||||
'title' => $conversation->title,
|
||||
'model' => $conversation->model,
|
||||
'created_at' => $conversation->created_at,
|
||||
'updated_at' => $conversation->updated_at,
|
||||
],
|
||||
'messages' => $messages,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a conversation.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function update(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$this->authorize('use ai');
|
||||
|
||||
$conversation = AiConversation::query()
|
||||
->where('id', $id)
|
||||
->where('company_id', $request->header('company'))
|
||||
->firstOrFail();
|
||||
|
||||
$this->authorize('update', $conversation);
|
||||
|
||||
$validated = $this->validate($request, [
|
||||
'title' => 'required|string|max:255',
|
||||
]);
|
||||
|
||||
$conversation->update(['title' => $validated['title']]);
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a conversation (cascades to messages via DB foreign key).
|
||||
*/
|
||||
public function destroy(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$this->authorize('use ai');
|
||||
|
||||
$conversation = AiConversation::query()
|
||||
->where('id', $id)
|
||||
->where('company_id', $request->header('company'))
|
||||
->firstOrFail();
|
||||
|
||||
$this->authorize('delete', $conversation);
|
||||
|
||||
$conversation->delete();
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user