finished the upgrade to filament 4. completely revamped the frontend with codex, now it looks great!

This commit is contained in:
2025-11-13 17:42:43 +01:00
parent f59fda588b
commit b311188bc1
138 changed files with 5440 additions and 4105 deletions

1
.gitignore vendored
View File

@@ -19,3 +19,4 @@ yarn-error.log
/.vscode /.vscode
GEMINI.md GEMINI.md
GEMINI.md.prompt GEMINI.md.prompt
app/Filament/Resources/Styles/StyleResource.php

16
.kilocode/mcp.json Normal file
View File

@@ -0,0 +1,16 @@
{
"mcpServers": {
"laravel-boost": {
"command": "php",
"args": [
"artisan",
"boost:mcp"
],
"transport": "stdio",
"alwaysAllow": [
"application-info"
],
"disabled": false
}
}
}

1
.phpunit.result.cache Normal file
View File

@@ -0,0 +1 @@
{"version":2,"defects":{"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_authenticate_using_the_login_screen":8,"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_not_authenticate_with_invalid_password":8,"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_logout":8,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_verification_screen_can_be_rendered":8,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_can_be_verified":8,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_is_not_verified_with_invalid_hash":8,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_confirm_password_screen_can_be_rendered":8,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_password_can_be_confirmed":8,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_password_is_not_confirmed_with_invalid_password":8,"Tests\\Feature\\Auth\\PasswordResetTest::test_reset_password_link_can_be_requested":8,"Tests\\Feature\\Auth\\PasswordResetTest::test_reset_password_screen_can_be_rendered":8,"Tests\\Feature\\Auth\\PasswordResetTest::test_password_can_be_reset_with_valid_token":8,"Tests\\Feature\\Auth\\PasswordUpdateTest::test_password_can_be_updated":8,"Tests\\Feature\\Auth\\PasswordUpdateTest::test_correct_password_must_be_provided_to_update_password":8,"Tests\\Feature\\Auth\\RegistrationTest::test_new_users_can_register":7,"Tests\\Feature\\ProfileTest::test_profile_page_is_displayed":8,"Tests\\Feature\\ProfileTest::test_profile_information_can_be_updated":8,"Tests\\Feature\\ProfileTest::test_email_verification_status_is_unchanged_when_the_email_address_is_unchanged":8,"Tests\\Feature\\ProfileTest::test_user_can_delete_their_account":8,"Tests\\Feature\\ProfileTest::test_correct_password_must_be_provided_to_delete_account":8,"Tests\\Feature\\ExampleTest::test_the_application_returns_a_successful_response":7,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_index_pages_render":7,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_create_pages_render":7,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_edit_pages_render":7},"times":{"Tests\\Unit\\ExampleTest::test_that_true_is_true":0.001,"Tests\\Feature\\Auth\\AuthenticationTest::test_login_screen_can_be_rendered":2.652,"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_authenticate_using_the_login_screen":0.844,"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_not_authenticate_with_invalid_password":0.003,"Tests\\Feature\\Auth\\AuthenticationTest::test_users_can_logout":0.003,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_verification_screen_can_be_rendered":0.004,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_can_be_verified":0.003,"Tests\\Feature\\Auth\\EmailVerificationTest::test_email_is_not_verified_with_invalid_hash":0.004,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_confirm_password_screen_can_be_rendered":0.003,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_password_can_be_confirmed":0.004,"Tests\\Feature\\Auth\\PasswordConfirmationTest::test_password_is_not_confirmed_with_invalid_password":0.011,"Tests\\Feature\\Auth\\PasswordResetTest::test_reset_password_link_screen_can_be_rendered":0.685,"Tests\\Feature\\Auth\\PasswordResetTest::test_reset_password_link_can_be_requested":0.079,"Tests\\Feature\\Auth\\PasswordResetTest::test_reset_password_screen_can_be_rendered":0.004,"Tests\\Feature\\Auth\\PasswordResetTest::test_password_can_be_reset_with_valid_token":0.003,"Tests\\Feature\\Auth\\PasswordUpdateTest::test_password_can_be_updated":0.003,"Tests\\Feature\\Auth\\PasswordUpdateTest::test_correct_password_must_be_provided_to_update_password":0.003,"Tests\\Feature\\Auth\\RegistrationTest::test_registration_screen_can_be_rendered":0.653,"Tests\\Feature\\Auth\\RegistrationTest::test_new_users_can_register":2.449,"Tests\\Feature\\ExampleTest::test_the_application_returns_a_successful_response":3.546,"Tests\\Feature\\ProfileTest::test_profile_page_is_displayed":0.003,"Tests\\Feature\\ProfileTest::test_profile_information_can_be_updated":0.008,"Tests\\Feature\\ProfileTest::test_email_verification_status_is_unchanged_when_the_email_address_is_unchanged":0.005,"Tests\\Feature\\ProfileTest::test_user_can_delete_their_account":0.004,"Tests\\Feature\\ProfileTest::test_correct_password_must_be_provided_to_delete_account":0.004,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_index_pages_render":6.542,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_create_pages_render":3.055,"Tests\\Feature\\Filament\\ResourcePagesTest::test_admin_resource_edit_pages_render":3.132}}

515
AGENTS.md Normal file
View File

@@ -0,0 +1,515 @@
<laravel-boost-guidelines>
=== foundation rules ===
# Laravel Boost Guidelines
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.3.24
- filament/filament (FILAMENT) - v3
- inertiajs/inertia-laravel (INERTIA) - v1
- laravel/breeze (BREEZE) - v2
- laravel/framework (LARAVEL) - v12
- laravel/prompts (PROMPTS) - v0
- laravel/sanctum (SANCTUM) - v4
- livewire/livewire (LIVEWIRE) - v3
- tightenco/ziggy (ZIGGY) - v2
- laravel/mcp (MCP) - v0
- laravel/pint (PINT) - v1
- laravel/sail (SAIL) - v1
- phpunit/phpunit (PHPUNIT) - v12
- laravel-echo (ECHO) - v2
- @inertiajs/vue3 (INERTIA) - v1
- tailwindcss (TAILWINDCSS) - v3
- vue (VUE) - v3
## Conventions
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.
## Verification Scripts
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
## Application Structure & Architecture
- Stick to existing directory structure - don't create new base folders without approval.
- Do not change the application's dependencies without approval.
## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.
## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
## Documentation Files
- You must only create documentation files if explicitly requested by the user.
=== boost rules ===
## Laravel Boost
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
## Artisan
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double check the available parameters.
## URLs
- Whenever you share a project URL with the user you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain / IP, and port.
## Tinker / Debugging
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
- Use the `database-query` tool when you only need to read from the database.
## Reading Browser Logs With the `browser-logs` Tool
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
- Only recent browser logs will be useful - ignore old logs.
## Searching Documentation (Critically Important)
- Boost comes with a powerful `search-docs` tool you should use before any other approaches. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation specific for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
- The 'search-docs' tool is perfect for all Laravel related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
- You must use this tool to search for Laravel-ecosystem documentation before falling back to other approaches.
- Search the documentation before making code changes to ensure we are taking the correct approach.
- Use multiple, broad, simple, topic based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
- Do not add package names to queries - package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
### Available Search Syntax
- You can and should pass multiple queries at once. The most relevant results will be returned first.
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit"
3. Quoted Phrases (Exact Position) - query="infinite scroll" - Words must be adjacent and in that order
4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit"
5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms
=== php rules ===
## PHP
- Always use curly braces for control structures, even if it has one line.
### Constructors
- Use PHP 8 constructor property promotion in `__construct()`.
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
- Do not allow empty `__construct()` methods with zero parameters.
### Type Declarations
- Always use explicit return type declarations for methods and functions.
- Use appropriate PHP type hints for method parameters.
<code-snippet name="Explicit Return Types and Method Params" lang="php">
protected function isAccessible(User $user, ?string $path = null): bool
{
...
}
</code-snippet>
## Comments
- Prefer PHPDoc blocks over comments. Never use comments within the code itself unless there is something _very_ complex going on.
## PHPDoc Blocks
- Add useful array shape type definitions for arrays when appropriate.
## Enums
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
=== inertia-laravel/core rules ===
## Inertia Core
- Inertia.js components should be placed in the `resources/js/Pages` directory unless specified differently in the JS bundler (vite.config.js).
- Use `Inertia::render()` for server-side routing instead of traditional Blade views.
- Use `search-docs` for accurate guidance on all things Inertia.
<code-snippet lang="php" name="Inertia::render Example">
// routes/web.php example
Route::get('/users', function () {
return Inertia::render('Users/Index', [
'users' => User::all()
]);
});
</code-snippet>
=== inertia-laravel/v1 rules ===
## Inertia v1
- Inertia v1 does _not_ come with these features. Do not recommend using these Inertia v2 features directly.
- Polling
- Prefetching
- Deferred props
- Infinite scrolling using merging props and `WhenVisible`
- Lazy loading data on scroll
=== laravel/core rules ===
## Do Things the Laravel Way
- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
### Database
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
- Use Eloquent models and relationships before suggesting raw database queries
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
- Generate code that prevents N+1 query problems by using eager loading.
- Use Laravel's query builder for very complex database operations.
### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.
### APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
### Controllers & Validation
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
- Check sibling Form Requests to see if the application uses array or string based validation rules.
### Queues
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
### Authentication & Authorization
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
### URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
### Configuration
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
### Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `php artisan make:test [options] <name>` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
### Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
=== laravel/v12 rules ===
## Laravel 12
- Use the `search-docs` tool to get version specific documentation.
- Since Laravel 11, Laravel has a new streamlined file structure which this project uses.
### Laravel 12 Structure
- No middleware files in `app/Http/Middleware/`.
- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.
- `bootstrap/providers.php` contains application specific service providers.
- **No app\Console\Kernel.php** - use `bootstrap/app.php` or `routes/console.php` for console configuration.
- **Commands auto-register** - files in `app/Console/Commands/` are automatically available and do not require manual registration.
### Database
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
- Laravel 11 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
### Models
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
=== livewire/core rules ===
## Livewire Core
- Use the `search-docs` tool to find exact version specific documentation for how to write Livewire & Livewire tests.
- Use the `php artisan make:livewire [Posts\CreatePost]` artisan command to create new components
- State should live on the server, with the UI reflecting it.
- All Livewire requests hit the Laravel backend, they're like regular HTTP requests. Always validate form data, and run authorization checks in Livewire actions.
## Livewire Best Practices
- Livewire components require a single root element.
- Use `wire:loading` and `wire:dirty` for delightful loading states.
- Add `wire:key` in loops:
```blade
@foreach ($items as $item)
<div wire:key="item-{{ $item->id }}">
{{ $item->name }}
</div>
@endforeach
```
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
<code-snippet name="Lifecycle hook examples" lang="php">
public function mount(User $user) { $this->user = $user; }
public function updatedSearch() { $this->resetPage(); }
</code-snippet>
## Testing Livewire
<code-snippet name="Example Livewire component test" lang="php">
Livewire::test(Counter::class)
->assertSet('count', 0)
->call('increment')
->assertSet('count', 1)
->assertSee(1)
->assertStatus(200);
</code-snippet>
<code-snippet name="Testing a Livewire component exists within a page" lang="php">
$this->get('/posts/create')
->assertSeeLivewire(CreatePost::class);
</code-snippet>
=== livewire/v3 rules ===
## Livewire 3
### Key Changes From Livewire 2
- These things changed in Livewire 2, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions.
- Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default.
- Components now use the `App\Livewire` namespace (not `App\Http\Livewire`).
- Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`).
- Use the `components.layouts.app` view as the typical layout path (not `layouts.app`).
### New Directives
- `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples.
### Alpine
- Alpine is now included with Livewire, don't manually include Alpine.js.
- Plugins included with Alpine: persist, intersect, collapse, and focus.
### Lifecycle Hooks
- You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring:
<code-snippet name="livewire:load example" lang="js">
document.addEventListener('livewire:init', function () {
Livewire.hook('request', ({ fail }) => {
if (fail && fail.status === 419) {
alert('Your session expired');
}
});
Livewire.hook('message.failed', (message, component) => {
console.error(message);
});
});
</code-snippet>
=== pint/core rules ===
## Laravel Pint Code Formatter
- You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues.
=== phpunit/core rules ===
## PHPUnit Core
- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `php artisan make:test --phpunit <name>` to create a new test.
- If you see a test using "Pest", convert it to PHPUnit.
- Every time a test has been updated, run that singular test.
- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing.
- Tests should test all of the happy paths, failure paths, and weird paths.
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files, these are core to the application.
### Running Tests
- Run the minimal number of tests, using an appropriate filter, before finalizing.
- To run all tests: `php artisan test`.
- To run all tests in a file: `php artisan test tests/Feature/ExampleTest.php`.
- To filter on a particular test name: `php artisan test --filter=testName` (recommended after making a change to a related file).
=== inertia-vue/core rules ===
## Inertia + Vue
- Vue components must have a single root element.
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
<code-snippet name="Inertia Client Navigation" lang="vue">
import { Link } from '@inertiajs/vue3'
<Link href="/">Home</Link>
</code-snippet>
=== inertia-vue/v1/forms rules ===
## Inertia + Vue Forms
- For form handling in Inertia pages, use `router.post` and related methods. Do not use regular forms.
<code-snippet lang="vue" name="Inertia Vue Form Example">
<script setup>
import { reactive } from 'vue'
import { router } from '@inertiajs/vue3'
import { usePage } from '@inertiajs/vue3'
const page = usePage()
const form = reactive({
first_name: null,
last_name: null,
email: null,
})
function submit() {
router.post('/users', form)
}
</script>
<template>
<h1>Create {{ page.modelName }}</h1>
<form @submit.prevent="submit">
<label for="first_name">First name:</label>
<input id="first_name" v-model="form.first_name" />
<label for="last_name">Last name:</label>
<input id="last_name" v-model="form.last_name" />
<label for="email">Email:</label>
<input id="email" v-model="form.email" />
<button type="submit">Submit</button>
</form>
</template>
</code-snippet>
=== tailwindcss/core rules ===
## Tailwind Core
- Use Tailwind CSS classes to style HTML, check and use existing tailwind conventions within the project before writing your own.
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc..)
- Think through class placement, order, priority, and defaults - remove redundant classes, add classes to parent or child carefully to limit repetition, group elements logically
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
### Spacing
- When listing items, use gap utilities for spacing, don't use margins.
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
<div class="flex gap-8">
<div>Superior</div>
<div>Michigan</div>
<div>Erie</div>
</div>
</code-snippet>
### Dark Mode
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
=== tailwindcss/v3 rules ===
## Tailwind 3
- Always use Tailwind CSS v3 - verify you're using only classes supported by this version.
=== tests rules ===
## Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test` with a specific filename or filter.
=== filament/filament rules ===
## Filament
- Filament is used by this application, check how and where to follow existing application conventions.
- Filament is a Server-Driven UI (SDUI) framework for Laravel. It allows developers to define user interfaces in PHP using structured configuration objects. It is built on top of Livewire, Alpine.js, and Tailwind CSS.
- You can use the `search-docs` tool to get information from the official Filament documentation when needed. This is very useful for Artisan command arguments, specific code examples, testing functionality, relationship management, and ensuring you're following idiomatic practices.
- Utilize static `make()` methods for consistent component initialization.
### Artisan
- You must use the Filament specific Artisan commands to create new files or components for Filament. You can find these with the `list-artisan-commands` tool, or with `php artisan` and the `--help` option.
- Inspect the required options, always pass `--no-interaction`, and valid arguments for other options when applicable.
### Filament's Core Features
- Actions: Handle doing something within the application, often with a button or link. Actions encapsulate the UI, the interactive modal window, and the logic that should be executed when the modal window is submitted. They can be used anywhere in the UI and are commonly used to perform one-time actions like deleting a record, sending an email, or updating data in the database based on modal form input.
- Forms: Dynamic forms rendered within other features, such as resources, action modals, table filters, and more.
- Infolists: Read-only lists of data.
- Notifications: Flash notifications displayed to users within the application.
- Panels: The top-level container in Filament that can include all other features like pages, resources, forms, tables, notifications, actions, infolists, and widgets.
- Resources: Static classes that are used to build CRUD interfaces for Eloquent models. Typically live in `app/Filament/Resources`.
- Schemas: Represent components that define the structure and behavior of the UI, such as forms, tables, or lists.
- Tables: Interactive tables with filtering, sorting, pagination, and more.
- Widgets: Small component included within dashboards, often used for displaying data in charts, tables, or as a stat.
### Relationships
- Determine if you can use the `relationship()` method on form components when you need `options` for a select, checkbox, repeater, or when building a `Fieldset`:
<code-snippet name="Relationship example for Form Select" lang="php">
Forms\Components\Select::make('user_id')
->label('Author')
->relationship('author')
->required(),
</code-snippet>
## Testing
- It's important to test Filament functionality for user satisfaction.
- Ensure that you are authenticated to access the application within the test.
- Filament uses Livewire, so start assertions with `livewire()` or `Livewire::test()`.
### Example Tests
<code-snippet name="Filament Table Test" lang="php">
livewire(ListUsers::class)
->assertCanSeeTableRecords($users)
->searchTable($users->first()->name)
->assertCanSeeTableRecords($users->take(1))
->assertCanNotSeeTableRecords($users->skip(1))
->searchTable($users->last()->email)
->assertCanSeeTableRecords($users->take(-1))
->assertCanNotSeeTableRecords($users->take($users->count() - 1));
</code-snippet>
<code-snippet name="Filament Create Resource Test" lang="php">
livewire(CreateUser::class)
->fillForm([
'name' => 'Howdy',
'email' => 'howdy@example.com',
])
->call('create')
->assertNotified()
->assertRedirect();
assertDatabaseHas(User::class, [
'name' => 'Howdy',
'email' => 'howdy@example.com',
]);
</code-snippet>
<code-snippet name="Testing Multiple Panels (setup())" lang="php">
use Filament\Facades\Filament;
Filament::setCurrentPanel('app');
</code-snippet>
<code-snippet name="Calling an Action in a Test" lang="php">
livewire(EditInvoice::class, [
'invoice' => $invoice,
])->callAction('send');
expect($invoice->refresh())->isSent()->toBeTrue();
</code-snippet>
## Version 3 Changes To Focus On
- Resources are located in `app/Filament/Resources/` directory.
- Resource pages (List, Create, Edit) are auto-generated within the resource's directory - e.g., `app/Filament/Resources/PostResource/Pages/`.
- Forms use the `Forms\Components` namespace for form fields.
- Tables use the `Tables\Columns` namespace for table columns.
- A new `Filament\Forms\Components\RichEditor` component is available.
- Form and table schemas now use fluent method chaining.
- Added `php artisan filament:optimize` command for production optimization.
- Requires implementing `FilamentUser` contract for production access control.
</laravel-boost-guidelines>

View File

@@ -2,6 +2,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Settings\GeneralSettings;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class GetPrinterSetting extends Command class GetPrinterSetting extends Command
@@ -23,15 +24,21 @@ class GetPrinterSetting extends Command
/** /**
* Execute the console command. * Execute the console command.
*/ */
public function handle() public function handle(GeneralSettings $settings)
{ {
$setting = \App\Models\Setting::where('key', 'selected_printer')->first(); $value = $settings->selected_printer === '__custom__'
? $settings->custom_printer_address
: $settings->selected_printer;
if ($setting) { if ($value) {
$this->info('Raw value of \'selected_printer\' setting:'); $this->info('Raw value of \'selected_printer\' setting:');
$this->info(json_encode($setting->value, JSON_PRETTY_PRINT)); // Assuming \'value\' column holds the data $this->info($value);
} else {
$this->info('\'selected_printer\' setting not found.'); return Command::SUCCESS;
} }
$this->info('\'selected_printer\' setting not found.');
return Command::FAILURE;
} }
} }

View File

@@ -2,41 +2,44 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use App\Models\Setting;
use App\Services\PrinterService; use App\Services\PrinterService;
use App\Settings\GeneralSettings;
use BackedEnum;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms; use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Pages\Page; use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use UnitEnum;
class GlobalSettings extends Page implements HasForms class GlobalSettings extends Page implements HasForms
{ {
use InteractsWithForms; use InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-cog'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cog';
protected static string $view = 'filament.pages.global-settings';
protected static ?string $navigationGroup = 'Admin'; protected string $view = 'filament.pages.global-settings';
protected static string|UnitEnum|null $navigationGroup = 'Admin';
public ?array $data = []; public ?array $data = [];
public function mount(): void public function mount(GeneralSettings $settings): void
{ {
$settings = Setting::all()->pluck('value', 'key')->toArray(); $this->form->fill($settings->toArray());
$this->form->fill($settings);
} }
public function form(Form $form): Form public function form(Schema $schema): Schema
{ {
$printerService = new PrinterService(); $printerService = new PrinterService;
$printers = $printerService->getPrinters(); $printers = $printerService->getPrinters();
$printerOptions = array_merge($printers, ['__custom__' => __('filament.resource.setting.form.custom_printer')]); $printerOptions = array_merge($printers, ['__custom__' => __('filament.resource.setting.form.custom_printer')]);
return $form return $schema
->schema([ ->schema([
TextInput::make('gallery_heading') TextInput::make('gallery_heading')
->label(__('filament.resource.setting.form.gallery_heading')) ->label(__('filament.resource.setting.form.gallery_heading'))
@@ -66,18 +69,21 @@ class GlobalSettings extends Page implements HasForms
->statePath('data'); ->statePath('data');
} }
public function save(): void public function save(GeneralSettings $settings): void
{ {
$data = $this->form->getState(); $data = $this->form->getState();
// if a non-custom printer is selected, clear the custom address
if (Arr::get($data, 'selected_printer') !== '__custom__') { if (Arr::get($data, 'selected_printer') !== '__custom__') {
$data['custom_printer_address'] = ''; $data['custom_printer_address'] = null;
} }
foreach ($data as $key => $value) { $data['new_image_timespan_minutes'] = (int) Arr::get($data, 'new_image_timespan_minutes', 0);
Setting::where('key', $key)->update(['value' => $value]); $data['image_refresh_interval'] = (int) Arr::get($data, 'image_refresh_interval', 0);
} $data['max_number_of_copies'] = (int) Arr::get($data, 'max_number_of_copies', 0);
$data['show_print_button'] = (bool) Arr::get($data, 'show_print_button', false);
$data['custom_printer_address'] = $data['custom_printer_address'] ?: null;
$settings->fill($data)->save();
Notification::make() Notification::make()
->title(__('settings.saved_successfully')) ->title(__('settings.saved_successfully'))

View File

@@ -2,23 +2,25 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use BackedEnum;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms; use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Pages\Page; use Filament\Pages\Page;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\File;
use UnitEnum;
class InstallPluginPage extends Page implements HasForms class InstallPluginPage extends Page implements HasForms
{ {
use InteractsWithForms; use InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-cloud-arrow-up'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cloud-arrow-up';
protected static string $view = 'filament.pages.install-plugin-page'; protected string $view = 'filament.pages.install-plugin-page';
protected static ?string $navigationGroup = 'Plugins'; protected static string|UnitEnum|null $navigationGroup = 'Plugins';
protected static ?string $title = 'Install Plugin'; protected static ?string $title = 'Install Plugin';
@@ -29,9 +31,9 @@ class InstallPluginPage extends Page implements HasForms
$this->form->fill(); $this->form->fill();
} }
public function form(Form $form): Form public function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->schema([
FileUpload::make('plugin_file') FileUpload::make('plugin_file')
->label('Plugin File (.php)') ->label('Plugin File (.php)')
@@ -59,10 +61,10 @@ class InstallPluginPage extends Page implements HasForms
$uploadedFile = $data['plugin_file']; $uploadedFile = $data['plugin_file'];
$filename = File::basename($uploadedFile); $filename = File::basename($uploadedFile);
$destinationPath = app_path('Api/Plugins/' . $filename); $destinationPath = app_path('Api/Plugins/'.$filename);
try { try {
File::move(storage_path('app/temp_plugins/' . $filename), $destinationPath); File::move(storage_path('app/temp_plugins/'.$filename), $destinationPath);
Notification::make() Notification::make()
->title('Plugin installed successfully') ->title('Plugin installed successfully')

View File

@@ -2,30 +2,31 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use Filament\Pages\Page;
use App\Models\Plugin; use App\Models\Plugin;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Tables;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use UnitEnum;
class Plugins extends Page class Plugins extends Page implements Tables\Contracts\HasTable
{ {
protected static ?string $navigationIcon = 'heroicon-o-puzzle-piece'; use Tables\Concerns\InteractsWithTable;
protected static ?string $navigationGroup = 'Plugins'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-puzzle-piece';
protected static string|UnitEnum|null $navigationGroup = 'Plugins';
protected static ?string $navigationLabel = 'Plugin List'; protected static ?string $navigationLabel = 'Plugin List';
protected static ?string $title = 'Plugins'; protected static ?string $title = 'Plugins';
protected static string $view = 'filament.pages.plugins'; protected string $view = 'filament.pages.plugins';
protected static ?string $slug = 'list-plugins'; protected static ?string $slug = 'list-plugins';
public $plugins;
public function mount(): void
{
$this->plugins = Plugin::getAllPlugins();
}
public static function getNavigationGroup(): ?string public static function getNavigationGroup(): ?string
{ {
return __('filament.navigation.groups.plugins'); return __('filament.navigation.groups.plugins');
@@ -35,4 +36,29 @@ class Plugins extends Page
{ {
return __('filament.navigation.plugin_list'); return __('filament.navigation.plugin_list');
} }
public function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')
->label(__('Name'))
->searchable()
->sortable(),
TextColumn::make('identifier')
->label(__('Identifier'))
->searchable()
->sortable(),
IconColumn::make('enabled')
->label(__('Enabled'))
->boolean(),
IconColumn::make('configured')
->label(__('Configured'))
->boolean(),
])
->records(fn () => Plugin::getAllPlugins())
->paginated(false)
->emptyStateHeading(__('No plugins found'))
->emptyStateDescription(__('Drop PHP plugin files into app/Api/Plugins (excluding ApiPluginInterface.php).'));
}
} }

View File

@@ -1,108 +1,55 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\AiModels;
use App\Filament\Resources\AiModelResource\Pages; use BackedEnum;
use App\Filament\Resources\AiModelResource\RelationManagers; use App\Filament\Resources\AiModels\Pages;
use App\Filament\Resources\AiModels\RelationManagers;
use App\Models\AiModel; use App\Models\AiModel;
use Filament\Forms; use Filament\Schemas\Schema;
use Filament\Forms\Form;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Select; use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Actions\Action; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Database\Eloquent\Model;
use App\Models\ApiProvider; use App\Models\ApiProvider;
use App\Api\Plugins\PluginLoader; use App\Api\Plugins\PluginLoader;
use App\Api\Plugins\ApiPluginInterface; use App\Api\Plugins\ApiPluginInterface;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\Textarea;
class AiModelResource extends Resource class AiModelResource extends Resource
{ {
protected static ?string $model = AiModel::class; protected static ?string $model = AiModel::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; // protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\Section::make() TextInput::make('name')
->schema([ ->required(),
Select::make('api_provider_id') TextInput::make('model_id')
->label(__('filament.resource.ai_model.form.api_provider')) ->required(),
->relationship('primaryApiProvider', 'name') TextInput::make('model_type')
->live() ->nullable(),
->afterStateUpdated(function (callable $set) { Toggle::make('enabled')
$set('model_search_result', null); ->default(true),
}), Textarea::make('parameters')
Select::make('model_search_result') ->nullable()
->label(__('filament.resource.ai_model.form.search_model')) ->rows(15),
->searchable()
->live()
->hidden(fn (callable $get) => !static::canSearchModels($get('api_provider_id')))
->getSearchResultsUsing(function (string $search, callable $get) {
$apiProviderId = $get('api_provider_id');
if (!$apiProviderId) {
return [];
}
$pluginInstance = static::getPluginInstance($apiProviderId);
if ($pluginInstance && method_exists($pluginInstance, 'searchModels')) {
$models = $pluginInstance->searchModels($search);
$options = [];
foreach ($models as $model) {
$options[json_encode(['name' => $model['name'], 'id' => $model['id'], 'type' => $model['type'] ?? null, 'api_provider_id' => $apiProviderId])] = $model['name'] . ' (' . $model['id'] . ')';
}
return $options;
}
return [];
})
->getOptionLabelUsing(function ($value) {
$decoded = json_decode($value, true);
return $decoded['name'] . ' (' . $decoded['id'] . ')';
})
->afterStateUpdated(function (callable $set, $state) {
if ($state) {
$selectedModel = json_decode($state, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return; // Stop if JSON is invalid
}
$set('name', $selectedModel['name']);
$set('model_id', $selectedModel['id']);
$set('model_type', $selectedModel['type'] ?? null);
}
}),
TextInput::make('name')
->label(__('filament.resource.ai_model.form.name'))
->required()
->maxLength(255)
->live(),
TextInput::make('model_id')
->label(__('filament.resource.ai_model.form.model_id'))
->required()
->maxLength(255)
->live(),
TextInput::make('model_type')
->nullable()
->maxLength(255)
->live(),
Forms\Components\Toggle::make('enabled')
->label(__('filament.resource.ai_model.form.enabled'))
->default(true),
Forms\Components\Textarea::make('parameters')
->label(__('filament.resource.ai_model.form.parameters'))
->nullable()
->rows(15)
->json(JSON_PRETTY_PRINT)
->helperText(__('filament.resource.ai_model.form.parameters_help'))
])
]); ]);
} }
protected static function canSearchModelsWithAnyProvider(?array $apiProviderIds): bool protected static function canSearchModelsWithAnyProvider(?array $apiProviderIds): bool
{ {
if (empty($apiProviderIds)) { if (empty($apiProviderIds)) {
@@ -166,33 +113,32 @@ class AiModelResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
TextColumn::make('name')->label(__('filament.resource.ai_model.table.name'))->searchable()->sortable(), TextColumn::make('name')->searchable()->sortable(),
TextColumn::make('model_id')->label(__('filament.resource.ai_model.table.model_id'))->searchable()->sortable(), TextColumn::make('model_id')->searchable()->sortable(),
TextColumn::make('model_type')->label(__('filament.resource.ai_model.table.model_type'))->searchable()->sortable(), TextColumn::make('model_type')->searchable()->sortable(),
Tables\Columns\IconColumn::make('enabled') IconColumn::make('enabled')
->label(__('filament.resource.ai_model.table.enabled'))
->boolean(), ->boolean(),
TextColumn::make('primaryApiProvider.name')->label(__('filament.resource.ai_model.table.api_provider'))->searchable()->sortable()->limit(50), TextColumn::make('primaryApiProvider.name')->searchable()->sortable()->limit(50),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
Action::make('duplicate') Action::make('duplicate')
->label(__('filament.resource.style.action.duplicate')) ->label('Duplicate')
->icon('heroicon-o-document-duplicate') ->icon('heroicon-o-document-duplicate')
->action(function (AiModel $record, $livewire) { ->action(function (Model $record, $livewire) {
$livewire->redirect(AiModelResource::getUrl('create', ['sourceRecord' => $record->id])); $livewire->redirect(static::getUrl('create', ['sourceRecord' => $record->id]));
}), }),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]), ]),
]) ])
->emptyStateActions([ ->emptyStateActions([
Tables\Actions\CreateAction::make(), CreateAction::make(),
]); ]);
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\AiModelResource\Pages; namespace App\Filament\Resources\AiModels\Pages;
use App\Filament\Resources\AiModelResource; use App\Filament\Resources\AiModels\AiModelResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use Illuminate\Http\Request; use Illuminate\Http\Request;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\AiModelResource\Pages; namespace App\Filament\Resources\AiModels\Pages;
use App\Filament\Resources\AiModelResource; use App\Filament\Resources\AiModels\AiModelResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\AiModelResource\Pages; namespace App\Filament\Resources\AiModels\Pages;
use App\Filament\Resources\AiModelResource; use App\Filament\Resources\AiModels\AiModelResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Contracts\Pagination\Paginator;

View File

@@ -1,14 +1,18 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\ApiProviders;
use App\Filament\Resources\ApiProviderResource\Pages; use App\Filament\Resources\ApiProviders\Pages;
use App\Filament\Resources\ApiProviderResource\RelationManagers; use App\Filament\Resources\ApiProviders\RelationManagers;
use App\Models\ApiProvider; use App\Models\ApiProvider;
use Filament\Forms; use Filament\Schemas;
use Filament\Forms\Form; use Filament\Schemas\Schema;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
@@ -19,210 +23,102 @@ use Illuminate\Support\Facades\File;
use App\Api\Plugins\ApiPluginInterface; use App\Api\Plugins\ApiPluginInterface;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Tables\Columns\IconColumn; use Filament\Tables\Columns\IconColumn;
use Filament\Forms\Components\Actions; use BackedEnum;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Components\ViewField;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Log;
use App\Api\Plugins\PluginLoader;
class ApiProviderResource extends Resource class ApiProviderResource extends Resource
{ {
protected static ?string $model = ApiProvider::class; protected static ?string $model = ApiProvider::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
$plugins = self::getAvailablePlugins(); $plugins = self::getAvailablePlugins();
$livewire = $form->getLivewire(); return $schema
return $form ->components([
->schema([ TextInput::make('name')
Forms\Components\Section::make() ->required()
->schema([ ->maxLength(255),
TextInput::make('name') Toggle::make('enabled')
->label(__('filament.resource.api_provider.form.name')) ->default(true),
->required() TextInput::make('api_url')
->maxLength(255), ->required()
Toggle::make('enabled') ->url()
->label(__('filament.resource.api_provider.form.enabled')) ->maxLength(255),
->default(true), TextInput::make('username')
TextInput::make('api_url') ->nullable()
->label(__('filament.resource.api_provider.form.api_url')) ->maxLength(255),
->required() TextInput::make('password')
->url() ->password()
->maxLength(255), ->nullable()
TextInput::make('username') ->maxLength(255),
->label(__('filament.resource.api_provider.form.username')) TextInput::make('token')
->nullable() ->nullable()
->maxLength(255), ->maxLength(255),
TextInput::make('password') Select::make('plugin')
->label(__('filament.resource.api_provider.form.password')) ->options($plugins)
->password() ->nullable(),
->nullable()
->maxLength(255),
TextInput::make('token')
->label(__('filament.resource.api_provider.form.token'))
->nullable()
->maxLength(255),
Select::make('plugin')
->options($plugins)
->nullable()
->label(__('filament.resource.api_provider.form.plugin')),
Actions::make([
Action::make('test_connection')
->label(__('filament.resource.api_provider.action.test_connection'))
->icon(function (\Livewire\Component $livewire) {
return match ($livewire->testResultState) {
'success' => 'heroicon-o-check-circle',
'failed' => 'heroicon-o-x-circle',
default => 'heroicon-o-link',
};
})
->color(function (\Livewire\Component $livewire) {
return match ($livewire->testResultState) {
'success' => 'success',
'failed' => 'danger',
default => 'gray',
};
})
->action(function (array $data, Forms\Components\Component $component, \Livewire\Component $livewire) {
$formData = $component->getLivewire()->form->getState();
$apiUrl = str_replace('127.0.0.1', 'localhost', $formData['api_url'] ?? null);
$pluginName = $formData['plugin'] ?? null;
$token = $formData['token'] ?? null;
if (!$pluginName) {
Notification::make()
->title(__('filament.resource.api_provider.notification.connection_failed'))
->body('Please select a plugin first.')
->danger()
->send();
$component->getLivewire()->dispatch('testConnectionFinished', result: 'failed');
return;
}
try {
// Create a dummy ApiProvider model for the test
$dummyApiProvider = new \App\Models\ApiProvider();
$dummyApiProvider->api_url = $apiUrl;
$dummyApiProvider->token = $token;
// Load the specific plugin using the PluginLoader
$pluginInstance = PluginLoader::getPlugin($pluginName, $dummyApiProvider);
// Call the testConnection method of the plugin
$testResult = $pluginInstance->testConnection([
'api_url' => $apiUrl,
'token' => $token,
'username' => $formData['username'] ?? null,
'password' => $formData['password'] ?? null,
]);
if ($testResult) {
Notification::make()
->title(__('filament.resource.api_provider.notification.connection_successful'))
->success()
->send();
$component->getLivewire()->dispatch('testConnectionFinished', result: 'success');
} else {
Notification::make()
->title(__('filament.resource.api_provider.notification.connection_failed'))
->body('Plugin reported connection failed. Check logs for details.')
->danger()
->send();
$component->getLivewire()->dispatch('testConnectionFinished', result: 'failed');
}
} catch (\Exception $e) {
Log::error('Plugin test connection failed: An unexpected error occurred.', [
'api_url' => $apiUrl,
'plugin' => $pluginName,
'error_message' => $e->getMessage(),
]);
Notification::make()
->title(__('filament.resource.api_provider.notification.connection_failed'))
->body('An unexpected error occurred during plugin test: ' . $e->getMessage())
->danger()
->send();
$component->getLivewire()->dispatch('testConnectionFinished', result: 'failed');
}
}),
]),
])
]); ]);
} }
public static function table(Table $table): Table public static function table(Table $table): Table
{ {
return $table return $table
->columns([ ->columns([
TextColumn::make('name')->label(__('filament.resource.api_provider.table.name'))->searchable()->sortable(), TextColumn::make('name')->searchable()->sortable(),
IconColumn::make('enabled') IconColumn::make('enabled')
->label(__('filament.resource.api_provider.table.enabled'))
->boolean(), ->boolean(),
TextColumn::make('api_url')->label(__('filament.resource.api_provider.table.api_url'))->searchable(), TextColumn::make('api_url')->searchable(),
TextColumn::make('plugin')->label(__('filament.resource.api_provider.table.plugin'))->searchable()->sortable(), TextColumn::make('plugin')->searchable()->sortable(),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
Tables\Actions\BulkAction::make('enable')
->label(__('filament.resource.api_provider.action.enable_selected'))
->icon('heroicon-o-check-circle')
->action(function (\Illuminate\Support\Collection $records) {
$records->each->update(['enabled' => true]);
}),
Tables\Actions\BulkAction::make('disable')
->label(__('filament.resource.api_provider.action.disable_selected'))
->icon('heroicon-o-x-circle')
->action(function (\Illuminate\Support\Collection $records) {
$records->each->update(['enabled' => false]);
}),
]), ]),
]) ])
->emptyStateActions([ ->emptyStateActions([
Tables\Actions\CreateAction::make(), CreateAction::make(),
]); ]);
} }
public static function getRelations(): array
{ public static function getRelations(): array
return [ {
// return [
]; //
];
} }
public static function getPages(): array
{ public static function getPages(): array
return [ {
'index' => Pages\ListApiProviders::route('/'), return [
'create' => Pages\CreateApiProvider::route('/create'), 'index' => Pages\ListApiProviders::route('/'),
'edit' => Pages\EditApiProvider::route('/{record}/edit'), 'create' => Pages\CreateApiProvider::route('/create'),
]; 'edit' => Pages\EditApiProvider::route('/{record}/edit'),
];
} }
protected static function getAvailablePlugins(): array
{ protected static function getAvailablePlugins(): array
$plugins = []; {
$path = app_path('Api/Plugins'); $plugins = [];
$files = File::files($path); $path = app_path('Api/Plugins');
$files = File::files($path);
foreach ($files as $file) {
$filename = $file->getFilenameWithoutExtension(); foreach ($files as $file) {
if (in_array($filename, ['ApiPluginInterface', 'PluginLoader'])) { $filename = $file->getFilenameWithoutExtension();
continue; if (in_array($filename, ['ApiPluginInterface', 'PluginLoader'])) {
} continue;
$class = "App\Api\Plugins\\" . $filename;
if (class_exists($class) && in_array(ApiPluginInterface::class, class_implements($class))) {
// Do not instantiate here, just get identifier and name if possible statically or by convention
// For now, we'll use filename as identifier and name
$plugins[$filename] = $filename;
} }
} $class = "App\Api\Plugins\\" . $filename;
return $plugins; if (class_exists($class) && in_array(ApiPluginInterface::class, class_implements($class))) {
} $plugins[$filename] = $filename;
} }
}
return $plugins;
}
}

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ApiProviderResource\Pages; namespace App\Filament\Resources\ApiProviders\Pages;
use App\Filament\Resources\ApiProviderResource; use App\Filament\Resources\ApiProviders\ApiProviderResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
use Livewire\Attributes\On; use Livewire\Attributes\On;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ApiProviderResource\Pages; namespace App\Filament\Resources\ApiProviders\Pages;
use App\Filament\Resources\ApiProviderResource; use App\Filament\Resources\ApiProviders\ApiProviderResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
use Livewire\Attributes\On; use Livewire\Attributes\On;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ApiProviderResource\Pages; namespace App\Filament\Resources\ApiProviders\Pages;
use App\Filament\Resources\ApiProviderResource; use App\Filament\Resources\ApiProviders\ApiProviderResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Contracts\Pagination\Paginator;

View File

@@ -1,38 +1,43 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Images;
use App\Filament\Resources\ImageResource\Pages; use BackedEnum;
use App\Filament\Resources\ImageResource\RelationManagers; use App\Filament\Resources\Images\Pages;
use App\Filament\Resources\Images\RelationManagers;
use App\Models\Image; use App\Models\Image;
use Filament\Forms; use Filament\Schemas;
use Filament\Forms\Form; use Filament\Schemas\Schema;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Toggle;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
class ImageResource extends Resource class ImageResource extends Resource
{ {
protected static ?string $model = Image::class; protected static ?string $model = Image::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
FileUpload::make('path') FileUpload::make('path')
->label(__('filament.resource.image.form.path'))
->required() ->required()
->image() ->image()
->directory('uploads'), ->directory('uploads')
Forms\Components\Toggle::make('is_public') ->disk('public'),
->label(__('Publicly Visible')) Toggle::make('is_public')
->default(false), ->default(false),
]); ]);
} }
@@ -41,19 +46,23 @@ class ImageResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
TextColumn::make('path')->label(__('filament.resource.image.table.path'))->searchable()->sortable(), TextColumn::make('path')->searchable()->sortable(),
Tables\Columns\ImageColumn::make('path')->label(__('filament.resource.image.table.image')), ImageColumn::make('path')
->disk('public'),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]), ]),
])
->emptyStateActions([
CreateAction::make(),
]); ]);
} }
@@ -71,4 +80,4 @@ class ImageResource extends Resource
'edit' => Pages\EditImage::route('/{record}/edit'), 'edit' => Pages\EditImage::route('/{record}/edit'),
]; ];
} }
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ImageResource\Pages; namespace App\Filament\Resources\Images\Pages;
use App\Filament\Resources\ImageResource; use App\Filament\Resources\Images\ImageResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\ImageResource\Pages; namespace App\Filament\Resources\Images\Pages;
use App\Filament\Resources\ImageResource; use App\Filament\Resources\Images\ImageResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Contracts\Pagination\Paginator;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\RoleResource\Pages; namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\RoleResource; use App\Filament\Resources\Roles\RoleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\RoleResource\Pages; namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\RoleResource; use App\Filament\Resources\Roles\RoleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\RoleResource\Pages; namespace App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\RoleResource; use App\Filament\Resources\Roles\RoleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;

View File

@@ -1,33 +1,36 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Roles;
use App\Filament\Resources\RoleResource\Pages; use UnitEnum;
use App\Filament\Resources\RoleResource\RelationManagers; use App\Filament\Resources\Roles\Pages;
use App\Filament\Resources\Roles\RelationManagers;
use App\Models\Role; use App\Models\Role;
use Filament\Forms; use Filament\Schemas;
use Filament\Forms\Form; use Filament\Schemas\Schema;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
class RoleResource extends Resource class RoleResource extends Resource
{ {
protected static ?string $model = Role::class; protected static ?string $model = Role::class;
protected static ?string $navigationGroup = 'User Management'; protected static UnitEnum|string|null $navigationGroup = 'User Management';
protected static ?string $navigationLabel = 'User Roles'; protected static ?string $navigationLabel = 'User Roles';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
TextInput::make('name') TextInput::make('name')
->label(__('filament.resource.role.form.name'))
->required() ->required()
->maxLength(255), ->maxLength(255),
]); ]);
@@ -37,21 +40,21 @@ class RoleResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
TextColumn::make('name')->label(__('filament.resource.role.table.name'))->searchable()->sortable(), TextColumn::make('name')->searchable()->sortable(),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]), ]),
]) ])
->emptyStateActions([ ->emptyStateActions([
Tables\Actions\CreateAction::make(), CreateAction::make(),
]); ]);
} }
@@ -70,4 +73,4 @@ class RoleResource extends Resource
'edit' => Pages\EditRole::route('/{record}/edit'), 'edit' => Pages\EditRole::route('/{record}/edit'),
]; ];
} }
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\StyleResource\Pages; namespace App\Filament\Resources\Styles\Pages;
use App\Filament\Resources\StyleResource; use App\Filament\Resources\Styles\StyleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\StyleResource\Pages; namespace App\Filament\Resources\Styles\Pages;
use App\Filament\Resources\StyleResource; use App\Filament\Resources\Styles\StyleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\StyleResource\Pages; namespace App\Filament\Resources\Styles\Pages;
use App\Filament\Resources\StyleResource; use App\Filament\Resources\Styles\StyleResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Filament\Tables\Concerns\CanReorderRecords; use Filament\Tables\Concerns\CanReorderRecords;

View File

@@ -1,10 +1,11 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Styles;
use App\Filament\Resources\StyleResource\Pages; use BackedEnum;
use App\Filament\Resources\Styles\Pages;
use App\Models\Style; use App\Models\Style;
use Filament\Forms; use Filament\Schemas;
use Filament\Forms\Form; use Filament\Schemas\Schema;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
@@ -17,70 +18,68 @@ use Filament\Tables\Columns\ImageColumn;
use Filament\Forms\Components\Toggle; use Filament\Forms\Components\Toggle;
use Filament\Tables\Columns\IconColumn; use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Filters\SelectFilter; use Filament\Tables\Filters\SelectFilter;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
class StyleResource extends Resource class StyleResource extends Resource
{ {
protected static ?string $model = Style::class; protected static ?string $model = Style::class;
protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack'; protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-rectangle-stack';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->columns('full') ->columns(1)
->schema([ ->components([
Forms\Components\Tabs::make('Style Details') Tabs::make('Style Details')
->tabs([ ->tabs([
Forms\Components\Tabs\Tab::make('General') Tab::make('General')
->schema([ ->components([
Forms\Components\Grid::make(2) Grid::make(2)
->schema([ ->columnSpanFull()
->components([
TextInput::make('title') TextInput::make('title')
->label(__('filament.resource.style.form.title')) ->required()
->required() ->maxLength(255),
->maxLength(255), Toggle::make('enabled')
Toggle::make('enabled') ->default(true),
->label(__('filament.resource.style.form.enabled')) ]),
->default(true), Grid::make(2)
]), ->columnSpanFull()
Forms\Components\Grid::make(2) ->components([
->schema([
Textarea::make('prompt') Textarea::make('prompt')
->label(__('filament.resource.style.form.prompt'))
->required() ->required()
->rows(5), ->rows(5),
Textarea::make('description') Textarea::make('description')
->label(__('filament.resource.style.form.description'))
->required() ->required()
->rows(5), ->rows(5),
]), ]),
Select::make('ai_model_id') Select::make('ai_model_id')
->relationship('aiModel', 'name') ->relationship('aiModel', 'name')
->label(__('filament.resource.style.form.ai_model'))
->required(), ->required(),
FileUpload::make('preview_image') FileUpload::make('preview_image')
->label(__('filament.resource.style.form.preview_image'))
->disk('public') ->disk('public')
->directory('style_previews') ->directory('style_previews')
->image() ->image()
->imageEditor() ->imageEditor()
->required() ->required(),
->rules(['mimes:jpeg,png,bmp,gif,webp']),
]), ]),
Forms\Components\Tabs\Tab::make('Details') Tab::make('Details')
->schema([ ->components([
TextInput::make('sort_order')
Forms\Components\TextInput::make('sort_order')
->numeric() ->numeric()
->default(0) ->default(0),
->label(__('filament.resource.style.form.sort_order')),
Textarea::make('parameters') Textarea::make('parameters')
->label(__('filament.resource.style.form.parameters'))
->nullable() ->nullable()
->rows(15) ->rows(15),
->json()
->helperText(__('filament.resource.style.form.parameters_help'))
->formatStateUsing(fn (?array $state): ?string => $state ? json_encode($state, JSON_PRETTY_PRINT) : null),
]), ]),
]), ]),
]); ]);
@@ -90,45 +89,42 @@ class StyleResource extends Resource
{ {
return $table return $table
->defaultSort('sort_order') ->defaultSort('sort_order')
->reorderable('sort_order')
->columns([ ->columns([
TextColumn::make('title')->label(__('filament.resource.style.table.title'))->searchable()->sortable(), TextColumn::make('title')->searchable()->sortable(),
IconColumn::make('enabled') IconColumn::make('enabled')
->label(__('filament.resource.style.table.enabled'))
->boolean(), ->boolean(),
TextColumn::make('aiModel.name')->label(__('filament.resource.style.table.ai_model'))->searchable()->sortable(), TextColumn::make('aiModel.name')->searchable()->sortable(),
ImageColumn::make('preview_image')->label(__('filament.resource.style.table.preview_image'))->disk('public'), ImageColumn::make('preview_image')->disk('public'),
TextColumn::make('sort_order')->label(__('filament.resource.style.table.sort_order'))->sortable(), TextColumn::make('sort_order')->sortable(),
]) ])
->filters([ ->filters([
SelectFilter::make('ai_model') SelectFilter::make('ai_model')
->relationship('aiModel', 'name') ->relationship('aiModel', 'name'),
->label(__('filament.resource.style.table.ai_model')),
]) ])
->deferFilters(false)
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
Tables\Actions\Action::make('duplicate') Action::make('duplicate')
->label(__('filament.resource.style.action.duplicate')) ->label('Duplicate')
->icon('heroicon-o-document-duplicate') ->icon('heroicon-o-document-duplicate')
->action(function (\App\Models\Style $record) { ->action(function (\App\Models\Style $record) {
$newStyle = $record->replicate(); $newStyle = $record->replicate();
$newStyle->title = $record->title . ' (Kopie)'; $newStyle->title = $record->title . ' (Kopie)';
$newStyle->save(); $newStyle->save();
return redirect()->to(\App\Filament\Resources\Styles\StyleResource::getUrl('edit', ['record' => $newStyle->id]));
return redirect()->to(StyleResource::getUrl('edit', ['record' => $newStyle->id]));
}), }),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
Tables\Actions\BulkAction::make('enable') BulkAction::make('enable')
->label(__('filament.resource.style.action.enable_selected')) ->label('Enable Selected')
->icon('heroicon-o-check-circle') ->icon('heroicon-o-check-circle')
->action(function (\Illuminate\Support\Collection $records) { ->action(function (\Illuminate\Support\Collection $records) {
$records->each->update(['enabled' => true]); $records->each->update(['enabled' => true]);
}), }),
Tables\Actions\BulkAction::make('disable') BulkAction::make('disable')
->label(__('filament.resource.style.action.disable_selected')) ->label('Disable Selected')
->icon('heroicon-o-x-circle') ->icon('heroicon-o-x-circle')
->action(function (\Illuminate\Support\Collection $records) { ->action(function (\Illuminate\Support\Collection $records) {
$records->each->update(['enabled' => false]); $records->each->update(['enabled' => false]);
@@ -136,7 +132,7 @@ class StyleResource extends Resource
]), ]),
]) ])
->emptyStateActions([ ->emptyStateActions([
Tables\Actions\CreateAction::make(), CreateAction::make(),
]); ]);
} }
@@ -155,4 +151,4 @@ class StyleResource extends Resource
'edit' => Pages\EditStyle::route('/{record}/edit'), 'edit' => Pages\EditStyle::route('/{record}/edit'),
]; ];
} }
} }

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\UserResource\Pages; namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\UserResource; use App\Filament\Resources\Users\UserResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\UserResource\Pages; namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\UserResource; use App\Filament\Resources\Users\UserResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;

View File

@@ -1,8 +1,8 @@
<?php <?php
namespace App\Filament\Resources\UserResource\Pages; namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\UserResource; use App\Filament\Resources\Users\UserResource;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\ListRecords; use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Contracts\Pagination\Paginator;

View File

@@ -1,45 +1,48 @@
<?php <?php
namespace App\Filament\Resources; namespace App\Filament\Resources\Users;
use App\Filament\Resources\UserResource\Pages; use UnitEnum;
use App\Filament\Resources\UserResource\RelationManagers; use App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\RelationManagers;
use App\Models\User; use App\Models\User;
use Filament\Forms; use Filament\Schemas;
use Filament\Forms\Form; use Filament\Schemas\Schema;
use Filament\Resources\Resource; use Filament\Resources\Resource;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope; use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\Toggle;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
class UserResource extends Resource class UserResource extends Resource
{ {
protected static ?string $model = User::class; protected static ?string $model = User::class;
protected static ?string $navigationGroup = 'User Management'; protected static string|UnitEnum|null $navigationGroup = 'User Management';
protected static ?string $navigationLabel = 'User Roles'; protected static ?string $navigationLabel = 'Users';
public static function form(Form $form): Form public static function form(Schema $schema): Schema
{ {
return $form return $schema
->schema([ ->components([
Forms\Components\Section::make('User Details') Section::make('User Details')
->schema([ ->components([
TextInput::make('name') TextInput::make('name')
->label(__('filament.resource.user.form.name'))
->required() ->required()
->maxLength(255), ->maxLength(255),
TextInput::make('email') TextInput::make('email')
->label(__('filament.resource.user.form.email'))
->email() ->email()
->required() ->required()
->maxLength(255), ->maxLength(255),
TextInput::make('password') TextInput::make('password')
->label(__('filament.resource.user.form.password'))
->password() ->password()
->dehydrateStateUsing(fn (string $state): string => bcrypt($state)) ->dehydrateStateUsing(fn (string $state): string => bcrypt($state))
->dehydrated(fn (?string $state): bool => filled($state)) ->dehydrated(fn (?string $state): bool => filled($state))
@@ -47,30 +50,28 @@ class UserResource extends Resource
->maxLength(255), ->maxLength(255),
Select::make('role_id') Select::make('role_id')
->relationship('role', 'name') ->relationship('role', 'name')
->label(__('filament.resource.user.form.role'))
->required(), ->required(),
])->columns(2), ])->columns(2)
->columnSpanFull(),
Forms\Components\Section::make('Preferences') Section::make('Preferences')
->schema([ ->components([
Forms\Components\Toggle::make('email_notifications_enabled') Toggle::make('email_notifications_enabled')
->label(__('Email Notifications'))
->default(true), ->default(true),
Select::make('theme_preference') Select::make('theme_preference')
->label(__('Theme'))
->options([ ->options([
'light' => 'Light', 'light' => 'Light',
'dark' => 'Dark', 'dark' => 'Dark',
]) ])
->default('light'), ->default('light'),
Select::make('locale') Select::make('locale')
->label(__('Language'))
->options([ ->options([
'en' => 'English', 'en' => 'English',
'de' => 'Deutsch', 'de' => 'Deutsch',
]) ])
->default('en'), ->default('en'),
])->columns(2), ])->columns(2)
->columnSpanFull(),
]); ]);
} }
@@ -78,23 +79,23 @@ class UserResource extends Resource
{ {
return $table return $table
->columns([ ->columns([
TextColumn::make('name')->label(__('filament.resource.user.table.name'))->searchable()->sortable(), TextColumn::make('name')->searchable()->sortable(),
TextColumn::make('email')->label(__('filament.resource.user.table.email'))->searchable()->sortable(), TextColumn::make('email')->searchable()->sortable(),
TextColumn::make('role.name')->label(__('filament.resource.user.table.role'))->searchable()->sortable(), TextColumn::make('role.name')->searchable()->sortable(),
]) ])
->filters([ ->filters([
// //
]) ])
->actions([ ->actions([
Tables\Actions\EditAction::make(), EditAction::make(),
]) ])
->bulkActions([ ->bulkActions([
Tables\Actions\BulkActionGroup::make([ BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(), DeleteBulkAction::make(),
]), ]),
]) ])
->emptyStateActions([ ->emptyStateActions([
Tables\Actions\CreateAction::make(), CreateAction::make(),
]); ]);
} }
@@ -123,4 +124,4 @@ class UserResource extends Resource
{ {
return __('filament.navigation.user_roles'); return __('filament.navigation.user_roles');
} }
} }

View File

@@ -2,25 +2,27 @@
namespace App\Http\Controllers\Api; namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Api\Plugins\PluginLoader; use App\Api\Plugins\PluginLoader;
use App\Http\Controllers\Controller;
use App\Models\ApiProvider; use App\Models\ApiProvider;
use App\Models\Style;
use App\Models\Image; use App\Models\Image;
use App\Models\Style;
use App\Settings\GeneralSettings;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use App\Models\Setting;
class ImageController extends Controller class ImageController extends Controller
{ {
public function __construct(private GeneralSettings $settings) {}
public function index(Request $request) public function index(Request $request)
{ {
$publicUploadsPath = public_path('storage/uploads'); $publicUploadsPath = public_path('storage/uploads');
// Ensure the directory exists // Ensure the directory exists
if (!File::exists($publicUploadsPath)) { if (! File::exists($publicUploadsPath)) {
File::makeDirectory($publicUploadsPath, 0755, true); File::makeDirectory($publicUploadsPath, 0755, true);
} }
@@ -29,7 +31,7 @@ class ImageController extends Controller
$diskImagePaths = []; $diskImagePaths = [];
foreach ($diskFiles as $file) { foreach ($diskFiles as $file) {
// Store path relative to public/storage/ // Store path relative to public/storage/
$diskImagePaths[] = 'uploads/' . $file->getFilename(); $diskImagePaths[] = 'uploads/'.$file->getFilename();
} }
$dbImagePaths = Image::pluck('path')->toArray(); $dbImagePaths = Image::pluck('path')->toArray();
@@ -48,7 +50,7 @@ class ImageController extends Controller
$query = Image::orderBy('updated_at', 'desc'); $query = Image::orderBy('updated_at', 'desc');
// If user is not authenticated, filter by is_public, but also include their temporary images // If user is not authenticated, filter by is_public, but also include their temporary images
if (!auth()->check()) { if (! auth()->check()) {
$query->where(function ($q) { $query->where(function ($q) {
$q->where('is_public', true)->orWhere('is_temp', true); $q->where('is_public', true)->orWhere('is_temp', true);
}); });
@@ -56,10 +58,11 @@ class ImageController extends Controller
// If user is authenticated, show all their images // If user is authenticated, show all their images
} }
$newImageTimespanMinutes = Setting::where('key', 'new_image_timespan_minutes')->first()->value ?? 60; // Default to 60 minutes $newImageTimespanMinutes = $this->settings->new_image_timespan_minutes;
$images = $query->get()->map(function ($image) use ($newImageTimespanMinutes) { $images = $query->get()->map(function ($image) use ($newImageTimespanMinutes) {
$image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes; $image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes;
return $image; return $image;
}); });
@@ -67,13 +70,14 @@ class ImageController extends Controller
foreach ($images as $image) { foreach ($images as $image) {
$formattedImages[] = [ $formattedImages[] = [
'image_id' => $image->id, 'image_id' => $image->id,
'path' => asset('storage/' . $image->path), 'path' => asset('storage/'.$image->path),
'name' => basename($image->path), 'name' => basename($image->path),
'is_temp' => (bool) $image->is_temp, 'is_temp' => (bool) $image->is_temp,
'is_public' => (bool) $image->is_public, 'is_public' => (bool) $image->is_public,
'is_new' => (bool) $image->is_new, 'is_new' => (bool) $image->is_new,
]; ];
} }
return response()->json($formattedImages); return response()->json($formattedImages);
} }
@@ -84,16 +88,16 @@ class ImageController extends Controller
]); ]);
$file = $request->file('image'); $file = $request->file('image');
$fileName = uniqid() . '.' . $file->getClientOriginalExtension(); $fileName = uniqid().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('storage/uploads'); $destinationPath = public_path('storage/uploads');
// Ensure the directory exists // Ensure the directory exists
if (!File::exists($destinationPath)) { if (! File::exists($destinationPath)) {
File::makeDirectory($destinationPath, 0755, true); File::makeDirectory($destinationPath, 0755, true);
} }
$file->move($destinationPath, $fileName); $file->move($destinationPath, $fileName);
$relativePath = 'uploads/' . $fileName; // Path relative to public/storage/ $relativePath = 'uploads/'.$fileName; // Path relative to public/storage/
$image = Image::create([ $image = Image::create([
'path' => $relativePath, 'path' => $relativePath,
@@ -103,7 +107,7 @@ class ImageController extends Controller
return response()->json([ return response()->json([
'message' => __('api.image_uploaded_successfully'), 'message' => __('api.image_uploaded_successfully'),
'image_id' => $image->id, 'image_id' => $image->id,
'path' => asset('storage/' . $relativePath), 'path' => asset('storage/'.$relativePath),
]); ]);
} }
@@ -113,9 +117,9 @@ class ImageController extends Controller
\Illuminate\Support\Facades\Log::info('styleChangeRequest called', [ \Illuminate\Support\Facades\Log::info('styleChangeRequest called', [
'image_id' => $request->image_id, 'image_id' => $request->image_id,
'style_id' => $request->style_id, 'style_id' => $request->style_id,
'all_params' => $request->all() 'all_params' => $request->all(),
]); ]);
// Same-origin check // Same-origin check
$appUrl = config('app.url'); $appUrl = config('app.url');
$referer = $request->headers->get('referer'); $referer = $request->headers->get('referer');
@@ -123,8 +127,9 @@ class ImageController extends Controller
if ($referer && parse_url($referer, PHP_URL_HOST) !== parse_url($appUrl, PHP_URL_HOST)) { if ($referer && parse_url($referer, PHP_URL_HOST) !== parse_url($appUrl, PHP_URL_HOST)) {
\Illuminate\Support\Facades\Log::warning('Unauthorized styleChangeRequest', [ \Illuminate\Support\Facades\Log::warning('Unauthorized styleChangeRequest', [
'referer' => $referer, 'referer' => $referer,
'app_url' => $appUrl 'app_url' => $appUrl,
]); ]);
return response()->json(['error' => 'Unauthorized: Request must originate from the same domain.'], 403); return response()->json(['error' => 'Unauthorized: Request must originate from the same domain.'], 403);
} }
@@ -142,39 +147,41 @@ class ImageController extends Controller
}])->find($request->style_id); }])->find($request->style_id);
} else { } else {
// Attempt to get default style from settings // Attempt to get default style from settings
$defaultStyleSetting = \App\Models\Setting::where('key', 'default_style_id')->first(); $defaultStyleId = $this->settings->default_style_id;
if ($defaultStyleSetting && $defaultStyleSetting->value) { if ($defaultStyleId) {
$style = Style::with(['aiModel' => function ($query) { $style = Style::with(['aiModel' => function ($query) {
$query->where('enabled', true)->with('primaryApiProvider'); $query->where('enabled', true)->with('primaryApiProvider');
}])->find($defaultStyleSetting->value); }])->find($defaultStyleId);
} }
} }
if (!$style || !$style->aiModel || !$style->aiModel->primaryApiProvider) { if (! $style || ! $style->aiModel || ! $style->aiModel->primaryApiProvider) {
\Illuminate\Support\Facades\Log::warning('Style or provider not found', [ \Illuminate\Support\Facades\Log::warning('Style or provider not found', [
'style' => $style ? $style->toArray() : null, 'style' => $style ? $style->toArray() : null,
'ai_model' => $style && $style->aiModel ? $style->aiModel->toArray() : null 'ai_model' => $style && $style->aiModel ? $style->aiModel->toArray() : null,
]); ]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404); return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
} }
try { try {
// Use the primary API provider for this AI model // Use the primary API provider for this AI model
$apiProvider = $style->aiModel->primaryApiProvider; $apiProvider = $style->aiModel->primaryApiProvider;
if (!$apiProvider) { if (! $apiProvider) {
\Illuminate\Support\Facades\Log::error('No API provider found for style', [ \Illuminate\Support\Facades\Log::error('No API provider found for style', [
'style_id' => $style->id, 'style_id' => $style->id,
'ai_model_id' => $style->aiModel->id 'ai_model_id' => $style->aiModel->id,
]); ]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404); return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
} }
\Illuminate\Support\Facades\Log::info('Selected API provider for style change', [ \Illuminate\Support\Facades\Log::info('Selected API provider for style change', [
'api_provider_id' => $apiProvider->id, 'api_provider_id' => $apiProvider->id,
'api_provider_name' => $apiProvider->name, 'api_provider_name' => $apiProvider->name,
'plugin' => $apiProvider->plugin 'plugin' => $apiProvider->plugin,
]); ]);
$plugin = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider); $plugin = PluginLoader::getPlugin($apiProvider->plugin, $apiProvider);
$result = $plugin->processImageStyleChange($image, $style); $result = $plugin->processImageStyleChange($image, $style);
@@ -187,9 +194,9 @@ class ImageController extends Controller
// Return the prompt_id for WebSocket tracking // Return the prompt_id for WebSocket tracking
\Illuminate\Support\Facades\Log::info('Style change request completed', [ \Illuminate\Support\Facades\Log::info('Style change request completed', [
'prompt_id' => $result['prompt_id'], 'prompt_id' => $result['prompt_id'],
'image_uuid' => $image->uuid 'image_uuid' => $image->uuid,
]); ]);
return response()->json([ return response()->json([
'message' => 'Style change request sent.', 'message' => 'Style change request sent.',
'prompt_id' => $result['prompt_id'], 'prompt_id' => $result['prompt_id'],
@@ -199,8 +206,9 @@ class ImageController extends Controller
} catch (\Exception $e) { } catch (\Exception $e) {
\Illuminate\Support\Facades\Log::error('Error in styleChangeRequest', [ \Illuminate\Support\Facades\Log::error('Error in styleChangeRequest', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString(),
]); ]);
return response()->json(['error' => $e->getMessage()], 500); return response()->json(['error' => $e->getMessage()], 500);
} }
} }
@@ -213,7 +221,7 @@ class ImageController extends Controller
$image = Image::find($request->image_id); $image = Image::find($request->image_id);
if (!$image) { if (! $image) {
return response()->json(['error' => __('api.image_not_found')], 404); return response()->json(['error' => __('api.image_not_found')], 404);
} }
@@ -227,8 +235,9 @@ class ImageController extends Controller
{ {
try { try {
// Delete from the public/storage directory // Delete from the public/storage directory
File::delete(public_path('storage/' . $image->path)); File::delete(public_path('storage/'.$image->path));
$image->delete(); $image->delete();
return response()->json(['message' => __('api.image_deleted_successfully')]); return response()->json(['message' => __('api.image_deleted_successfully')]);
} catch (\Exception $e) { } catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500); return response()->json(['error' => $e->getMessage()], 500);
@@ -245,13 +254,14 @@ class ImageController extends Controller
$image = Image::find($request->image_id); $image = Image::find($request->image_id);
$apiProvider = ApiProvider::where('name', $request->api_provider_name)->first(); $apiProvider = ApiProvider::where('name', $request->api_provider_name)->first();
if (!$image || !$apiProvider) { if (! $image || ! $apiProvider) {
return response()->json(['error' => __('api.image_or_provider_not_found')], 404); return response()->json(['error' => __('api.image_or_provider_not_found')], 404);
} }
try { try {
$plugin = PluginLoader::getPlugin($apiProvider->name); $plugin = PluginLoader::getPlugin($apiProvider->name);
$status = $plugin->getStatus($image->uuid); // Annahme: Image Model hat eine UUID $status = $plugin->getStatus($image->uuid); // Annahme: Image Model hat eine UUID
return response()->json($status); return response()->json($status);
} catch (\Exception $e) { } catch (\Exception $e) {
return response()->json(['error' => $e->getMessage()], 500); return response()->json(['error' => $e->getMessage()], 500);
@@ -267,8 +277,9 @@ class ImageController extends Controller
$query->with('primaryApiProvider'); $query->with('primaryApiProvider');
}])->where('comfyui_prompt_id', $promptId)->first(); }])->where('comfyui_prompt_id', $promptId)->first();
if (!$image) { if (! $image) {
Log::warning('fetchStyledImage: Image not found for prompt_id.', ['prompt_id' => $promptId]); Log::warning('fetchStyledImage: Image not found for prompt_id.', ['prompt_id' => $promptId]);
return response()->json(['error' => __('api.image_not_found')], 404); return response()->json(['error' => __('api.image_not_found')], 404);
} }
@@ -276,22 +287,25 @@ class ImageController extends Controller
// Get the style and API provider associated with the image // Get the style and API provider associated with the image
$style = $image->style; $style = $image->style;
if (!$style) { if (! $style) {
Log::warning('fetchStyledImage: Style not found for image.', ['image_id' => $image->id]); Log::warning('fetchStyledImage: Style not found for image.', ['image_id' => $image->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404); return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
} }
Log::info('fetchStyledImage: Style found.', ['style_id' => $style->id, 'style_name' => $style->title]); Log::info('fetchStyledImage: Style found.', ['style_id' => $style->id, 'style_name' => $style->title]);
if (!$style->aiModel) { if (! $style->aiModel) {
Log::warning('fetchStyledImage: AI Model not found for style.', ['style_id' => $style->id]); Log::warning('fetchStyledImage: AI Model not found for style.', ['style_id' => $style->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404); return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
} }
Log::info('fetchStyledImage: AI Model found.', ['ai_model_id' => $style->aiModel->id, 'ai_model_name' => $style->aiModel->name]); Log::info('fetchStyledImage: AI Model found.', ['ai_model_id' => $style->aiModel->id, 'ai_model_name' => $style->aiModel->name]);
// Use the primary API provider for this AI model // Use the primary API provider for this AI model
$apiProvider = $style->aiModel->primaryApiProvider; $apiProvider = $style->aiModel->primaryApiProvider;
if (!$apiProvider) { if (! $apiProvider) {
Log::warning('fetchStyledImage: No API Provider found for AI Model.', ['ai_model_id' => $style->aiModel->id]); Log::warning('fetchStyledImage: No API Provider found for AI Model.', ['ai_model_id' => $style->aiModel->id]);
return response()->json(['error' => __('api.style_or_provider_not_found')], 404); return response()->json(['error' => __('api.style_or_provider_not_found')], 404);
} }
Log::info('fetchStyledImage: API Provider found.', ['api_provider_id' => $apiProvider->id, 'api_provider_name' => $apiProvider->name]); Log::info('fetchStyledImage: API Provider found.', ['api_provider_id' => $apiProvider->id, 'api_provider_name' => $apiProvider->name]);
@@ -303,17 +317,18 @@ class ImageController extends Controller
if (empty($base64Image)) { if (empty($base64Image)) {
Log::error('Received empty base64 image from plugin.', ['prompt_id' => $promptId]); Log::error('Received empty base64 image from plugin.', ['prompt_id' => $promptId]);
return response()->json(['error' => 'Received empty image data.'], 500); return response()->json(['error' => 'Received empty image data.'], 500);
} }
Log::info('Base64 image received. Decoding and saving.'); Log::info('Base64 image received. Decoding and saving.');
$decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64, #i', '', $base64Image)); $decodedImage = base64_decode(preg_replace('#^data:image/\w+;base64, #i', '', $base64Image));
$newImageName = 'styled_' . uniqid() . '.png'; $newImageName = 'styled_'.uniqid().'.png';
$newImagePathRelative = 'uploads/' . $newImageName; $newImagePathRelative = 'uploads/'.$newImageName;
$newImageFullPath = public_path('storage/' . $newImagePathRelative); $newImageFullPath = public_path('storage/'.$newImagePathRelative);
if (!File::exists(public_path('storage/uploads'))) { if (! File::exists(public_path('storage/uploads'))) {
File::makeDirectory(public_path('storage/uploads'), 0755, true); File::makeDirectory(public_path('storage/uploads'), 0755, true);
Log::info('Created uploads directory.', ['path' => public_path('storage/uploads')]); Log::info('Created uploads directory.', ['path' => public_path('storage/uploads')]);
} }
@@ -334,12 +349,13 @@ class ImageController extends Controller
'message' => 'Styled image fetched successfully', 'message' => 'Styled image fetched successfully',
'styled_image' => [ 'styled_image' => [
'id' => $newImage->id, 'id' => $newImage->id,
'path' => asset('storage/' . $newImage->path), 'path' => asset('storage/'.$newImage->path),
'is_temp' => $newImage->is_temp, 'is_temp' => $newImage->is_temp,
], ],
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error in fetchStyledImage: ' . $e->getMessage(), ['exception' => $e]); Log::error('Error in fetchStyledImage: '.$e->getMessage(), ['exception' => $e]);
return response()->json(['error' => $e->getMessage()], 500); return response()->json(['error' => $e->getMessage()], 500);
} }
} }
@@ -348,15 +364,15 @@ class ImageController extends Controller
{ {
$styleId = $request->query('style_id'); $styleId = $request->query('style_id');
$imageUuid = $request->query('image_uuid'); $imageUuid = $request->query('image_uuid');
$apiProvider = null; $apiProvider = null;
// If style_id is provided, get the API provider for that style // If style_id is provided, get the API provider for that style
if ($styleId) { if ($styleId) {
$style = Style::with(['aiModel' => function ($query) { $style = Style::with(['aiModel' => function ($query) {
$query->where('enabled', true)->with('primaryApiProvider'); $query->where('enabled', true)->with('primaryApiProvider');
}])->find($styleId); }])->find($styleId);
if ($style && $style->aiModel) { if ($style && $style->aiModel) {
// Use the primary API provider for this AI model // Use the primary API provider for this AI model
$apiProvider = $style->aiModel->primaryApiProvider; $apiProvider = $style->aiModel->primaryApiProvider;
@@ -367,7 +383,7 @@ class ImageController extends Controller
$image = Image::with(['style.aiModel' => function ($query) { $image = Image::with(['style.aiModel' => function ($query) {
$query->with('primaryApiProvider'); $query->with('primaryApiProvider');
}])->where('uuid', $imageUuid)->first(); }])->where('uuid', $imageUuid)->first();
if ($image && $image->style && $image->style->aiModel) { if ($image && $image->style && $image->style->aiModel) {
// Use the primary API provider for this AI model // Use the primary API provider for this AI model
$apiProvider = $image->style->aiModel->primaryApiProvider; $apiProvider = $image->style->aiModel->primaryApiProvider;
@@ -376,25 +392,25 @@ class ImageController extends Controller
// Fallback to the old behavior if no style_id or image_uuid is provided // Fallback to the old behavior if no style_id or image_uuid is provided
else { else {
// Try to get a default style if none is provided // Try to get a default style if none is provided
$defaultStyleSetting = \App\Models\Setting::where('key', 'default_style_id')->first(); $defaultStyleId = $this->settings->default_style_id;
if ($defaultStyleSetting && $defaultStyleSetting->value) { if ($defaultStyleId) {
$style = Style::with(['aiModel' => function ($query) { $style = Style::with(['aiModel' => function ($query) {
$query->where('enabled', true)->with('primaryApiProvider'); $query->where('enabled', true)->with('primaryApiProvider');
}])->find($defaultStyleSetting->value); }])->find($defaultStyleId);
if ($style && $style->aiModel) { if ($style && $style->aiModel) {
// Use the primary API provider for this AI model // Use the primary API provider for this AI model
$apiProvider = $style->aiModel->primaryApiProvider; $apiProvider = $style->aiModel->primaryApiProvider;
} }
} }
// If still no API provider, use the first available ComfyUI provider // If still no API provider, use the first available ComfyUI provider
if (!$apiProvider) { if (! $apiProvider) {
$apiProvider = ApiProvider::where('plugin', 'ComfyUi')->where('enabled', true)->first(); $apiProvider = ApiProvider::where('plugin', 'ComfyUi')->where('enabled', true)->first();
} }
} }
if (!$apiProvider) { if (! $apiProvider) {
return response()->json(['error' => 'No enabled ComfyUI API provider found.'], 404); return response()->json(['error' => 'No enabled ComfyUI API provider found.'], 404);
} }

View File

@@ -4,11 +4,12 @@ namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\Style; use App\Models\Style;
use App\Models\Setting; use App\Settings\GeneralSettings;
use Illuminate\Http\Request;
class StyleController extends Controller class StyleController extends Controller
{ {
public function __construct(private GeneralSettings $settings) {}
public function index() public function index()
{ {
$styles = Style::with(['aiModel.primaryApiProvider']) $styles = Style::with(['aiModel.primaryApiProvider'])
@@ -31,15 +32,15 @@ class StyleController extends Controller
public function getImageRefreshInterval() public function getImageRefreshInterval()
{ {
$interval = Setting::where('key', 'image_refresh_interval')->first(); return response()->json([
'interval' => $this->settings->image_refresh_interval / 1000,
return response()->json(['interval' => $interval ? (int)$interval->value / 1000 : 5]); ]);
} }
public function getMaxNumberOfCopies() public function getMaxNumberOfCopies()
{ {
$maxCopies = Setting::where('key', 'max_number_of_copies')->first(); return response()->json([
'max_copies' => $this->settings->max_number_of_copies,
return response()->json(['max_copies' => $maxCopies ? (int)$maxCopies->value : 10]); // Default to 10 if not set ]);
} }
} }

View File

@@ -2,9 +2,11 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str;
class DownloadController extends Controller class DownloadController extends Controller
{ {
@@ -14,39 +16,61 @@ class DownloadController extends Controller
'image_path' => 'required|string', 'image_path' => 'required|string',
]); ]);
$imagePath = $request->input('image_path'); $resolvedPath = $this->resolveImagePath($request->input('image_path'));
// Check if it's a relative path and make it absolute if (! $resolvedPath || ! File::exists($resolvedPath)) {
if (!filter_var($imagePath, FILTER_VALIDATE_URL)) { Log::error("DownloadController: Image file not found at {$resolvedPath}");
$imagePath = public_path(str_replace(url('/'), '', $imagePath));
}
// Validate file exists
if (!file_exists($imagePath)) {
Log::error("DownloadController: Image file not found at {$imagePath}");
return response()->json(['error' => 'Image file not found.'], 404); return response()->json(['error' => 'Image file not found.'], 404);
} }
// Get file info $extension = strtolower(File::extension($resolvedPath) ?: 'jpg');
$fileName = basename($imagePath); $downloadName = $this->buildDownloadName($extension);
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION); $mimeType = File::mimeType($resolvedPath) ?: $this->getMimeType($extension);
$mimeType = $this->getMimeType($fileExtension);
try { try {
Log::info("DownloadController: Serving download for {$imagePath}"); Log::info("DownloadController: Serving download for {$resolvedPath}");
// Return the file with proper headers for download return response()->download($resolvedPath, $downloadName, [
return response()->download($imagePath, $fileName, [
'Content-Type' => $mimeType, 'Content-Type' => $mimeType,
'Content-Disposition' => 'attachment; filename="' . $fileName . '"', 'Content-Disposition' => 'attachment; filename="'.$downloadName.'"',
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("DownloadController: Error serving download: " . $e->getMessage()); Log::error('DownloadController: Error serving download: '.$e->getMessage());
return response()->json(['error' => 'Failed to serve download.'], 500); return response()->json(['error' => 'Failed to serve download.'], 500);
} }
} }
private function resolveImagePath(string $path): ?string
{
if (filter_var($path, FILTER_VALIDATE_URL)) {
$parsed = parse_url($path, PHP_URL_PATH);
return $parsed ? public_path(ltrim($parsed, '/')) : null;
}
if (Str::startsWith($path, ['storage/', 'public/'])) {
return public_path(ltrim($path, '/'));
}
if (File::exists($path)) {
return $path;
}
$candidate = public_path(ltrim($path, '/'));
return File::exists($candidate) ? $candidate : null;
}
private function buildDownloadName(string $extension): string
{
$timestamp = Carbon::now()->format('Ymd_His');
return sprintf('stylegallery_%s.%s', $timestamp, $extension);
}
private function getMimeType(string $extension): string private function getMimeType(string $extension): string
{ {
$mimeTypes = [ $mimeTypes = [
@@ -61,4 +85,4 @@ class DownloadController extends Controller
return $mimeTypes[strtolower($extension)] ?? 'application/octet-stream'; return $mimeTypes[strtolower($extension)] ?? 'application/octet-stream';
} }
} }

View File

@@ -2,15 +2,16 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Setting;
use App\Models\Image; use App\Models\Image;
use Inertia\Inertia; use App\Settings\GeneralSettings;
use Illuminate\Support\Facades\Lang;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Support\Facades\Lang;
use Inertia\Inertia;
class HomeController extends Controller class HomeController extends Controller
{ {
public function __construct(private GeneralSettings $settings) {}
public function index() public function index()
{ {
$locale = app()->getLocale(); $locale = app()->getLocale();
@@ -18,12 +19,13 @@ class HomeController extends Controller
Lang::get('api', [], $locale), Lang::get('api', [], $locale),
Lang::get('settings', [], $locale) Lang::get('settings', [], $locale)
); );
$galleryHeading = Setting::where('key', 'gallery_heading')->first()->value ?? 'Style Gallery'; $galleryHeading = $this->settings->gallery_heading;
$newImageTimespanMinutes = Setting::where('key', 'new_image_timespan_minutes')->first()->value ?? 60; // Default to 60 minutes $newImageTimespanMinutes = $this->settings->new_image_timespan_minutes;
$images = Image::all()->map(function ($image) use ($newImageTimespanMinutes) { $images = Image::all()->map(function ($image) use ($newImageTimespanMinutes) {
$image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes; $image->is_new = Carbon::parse($image->created_at)->diffInMinutes(Carbon::now()) <= $newImageTimespanMinutes;
$image->path = 'storage/' . $image->path; $image->path = 'storage/'.$image->path;
return $image; return $image;
}); });
@@ -33,4 +35,4 @@ class HomeController extends Controller
'images' => $images, 'images' => $images,
]); ]);
} }
} }

View File

@@ -2,12 +2,15 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Services\PrinterService;
use App\Settings\GeneralSettings;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use App\Services\PrinterService;
class PrintController extends Controller class PrintController extends Controller
{ {
public function __construct(private GeneralSettings $settings) {}
public function printImage(Request $request, PrinterService $printerService) public function printImage(Request $request, PrinterService $printerService)
{ {
$request->validate([ $request->validate([
@@ -17,21 +20,20 @@ class PrintController extends Controller
$imagePath = public_path(str_replace(url('/'), '', $request->input('image_path'))); $imagePath = public_path(str_replace(url('/'), '', $request->input('image_path')));
$quantity = $request->input('quantity'); $quantity = $request->input('quantity');
// Retrieve printer name from global settings using standard Eloquent
$printerName = \App\Models\Setting::where('key', 'selected_printer')->value('value');
if (!$printerName) { $printerName = $this->settings->selected_printer === '__custom__'
Log::error("PrintController: Default printer name not found in settings."); ? $this->settings->custom_printer_address
: $this->settings->selected_printer;
if (! $printerName) {
Log::error('PrintController: Default printer name not found in settings.');
return response()->json(['error' => 'Default printer not configured.'], 500); return response()->json(['error' => 'Default printer not configured.'], 500);
} }
if (!$printerName) { if (! file_exists($imagePath)) {
Log::error("PrintController: Default printer name not found in settings.");
return response()->json(['error' => 'Default printer not configured.'], 500);
}
if (!file_exists($imagePath)) {
Log::error("PrintController: Image file not found at {$imagePath}"); Log::error("PrintController: Image file not found at {$imagePath}");
return response()->json(['error' => 'Image file not found.'], 404); return response()->json(['error' => 'Image file not found.'], 404);
} }
@@ -39,9 +41,11 @@ class PrintController extends Controller
if ($printSuccess) { if ($printSuccess) {
Log::info("PrintController: Successfully sent print command for {$imagePath} (x{$quantity}) to {$printerName}"); Log::info("PrintController: Successfully sent print command for {$imagePath} (x{$quantity}) to {$printerName}");
return response()->json(['message' => 'Print command sent successfully.']); return response()->json(['message' => 'Print command sent successfully.']);
} else { } else {
Log::error("PrintController: Failed to send print command for {$imagePath} (x{$quantity}) to {$printerName}"); Log::error("PrintController: Failed to send print command for {$imagePath} (x{$quantity}) to {$printerName}");
return response()->json(['error' => 'Failed to send print command.'], 500); return response()->json(['error' => 'Failed to send print command.'], 500);
} }
} }

View File

@@ -2,9 +2,9 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Settings\GeneralSettings;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Middleware; use Inertia\Middleware;
use App\Models\Setting;
class HandleInertiaRequests extends Middleware class HandleInertiaRequests extends Middleware
{ {
@@ -18,7 +18,7 @@ class HandleInertiaRequests extends Middleware
/** /**
* Determine the current asset version. * Determine the current asset version.
*/ */
public function version(Request $request): string|null public function version(Request $request): ?string
{ {
return parent::version($request); return parent::version($request);
} }
@@ -36,7 +36,7 @@ class HandleInertiaRequests extends Middleware
'user' => $request->user(), 'user' => $request->user(),
], ],
'locale' => app()->getLocale(), 'locale' => app()->getLocale(),
'settings' => Setting::all()->pluck('value', 'key'), 'settings' => app(GeneralSettings::class)->toArray(),
'translations' => function () use ($request) { 'translations' => function () use ($request) {
$currentLocale = app()->getLocale(); // Store current locale $currentLocale = app()->getLocale(); // Store current locale
$requestedLocale = $request->input('locale', $currentLocale); $requestedLocale = $request->input('locale', $currentLocale);
@@ -50,6 +50,7 @@ class HandleInertiaRequests extends Middleware
]; ];
app()->setLocale($currentLocale); // Revert to original locale app()->setLocale($currentLocale); // Revert to original locale
return $lang; return $lang;
}, },
]; ];

View File

@@ -1,13 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
protected $fillable = ['key', 'value'];
}

View File

@@ -3,12 +3,14 @@
namespace App\Models; namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail; // use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable class User extends Authenticatable implements FilamentUser
{ {
use HasApiTokens, HasFactory, Notifiable; use HasApiTokens, HasFactory, Notifiable;
@@ -50,4 +52,9 @@ class User extends Authenticatable
protected $casts = [ protected $casts = [
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
]; ];
public function canAccessPanel(Panel $panel): bool
{
return true;
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Providers\Filament; namespace App\Providers\Filament;
use App\Filament\Resources\PluginResource;
use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\DisableBladeIconComponents; use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent; use Filament\Http\Middleware\DispatchServingFilamentEvent;
@@ -16,12 +17,9 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings; use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\AuthenticateSession; use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\Session\Middleware\StartSession; use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use App\Filament\Resources\StyleResource;
use App\Filament\Resources\SettingResource\Pages\Settings;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString; use Illuminate\Support\HtmlString;
use App\Filament\Resources\PluginResource; use Illuminate\View\Middleware\ShareErrorsFromSession;
class AdminPanelProvider extends PanelProvider class AdminPanelProvider extends PanelProvider
{ {
@@ -33,8 +31,8 @@ class AdminPanelProvider extends PanelProvider
->path('admin') ->path('admin')
->login() ->login()
->brandLogo(fn () => new HtmlString( ->brandLogo(fn () => new HtmlString(
'<img src="' . asset('icon.png') . '" alt="App Icon" style="height: 2.5rem; display: inline-block; vertical-align: middle; margin-right: 0.5rem;" />' . '<img src="'.asset('icon.png').'" alt="App Icon" style="height: 2.5rem; display: inline-block; vertical-align: middle; margin-right: 0.5rem;" />'.
'<span style="vertical-align: middle; font-weight: bold; font-size: 1.25rem;">' . config('app.name') . '</span>' '<span style="vertical-align: middle; font-weight: bold; font-size: 1.25rem;">'.config('app.name').'</span>'
)) ))
->colors([ ->colors([
'primary' => Color::Amber, 'primary' => Color::Amber,
@@ -70,7 +68,7 @@ class AdminPanelProvider extends PanelProvider
Authenticate::class, Authenticate::class,
]) ])
->plugins([ ->plugins([
]) ])
->profile(); ->profile();
@@ -86,4 +84,3 @@ class AdminPanelProvider extends PanelProvider
return $panel; return $panel;
} }
} }

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Settings;
use Spatie\LaravelSettings\Settings;
class GeneralSettings extends Settings
{
public string $gallery_heading = 'Style Gallery';
public int $new_image_timespan_minutes = 60;
public int $image_refresh_interval = 30_000;
public int $max_number_of_copies = 3;
public bool $show_print_button = true;
public ?string $selected_printer = null;
public ?string $custom_printer_address = null;
public ?int $default_style_id = null;
public static function group(): string
{
return 'general';
}
}

Binary file not shown.

7
boost.json Normal file
View File

@@ -0,0 +1,7 @@
{
"agents": [
"codex",
"opencode"
],
"guidelines": []
}

View File

@@ -8,7 +8,7 @@
"php": "^8.3", "php": "^8.3",
"amphp/websocket-client": "^2.0", "amphp/websocket-client": "^2.0",
"blade-ui-kit/blade-icons": "^1.8", "blade-ui-kit/blade-icons": "^1.8",
"filament/filament": "^3.3", "filament/filament": "^4.0",
"guzzlehttp/guzzle": "^7.2", "guzzlehttp/guzzle": "^7.2",
"inertiajs/inertia-laravel": "^1.0", "inertiajs/inertia-laravel": "^1.0",
"laravel/breeze": "^2.0", "laravel/breeze": "^2.0",
@@ -16,10 +16,12 @@
"laravel/sanctum": "^4.0", "laravel/sanctum": "^4.0",
"laravel/tinker": "^2.8", "laravel/tinker": "^2.8",
"predis/predis": "^3.1", "predis/predis": "^3.1",
"spatie/laravel-settings": "*",
"tightenco/ziggy": "^2.0" "tightenco/ziggy": "^2.0"
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.9.1", "fakerphp/faker": "^1.9.1",
"laravel/boost": "^1.1",
"laravel/pint": "^1.0", "laravel/pint": "^1.0",
"laravel/sail": "^1.18", "laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4", "mockery/mockery": "^1.4.4",

2815
composer.lock generated

File diff suppressed because it is too large Load Diff

BIN
composer.phar Normal file

Binary file not shown.

View File

@@ -15,7 +15,7 @@ return [
| |
*/ */
'name' => env('APP_NAME', 'Laravel'), 'name' => env('APP_NAME', 'AI Stylegallery'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

94
config/settings.php Normal file
View File

@@ -0,0 +1,94 @@
<?php
return [
/*
* Each settings class used in your application must be registered, you can
* put them (manually) here.
*/
'settings' => [
],
/*
* The path where the settings classes will be created.
*/
'setting_class_path' => app_path('Settings'),
/*
* In these directories settings migrations will be stored and ran when migrating. A settings
* migration created via the make:settings-migration command will be stored in the first path or
* a custom defined path when running the command.
*/
'migrations_paths' => [
database_path('settings'),
],
/*
* When no repository was set for a settings class the following repository
* will be used for loading and saving settings.
*/
'default_repository' => 'database',
/*
* Settings will be stored and loaded from these repositories.
*/
'repositories' => [
'database' => [
'type' => Spatie\LaravelSettings\SettingsRepositories\DatabaseSettingsRepository::class,
'model' => null,
'table' => null,
'connection' => null,
],
'redis' => [
'type' => Spatie\LaravelSettings\SettingsRepositories\RedisSettingsRepository::class,
'connection' => null,
'prefix' => null,
],
],
/*
* The encoder and decoder will determine how settings are stored and
* retrieved in the database. By default, `json_encode` and `json_decode`
* are used.
*/
'encoder' => null,
'decoder' => null,
/*
* The contents of settings classes can be cached through your application,
* settings will be stored within a provided Laravel store and can have an
* additional prefix.
*/
'cache' => [
'enabled' => env('SETTINGS_CACHE_ENABLED', false),
'store' => null,
'prefix' => null,
'ttl' => null,
],
/*
* These global casts will be automatically used whenever a property within
* your settings class isn't a default PHP type.
*/
'global_casts' => [
DateTimeInterface::class => Spatie\LaravelSettings\SettingsCasts\DateTimeInterfaceCast::class,
DateTimeZone::class => Spatie\LaravelSettings\SettingsCasts\DateTimeZoneCast::class,
// Spatie\DataTransferObject\DataTransferObject::class => Spatie\LaravelSettings\SettingsCasts\DtoCast::class,
Spatie\LaravelData\Data::class => Spatie\LaravelSettings\SettingsCasts\DataCast::class,
],
/*
* The package will look for settings in these paths and automatically
* register them.
*/
'auto_discover_settings' => [
app_path('Settings'),
],
/*
* Automatically discovered settings classes can be cached, so they don't
* need to be searched each time the application boots up.
*/
'discovered_settings_cache_path' => base_path('bootstrap/cache'),
];

View File

@@ -0,0 +1,180 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
if (! Schema::hasTable('settings')) {
$this->createSpatieSettingsTable();
$this->seedDefaultSettings();
return;
}
if (Schema::hasColumn('settings', 'group')) {
// Already migrated.
return;
}
Schema::rename('settings', 'legacy_settings');
$this->createSpatieSettingsTable();
$legacySettings = DB::table('legacy_settings')->pluck('value', 'key')->toArray();
$records = $this->buildSettingsRecords($legacySettings);
if (! empty($records)) {
DB::table('settings')->insert($records);
}
Schema::dropIfExists('legacy_settings');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
if (! Schema::hasTable('settings')) {
return;
}
if (Schema::hasColumn('settings', 'key')) {
// Already reverted.
return;
}
Schema::rename('settings', 'spatie_settings');
Schema::create('settings', function (Blueprint $table): void {
$table->id();
$table->string('key')->unique();
$table->text('value')->nullable();
$table->timestamps();
});
$spatieSettings = DB::table('spatie_settings')
->where('group', 'general')
->get(['name', 'payload']);
$now = now();
$rows = $spatieSettings
->map(function ($setting) use ($now) {
$value = json_decode($setting->payload, true);
if (is_bool($value)) {
$value = $value ? '1' : '0';
}
return [
'key' => $setting->name,
'value' => is_array($value) ? json_encode($value) : (string) $value,
'created_at' => $now,
'updated_at' => $now,
];
})
->toArray();
if (! empty($rows)) {
DB::table('settings')->insert($rows);
}
Schema::dropIfExists('spatie_settings');
}
protected function createSpatieSettingsTable(): void
{
Schema::create('settings', function (Blueprint $table): void {
$table->id();
$table->string('group');
$table->string('name');
$table->boolean('locked')->default(false);
$table->json('payload');
$table->timestamps();
$table->unique(['group', 'name']);
});
}
protected function buildSettingsRecords(array $legacySettings): array
{
$defaults = [
'gallery_heading' => 'Style Gallery',
'new_image_timespan_minutes' => 60,
'image_refresh_interval' => 30_000,
'max_number_of_copies' => 3,
'show_print_button' => true,
'selected_printer' => null,
'custom_printer_address' => null,
'default_style_id' => null,
];
$intKeys = [
'new_image_timespan_minutes',
'image_refresh_interval',
'max_number_of_copies',
'default_style_id',
];
$boolKeys = ['show_print_button'];
$now = now();
return collect($defaults)
->map(function ($default, string $key) use ($legacySettings) {
return array_key_exists($key, $legacySettings)
? $legacySettings[$key]
: $default;
})
->map(function ($value, string $key) use ($intKeys, $boolKeys) {
if (in_array($key, $intKeys, true)) {
return is_null($value) || $value === '' ? null : (int) $value;
}
if (in_array($key, $boolKeys, true)) {
if (is_null($value) || $value === '') {
return false;
}
if (is_bool($value)) {
return $value;
}
return in_array((string) $value, ['1', 'true', 'on'], true);
}
return $value;
})
->map(function ($value, string $key) use ($now) {
return [
'group' => 'general',
'name' => $key,
'payload' => json_encode($value),
'locked' => false,
'created_at' => $now,
'updated_at' => $now,
];
})
->values()
->toArray();
}
protected function seedDefaultSettings(): void
{
$records = $this->buildSettingsRecords([]);
if (! empty($records)) {
DB::table('settings')->insert($records);
}
}
};

View File

@@ -2,9 +2,7 @@
namespace Database\Seeders; namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class AiModelApiProviderSeeder extends Seeder class AiModelApiProviderSeeder extends Seeder
{ {
@@ -14,13 +12,11 @@ class AiModelApiProviderSeeder extends Seeder
public function run(): void public function run(): void
{ {
$data = [ $data = [
[ ['ai_model_id' => 2, 'api_provider_id' => 1],
['ai_model_id' => 2, 'api_provider_id' => 1], ['ai_model_id' => 5, 'api_provider_id' => 1],
['ai_model_id' => 5, 'api_provider_id' => 1], ['ai_model_id' => 6, 'api_provider_id' => 1],
['ai_model_id' => 6, 'api_provider_id' => 1], ['ai_model_id' => 7, 'api_provider_id' => 3],
['ai_model_id' => 7, 'api_provider_id' => 3], ['ai_model_id' => 8, 'api_provider_id' => 1],
['ai_model_id' => 8, 'api_provider_id' => 1],
]
]; ];
// Update existing AI models with their API provider IDs // Update existing AI models with their API provider IDs
@@ -28,4 +24,4 @@ class AiModelApiProviderSeeder extends Seeder
\App\Models\AiModel::where('id', $row['ai_model_id'])->update(['api_provider_id' => $row['api_provider_id']]); \App\Models\AiModel::where('id', $row['ai_model_id'])->update(['api_provider_id' => $row['api_provider_id']]);
} }
} }
} }

View File

@@ -2,9 +2,8 @@
namespace Database\Seeders; namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\AiModel; use App\Models\AiModel;
use Illuminate\Database\Seeder;
class AiModelSeeder extends Seeder class AiModelSeeder extends Seeder
{ {
@@ -13,66 +12,69 @@ class AiModelSeeder extends Seeder
*/ */
public function run(): void public function run(): void
{ {
// Für SQLite: Lösche alle existierenden Modelle und füge sie frisch ein
AiModel::truncate();
$data = [ $data = [
[ [
'id' => 2, 'id' => 2,
'name' => 'FLUX.1 Kontext [dev]', 'name' => 'FLUX.1 Kontext [dev]',
'model_type' => 'flux', 'model_type' => 'flux',
'created_at' => '2025-07-27T20:46:32', 'created_at' => '2025-07-27T20:46:32.000000',
'updated_at' => '2025-07-28T18:07:14', 'updated_at' => '2025-07-28T18:07:14.000000',
'model_id' => 'runware:106@1', 'model_id' => 'runware:106@1',
'api_provider_id' => 1, 'api_provider_id' => null, // Verwende null statt 0 oder ungültiger IDs
'enabled' => 1, 'enabled' => 1,
'parameters' => null, 'parameters' => null,
], ],
[ [
'id' => 5, 'id' => 5,
'name' => 'AbsoluteReality', 'name' => 'AbsoluteReality',
'model_type' => 'sd1.5', 'model_type' => 'sd1.5',
'created_at' => '2025-07-27T20:46:32', 'created_at' => '2025-07-27T20:46:32.000000',
'updated_at' => '2025-07-27T20:46:32', 'updated_at' => '2025-07-27T20:46:32.000000',
'model_id' => 'civitai:81458@256668', 'model_id' => 'civitai:81458@256668',
'api_provider_id' => 0, 'api_provider_id' => null,
'enabled' => 1, 'enabled' => 1,
'parameters' => null, 'parameters' => null,
], ],
[ [
'id' => 6, 'id' => 6,
'name' => 'DreamShaper 8', 'name' => 'DreamShaper 8',
'model_type' => 'sd1.5', 'model_type' => 'sd1.5',
'created_at' => '2025-07-27T20:46:32', 'created_at' => '2025-07-27T20:46:32.000000',
'updated_at' => '2025-07-27T20:46:32', 'updated_at' => '2025-07-27T20:46:32.000000',
'model_id' => 'civitai:4384@252914', 'model_id' => 'civitai:4384@252914',
'api_provider_id' => 0, 'api_provider_id' => null,
'enabled' => 1, 'enabled' => 1,
'parameters' => null, 'parameters' => null,
], ],
[ [
'id' => 7, 'id' => 7,
'name' => 'FLUX.1 Kontext [dev] in ComfyUI', 'name' => 'FLUX.1 Kontext [dev] in ComfyUI',
'model_type' => 'flux', 'model_type' => 'flux',
'created_at' => '2025-07-31T18:51:48', 'created_at' => '2025-07-31T18:51:48.000000',
'updated_at' => '2025-08-06 11:26:30', 'updated_at' => '2025-08-06T11:26:30.000000',
'model_id' => 'flux1-kontext-dev', 'model_id' => 'flux1-kontext-dev',
'api_provider_id' => null, 'api_provider_id' => null,
'enabled' => 1, 'enabled' => 1,
'parameters' => " ... dein langer JSON-String hier ... ", 'parameters' => json_encode(['example' => 'parameter']),
], ],
[ [
'id' => 8, 'id' => 8,
'name' => 'HiDream-I1-Dev', 'name' => 'HiDream-I1-Dev',
'model_type' => 'base', 'model_type' => 'base',
'created_at' => '2025-08-08 10:46:29', 'created_at' => '2025-08-08T10:46:29.000000',
'updated_at' => '2025-08-08 10:46:29', 'updated_at' => '2025-08-08T10:46:29.000000',
'model_id' => 'runware:97@2', 'model_id' => 'runware:97@2',
'api_provider_id' => null, 'api_provider_id' => null,
'enabled' => 1, 'enabled' => 1,
'parameters' => null, 'parameters' => null,
], ],
]; ];
foreach ($data as $row) { foreach ($data as $row) {
AiModel::updateOrCreate(['id' => $row['id']], $row); AiModel::create($row);
} }
} }
} }

View File

@@ -2,9 +2,8 @@
namespace Database\Seeders; namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents; use App\Settings\GeneralSettings;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use App\Models\Setting;
class SettingSeeder extends Seeder class SettingSeeder extends Seeder
{ {
@@ -13,39 +12,18 @@ class SettingSeeder extends Seeder
*/ */
public function run(): void public function run(): void
{ {
$data = [ /** @var \App\Settings\GeneralSettings $settings */
[ $settings = app(GeneralSettings::class);
'id' => 1,
'key' => 'gallery_heading',
'value' => 'Eure Bilder aus der Fotoboxx',
'created_at' => '2025-07-30T14:03:55',
'updated_at' => '2025-08-01T11:05:52',
],
[
'id' => 2,
'key' => 'new_image_timespan_minutes',
'value' => '10000',
'created_at' => '2025-08-01T12:46:00',
'updated_at' => '2025-08-01T12:49:52',
],
[
'id' => 3,
'key' => 'image_refresh_interval',
'value' => '30000',
'created_at' => '2025-08-06 13:39:27',
'updated_at' => '2025-08-06 13:46:22',
],
[
'id' => 4,
'key' => 'max_number_of_copies',
'value' => '3',
'created_at' => '2025-08-08 11:05:20',
'updated_at' => '2025-08-08 11:05:20',
],
];
foreach ($data as $row) { $settings->fill([
Setting::updateOrCreate(['id' => $row['id']], $row); 'gallery_heading' => 'Eure Bilder aus der Fotoboxx',
} 'new_image_timespan_minutes' => 10_000,
'image_refresh_interval' => 30_000,
'max_number_of_copies' => 3,
'show_print_button' => true,
'selected_printer' => null,
'custom_printer_address' => null,
'default_style_id' => null,
])->save();
} }
} }

2058
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
{ {
"type": "module",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -7,12 +8,12 @@
"devDependencies": { "devDependencies": {
"@inertiajs/vue3": "^1.0.0", "@inertiajs/vue3": "^1.0.0",
"@tailwindcss/forms": "^0.5.3", "@tailwindcss/forms": "^0.5.3",
"@tailwindcss/postcss": "^4.1.17",
"@vitejs/plugin-vue": "^5.0.0", "@vitejs/plugin-vue": "^5.0.0",
"autoprefixer": "^10.4.12",
"axios": "^1.1.2", "axios": "^1.1.2",
"laravel-vite-plugin": "^1.0.0", "laravel-vite-plugin": "^1.0.0",
"postcss": "^8.4.31", "postcss": "^8.4.31",
"tailwindcss": "^3.2.1", "tailwindcss": "^4.1.17",
"vite": "^5.0.0", "vite": "^5.0.0",
"vue": "^3.4.0" "vue": "^3.4.0"
}, },
@@ -20,6 +21,7 @@
"@fortawesome/fontawesome-svg-core": "^7.0.0", "@fortawesome/fontawesome-svg-core": "^7.0.0",
"@fortawesome/free-solid-svg-icons": "^7.0.0", "@fortawesome/free-solid-svg-icons": "^7.0.0",
"@fortawesome/vue-fontawesome": "^3.1.1", "@fortawesome/vue-fontawesome": "^3.1.1",
"@rollup/rollup-linux-x64-gnu": "^4.45.1",
"laravel-echo": "^2.1.7", "laravel-echo": "^2.1.7",
"pusher-js": "^8.4.0", "pusher-js": "^8.4.0",
"vanilla-lazyload": "^19.1.3" "vanilla-lazyload": "^19.1.3"

View File

@@ -21,8 +21,8 @@
<env name="APP_ENV" value="testing"/> <env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/> <env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/> <env name="CACHE_DRIVER" value="array"/>
<!-- <env name="DB_CONNECTION" value="sqlite"/> --> <env name="DB_CONNECTION" value="sqlite"/>
<!-- <env name="DB_DATABASE" value=":memory:"/> --> <env name="DB_DATABASE" value="database/database.sqlite"/>
<env name="MAIL_MAILER" value="array"/> <env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/> <env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/>

View File

@@ -1,6 +1,5 @@
export default { export default {
plugins: { plugins: {
tailwindcss: {}, '@tailwindcss/postcss': {},
autoprefixer: {},
}, },
}; };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-cyrillic-ext-wght-normal-IYF56FF6.woff2") format("woff2-variations");unicode-range:U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-cyrillic-wght-normal-JEOLYBOO.woff2") format("woff2-variations");unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-greek-ext-wght-normal-EOVOK2B5.woff2") format("woff2-variations");unicode-range:U+1F00-1FFF}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-greek-wght-normal-IRE366VL.woff2") format("woff2-variations");unicode-range:U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-vietnamese-wght-normal-CE5GGD3W.woff2") format("woff2-variations");unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-latin-ext-wght-normal-HA22NDSG.woff2") format("woff2-variations");unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Inter Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url("./inter-latin-wght-normal-NRMW37G5.woff2") format("woff2-variations");unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}

View File

@@ -0,0 +1 @@
(()=>{var n=({livewireId:e})=>({actionNestingIndex:null,init(){window.addEventListener("sync-action-modals",t=>{t.detail.id===e&&this.syncActionModals(t.detail.newActionNestingIndex)})},syncActionModals(t){if(this.actionNestingIndex===t){this.actionNestingIndex!==null&&this.$nextTick(()=>this.openModal());return}if(this.actionNestingIndex!==null&&this.closeModal(),this.actionNestingIndex=t,this.actionNestingIndex!==null){if(!this.$el.querySelector(`#${this.generateModalId(t)}`)){this.$nextTick(()=>this.openModal());return}this.openModal()}},generateModalId(t){return`fi-${e}-action-`+t},openModal(){let t=this.generateModalId(this.actionNestingIndex);document.dispatchEvent(new CustomEvent("open-modal",{bubbles:!0,composed:!0,detail:{id:t}}))},closeModal(){let t=this.generateModalId(this.actionNestingIndex);document.dispatchEvent(new CustomEvent("close-modal-quietly",{bubbles:!0,composed:!0,detail:{id:t}}))}});document.addEventListener("alpine:init",()=>{window.Alpine.data("filamentActionModals",n)});})();

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
function c({livewireId:s}){return{areAllCheckboxesChecked:!1,checkboxListOptions:[],search:"",visibleCheckboxListOptions:[],init(){this.checkboxListOptions=Array.from(this.$root.querySelectorAll(".fi-fo-checkbox-list-option")),this.updateVisibleCheckboxListOptions(),this.$nextTick(()=>{this.checkIfAllCheckboxesAreChecked()}),Livewire.hook("commit",({component:e,commit:t,succeed:i,fail:o,respond:h})=>{i(({snapshot:r,effect:l})=>{this.$nextTick(()=>{e.id===s&&(this.checkboxListOptions=Array.from(this.$root.querySelectorAll(".fi-fo-checkbox-list-option")),this.updateVisibleCheckboxListOptions(),this.checkIfAllCheckboxesAreChecked())})})}),this.$watch("search",()=>{this.updateVisibleCheckboxListOptions(),this.checkIfAllCheckboxesAreChecked()})},checkIfAllCheckboxesAreChecked(){this.areAllCheckboxesChecked=this.visibleCheckboxListOptions.length===this.visibleCheckboxListOptions.filter(e=>e.querySelector("input[type=checkbox]:checked, input[type=checkbox]:disabled")).length},toggleAllCheckboxes(){this.checkIfAllCheckboxesAreChecked();let e=!this.areAllCheckboxesChecked;this.visibleCheckboxListOptions.forEach(t=>{let i=t.querySelector("input[type=checkbox]");i.disabled||i.checked!==e&&(i.checked=e,i.dispatchEvent(new Event("change")))}),this.areAllCheckboxesChecked=e},updateVisibleCheckboxListOptions(){this.visibleCheckboxListOptions=this.checkboxListOptions.filter(e=>["",null,void 0].includes(this.search)||e.querySelector(".fi-fo-checkbox-list-option-label")?.innerText.toLowerCase().includes(this.search.toLowerCase())?!0:e.querySelector(".fi-fo-checkbox-list-option-description")?.innerText.toLowerCase().includes(this.search.toLowerCase()))}}}export{c as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
function r({state:o}){return{state:o,rows:[],shouldUpdateRows:!0,init:function(){this.updateRows(),this.rows.length<=0?this.rows.push({key:"",value:""}):this.updateState(),this.$watch("state",(t,e)=>{let s=i=>i===null?0:Array.isArray(i)?i.length:typeof i!="object"?0:Object.keys(i).length;s(t)===0&&s(e)===0||this.updateRows()})},addRow:function(){this.rows.push({key:"",value:""}),this.updateState()},deleteRow:function(t){this.rows.splice(t,1),this.rows.length<=0&&this.addRow(),this.updateState()},reorderRows:function(t){let e=Alpine.raw(this.rows);this.rows=[];let s=e.splice(t.oldIndex,1)[0];e.splice(t.newIndex,0,s),this.$nextTick(()=>{this.rows=e,this.updateState()})},updateRows:function(){if(!this.shouldUpdateRows){this.shouldUpdateRows=!0;return}let t=[];for(let[e,s]of Object.entries(this.state??{}))t.push({key:e,value:s});this.rows=t},updateState:function(){let t={};this.rows.forEach(e=>{e.key===""||e.key===null||(t[e.key]=e.value)}),this.shouldUpdateRows=!1,this.state=t}}}export{r as default}; function h({state:r}){return{state:r,rows:[],init(){this.updateRows(),this.rows.length<=0?this.rows.push({key:"",value:""}):this.updateState(),this.$watch("state",(e,t)=>{let s=i=>i===null?0:Array.isArray(i)?i.length:typeof i!="object"?0:Object.keys(i).length;s(e)===0&&s(t)===0||this.updateRows()})},addRow(){this.rows.push({key:"",value:""}),this.updateState()},deleteRow(e){this.rows.splice(e,1),this.rows.length<=0&&this.addRow(),this.updateState()},reorderRows(e){let t=Alpine.raw(this.rows);this.rows=[];let s=t.splice(e.oldIndex,1)[0];t.splice(e.newIndex,0,s),this.$nextTick(()=>{this.rows=t,this.updateState()})},updateRows(){let t=Alpine.raw(this.state).map(({key:s,value:i})=>({key:s,value:i}));this.rows.forEach(s=>{(s.key===""||s.key===null)&&t.push({key:"",value:s.value})}),this.rows=t},updateState(){let e=[];this.rows.forEach(t=>{t.key===""||t.key===null||e.push({key:t.key,value:t.value})}),JSON.stringify(this.state)!==JSON.stringify(e)&&(this.state=e)}}}export{h as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
function i({state:a,splitKeys:n}){return{newTag:"",state:a,createTag:function(){if(this.newTag=this.newTag.trim(),this.newTag!==""){if(this.state.includes(this.newTag)){this.newTag="";return}this.state.push(this.newTag),this.newTag=""}},deleteTag:function(t){this.state=this.state.filter(e=>e!==t)},reorderTags:function(t){let e=this.state.splice(t.oldIndex,1)[0];this.state.splice(t.newIndex,0,e),this.state=[...this.state]},input:{"x-on:blur":"createTag()","x-model":"newTag","x-on:keydown"(t){["Enter",...n].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),this.createTag())},"x-on:paste"(){this.$nextTick(()=>{if(n.length===0){this.createTag();return}let t=n.map(e=>e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")).join("|");this.newTag.split(new RegExp(t,"g")).forEach(e=>{this.newTag=e,this.createTag()})})}}}}export{i as default}; function s({state:n,splitKeys:a}){return{newTag:"",state:n,createTag(){if(this.newTag=this.newTag.trim(),this.newTag!==""){if(this.state.includes(this.newTag)){this.newTag="";return}this.state.push(this.newTag),this.newTag=""}},deleteTag(t){this.state=this.state.filter(e=>e!==t)},reorderTags(t){let e=this.state.splice(t.oldIndex,1)[0];this.state.splice(t.newIndex,0,e),this.state=[...this.state]},input:{"x-on:blur":"createTag()","x-model":"newTag","x-on:keydown"(t){["Enter",...a].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),this.createTag())},"x-on:paste"(){this.$nextTick(()=>{if(a.length===0){this.createTag();return}let t=a.map(e=>e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")).join("|");this.newTag.split(new RegExp(t,"g")).forEach(e=>{this.newTag=e,this.createTag()})})}}}}export{s as default};

View File

@@ -1 +1 @@
function r({initialHeight:t,shouldAutosize:i,state:s}){return{state:s,wrapperEl:null,init:function(){this.wrapperEl=this.$el.parentNode,this.setInitialHeight(),i?this.$watch("state",()=>{this.resize()}):this.setUpResizeObserver()},setInitialHeight:function(){this.$el.scrollHeight<=0||(this.wrapperEl.style.height=t+"rem")},resize:function(){if(this.setInitialHeight(),this.$el.scrollHeight<=0)return;let e=this.$el.scrollHeight+"px";this.wrapperEl.style.height!==e&&(this.wrapperEl.style.height=e)},setUpResizeObserver:function(){new ResizeObserver(()=>{this.wrapperEl.style.height=this.$el.style.height}).observe(this.$el)}}}export{r as default}; function r({initialHeight:t,shouldAutosize:i,state:s}){return{state:s,wrapperEl:null,init(){this.wrapperEl=this.$el.parentNode,this.setInitialHeight(),i?this.$watch("state",()=>{this.resize()}):this.setUpResizeObserver()},setInitialHeight(){this.$el.scrollHeight<=0||(this.wrapperEl.style.height=t+"rem")},resize(){if(this.setInitialHeight(),this.$el.scrollHeight<=0)return;let e=this.$el.scrollHeight+"px";this.wrapperEl.style.height!==e&&(this.wrapperEl.style.height=e)},setUpResizeObserver(){new ResizeObserver(()=>{this.wrapperEl.style.height=this.$el.style.height}).observe(this.$el)}}}export{r as default};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
var i=()=>({isSticky:!1,width:0,resizeObserver:null,boundUpdateWidth:null,init(){let e=this.$el.parentElement;e&&(this.updateWidth(),this.resizeObserver=new ResizeObserver(()=>this.updateWidth()),this.resizeObserver.observe(e),this.boundUpdateWidth=this.updateWidth.bind(this),window.addEventListener("resize",this.boundUpdateWidth))},enableSticky(){this.isSticky=this.$el.getBoundingClientRect().top>0},disableSticky(){this.isSticky=!1},updateWidth(){let e=this.$el.parentElement;if(!e)return;let t=getComputedStyle(this.$root.querySelector(".fi-ac"));this.width=e.offsetWidth+parseInt(t.marginInlineStart,10)*-1+parseInt(t.marginInlineEnd,10)*-1},destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.boundUpdateWidth&&(window.removeEventListener("resize",this.boundUpdateWidth),this.boundUpdateWidth=null)}});export{i as default};

View File

@@ -0,0 +1 @@
function u({activeTab:a,isTabPersistedInQueryString:e,livewireId:h,tab:o,tabQueryStringKey:s}){return{tab:o,init(){let t=this.getTabs(),i=new URLSearchParams(window.location.search);e&&i.has(s)&&t.includes(i.get(s))&&(this.tab=i.get(s)),this.$watch("tab",()=>this.updateQueryString()),(!this.tab||!t.includes(this.tab))&&(this.tab=t[a-1]),Livewire.hook("commit",({component:r,commit:f,succeed:c,fail:l,respond:b})=>{c(({snapshot:d,effect:m})=>{this.$nextTick(()=>{if(r.id!==h)return;let n=this.getTabs();n.includes(this.tab)||(this.tab=n[a-1]??this.tab)})})})},getTabs(){return this.$refs.tabsData?JSON.parse(this.$refs.tabsData.value):[]},updateQueryString(){if(!e)return;let t=new URL(window.location.href);t.searchParams.set(s,this.tab),history.replaceState(null,document.title,t.toString())}}}export{u as default};

View File

@@ -0,0 +1 @@
function o({isSkippable:s,isStepPersistedInQueryString:i,key:r,startStep:h,stepQueryStringKey:n}){return{step:null,init(){this.$watch("step",()=>this.updateQueryString()),this.step=this.getSteps().at(h-1),this.autofocusFields()},async requestNextStep(){await this.$wire.callSchemaComponentMethod(r,"nextStep",{currentStepIndex:this.getStepIndex(this.step)})},goToNextStep(){let t=this.getStepIndex(this.step)+1;t>=this.getSteps().length||(this.step=this.getSteps()[t],this.autofocusFields(),this.scroll())},goToPreviousStep(){let t=this.getStepIndex(this.step)-1;t<0||(this.step=this.getSteps()[t],this.autofocusFields(),this.scroll())},scroll(){this.$nextTick(()=>{this.$refs.header?.children[this.getStepIndex(this.step)].scrollIntoView({behavior:"smooth",block:"start"})})},autofocusFields(){this.$nextTick(()=>this.$refs[`step-${this.step}`].querySelector("[autofocus]")?.focus())},getStepIndex(t){let e=this.getSteps().findIndex(p=>p===t);return e===-1?0:e},getSteps(){return JSON.parse(this.$refs.stepsData.value)},isFirstStep(){return this.getStepIndex(this.step)<=0},isLastStep(){return this.getStepIndex(this.step)+1>=this.getSteps().length},isStepAccessible(t){return s||this.getStepIndex(this.step)>this.getStepIndex(t)},updateQueryString(){if(!i)return;let t=new URL(window.location.href);t.searchParams.set(n,this.step),history.replaceState(null,document.title,t.toString())}}}export{o as default};

View File

@@ -0,0 +1 @@
(()=>{var d=()=>({isSticky:!1,width:0,resizeObserver:null,boundUpdateWidth:null,init(){let t=this.$el.parentElement;t&&(this.updateWidth(),this.resizeObserver=new ResizeObserver(()=>this.updateWidth()),this.resizeObserver.observe(t),this.boundUpdateWidth=this.updateWidth.bind(this),window.addEventListener("resize",this.boundUpdateWidth))},enableSticky(){this.isSticky=this.$el.getBoundingClientRect().top>0},disableSticky(){this.isSticky=!1},updateWidth(){let t=this.$el.parentElement;if(!t)return;let e=getComputedStyle(this.$root.querySelector(".fi-ac"));this.width=t.offsetWidth+parseInt(e.marginInlineStart,10)*-1+parseInt(e.marginInlineEnd,10)*-1},destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.boundUpdateWidth&&(window.removeEventListener("resize",this.boundUpdateWidth),this.boundUpdateWidth=null)}});var u=function(t,e,n){let i=t;if(e.startsWith("/")&&(n=!0,e=e.slice(1)),n)return e;for(;e.startsWith("../");)i=i.includes(".")?i.slice(0,i.lastIndexOf(".")):null,e=e.slice(3);return["",null,void 0].includes(i)?e:["",null,void 0].includes(e)?i:`${i}.${e}`},c=t=>{let e=Alpine.findClosest(t,n=>n.__livewire);if(!e)throw"Could not find Livewire component in DOM tree.";return e.__livewire};document.addEventListener("alpine:init",()=>{window.Alpine.data("filamentSchema",({livewireId:t})=>({handleFormValidationError(e){e.detail.livewireId===t&&this.$nextTick(()=>{let n=this.$el.querySelector("[data-validation-error]");if(!n)return;let i=n;for(;i;)i.dispatchEvent(new CustomEvent("expand")),i=i.parentNode;setTimeout(()=>n.closest("[data-field-wrapper]").scrollIntoView({behavior:"smooth",block:"start",inline:"start"}),200)})},isStateChanged(e,n){if(e===void 0)return!1;try{return JSON.stringify(e)!==JSON.stringify(n)}catch{return e!==n}}})),window.Alpine.data("filamentSchemaComponent",({path:t,containerPath:e,$wire:n})=>({$statePath:t,$get:(i,s)=>n.$get(u(e,i,s)),$set:(i,s,a,o=!1)=>n.$set(u(e,i,a),s,o),get $state(){return n.$get(t)}})),window.Alpine.data("filamentActionsSchemaComponent",d),Livewire.hook("commit",({component:t,commit:e,respond:n,succeed:i,fail:s})=>{i(({snapshot:a,effects:o})=>{o.dispatches?.forEach(r=>{if(!r.params?.awaitSchemaComponent)return;let l=Array.from(t.el.querySelectorAll(`[wire\\:partial="schema-component::${r.params.awaitSchemaComponent}"]`)).filter(h=>c(h)===t);if(l.length!==1){if(l.length>1)throw`Multiple schema components found with key [${r.params.awaitSchemaComponent}].`;window.addEventListener(`schema-component-${t.id}-${r.params.awaitSchemaComponent}-loaded`,()=>{window.dispatchEvent(new CustomEvent(r.name,{detail:r.params}))},{once:!0})}})})})});})();

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More