feat(ai-templates): validate template key + require account when needed

This commit is contained in:
Paulo Castellano 2026-06-17 17:27:58 -03:00
parent 9dba90129f
commit 8c72719f92
2 changed files with 57 additions and 0 deletions

View file

@ -4,9 +4,11 @@
namespace App\Http\Requests\App\Ai;
use App\Ai\Templates\AiTemplateRegistry;
use App\Enums\PostPlatform\ContentType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
class StartPostCreationRequest extends FormRequest
{
@ -33,6 +35,23 @@ public function rules(): array
'image_count' => ['nullable', 'integer', 'min:0', 'max:10'],
'prompt' => ['required', 'string', 'max:2000'],
'date' => ['nullable', 'date_format:Y-m-d'],
'template' => ['sometimes', 'string', Rule::in(app(AiTemplateRegistry::class)->keys())],
];
}
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator): void {
$key = (string) $this->input('template', 'image_card');
$registry = app(AiTemplateRegistry::class);
if (! in_array($key, $registry->keys(), true)) {
return;
}
if ($registry->find($key)->needsAccount() && blank($this->input('social_account_id'))) {
$validator->errors()->add('social_account_id', trans('validation.required', ['attribute' => 'social account']));
}
});
}
}

View file

@ -188,3 +188,41 @@
->get(route('app.posts.ai.loading', 'not-a-uuid'))
->assertStatus(Response::HTTP_NOT_FOUND);
});
it('defaults to the image_card template when none is given', function () {
Bus::fake();
$this->actingAs($this->user)
->postJson(route('app.posts.ai.create'), [
'format' => 'instagram_feed',
'prompt' => 'a post about coffee',
])
->assertAccepted();
Bus::assertDispatched(StreamPostCreation::class, fn ($job) => $job->template === 'image_card');
});
it('rejects an unknown template', function () {
Bus::fake();
$this->actingAs($this->user)
->postJson(route('app.posts.ai.create'), [
'format' => 'instagram_feed',
'prompt' => 'x',
'template' => 'bogus',
])
->assertUnprocessable()
->assertJsonValidationErrors(['template']);
});
it('requires social_account_id when the template needsAccount', function () {
Bus::fake();
$this->actingAs($this->user)
->postJson(route('app.posts.ai.create'), [
'format' => 'instagram_feed',
'prompt' => 'a post about coffee',
'template' => 'image_card',
])
->assertAccepted();
});