Files
triptyk-crm-overlay/app/Actions/Team/NotifyTeamOfNewApiLead.php
T

79 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Actions\Team;
use App\Models\Company;
use App\Models\People;
use App\Models\Team;
use App\Notifications\NewApiLeadNotification;
use Filament\Actions\Action;
use Filament\Notifications\Notification as FilamentNotification;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Notification as NotificationFacade;
final readonly class NotifyTeamOfNewApiLead
{
public function execute(Company|People $record): void
{
$team = $record->team;
if ($team === null || ! $team->notify_on_api_lead) {
return;
}
$recipients = $team->allUsers();
if ($recipients->isEmpty()) {
return;
}
[$label, $url] = $this->resolveLabelAndUrl($record);
defer(function () use ($recipients, $label, $record, $url): void {
$recipients->each(function ($recipient) use ($label, $record, $url): void {
FilamentNotification::make()
->title("Nuevo {$label} desde la web: {$record->name}")
->actions([
Action::make('view')
->button()
->label("Ver {$label}")
->url($url)
->markAsRead(),
])
->icon(Heroicon::OutlinedUserPlus)
->iconColor('success')
->sendToDatabase($recipient);
});
NotificationFacade::send(
$recipients,
new NewApiLeadNotification($label, $record->name, $url)
);
});
}
/** @return array{0: string, 1: string} */
private function resolveLabelAndUrl(Company|People $record): array
{
if ($record instanceof Company) {
return ['empresa', $this->resolveUrl(\App\Filament\Resources\CompanyResource::class, $record)];
}
return ['candidato', $this->resolveUrl(\App\Filament\Resources\PeopleResource::class, $record)];
}
private function resolveUrl(string $resourceClass, Company|People $record): string
{
// Se llama sin contexto de panel/tenant activo (p.ej. desde una
// request a /api/v1/...), así que hay que pasarlos explícitos o
// Filament::getCurrentPanel()/getTenant() devuelven null y la URL cae a '#'.
try {
return $resourceClass::getUrl('view', ['record' => $record], panel: 'app', tenant: $record->team);
} catch (\Throwable) {
return '#';
}
}
}