Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
29 / 29 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| SaveDocumentTemplateAction | |
100.00% |
29 / 29 |
|
100.00% |
1 / 1 |
3 | |
100.00% |
1 / 1 |
| execute | |
100.00% |
29 / 29 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace ImovelZapAi\Documents\Application\Actions; |
| 6 | |
| 7 | use App\Models\User; |
| 8 | use Illuminate\Support\Facades\DB; |
| 9 | use ImovelZapAi\Documents\Domain\Enums\DocumentType; |
| 10 | use ImovelZapAi\Documents\Infrastructure\Persistence\Eloquent\DocumentTemplateModel; |
| 11 | |
| 12 | final class SaveDocumentTemplateAction |
| 13 | { |
| 14 | /** |
| 15 | * @param array{ |
| 16 | * name: string, |
| 17 | * document_type: string, |
| 18 | * body_html: string, |
| 19 | * body_json?: array<string, mixed>|null, |
| 20 | * is_default?: bool|null, |
| 21 | * } $data |
| 22 | */ |
| 23 | public function execute(string $tenantId, User $actor, array $data, ?DocumentTemplateModel $existing = null): DocumentTemplateModel |
| 24 | { |
| 25 | return DB::transaction(function () use ($tenantId, $actor, $data, $existing): DocumentTemplateModel { |
| 26 | $documentType = DocumentType::from($data['document_type']); |
| 27 | |
| 28 | if (! empty($data['is_default'])) { |
| 29 | DocumentTemplateModel::query() |
| 30 | ->where('tenant_id', $tenantId) |
| 31 | ->where('document_type', $documentType) |
| 32 | ->where('is_default', true) |
| 33 | ->when($existing !== null, fn ($q) => $q->whereKeyNot($existing->id)) |
| 34 | ->update(['is_default' => false]); |
| 35 | } |
| 36 | |
| 37 | if ($existing !== null) { |
| 38 | $existing->forceFill([ |
| 39 | 'name' => $data['name'], |
| 40 | 'document_type' => $documentType, |
| 41 | 'body_html' => $data['body_html'], |
| 42 | 'body_json' => $data['body_json'] ?? $existing->body_json, |
| 43 | 'is_default' => $data['is_default'] ?? $existing->is_default, |
| 44 | ])->save(); |
| 45 | |
| 46 | return $existing->fresh(); |
| 47 | } |
| 48 | |
| 49 | return DocumentTemplateModel::query()->create([ |
| 50 | 'tenant_id' => $tenantId, |
| 51 | 'name' => $data['name'], |
| 52 | 'document_type' => $documentType, |
| 53 | 'body_html' => $data['body_html'], |
| 54 | 'body_json' => $data['body_json'] ?? null, |
| 55 | 'is_default' => $data['is_default'] ?? false, |
| 56 | 'is_system' => false, |
| 57 | 'created_by' => $actor->id, |
| 58 | ]); |
| 59 | }); |
| 60 | } |
| 61 | } |