Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
30 / 30 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| VisitMessageRenderer | |
100.00% |
30 / 30 |
|
100.00% |
3 / 3 |
9 | |
100.00% |
1 / 1 |
| templateBody | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| render | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
4 | |||
| ensureDefaultTemplates | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace ImovelZapAi\Visits\Application\Services; |
| 6 | |
| 7 | use ImovelZapAi\Visits\Domain\Enums\VisitReminderType; |
| 8 | use ImovelZapAi\Visits\Infrastructure\Persistence\Eloquent\VisitMessageTemplateModel; |
| 9 | use ImovelZapAi\Visits\Infrastructure\Persistence\Eloquent\VisitModel; |
| 10 | |
| 11 | final class VisitMessageRenderer |
| 12 | { |
| 13 | public function templateBody(string $tenantId, VisitReminderType $type): ?string |
| 14 | { |
| 15 | $template = VisitMessageTemplateModel::query() |
| 16 | ->where('tenant_id', $tenantId) |
| 17 | ->where('type', $type) |
| 18 | ->first(); |
| 19 | |
| 20 | if ($template !== null && ! $template->enabled) { |
| 21 | return null; |
| 22 | } |
| 23 | |
| 24 | return $template?->body ?? $type->defaultTemplate(); |
| 25 | } |
| 26 | |
| 27 | public function render(string $tenantId, VisitReminderType $type, VisitModel $visit): ?string |
| 28 | { |
| 29 | $body = $this->templateBody($tenantId, $type); |
| 30 | if ($body === null) { |
| 31 | return null; |
| 32 | } |
| 33 | |
| 34 | $visit->loadMissing(['contact', 'property']); |
| 35 | |
| 36 | $start = $visit->scheduled_start; |
| 37 | $replacements = [ |
| 38 | '{{nome}}' => (string) ($visit->contact?->display_name ?: 'cliente'), |
| 39 | '{{imovel}}' => (string) ($visit->property?->title ?: 'o imóvel'), |
| 40 | '{{data}}' => $start?->timezone($visit->timezone)->format('d/m/Y') ?? '', |
| 41 | '{{hora}}' => $start?->timezone($visit->timezone)->format('H:i') ?? '', |
| 42 | ]; |
| 43 | |
| 44 | return str_replace(array_keys($replacements), array_values($replacements), $body); |
| 45 | } |
| 46 | |
| 47 | public function ensureDefaultTemplates(string $tenantId): void |
| 48 | { |
| 49 | foreach (VisitReminderType::cases() as $type) { |
| 50 | VisitMessageTemplateModel::query()->firstOrCreate( |
| 51 | [ |
| 52 | 'tenant_id' => $tenantId, |
| 53 | 'type' => $type, |
| 54 | ], |
| 55 | [ |
| 56 | 'body' => $type->defaultTemplate(), |
| 57 | 'enabled' => true, |
| 58 | ], |
| 59 | ); |
| 60 | } |
| 61 | } |
| 62 | } |