Files
hoshpoint-backend/app/Filament/Resources/Templates/Actions/GenerateWithAiAction.php

100 lines
3.7 KiB
PHP

<?php
namespace App\Filament\Resources\Templates\Actions;
use App\Enums\TemplateGenerationStatus;
use App\Enums\TemplateKeyType;
use App\Jobs\GenerateTemplateJob;
use App\Models\AiProvider;
use App\Models\Template;
use App\Models\TemplateGeneration;
use App\Services\Ai\OpenAiCompatibleTextGenerator;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Str;
use Throwable;
class GenerateWithAiAction
{
public static function make(): Action
{
return Action::make('generateWithAi')
->label('تولید با هوش مصنوعی')
->icon(Heroicon::OutlinedSparkles)
->color('info')
->schema(function (Template $record): array {
$components = [
Textarea::make('topic')
->label('موضوع / محتوای خام')
->helperText('هوش مصنوعی بر اساس این متن، کلیدهای متنی قالب را تکمیل می‌کند.')
->required()
->rows(4),
];
foreach ($record->keys->where('type', TemplateKeyType::Image) as $key) {
$components[] = FileUpload::make("images.{$key->key}")
->label($key->label)
->image()
->disk('local')
->directory('templates/generations/inputs')
->required($key->is_required);
}
return $components;
})
->action(function (array $data, Template $record): void {
$provider = AiProvider::query()
->where('is_active', true)
->orderByDesc('is_default')
->first();
if (! $provider) {
Notification::make()
->title('هیچ سرویس هوش مصنوعی فعالی تنظیم نشده است.')
->body('ابتدا از بخش «سرویس‌های AI» یک سرویس فعال تعریف کنید.')
->danger()
->send();
return;
}
try {
$values = app(OpenAiCompatibleTextGenerator::class)->generateForTemplate($record, $data['topic'], $provider);
} catch (Throwable $exception) {
Notification::make()
->title('خطا در تولید محتوا با هوش مصنوعی')
->body($exception->getMessage())
->danger()
->send();
return;
}
foreach ($data['images'] ?? [] as $key => $path) {
if ($path) {
$values[$key] = $path;
}
}
$generation = TemplateGeneration::query()->create([
'template_id' => $record->id,
'uuid' => (string) Str::uuid(),
'status' => TemplateGenerationStatus::Pending,
'values' => $values,
'requested_by' => auth()->id(),
]);
GenerateTemplateJob::dispatch($generation);
Notification::make()
->title('درخواست تولید ثبت شد')
->body('نتیجه را می‌توانید در تب «تولیدها» مشاهده کنید.')
->success()
->send();
});
}
}