mirror of
https://github.com/InvoiceShelf/InvoiceShelf.git
synced 2026-07-17 06:15: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.
197 lines
6.8 KiB
PHP
197 lines
6.8 KiB
PHP
<?php
|
|
|
|
namespace App\Providers;
|
|
|
|
use App\Models\AiConversation;
|
|
use App\Policies\AiConversationPolicy;
|
|
use App\Policies\CompanyPolicy;
|
|
use App\Policies\CustomerPolicy;
|
|
use App\Policies\DashboardPolicy;
|
|
use App\Policies\EstimatePolicy;
|
|
use App\Policies\ExpensePolicy;
|
|
use App\Policies\InvoicePolicy;
|
|
use App\Policies\ItemPolicy;
|
|
use App\Policies\ModulesPolicy;
|
|
use App\Policies\NotePolicy;
|
|
use App\Policies\OwnerPolicy;
|
|
use App\Policies\PaymentPolicy;
|
|
use App\Policies\RecurringInvoicePolicy;
|
|
use App\Policies\ReportPolicy;
|
|
use App\Policies\RolePolicy;
|
|
use App\Policies\SettingsPolicy;
|
|
use App\Policies\UserPolicy;
|
|
use App\Support\Bouncer\BouncerDefaultScope;
|
|
use App\Support\Setup\InstallUtils;
|
|
use App\Support\Setup\InstallWizardAuth;
|
|
use Gate;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Broadcast;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Facades\Notification;
|
|
use Illuminate\Support\ServiceProvider;
|
|
use Laravel\Sanctum\Sanctum;
|
|
use Silber\Bouncer\Database\Models as BouncerModels;
|
|
use Silber\Bouncer\Database\Role;
|
|
use View;
|
|
|
|
class AppServiceProvider extends ServiceProvider
|
|
{
|
|
/**
|
|
* The path to your application's "home" route.
|
|
*
|
|
* Typically, users are redirected here after authentication.
|
|
*
|
|
* @var string
|
|
*/
|
|
public const HOME = '/admin/dashboard';
|
|
|
|
/**
|
|
* The path to the "customer home" route for your application.
|
|
*
|
|
* This is used by Laravel authentication to redirect customers after login.
|
|
*
|
|
* @var string
|
|
*/
|
|
public const CUSTOMER_HOME = '/customer/dashboard';
|
|
|
|
/**
|
|
* Bootstrap any application services.
|
|
*/
|
|
public function boot(): void
|
|
{
|
|
$this->configureInstallWizardTokenAuth();
|
|
|
|
if (InstallUtils::isDbCreated()) {
|
|
$this->addMenus();
|
|
}
|
|
|
|
Gate::policy(Role::class, RolePolicy::class);
|
|
Gate::policy(AiConversation::class, AiConversationPolicy::class);
|
|
|
|
View::addNamespace('pdf_templates', storage_path('app/templates/pdf'));
|
|
|
|
$this->bootAuth();
|
|
$this->bootBroadcast();
|
|
|
|
// In demo mode, prevent all outgoing emails and notifications
|
|
if (config('app.env') === 'demo') {
|
|
Mail::fake();
|
|
Notification::fake();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Register any application services.
|
|
*/
|
|
public function register(): void
|
|
{
|
|
BouncerModels::scope(new BouncerDefaultScope);
|
|
}
|
|
|
|
public function addMenus()
|
|
{
|
|
// main menu
|
|
\Menu::make('main_menu', function ($menu) {
|
|
foreach (config('invoiceshelf.main_menu') as $data) {
|
|
$this->generateMenu($menu, $data);
|
|
}
|
|
});
|
|
|
|
// admin menu (super admin mode)
|
|
\Menu::make('admin_menu', function ($menu) {
|
|
foreach (config('invoiceshelf.admin_menu') as $data) {
|
|
$this->generateMenu($menu, $data);
|
|
}
|
|
});
|
|
|
|
// setting menu
|
|
\Menu::make('setting_menu', function ($menu) {
|
|
foreach (config('invoiceshelf.setting_menu') as $data) {
|
|
$this->generateMenu($menu, $data);
|
|
}
|
|
});
|
|
|
|
\Menu::make('customer_portal_menu', function ($menu) {
|
|
foreach (config('invoiceshelf.customer_menu') as $data) {
|
|
$this->generateMenu($menu, $data);
|
|
}
|
|
});
|
|
}
|
|
|
|
public function generateMenu($menu, $data)
|
|
{
|
|
$menu->add($data['title'], $data['link'])
|
|
->data('icon', $data['icon'])
|
|
->data('name', $data['name'])
|
|
->data('owner_only', $data['owner_only'])
|
|
->data('super_admin_only', $data['super_admin_only'] ?? false)
|
|
->data('ability', $data['ability'])
|
|
->data('model', $data['model'])
|
|
->data('group', $data['group'])
|
|
->data('group_label', $data['group_label'] ?? '')
|
|
->data('priority', $data['priority'] ?? 100);
|
|
}
|
|
|
|
public function bootAuth()
|
|
{
|
|
|
|
Gate::define('create company', [CompanyPolicy::class, 'create']);
|
|
Gate::define('transfer company ownership', [CompanyPolicy::class, 'transferOwnership']);
|
|
Gate::define('delete company', [CompanyPolicy::class, 'delete']);
|
|
|
|
Gate::define('manage modules', [ModulesPolicy::class, 'manageModules']);
|
|
|
|
Gate::define('manage settings', [SettingsPolicy::class, 'manageSettings']);
|
|
Gate::define('manage company', [SettingsPolicy::class, 'manageCompany']);
|
|
Gate::define('manage backups', [SettingsPolicy::class, 'manageBackups']);
|
|
Gate::define('manage file disk', [SettingsPolicy::class, 'manageFileDisk']);
|
|
Gate::define('manage email config', [SettingsPolicy::class, 'manageEmailConfig']);
|
|
Gate::define('manage ai config', [SettingsPolicy::class, 'manageAiConfig']);
|
|
Gate::define('use ai', [SettingsPolicy::class, 'useAi']);
|
|
Gate::define('manage pdf config', [SettingsPolicy::class, 'managePDFConfig']);
|
|
Gate::define('manage notes', [NotePolicy::class, 'manageNotes']);
|
|
Gate::define('view notes', [NotePolicy::class, 'viewNotes']);
|
|
|
|
Gate::define('send invoice', [InvoicePolicy::class, 'send']);
|
|
Gate::define('send estimate', [EstimatePolicy::class, 'send']);
|
|
Gate::define('send payment', [PaymentPolicy::class, 'send']);
|
|
|
|
Gate::define('delete multiple items', [ItemPolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple customers', [CustomerPolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple users', [UserPolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple invoices', [InvoicePolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple estimates', [EstimatePolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple expenses', [ExpensePolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple payments', [PaymentPolicy::class, 'deleteMultiple']);
|
|
Gate::define('delete multiple recurring invoices', [RecurringInvoicePolicy::class, 'deleteMultiple']);
|
|
|
|
Gate::define('view dashboard', [DashboardPolicy::class, 'view']);
|
|
|
|
Gate::define('view report', [ReportPolicy::class, 'viewReport']);
|
|
|
|
Gate::define('owner only', [OwnerPolicy::class, 'managedByOwner']);
|
|
}
|
|
|
|
public function bootBroadcast()
|
|
{
|
|
Broadcast::routes(['middleware' => 'api.auth']);
|
|
}
|
|
|
|
private function configureInstallWizardTokenAuth(): void
|
|
{
|
|
Sanctum::authenticateAccessTokensUsing(function ($accessToken, bool $isValid): bool {
|
|
if (! $isValid) {
|
|
return false;
|
|
}
|
|
|
|
$request = request();
|
|
|
|
if (! $request instanceof Request || ! $request->attributes->get('install_wizard', false)) {
|
|
return $isValid;
|
|
}
|
|
|
|
return $accessToken->can(InstallWizardAuth::TOKEN_ABILITY);
|
|
});
|
|
}
|
|
}
|