Files

97 lines
3.3 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Contracts\PhoneNumberNormalizerInterface;
use App\Models\Contact;
use App\Models\ContactPhoneNumber;
use App\Models\User;
use App\Services\Sms\SmsCampaignSender;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class SendTestSmsCommand extends Command
{
protected $signature = 'sms:send-test {phone} {--message=Test RelaisSMS}';
protected $description = 'Cree le contact de test si besoin et envoie un SMS uniquement a ce numero.';
public function handle(PhoneNumberNormalizerInterface $normalizer, SmsCampaignSender $sender): int
{
$phone = (string) $this->argument('phone');
$message = trim((string) $this->option('message'));
$normalized = $normalizer->normalize($phone, (string) config('relais_sms.default_settings.default_country', 'FR'));
if (! $normalized->isValid || ! $normalized->isMobile || $normalized->normalizedNumber === null) {
$this->error($normalized->error ?: 'Numero invalide ou non mobile.');
return self::FAILURE;
}
if ($message === '') {
$this->error('Message vide.');
return self::FAILURE;
}
[$contact, $phoneNumber] = DB::transaction(function () use ($normalized): array {
$phoneNumber = ContactPhoneNumber::query()
->where('normalized_number', $normalized->normalizedNumber)
->with('contact')
->first();
if ($phoneNumber !== null && $phoneNumber->contact !== null) {
return [$phoneNumber->contact, $phoneNumber];
}
$contact = Contact::query()->create([
'source' => 'local',
'first_name' => 'Test',
'last_name' => 'RelaisSMS',
'notes' => 'Contact cree pour test envoi SMS.',
]);
$phoneNumber = $contact->phoneNumbers()->create([
'label' => 'Test',
'raw_number' => $normalized->rawNumber,
'normalized_number' => $normalized->normalizedNumber,
'country' => $normalized->country,
'is_valid' => $normalized->isValid,
'is_mobile' => $normalized->isMobile,
'is_primary' => true,
'validation_error' => $normalized->error,
]);
return [$contact, $phoneNumber];
});
$user = User::query()->first();
if ($user === null) {
$this->error('Aucun utilisateur applicatif disponible.');
return self::FAILURE;
}
$campaign = $sender->send($user, $message, [[
'contact_id' => $contact->id,
'contact_name' => $contact->displayName(),
'phone_number_id' => $phoneNumber->id,
'number' => $normalized->normalizedNumber,
'raw_number' => $normalized->rawNumber,
'label' => $phoneNumber->label,
'selection' => ['Test CLI'],
]]);
$this->line('Campagne #'.$campaign->id.' : '.$campaign->status);
if ($campaign->error_message !== null) {
$this->error($campaign->error_message);
return self::FAILURE;
}
return $campaign->status === 'failed' ? self::FAILURE : self::SUCCESS;
}
}