Publication initiale de RelaisSMS : documentation et sources nettoyees
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\SourceSyncRun;
|
||||
use App\Services\Calendar\CalendarEventSyncService;
|
||||
use App\Services\Calendar\CalendarReminderSender;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Throwable;
|
||||
|
||||
class ProcessCalendarRemindersCommand extends Command
|
||||
{
|
||||
protected $signature = 'calendar:process-reminders
|
||||
{--no-sync : Ne synchronise pas l agenda avant traitement}
|
||||
{--force-sync : Force la synchronisation CalDAV avant traitement}';
|
||||
|
||||
protected $description = 'Synchronise l agenda CalDAV et envoie les rappels SMS dus.';
|
||||
|
||||
public function handle(CalendarEventSyncService $syncService, CalendarReminderSender $sender): int
|
||||
{
|
||||
if ($this->shouldSync()) {
|
||||
try {
|
||||
$run = $syncService->sync();
|
||||
$this->line((string) $run->message);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('Synchronisation CalDAV agenda en echec : '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
} elseif (! $this->option('no-sync')) {
|
||||
$interval = (int) config('relais_sms.caldav.sync_interval_minutes', 60);
|
||||
$this->line('Synchronisation CalDAV ignoree : derniere synchronisation recente, intervalle '.$interval.' minute(s).');
|
||||
}
|
||||
|
||||
$sent = $sender->sendDue();
|
||||
$this->info($sent.' rappel(s) SMS envoye(s).');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function shouldSync(): bool
|
||||
{
|
||||
if ($this->option('no-sync')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->option('force-sync')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$interval = max(1, (int) config('relais_sms.caldav.sync_interval_minutes', 60));
|
||||
$lastRun = SourceSyncRun::query()
|
||||
->where('source', 'caldav_calendar')
|
||||
->latest('started_at')
|
||||
->first();
|
||||
|
||||
$rawStartedAt = $lastRun?->getRawOriginal('started_at');
|
||||
|
||||
if ($rawStartedAt === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$lastStartedAt = Carbon::parse((string) $rawStartedAt, 'UTC');
|
||||
$nextAllowedSyncAt = Carbon::now()->utc()->subMinutes($interval);
|
||||
|
||||
return $lastStartedAt->lessThanOrEqualTo($nextAllowedSyncAt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\SmsCampaign;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class PruneSmsHistoryCommand extends Command
|
||||
{
|
||||
protected $signature = 'sms-campaigns:prune-history {--dry-run : Compte les campagnes expirees sans les supprimer.}';
|
||||
|
||||
protected $description = 'Supprime les campagnes SMS plus anciennes que la duree de retention configuree.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$retentionYears = (int) config('relais_sms.default_settings.history_retention_years', 3);
|
||||
|
||||
if ($retentionYears < 1) {
|
||||
$this->error('La retention doit etre superieure ou egale a 1 an.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$expiresBefore = now()->subYears($retentionYears);
|
||||
$query = SmsCampaign::query()->where('created_at', '<', $expiresBefore);
|
||||
$count = $query->count();
|
||||
|
||||
if ($this->option('dry-run')) {
|
||||
$this->line($count.' campagne(s) SMS expiree(s) avant '.$expiresBefore->format('Y-m-d H:i:s').'.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$query->delete();
|
||||
$this->line($count.' campagne(s) SMS supprimee(s).');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\SmsCampaign;
|
||||
use App\Services\Sms\SmsCampaignReconciler;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class ReconcileSmsCampaignsCommand extends Command
|
||||
{
|
||||
protected $signature = 'sms-campaigns:reconcile {--limit=50 : Nombre maximum de campagnes a verifier.}';
|
||||
|
||||
protected $description = 'Verifie les envois incertains dans l historique OVH sans renvoyer de SMS.';
|
||||
|
||||
public function handle(SmsCampaignReconciler $reconciler): int
|
||||
{
|
||||
$processed = 0;
|
||||
SmsCampaign::query()
|
||||
->where('provider', 'ovh')
|
||||
->where(function (Builder $query): void {
|
||||
$query->where('status', 'uncertain')
|
||||
->orWhere(fn (Builder $query): Builder => $query->where('status', 'sending')->where('updated_at', '<', now()->subMinutes(10)));
|
||||
})
|
||||
->orderBy('updated_at')
|
||||
->limit(max(1, (int) $this->option('limit')))
|
||||
->get()
|
||||
->each(function (SmsCampaign $campaign) use ($reconciler, &$processed): void {
|
||||
if ($campaign->status === 'sending') {
|
||||
$campaign->update([
|
||||
'status' => 'uncertain',
|
||||
'error_message' => 'Envoi interrompu avant confirmation. Verification OVH necessaire ; ne pas renvoyer cette campagne.',
|
||||
]);
|
||||
$campaign->deliveries()->where('status', 'queued')->update(['status' => 'uncertain']);
|
||||
}
|
||||
$reconciler->reconcile($campaign);
|
||||
$processed++;
|
||||
});
|
||||
|
||||
$this->line($processed.' campagne(s) verifiee(s), sans nouvel envoi.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\SmsCampaign;
|
||||
use App\Services\Sms\SmsCampaignSender;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class SendDueSmsCampaignsCommand extends Command
|
||||
{
|
||||
protected $signature = 'sms-campaigns:send-due {--limit=50 : Nombre maximum de campagnes a prendre en charge.}';
|
||||
|
||||
protected $description = 'Envoie les campagnes SMS programmees arrivees a echeance.';
|
||||
|
||||
public function handle(SmsCampaignSender $sender): int
|
||||
{
|
||||
$limit = max(1, (int) $this->option('limit'));
|
||||
$processed = 0;
|
||||
|
||||
SmsCampaign::query()
|
||||
->where('status', 'scheduled')
|
||||
->whereNotNull('scheduled_at')
|
||||
->where('scheduled_at', '<=', now())
|
||||
->orderBy('scheduled_at')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->each(function (SmsCampaign $campaign) use ($sender, &$processed): void {
|
||||
if ($sender->sendScheduled($campaign) !== null) {
|
||||
$processed++;
|
||||
}
|
||||
});
|
||||
|
||||
$this->line($processed.' campagne(s) SMS programmee(s) prise(s) en charge.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Calendar\CalendarEventSyncService;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class SyncCalDavCalendarCommand extends Command
|
||||
{
|
||||
protected $signature = 'calendar:sync-caldav';
|
||||
|
||||
protected $description = 'Synchronise les evenements depuis l agenda CalDAV configure.';
|
||||
|
||||
public function handle(CalendarEventSyncService $syncService): int
|
||||
{
|
||||
try {
|
||||
$run = $syncService->sync();
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('Synchronisation CalDAV agenda en echec : '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info((string) $run->message);
|
||||
$this->line('Objets lus : '.$run->fetched_contacts);
|
||||
$this->line('Evenements synchronises : '.$run->synced_contacts);
|
||||
$this->line('Evenements annules localement : '.$run->deleted_contacts);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\CardDav\CardDavContactSyncService;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class SyncCardDavContactsCommand extends Command
|
||||
{
|
||||
protected $signature = 'contacts:sync-carddav';
|
||||
|
||||
protected $description = 'Synchronise les contacts depuis le carnet CardDAV configure.';
|
||||
|
||||
public function handle(CardDavContactSyncService $syncService): int
|
||||
{
|
||||
try {
|
||||
$run = $syncService->sync();
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('Synchronisation CardDAV en echec : '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info((string) $run->message);
|
||||
$this->line('Contacts lus : '.$run->fetched_contacts);
|
||||
$this->line('Contacts synchronises : '.$run->synced_contacts);
|
||||
$this->line('Contacts supprimes localement : '.$run->deleted_contacts);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Calendar;
|
||||
|
||||
use App\Services\Calendar\CalendarRemoteEvent;
|
||||
use Carbon\CarbonInterface;
|
||||
|
||||
interface CalendarClientInterface
|
||||
{
|
||||
/**
|
||||
* @return array<int, CalendarRemoteEvent>
|
||||
*/
|
||||
public function fetchEvents(CarbonInterface $from, CarbonInterface $to): array;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\CardDav;
|
||||
|
||||
use App\Services\CardDav\CardDavRemoteCard;
|
||||
|
||||
interface CardDavClientInterface
|
||||
{
|
||||
/**
|
||||
* @return array<int, CardDavRemoteCard>
|
||||
*/
|
||||
public function fetchCards(): array;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts;
|
||||
|
||||
use App\Services\Phone\PhoneNumberResult;
|
||||
|
||||
interface PhoneNumberNormalizerInterface
|
||||
{
|
||||
public function normalize(string $rawNumber, string $defaultCountry): PhoneNumberResult;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Sms;
|
||||
|
||||
use App\Models\SmsCampaign;
|
||||
use App\Services\Sms\SmsSendResult;
|
||||
|
||||
interface SmsProviderInterface
|
||||
{
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
*/
|
||||
public function send(SmsCampaign $campaign, array $recipients): SmsSendResult;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AuthenticatedSessionController extends Controller
|
||||
{
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'string', 'max:255'],
|
||||
'password' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$remember = $request->boolean('remember');
|
||||
|
||||
if (! Auth::attempt($credentials, $remember)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended(route('recipients.index', absolute: false));
|
||||
}
|
||||
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect()->route('login');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\CardDav\CardDavContactSyncService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Throwable;
|
||||
|
||||
class CardDavSyncController extends Controller
|
||||
{
|
||||
public function __invoke(CardDavContactSyncService $syncService): RedirectResponse
|
||||
{
|
||||
try {
|
||||
$run = $syncService->sync();
|
||||
} catch (Throwable $exception) {
|
||||
return redirect()
|
||||
->route('contacts.index')
|
||||
->with('status', 'Synchronisation CardDAV en echec : '.$exception->getMessage());
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('contacts.index')
|
||||
->with('status', $run->message ?? 'Synchronisation CardDAV terminee.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||
use App\Models\Contact;
|
||||
use App\Models\ContactGroup;
|
||||
use App\Models\SourceSyncRun;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ContactController extends Controller
|
||||
{
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$search = (string) $request->query('q', '');
|
||||
$groupId = $request->integer('group');
|
||||
$favoriteOnly = $request->boolean('favorite');
|
||||
$selectedStatus = (string) $request->query('status', '');
|
||||
$selectedMobileFilter = (string) $request->query('mobile', 'detected');
|
||||
|
||||
if (! in_array($selectedStatus, ['', 'active', 'favorite', 'opt_out'], true)) {
|
||||
$selectedStatus = '';
|
||||
}
|
||||
|
||||
if (! in_array($selectedMobileFilter, ['all', 'detected', 'non_mobile', 'invalid', 'missing'], true)) {
|
||||
$selectedMobileFilter = 'detected';
|
||||
}
|
||||
|
||||
$contacts = Contact::query()
|
||||
->with(['groups', 'phoneNumbers'])
|
||||
->withCount('groups')
|
||||
->search($search)
|
||||
->when($groupId > 0, function ($query) use ($groupId): void {
|
||||
$query->whereHas('groups', fn ($query) => $query->whereKey($groupId));
|
||||
})
|
||||
->when($favoriteOnly || $selectedStatus === 'favorite', function ($query): void {
|
||||
$query->where('is_favorite', true);
|
||||
})
|
||||
->when($selectedStatus === 'opt_out', function ($query): void {
|
||||
$query->where('sms_opt_out', true);
|
||||
})
|
||||
->when($selectedStatus === 'active', function ($query): void {
|
||||
$query->where('sms_opt_out', false);
|
||||
})
|
||||
->when($selectedMobileFilter === 'detected', function ($query): void {
|
||||
$query->whereHas('phoneNumbers', function ($query): void {
|
||||
$query->where('is_valid', true)
|
||||
->where(function ($query): void {
|
||||
$query
|
||||
->where('is_mobile', true)
|
||||
->orWhere('normalized_number', 'like', '+336%')
|
||||
->orWhere('normalized_number', 'like', '+337%');
|
||||
});
|
||||
});
|
||||
})
|
||||
->when($selectedMobileFilter === 'non_mobile', function ($query): void {
|
||||
$query->whereHas('phoneNumbers', function ($query): void {
|
||||
$query->where('is_valid', true)
|
||||
->where('is_mobile', false)
|
||||
->where('normalized_number', 'not like', '+336%')
|
||||
->where('normalized_number', 'not like', '+337%');
|
||||
});
|
||||
})
|
||||
->when($selectedMobileFilter === 'invalid', function ($query): void {
|
||||
$query->whereHas('phoneNumbers', fn ($query) => $query->where('is_valid', false));
|
||||
})
|
||||
->when($selectedMobileFilter === 'missing', function ($query): void {
|
||||
$query->whereDoesntHave('phoneNumbers');
|
||||
})
|
||||
->orderByDesc('is_favorite')
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->paginate(15)
|
||||
->withQueryString();
|
||||
|
||||
$groups = ContactGroup::query()
|
||||
->withCount('contacts')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return view('contacts.index', [
|
||||
'contacts' => $contacts,
|
||||
'groups' => $groups,
|
||||
'search' => $search,
|
||||
'selectedGroupId' => $groupId,
|
||||
'favoriteOnly' => $favoriteOnly,
|
||||
'selectedStatus' => $selectedStatus,
|
||||
'selectedMobileFilter' => $selectedMobileFilter,
|
||||
'cardDavSyncEnabled' => (bool) config('relais_sms.default_settings.carddav_sync_enabled'),
|
||||
'lastCardDavSyncRun' => SourceSyncRun::query()
|
||||
->where('source', 'carddav')
|
||||
->latest('started_at')
|
||||
->first(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
return view('contacts.create', [
|
||||
'groups' => ContactGroup::query()->where('source', 'local')->orderBy('name')->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request, PhoneNumberNormalizerInterface $normalizer): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate($this->rules());
|
||||
|
||||
$contact = DB::transaction(function () use ($request, $validated, $normalizer): Contact {
|
||||
$contact = Contact::query()->create([
|
||||
'source' => 'local',
|
||||
'first_name' => $validated['first_name'] ?? null,
|
||||
'last_name' => $validated['last_name'],
|
||||
'organization' => $validated['organization'] ?? null,
|
||||
'email' => $validated['email'] ?? null,
|
||||
'notes' => $validated['notes'] ?? null,
|
||||
'sms_opt_out' => $request->boolean('sms_opt_out'),
|
||||
'is_favorite' => $request->boolean('is_favorite'),
|
||||
]);
|
||||
|
||||
$contact->groups()->sync($validated['group_ids'] ?? []);
|
||||
$this->syncPrimaryPhoneNumber($contact, $validated, $normalizer);
|
||||
|
||||
return $contact;
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('contacts.show', $contact)
|
||||
->with('status', 'Contact cree.');
|
||||
}
|
||||
|
||||
public function show(Contact $contact): View
|
||||
{
|
||||
$contact->load(['groups', 'phoneNumbers']);
|
||||
|
||||
return view('contacts.show', [
|
||||
'contact' => $contact,
|
||||
]);
|
||||
}
|
||||
|
||||
public function favorite(Request $request, Contact $contact): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'is_favorite' => ['required', 'boolean'],
|
||||
]);
|
||||
|
||||
$contact->update([
|
||||
'is_favorite' => (bool) $validated['is_favorite'],
|
||||
]);
|
||||
|
||||
return back()->with('status', $contact->is_favorite ? 'Contact ajoute aux favoris.' : 'Contact retire des favoris.');
|
||||
}
|
||||
|
||||
public function optOut(Request $request, Contact $contact): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'sms_opt_out' => ['required', 'boolean'],
|
||||
]);
|
||||
|
||||
$contact->update([
|
||||
'sms_opt_out' => (bool) $validated['sms_opt_out'],
|
||||
]);
|
||||
|
||||
return back()->with('status', $contact->sms_opt_out ? 'Contact ajoute aux refus SMS.' : 'Contact retire des refus SMS.');
|
||||
}
|
||||
|
||||
public function edit(Contact $contact): View
|
||||
{
|
||||
$this->ensureLocalContact($contact);
|
||||
|
||||
$contact->load(['groups', 'phoneNumbers']);
|
||||
|
||||
return view('contacts.edit', [
|
||||
'contact' => $contact,
|
||||
'groups' => ContactGroup::query()->where('source', 'local')->orderBy('name')->get(),
|
||||
'primaryPhone' => $contact->phoneNumbers->firstWhere('is_primary', true) ?? $contact->phoneNumbers->first(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Contact $contact, PhoneNumberNormalizerInterface $normalizer): RedirectResponse
|
||||
{
|
||||
$this->ensureLocalContact($contact);
|
||||
|
||||
$validated = $request->validate($this->rules());
|
||||
|
||||
DB::transaction(function () use ($request, $contact, $validated, $normalizer): void {
|
||||
$contact->update([
|
||||
'first_name' => $validated['first_name'] ?? null,
|
||||
'last_name' => $validated['last_name'],
|
||||
'organization' => $validated['organization'] ?? null,
|
||||
'email' => $validated['email'] ?? null,
|
||||
'notes' => $validated['notes'] ?? null,
|
||||
'sms_opt_out' => $request->boolean('sms_opt_out'),
|
||||
'is_favorite' => $request->boolean('is_favorite'),
|
||||
]);
|
||||
|
||||
$contact->groups()->sync($validated['group_ids'] ?? []);
|
||||
$this->syncPrimaryPhoneNumber($contact, $validated, $normalizer);
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('contacts.show', $contact)
|
||||
->with('status', 'Contact modifie.');
|
||||
}
|
||||
|
||||
public function destroy(Contact $contact): RedirectResponse
|
||||
{
|
||||
$this->ensureLocalContact($contact);
|
||||
|
||||
$contact->delete();
|
||||
|
||||
return redirect()
|
||||
->route('contacts.index')
|
||||
->with('status', 'Contact supprime.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
private function rules(): array
|
||||
{
|
||||
return [
|
||||
'first_name' => ['nullable', 'string', 'max:255'],
|
||||
'last_name' => ['required', 'string', 'max:255'],
|
||||
'organization' => ['nullable', 'string', 'max:255'],
|
||||
'email' => ['nullable', 'email', 'max:255'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
'phone_label' => ['nullable', 'string', 'max:255'],
|
||||
'raw_phone_number' => ['nullable', 'string', 'max:255'],
|
||||
'group_ids' => ['array'],
|
||||
'group_ids.*' => [
|
||||
'integer',
|
||||
Rule::exists('contact_groups', 'id')
|
||||
->where('source', 'local')
|
||||
->whereNull('deleted_at'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function ensureLocalContact(Contact $contact): void
|
||||
{
|
||||
abort_if($contact->source !== 'local', 403, 'Les contacts importes ne sont pas modifiables localement.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $validated
|
||||
*/
|
||||
private function syncPrimaryPhoneNumber(Contact $contact, array $validated, PhoneNumberNormalizerInterface $normalizer): void
|
||||
{
|
||||
$rawPhoneNumber = trim((string) ($validated['raw_phone_number'] ?? ''));
|
||||
$primaryPhone = $contact->phoneNumbers()->where('is_primary', true)->first()
|
||||
?? $contact->phoneNumbers()->first();
|
||||
|
||||
if ($rawPhoneNumber === '') {
|
||||
$primaryPhone?->delete();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = $normalizer->normalize(
|
||||
$rawPhoneNumber,
|
||||
(string) config('relais_sms.default_settings.default_country'),
|
||||
);
|
||||
|
||||
$attributes = [
|
||||
'label' => $validated['phone_label'] ?? null,
|
||||
'raw_number' => $result->rawNumber,
|
||||
'normalized_number' => $result->normalizedNumber,
|
||||
'country' => $result->country,
|
||||
'is_valid' => $result->isValid,
|
||||
'is_mobile' => $result->isMobile,
|
||||
'is_primary' => true,
|
||||
'validation_error' => $result->error,
|
||||
];
|
||||
|
||||
if ($primaryPhone) {
|
||||
$primaryPhone->update($attributes);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$contact->phoneNumbers()->create($attributes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Contact;
|
||||
use App\Models\ContactGroup;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ContactGroupController extends Controller
|
||||
{
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => ['required', 'string', 'max:255', Rule::unique('contact_groups', 'name')->whereNull('deleted_at')],
|
||||
'description' => ['nullable', 'string'],
|
||||
]);
|
||||
|
||||
ContactGroup::query()->create([
|
||||
'source' => 'local',
|
||||
'name' => $validated['name'],
|
||||
'slug' => $this->uniqueSlug($validated['name']),
|
||||
'description' => $validated['description'] ?? null,
|
||||
'is_favorite' => $request->boolean('is_favorite'),
|
||||
]);
|
||||
|
||||
return redirect()
|
||||
->route('contacts.index')
|
||||
->with('status', 'Groupe cree.');
|
||||
}
|
||||
|
||||
public function edit(ContactGroup $contactGroup): View
|
||||
{
|
||||
$this->ensureLocalGroup($contactGroup);
|
||||
|
||||
return view('contact-groups.edit', [
|
||||
'group' => $contactGroup->load('contacts')->loadCount('contacts'),
|
||||
'contacts' => Contact::query()
|
||||
->with('phoneNumbers')
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->get(),
|
||||
'selectedContactIds' => $contactGroup->contacts->pluck('id')->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, ContactGroup $contactGroup): RedirectResponse
|
||||
{
|
||||
$this->ensureLocalGroup($contactGroup);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('contact_groups', 'name')->ignore($contactGroup)->whereNull('deleted_at'),
|
||||
],
|
||||
'description' => ['nullable', 'string'],
|
||||
'contact_ids' => ['array'],
|
||||
'contact_ids.*' => [Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||
]);
|
||||
|
||||
$contactGroup->update([
|
||||
'name' => $validated['name'],
|
||||
'slug' => $this->uniqueSlug($validated['name'], $contactGroup),
|
||||
'description' => $validated['description'] ?? null,
|
||||
'is_favorite' => $request->boolean('is_favorite'),
|
||||
]);
|
||||
|
||||
if ($request->has('members_submitted')) {
|
||||
$contactGroup->contacts()->sync($validated['contact_ids'] ?? []);
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('contacts.index', ['group' => $contactGroup->id])
|
||||
->with('status', 'Groupe modifie.');
|
||||
}
|
||||
|
||||
public function destroy(ContactGroup $contactGroup): RedirectResponse
|
||||
{
|
||||
$this->ensureLocalGroup($contactGroup);
|
||||
|
||||
$contactGroup->contacts()->detach();
|
||||
$contactGroup->delete();
|
||||
|
||||
return redirect()
|
||||
->route('contacts.index')
|
||||
->with('status', 'Groupe supprime.');
|
||||
}
|
||||
|
||||
private function uniqueSlug(string $name, ?ContactGroup $ignore = null): string
|
||||
{
|
||||
$baseSlug = Str::slug($name);
|
||||
$baseSlug = $baseSlug === '' ? 'groupe' : $baseSlug;
|
||||
$slug = $baseSlug;
|
||||
$index = 2;
|
||||
|
||||
while (ContactGroup::query()
|
||||
->where('slug', $slug)
|
||||
->when($ignore, fn ($query) => $query->whereKeyNot($ignore->id))
|
||||
->exists()
|
||||
) {
|
||||
$slug = $baseSlug.'-'.$index;
|
||||
$index++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
private function ensureLocalGroup(ContactGroup $contactGroup): void
|
||||
{
|
||||
abort_if($contactGroup->source !== 'local', 403, 'Les groupes importes ne sont pas modifiables localement.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||
use App\Models\ContactPhoneNumber;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OvhStopCallbackController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, PhoneNumberNormalizerInterface $normalizer): JsonResponse
|
||||
{
|
||||
$configuredToken = trim((string) config('relais_sms.ovh.stop_callback_token', ''));
|
||||
$receivedToken = trim((string) ($request->query('token') ?: $request->header('X-RelaisSMS-Callback-Token', '')));
|
||||
|
||||
abort_if($configuredToken === '' || ! hash_equals($configuredToken, $receivedToken), 403);
|
||||
|
||||
$sender = $this->sender($request);
|
||||
|
||||
if ($sender === '') {
|
||||
return response()->json([
|
||||
'status' => 'ignored',
|
||||
'reason' => 'missing_sender',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$result = $normalizer->normalize(
|
||||
$sender,
|
||||
(string) config('relais_sms.default_settings.default_country'),
|
||||
);
|
||||
|
||||
if (! $result->isValid || $result->normalizedNumber === null) {
|
||||
return response()->json([
|
||||
'status' => 'ignored',
|
||||
'reason' => 'invalid_sender',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$contacts = ContactPhoneNumber::query()
|
||||
->with('contact')
|
||||
->where('normalized_number', $result->normalizedNumber)
|
||||
->get()
|
||||
->pluck('contact')
|
||||
->filter()
|
||||
->unique('id')
|
||||
->values();
|
||||
|
||||
$updatedContacts = 0;
|
||||
$alreadyOptedOutContacts = 0;
|
||||
|
||||
foreach ($contacts as $contact) {
|
||||
if ($contact->sms_opt_out) {
|
||||
$alreadyOptedOutContacts++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$contact->update(['sms_opt_out' => true]);
|
||||
$updatedContacts++;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => $contacts->isEmpty() ? 'unmatched' : 'ok',
|
||||
'sender' => $result->normalizedNumber,
|
||||
'updated_contacts' => $updatedContacts,
|
||||
'already_opted_out_contacts' => $alreadyOptedOutContacts,
|
||||
]);
|
||||
}
|
||||
|
||||
private function sender(Request $request): string
|
||||
{
|
||||
foreach (['sender', 'from', 'number', 'phone', 'msisdn'] as $key) {
|
||||
$value = $request->input($key);
|
||||
|
||||
if (is_string($value) && trim($value) !== '') {
|
||||
return trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Contact;
|
||||
use App\Models\ContactGroup;
|
||||
use App\Services\Recipients\RecipientResolutionResult;
|
||||
use App\Services\Recipients\RecipientResolver;
|
||||
use App\Services\Sms\SmsMessageComposer;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class RecipientSelectionController extends Controller
|
||||
{
|
||||
public function index(Request $request, SmsMessageComposer $messageComposer): View
|
||||
{
|
||||
return $this->view($request, messageComposer: $messageComposer);
|
||||
}
|
||||
|
||||
public function search(Request $request): JsonResponse
|
||||
{
|
||||
$search = trim((string) $request->query('q', ''));
|
||||
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $search).'%';
|
||||
|
||||
$contacts = Contact::query()
|
||||
->with('phoneNumbers')
|
||||
->search($search)
|
||||
->orderByDesc('is_favorite')
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->limit(10)
|
||||
->get()
|
||||
->map(function (Contact $contact): array {
|
||||
$primaryPhone = $contact->phoneNumbers->firstWhere('is_primary', true)
|
||||
?? $contact->phoneNumbers->first();
|
||||
|
||||
return [
|
||||
'type' => 'contact',
|
||||
'id' => $contact->id,
|
||||
'label' => $contact->displayName(),
|
||||
'meta' => $primaryPhone?->normalized_number
|
||||
?: $primaryPhone?->raw_number
|
||||
?: $contact->email
|
||||
?: ucfirst($contact->source),
|
||||
'source' => $contact->source,
|
||||
'is_favorite' => $contact->is_favorite,
|
||||
];
|
||||
});
|
||||
|
||||
$groups = ContactGroup::query()
|
||||
->withCount('contacts')
|
||||
->when($search !== '', function ($query) use ($like): void {
|
||||
$query->where(function ($query) use ($like): void {
|
||||
$query
|
||||
->where('name', 'like', $like)
|
||||
->orWhere('description', 'like', $like);
|
||||
});
|
||||
})
|
||||
->orderByDesc('is_favorite')
|
||||
->orderBy('name')
|
||||
->limit(10)
|
||||
->get()
|
||||
->map(fn (ContactGroup $group): array => [
|
||||
'type' => 'group',
|
||||
'id' => $group->id,
|
||||
'label' => $group->name,
|
||||
'meta' => $group->contacts_count.' contact(s)',
|
||||
'source' => $group->source,
|
||||
'is_favorite' => $group->is_favorite,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'results' => $groups->concat($contacts)->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function preview(Request $request, RecipientResolver $resolver, SmsMessageComposer $messageComposer): View|RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:255'],
|
||||
'message' => ['nullable', 'string', 'max:612'],
|
||||
'include_sms_header' => ['nullable', 'boolean'],
|
||||
'include_sms_footer' => ['nullable', 'boolean'],
|
||||
'contact_ids' => ['array'],
|
||||
'contact_ids.*' => ['integer', Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||
'group_ids' => ['array'],
|
||||
'group_ids.*' => ['integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||
]);
|
||||
|
||||
$contactIds = $validated['contact_ids'] ?? [];
|
||||
$groupIds = $validated['group_ids'] ?? [];
|
||||
|
||||
if ($contactIds === [] && $groupIds === []) {
|
||||
return redirect()
|
||||
->route('recipients.index', ['q' => $validated['q'] ?? null])
|
||||
->withErrors(['selection' => 'Selectionnez au moins un contact ou un groupe.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
return $this->view(
|
||||
$request,
|
||||
$resolver->resolve($contactIds, $groupIds),
|
||||
$contactIds,
|
||||
$groupIds,
|
||||
$messageComposer,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int|string> $selectedContactIds
|
||||
* @param array<int, int|string> $selectedGroupIds
|
||||
*/
|
||||
private function view(
|
||||
Request $request,
|
||||
?RecipientResolutionResult $resolution = null,
|
||||
array $selectedContactIds = [],
|
||||
array $selectedGroupIds = [],
|
||||
?SmsMessageComposer $messageComposer = null,
|
||||
): View {
|
||||
$messageComposer ??= app(SmsMessageComposer::class);
|
||||
$messageSettings = $messageComposer->settings();
|
||||
$oldHeaderChoice = $request->old('include_sms_header');
|
||||
$oldFooterChoice = $request->old('include_sms_footer');
|
||||
$hasHeaderChoice = $oldHeaderChoice !== null || $request->has('include_sms_header');
|
||||
$hasFooterChoice = $oldFooterChoice !== null || $request->has('include_sms_footer');
|
||||
$includeHeader = $hasHeaderChoice
|
||||
? filter_var($oldHeaderChoice ?? $request->input('include_sms_header'), FILTER_VALIDATE_BOOLEAN)
|
||||
: $messageSettings['header'] !== '';
|
||||
$includeFooter = $hasFooterChoice
|
||||
? filter_var($oldFooterChoice ?? $request->input('include_sms_footer'), FILTER_VALIDATE_BOOLEAN)
|
||||
: $messageSettings['footer'] !== '';
|
||||
$messageBody = (string) $request->old('message', $request->input('message', ''));
|
||||
|
||||
$search = trim((string) $request->input('q', ''));
|
||||
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $search).'%';
|
||||
|
||||
$contacts = Contact::query()
|
||||
->with(['groups', 'phoneNumbers'])
|
||||
->search($search)
|
||||
->orderByDesc('is_favorite')
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->limit(50)
|
||||
->get();
|
||||
|
||||
$groups = ContactGroup::query()
|
||||
->withCount('contacts')
|
||||
->when($search !== '', function ($query) use ($like): void {
|
||||
$query->where(function ($query) use ($like): void {
|
||||
$query
|
||||
->where('name', 'like', $like)
|
||||
->orWhere('description', 'like', $like);
|
||||
});
|
||||
})
|
||||
->orderByDesc('is_favorite')
|
||||
->orderBy('name')
|
||||
->limit(50)
|
||||
->get();
|
||||
|
||||
return view('recipients.index', [
|
||||
'contacts' => $contacts,
|
||||
'groups' => $groups,
|
||||
'search' => $search,
|
||||
'selectedContactIds' => collect($selectedContactIds)->map(fn (int|string $id): int => (int) $id)->all(),
|
||||
'selectedGroupIds' => collect($selectedGroupIds)->map(fn (int|string $id): int => (int) $id)->all(),
|
||||
'selectedContacts' => Contact::query()
|
||||
->whereKey($selectedContactIds)
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->get(),
|
||||
'selectedGroups' => ContactGroup::query()
|
||||
->whereKey($selectedGroupIds)
|
||||
->orderBy('name')
|
||||
->get(),
|
||||
'resolution' => $resolution,
|
||||
'smsHeader' => $messageSettings['header'],
|
||||
'smsFooter' => $messageSettings['footer'],
|
||||
'includeSmsHeader' => $includeHeader,
|
||||
'includeSmsFooter' => $includeFooter,
|
||||
'composedMessage' => $messageComposer->compose($messageBody, $includeHeader, $includeFooter),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\AppSetting;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class SettingsController extends Controller
|
||||
{
|
||||
public function edit(): View
|
||||
{
|
||||
return view('settings.edit', [
|
||||
'smsHeader' => AppSetting::string('sms_message_header'),
|
||||
'smsFooter' => AppSetting::string('sms_message_footer'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'sms_message_header' => ['nullable', 'string', 'max:612'],
|
||||
'sms_message_footer' => ['nullable', 'string', 'max:612'],
|
||||
]);
|
||||
|
||||
AppSetting::putString('sms_message_header', trim((string) ($validated['sms_message_header'] ?? '')));
|
||||
AppSetting::putString('sms_message_footer', trim((string) ($validated['sms_message_footer'] ?? '')));
|
||||
|
||||
return redirect()
|
||||
->route('settings.edit')
|
||||
->with('status', 'Parametres enregistres.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ContactGroup;
|
||||
use App\Models\SmsCampaign;
|
||||
use App\Models\User;
|
||||
use App\Services\Recipients\RecipientResolver;
|
||||
use App\Services\Sms\SmsCampaignSender;
|
||||
use App\Services\Sms\SmsMessageComposer;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class SmsCampaignController extends Controller
|
||||
{
|
||||
private const STATUSES = [
|
||||
'draft' => 'Brouillon',
|
||||
'scheduled' => 'Programme',
|
||||
'sending' => 'Envoi',
|
||||
'uncertain' => 'A verifier',
|
||||
'sent' => 'Envoye',
|
||||
'partial' => 'Partiel',
|
||||
'failed' => 'Echec',
|
||||
'canceled' => 'Annule',
|
||||
];
|
||||
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$filters = $this->validateFilters($request);
|
||||
|
||||
return view('sms-campaigns.index', [
|
||||
'campaigns' => $this->filteredCampaignsQuery($filters)
|
||||
->latest()
|
||||
->paginate(20)
|
||||
->withQueryString(),
|
||||
'filters' => $filters,
|
||||
'groups' => ContactGroup::query()->orderBy('name')->get(['id', 'name']),
|
||||
'statuses' => self::STATUSES,
|
||||
'users' => User::query()->orderBy('name')->get(['id', 'name']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(SmsCampaign $smsCampaign): View
|
||||
{
|
||||
return view('sms-campaigns.show', [
|
||||
'campaign' => $smsCampaign->load(['deliveries' => fn ($query) => $query->orderBy('id'), 'user']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function export(Request $request): StreamedResponse
|
||||
{
|
||||
$filters = $this->validateFilters($request);
|
||||
$query = $this->filteredCampaignsQuery($filters)
|
||||
->with(['deliveries' => fn ($query) => $query->orderBy('id')])
|
||||
->latest();
|
||||
|
||||
return response()->streamDownload(function () use ($query): void {
|
||||
$csv = fopen('php://output', 'w');
|
||||
|
||||
fputcsv($csv, [
|
||||
'campagne_id',
|
||||
'date_creation',
|
||||
'date_programmee',
|
||||
'date_envoi',
|
||||
'utilisateur',
|
||||
'statut_campagne',
|
||||
'groupes_selectionnes',
|
||||
'message',
|
||||
'destinataires_prevus',
|
||||
'destinataires_envoyes',
|
||||
'destinataires_echoues',
|
||||
'contact',
|
||||
'numero',
|
||||
'statut_destinataire',
|
||||
'message_fournisseur_id',
|
||||
'erreur',
|
||||
], ';');
|
||||
|
||||
$query->chunk(100, function ($campaigns) use ($csv): void {
|
||||
foreach ($campaigns as $campaign) {
|
||||
foreach ($campaign->deliveries as $delivery) {
|
||||
fputcsv($csv, [
|
||||
$campaign->id,
|
||||
$campaign->created_at->format('Y-m-d H:i:s'),
|
||||
$campaign->scheduled_at?->format('Y-m-d H:i:s'),
|
||||
$campaign->sent_at?->format('Y-m-d H:i:s'),
|
||||
$campaign->user?->name ?: 'Utilisateur supprime',
|
||||
self::STATUSES[$campaign->status] ?? $campaign->status,
|
||||
implode(', ', $campaign->selected_group_names ?? []),
|
||||
$campaign->message,
|
||||
$campaign->recipients_count,
|
||||
$campaign->sent_count,
|
||||
$campaign->failed_count,
|
||||
$delivery->contact_name,
|
||||
$delivery->number,
|
||||
$delivery->status,
|
||||
$delivery->provider_message_id,
|
||||
$delivery->error_message,
|
||||
], ';');
|
||||
}
|
||||
}
|
||||
});
|
||||
}, 'historique-sms-'.now()->format('Ymd-His').'.csv', [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(
|
||||
Request $request,
|
||||
RecipientResolver $resolver,
|
||||
SmsCampaignSender $sender,
|
||||
SmsMessageComposer $messageComposer,
|
||||
): RedirectResponse {
|
||||
$validated = $request->validate([
|
||||
'message' => ['required', 'string', 'min:1', 'max:612'],
|
||||
'include_sms_header' => ['nullable', 'boolean'],
|
||||
'include_sms_footer' => ['nullable', 'boolean'],
|
||||
'contact_ids' => ['array'],
|
||||
'contact_ids.*' => ['integer', Rule::exists('contacts', 'id')->whereNull('deleted_at')],
|
||||
'group_ids' => ['array'],
|
||||
'group_ids.*' => ['integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||
'send_mode' => ['nullable', Rule::in(['now', 'scheduled'])],
|
||||
'scheduled_at' => ['nullable', 'date'],
|
||||
]);
|
||||
|
||||
$contactIds = $validated['contact_ids'] ?? [];
|
||||
$groupIds = $validated['group_ids'] ?? [];
|
||||
$resolution = $resolver->resolve($contactIds, $groupIds);
|
||||
$recipients = $resolution->recipients;
|
||||
$maxRecipients = (int) config('relais_sms.default_settings.max_sms_per_campaign', 100);
|
||||
$messageSettings = $messageComposer->settings();
|
||||
$message = $messageComposer->compose(
|
||||
(string) $validated['message'],
|
||||
$request->has('include_sms_header') ? $request->boolean('include_sms_header') : $messageSettings['header'] !== '',
|
||||
$request->has('include_sms_footer') ? $request->boolean('include_sms_footer') : $messageSettings['footer'] !== '',
|
||||
);
|
||||
|
||||
if ($recipients === []) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['selection' => 'Aucun numero valide a envoyer.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
if (mb_strlen($message) > 612) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['message' => 'Le message complet avec entete et pied depasse 612 caracteres.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
if (count($recipients) > $maxRecipients) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['selection' => 'La selection depasse la limite de '.$maxRecipients.' SMS.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
if (($validated['send_mode'] ?? 'now') === 'scheduled') {
|
||||
if (! (bool) config('relais_sms.default_settings.scheduled_sends_enabled', true)) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['scheduled_at' => 'Les envois programmes sont desactives.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
if (($validated['scheduled_at'] ?? null) === null) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['scheduled_at' => 'La date et l heure d envoi sont obligatoires pour programmer un SMS.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
$scheduledAt = Carbon::parse((string) $validated['scheduled_at'], $this->scheduledTimezone())->utc();
|
||||
|
||||
if ($scheduledAt->lte(now())) {
|
||||
return redirect()
|
||||
->route('recipients.index')
|
||||
->withErrors(['scheduled_at' => 'La date et l heure d envoi doivent etre futures.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
$campaign = $sender->schedule($request->user(), $message, $recipients, $contactIds, $groupIds, $scheduledAt);
|
||||
|
||||
return redirect()
|
||||
->route('sms-campaigns.show', $campaign)
|
||||
->with('status', 'Campagne programmee pour le '.$campaign->scheduled_at?->timezone($this->scheduledTimezone())->format('d/m/Y H:i').'.');
|
||||
}
|
||||
|
||||
$campaign = $sender->send($request->user(), $message, $recipients, $contactIds, $groupIds);
|
||||
|
||||
if ($campaign->status === 'uncertain') {
|
||||
return redirect()->route('sms-campaigns.show', $campaign)->with('status', $campaign->error_message);
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('sms-campaigns.show', $campaign)
|
||||
->with(
|
||||
$campaign->status === 'failed' ? 'error' : 'status',
|
||||
$campaign->status === 'failed'
|
||||
? 'Envoi refuse ou echoue : '.$campaign->error_message
|
||||
: 'Campagne envoyee a '.$campaign->sent_count.' destinataire(s).',
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(SmsCampaign $smsCampaign): RedirectResponse
|
||||
{
|
||||
$canceled = DB::transaction(function () use ($smsCampaign): bool {
|
||||
$campaign = SmsCampaign::query()
|
||||
->whereKey($smsCampaign->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $campaign || $campaign->status !== 'scheduled') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$campaign->update([
|
||||
'status' => 'canceled',
|
||||
'canceled_at' => now(),
|
||||
]);
|
||||
|
||||
$campaign->deliveries()
|
||||
->where('status', 'queued')
|
||||
->update(['status' => 'canceled']);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return redirect()
|
||||
->route('sms-campaigns.show', $smsCampaign)
|
||||
->with(
|
||||
$canceled ? 'status' : 'error',
|
||||
$canceled
|
||||
? 'Campagne programmee annulee.'
|
||||
: 'Cette campagne ne peut plus etre annulee.',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{from?: string|null, to?: string|null, status?: string|null, user_id?: string|null, group_id?: string|null}
|
||||
*/
|
||||
private function validateFilters(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'from' => ['nullable', 'date'],
|
||||
'to' => ['nullable', 'date'],
|
||||
'status' => ['nullable', Rule::in(array_keys(self::STATUSES))],
|
||||
'user_id' => ['nullable', 'integer', Rule::exists('users', 'id')],
|
||||
'group_id' => ['nullable', 'integer', Rule::exists('contact_groups', 'id')->whereNull('deleted_at')],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{from?: string|null, to?: string|null, status?: string|null, user_id?: string|null, group_id?: string|null} $filters
|
||||
* @return Builder<SmsCampaign>
|
||||
*/
|
||||
private function filteredCampaignsQuery(array $filters): Builder
|
||||
{
|
||||
return SmsCampaign::query()
|
||||
->with('user')
|
||||
->when($filters['from'] ?? null, fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '>=', $date))
|
||||
->when($filters['to'] ?? null, fn (Builder $query, string $date): Builder => $query->whereDate('created_at', '<=', $date))
|
||||
->when($filters['status'] ?? null, fn (Builder $query, string $status): Builder => $query->where('status', $status))
|
||||
->when($filters['user_id'] ?? null, fn (Builder $query, string $userId): Builder => $query->where('user_id', (int) $userId))
|
||||
->when($filters['group_id'] ?? null, function (Builder $query, string $groupId): Builder {
|
||||
$groupId = (int) $groupId;
|
||||
|
||||
return $query->where(function (Builder $query) use ($groupId): void {
|
||||
$query
|
||||
->whereJsonContains('selected_group_ids', $groupId)
|
||||
->orWhereHas('deliveries.contact.groups', fn (Builder $query): Builder => $query->where('contact_groups.id', $groupId));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private function scheduledTimezone(): string
|
||||
{
|
||||
return (string) config('relais_sms.default_settings.display_timezone', 'Europe/Paris');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
#[Fillable(['key', 'value', 'type'])]
|
||||
class AppSetting extends Model
|
||||
{
|
||||
public static function string(string $key, string $default = ''): string
|
||||
{
|
||||
$setting = self::query()->where('key', $key)->first();
|
||||
|
||||
if ($setting === null) {
|
||||
$configured = config('relais_sms.default_settings.'.$key);
|
||||
|
||||
return is_string($configured) ? $configured : $default;
|
||||
}
|
||||
|
||||
return (string) $setting->value;
|
||||
}
|
||||
|
||||
public static function putString(string $key, string $value): void
|
||||
{
|
||||
self::query()->updateOrCreate(
|
||||
['key' => $key],
|
||||
[
|
||||
'value' => $value,
|
||||
'type' => 'string',
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'source',
|
||||
'external_id',
|
||||
'remote_url',
|
||||
'remote_etag',
|
||||
'summary',
|
||||
'description',
|
||||
'location',
|
||||
'starts_at',
|
||||
'ends_at',
|
||||
'attendees',
|
||||
'synced_at',
|
||||
'deleted_at',
|
||||
])]
|
||||
class CalendarEvent extends Model
|
||||
{
|
||||
/**
|
||||
* @return HasMany<CalendarReminder, $this>
|
||||
*/
|
||||
public function reminders(): HasMany
|
||||
{
|
||||
return $this->hasMany(CalendarReminder::class);
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'starts_at' => 'datetime',
|
||||
'ends_at' => 'datetime',
|
||||
'attendees' => 'array',
|
||||
'synced_at' => 'datetime',
|
||||
'deleted_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'calendar_event_id',
|
||||
'sms_campaign_id',
|
||||
'reminder_key',
|
||||
'action',
|
||||
'trigger_minutes',
|
||||
'remind_at',
|
||||
'status',
|
||||
'last_error',
|
||||
'sent_at',
|
||||
])]
|
||||
class CalendarReminder extends Model
|
||||
{
|
||||
/**
|
||||
* @return BelongsTo<CalendarEvent, $this>
|
||||
*/
|
||||
public function event(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CalendarEvent::class, 'calendar_event_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<SmsCampaign, $this>
|
||||
*/
|
||||
public function smsCampaign(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SmsCampaign::class);
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'remind_at' => 'datetime',
|
||||
'sent_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
#[Fillable([
|
||||
'source',
|
||||
'external_id',
|
||||
'remote_url',
|
||||
'remote_etag',
|
||||
'first_name',
|
||||
'last_name',
|
||||
'organization',
|
||||
'email',
|
||||
'notes',
|
||||
'sms_opt_out',
|
||||
'is_favorite',
|
||||
'synced_at',
|
||||
])]
|
||||
class Contact extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
/**
|
||||
* @return HasMany<ContactPhoneNumber, $this>
|
||||
*/
|
||||
public function phoneNumbers(): HasMany
|
||||
{
|
||||
return $this->hasMany(ContactPhoneNumber::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<ContactGroup, $this>
|
||||
*/
|
||||
public function groups(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(ContactGroup::class, 'contact_contact_group')
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return trim(implode(' ', array_filter([$this->first_name, $this->last_name])));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Contact> $query
|
||||
*/
|
||||
#[Scope]
|
||||
protected function search(Builder $query, ?string $term): void
|
||||
{
|
||||
$term = trim((string) $term);
|
||||
|
||||
if ($term === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $term).'%';
|
||||
|
||||
$query->where(function (Builder $query) use ($like): void {
|
||||
$query
|
||||
->where('first_name', 'like', $like)
|
||||
->orWhere('last_name', 'like', $like)
|
||||
->orWhere('organization', 'like', $like)
|
||||
->orWhere('email', 'like', $like)
|
||||
->orWhereHas('phoneNumbers', function (Builder $query) use ($like): void {
|
||||
$query
|
||||
->where('raw_number', 'like', $like)
|
||||
->orWhere('normalized_number', 'like', $like);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'sms_opt_out' => 'boolean',
|
||||
'is_favorite' => 'boolean',
|
||||
'synced_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
#[Fillable([
|
||||
'source',
|
||||
'external_id',
|
||||
'name',
|
||||
'slug',
|
||||
'description',
|
||||
'is_favorite',
|
||||
'synced_at',
|
||||
])]
|
||||
class ContactGroup extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Contact, $this>
|
||||
*/
|
||||
public function contacts(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Contact::class, 'contact_contact_group')
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_favorite' => 'boolean',
|
||||
'synced_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'contact_id',
|
||||
'label',
|
||||
'raw_number',
|
||||
'normalized_number',
|
||||
'country',
|
||||
'is_valid',
|
||||
'is_mobile',
|
||||
'is_primary',
|
||||
'validation_error',
|
||||
])]
|
||||
class ContactPhoneNumber extends Model
|
||||
{
|
||||
public function hasDetectedMobileNumber(): bool
|
||||
{
|
||||
if ($this->is_mobile) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$normalizedNumber = (string) $this->normalized_number;
|
||||
|
||||
if (preg_match('/^\+33[67]\d{8}$/', $normalizedNumber) === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$rawDigits = preg_replace('/\D+/', '', (string) $this->raw_number) ?? '';
|
||||
|
||||
return preg_match('/^0[67]\d{8}$/', $rawDigits) === 1
|
||||
|| preg_match('/^33[67]\d{8}$/', $rawDigits) === 1
|
||||
|| preg_match('/^0033[67]\d{8}$/', $rawDigits) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Contact, $this>
|
||||
*/
|
||||
public function contact(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Contact::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_valid' => 'boolean',
|
||||
'is_mobile' => 'boolean',
|
||||
'is_primary' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'user_id',
|
||||
'provider',
|
||||
'status',
|
||||
'message',
|
||||
'recipients_count',
|
||||
'selected_contact_ids',
|
||||
'selected_group_ids',
|
||||
'selected_group_names',
|
||||
'sent_count',
|
||||
'failed_count',
|
||||
'provider_service_name',
|
||||
'provider_tag',
|
||||
'provider_job_id',
|
||||
'request_payload',
|
||||
'response_payload',
|
||||
'error_message',
|
||||
'scheduled_at',
|
||||
'sent_at',
|
||||
'canceled_at',
|
||||
])]
|
||||
class SmsCampaign extends Model
|
||||
{
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<SmsDelivery, $this>
|
||||
*/
|
||||
public function deliveries(): HasMany
|
||||
{
|
||||
return $this->hasMany(SmsDelivery::class);
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'request_payload' => 'array',
|
||||
'response_payload' => 'array',
|
||||
'selected_contact_ids' => 'array',
|
||||
'selected_group_ids' => 'array',
|
||||
'selected_group_names' => 'array',
|
||||
'scheduled_at' => 'datetime',
|
||||
'sent_at' => 'datetime',
|
||||
'canceled_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'sms_campaign_id',
|
||||
'contact_id',
|
||||
'contact_phone_number_id',
|
||||
'contact_name',
|
||||
'number',
|
||||
'status',
|
||||
'provider_message_id',
|
||||
'provider_response',
|
||||
'error_message',
|
||||
'sent_at',
|
||||
])]
|
||||
class SmsDelivery extends Model
|
||||
{
|
||||
/**
|
||||
* @return BelongsTo<SmsCampaign, $this>
|
||||
*/
|
||||
public function campaign(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SmsCampaign::class, 'sms_campaign_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Contact, $this>
|
||||
*/
|
||||
public function contact(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Contact::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ContactPhoneNumber, $this>
|
||||
*/
|
||||
public function phoneNumber(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContactPhoneNumber::class, 'contact_phone_number_id');
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'provider_response' => 'array',
|
||||
'sent_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
#[Fillable([
|
||||
'source',
|
||||
'status',
|
||||
'started_at',
|
||||
'finished_at',
|
||||
'fetched_contacts',
|
||||
'synced_contacts',
|
||||
'deleted_contacts',
|
||||
'message',
|
||||
'error',
|
||||
])]
|
||||
class SourceSyncRun extends Model
|
||||
{
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'started_at' => 'datetime',
|
||||
'finished_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
#[Fillable(['name', 'email', 'password'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Contracts\Calendar\CalendarClientInterface;
|
||||
use App\Contracts\CardDav\CardDavClientInterface;
|
||||
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||
use App\Contracts\Sms\SmsProviderInterface;
|
||||
use App\Services\Calendar\CalDavCalendarClient;
|
||||
use App\Services\CardDav\CardDavClient;
|
||||
use App\Services\Phone\LibPhoneNumberNormalizer;
|
||||
use App\Services\Sms\OvhSmsProvider;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use libphonenumber\PhoneNumberUtil;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(PhoneNumberUtil::class, fn (): PhoneNumberUtil => PhoneNumberUtil::getInstance());
|
||||
$this->app->bind(PhoneNumberNormalizerInterface::class, LibPhoneNumberNormalizer::class);
|
||||
$this->app->singleton(ClientInterface::class, fn (): ClientInterface => new Client);
|
||||
$this->app->bind(CardDavClientInterface::class, CardDavClient::class);
|
||||
$this->app->bind(CalendarClientInterface::class, CalDavCalendarClient::class);
|
||||
$this->app->bind(SmsProviderInterface::class, OvhSmsProvider::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use App\Contracts\Calendar\CalendarClientInterface;
|
||||
use Carbon\CarbonInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use RuntimeException;
|
||||
use SimpleXMLElement;
|
||||
use Throwable;
|
||||
|
||||
class CalDavCalendarClient implements CalendarClientInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientInterface $http,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, CalendarRemoteEvent>
|
||||
*/
|
||||
public function fetchEvents(CarbonInterface $from, CarbonInterface $to): array
|
||||
{
|
||||
try {
|
||||
$events = $this->fetchEventsWithReport($from, $to);
|
||||
|
||||
if ($events !== []) {
|
||||
return $events;
|
||||
}
|
||||
} catch (GuzzleException|RuntimeException) {
|
||||
// Some CalDAV servers restrict calendar-query. Fall back to PROPFIND + GET.
|
||||
}
|
||||
|
||||
return $this->fetchEventsWithPropfind();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CalendarRemoteEvent>
|
||||
*/
|
||||
private function fetchEventsWithReport(CarbonInterface $from, CarbonInterface $to): array
|
||||
{
|
||||
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
|
||||
$username = (string) config('relais_sms.caldav.username');
|
||||
$password = (string) config('relais_sms.caldav.password');
|
||||
|
||||
$this->ensureConfigured($url, $username, $password);
|
||||
|
||||
$response = $this->http->request('REPORT', $url, [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/xml; charset=utf-8',
|
||||
'Depth' => '1',
|
||||
],
|
||||
'body' => $this->calendarQueryBody($from, $to),
|
||||
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||
]);
|
||||
|
||||
return $this->parseReport((string) $response->getBody());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CalendarRemoteEvent>
|
||||
*/
|
||||
private function fetchEventsWithPropfind(): array
|
||||
{
|
||||
$url = rtrim((string) config('relais_sms.caldav.url'), '/').'/';
|
||||
$username = (string) config('relais_sms.caldav.username');
|
||||
$password = (string) config('relais_sms.caldav.password');
|
||||
|
||||
$this->ensureConfigured($url, $username, $password);
|
||||
|
||||
$response = $this->http->request('PROPFIND', $url, [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/xml; charset=utf-8',
|
||||
'Depth' => '1',
|
||||
],
|
||||
'body' => <<<'XML'
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<d:propfind xmlns:d="DAV:">
|
||||
<d:prop>
|
||||
<d:getetag />
|
||||
</d:prop>
|
||||
</d:propfind>
|
||||
XML,
|
||||
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||
]);
|
||||
|
||||
$entries = $this->parsePropfind((string) $response->getBody(), $url);
|
||||
$events = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$eventResponse = $this->http->request('GET', $entry['url'], [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Accept' => 'text/calendar,text/plain,*/*',
|
||||
],
|
||||
'timeout' => (float) config('relais_sms.caldav.timeout'),
|
||||
]);
|
||||
|
||||
$events[] = new CalendarRemoteEvent(
|
||||
href: $entry['href'],
|
||||
etag: $entry['etag'],
|
||||
ical: (string) $eventResponse->getBody(),
|
||||
);
|
||||
}
|
||||
|
||||
return $events;
|
||||
}
|
||||
|
||||
private function ensureConfigured(string $url, string $username, string $password): void
|
||||
{
|
||||
if ($url === '/' || $username === '' || $password === '') {
|
||||
throw new RuntimeException('Configuration CalDAV agenda incomplete.');
|
||||
}
|
||||
}
|
||||
|
||||
private function calendarQueryBody(CarbonInterface $from, CarbonInterface $to): string
|
||||
{
|
||||
$start = $from->copy()->utc()->format('Ymd\THis\Z');
|
||||
$end = $to->copy()->utc()->format('Ymd\THis\Z');
|
||||
|
||||
return <<<XML
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<c:calendar-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav">
|
||||
<d:prop>
|
||||
<d:getetag />
|
||||
<c:calendar-data />
|
||||
</d:prop>
|
||||
<c:filter>
|
||||
<c:comp-filter name="VCALENDAR">
|
||||
<c:comp-filter name="VEVENT">
|
||||
<c:time-range start="$start" end="$end" />
|
||||
</c:comp-filter>
|
||||
</c:comp-filter>
|
||||
</c:filter>
|
||||
</c:calendar-query>
|
||||
XML;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CalendarRemoteEvent>
|
||||
*/
|
||||
private function parseReport(string $xml): array
|
||||
{
|
||||
try {
|
||||
$document = new SimpleXMLElement($xml);
|
||||
} catch (Throwable $exception) {
|
||||
throw new RuntimeException('Reponse CalDAV REPORT illisible.', previous: $exception);
|
||||
}
|
||||
|
||||
$document->registerXPathNamespace('d', 'DAV:');
|
||||
$responses = $document->xpath('//d:response') ?: [];
|
||||
$events = [];
|
||||
|
||||
foreach ($responses as $response) {
|
||||
$response->registerXPathNamespace('d', 'DAV:');
|
||||
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav');
|
||||
|
||||
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||
$calendarDataNodes = $response->xpath('.//c:calendar-data') ?: [];
|
||||
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||
$ical = (string) ($calendarDataNodes[0] ?? '');
|
||||
|
||||
if ($href === '' || trim($ical) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||
$events[] = new CalendarRemoteEvent(
|
||||
href: $href,
|
||||
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||
ical: $ical,
|
||||
);
|
||||
}
|
||||
|
||||
return $events;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{href: string, etag: ?string, url: string}>
|
||||
*/
|
||||
private function parsePropfind(string $xml, string $baseUrl): array
|
||||
{
|
||||
try {
|
||||
$document = new SimpleXMLElement($xml);
|
||||
} catch (Throwable $exception) {
|
||||
throw new RuntimeException('Reponse CalDAV PROPFIND illisible.', previous: $exception);
|
||||
}
|
||||
|
||||
$document->registerXPathNamespace('d', 'DAV:');
|
||||
$responses = $document->xpath('//d:response') ?: [];
|
||||
$entries = [];
|
||||
|
||||
foreach ($responses as $response) {
|
||||
$response->registerXPathNamespace('d', 'DAV:');
|
||||
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||
|
||||
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.ics')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||
$entries[] = [
|
||||
'href' => $href,
|
||||
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||
'url' => $this->absoluteUrl($baseUrl, $href),
|
||||
];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
private function absoluteUrl(string $baseUrl, string $href): string
|
||||
{
|
||||
if (parse_url($href, PHP_URL_SCHEME)) {
|
||||
return $href;
|
||||
}
|
||||
|
||||
$base = parse_url($baseUrl);
|
||||
|
||||
if (! isset($base['scheme'], $base['host'])) {
|
||||
throw new RuntimeException('URL CalDAV agenda invalide.');
|
||||
}
|
||||
|
||||
$port = isset($base['port']) ? ':'.$base['port'] : '';
|
||||
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
|
||||
|
||||
return $base['scheme'].'://'.$base['host'].$port.$path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use App\Contracts\Calendar\CalendarClientInterface;
|
||||
use App\Models\CalendarEvent;
|
||||
use App\Models\CalendarReminder;
|
||||
use App\Models\SourceSyncRun;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Throwable;
|
||||
|
||||
class CalendarEventSyncService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CalendarClientInterface $client,
|
||||
private readonly ICalendarParser $parser,
|
||||
) {}
|
||||
|
||||
public function sync(?Carbon $from = null, ?Carbon $to = null): SourceSyncRun
|
||||
{
|
||||
$from ??= Carbon::now()->subDay();
|
||||
$to ??= Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90));
|
||||
|
||||
$run = SourceSyncRun::query()->create([
|
||||
'source' => 'caldav_calendar',
|
||||
'status' => 'running',
|
||||
'started_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
try {
|
||||
$remoteEvents = $this->client->fetchEvents($from, $to);
|
||||
|
||||
DB::transaction(function () use ($run, $remoteEvents, $from, $to): void {
|
||||
$seenExternalIds = [];
|
||||
$syncedEvents = 0;
|
||||
$scheduledReminders = 0;
|
||||
|
||||
foreach ($remoteEvents as $remoteEvent) {
|
||||
foreach ($this->parser->parse($remoteEvent->ical, $from, $to) as $parsedEvent) {
|
||||
$externalId = $parsedEvent->recurrenceId === null
|
||||
? $parsedEvent->uid
|
||||
: 'recurrence:'.sha1($parsedEvent->uid.'|'.$parsedEvent->recurrenceId->format('Y-m-d H:i:s'));
|
||||
$seenExternalIds[] = $externalId;
|
||||
|
||||
$event = $this->upsertEvent($externalId, $remoteEvent, $parsedEvent);
|
||||
$scheduledReminders += $this->syncReminders($event, $parsedEvent);
|
||||
$syncedEvents++;
|
||||
}
|
||||
}
|
||||
|
||||
$cancelledEvents = $this->cancelMissingEvents($seenExternalIds);
|
||||
|
||||
$run->update([
|
||||
'status' => 'success',
|
||||
'finished_at' => Carbon::now(),
|
||||
'fetched_contacts' => count($remoteEvents),
|
||||
'synced_contacts' => $syncedEvents,
|
||||
'deleted_contacts' => $cancelledEvents,
|
||||
'message' => $syncedEvents.' evenement(s) CalDAV synchronise(s), '.$scheduledReminders.' rappel(s) programme(s).',
|
||||
]);
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
$run->update([
|
||||
'status' => 'failed',
|
||||
'finished_at' => Carbon::now(),
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return $run->refresh();
|
||||
}
|
||||
|
||||
private function upsertEvent(string $externalId, CalendarRemoteEvent $remoteEvent, ParsedCalendarEvent $parsedEvent): CalendarEvent
|
||||
{
|
||||
$event = CalendarEvent::query()
|
||||
->where('source', 'caldav')
|
||||
->where('external_id', $externalId)
|
||||
->first();
|
||||
|
||||
// Preserve the reminder history when an existing single event becomes a series.
|
||||
if (! $event && $parsedEvent->recurrenceId !== null) {
|
||||
$event = CalendarEvent::query()
|
||||
->where('source', 'caldav')
|
||||
->where('external_id', $parsedEvent->uid)
|
||||
->where('starts_at', $parsedEvent->recurrenceId->format('Y-m-d H:i:s'))
|
||||
->first();
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
'source' => 'caldav',
|
||||
'external_id' => $externalId,
|
||||
'remote_url' => $remoteEvent->href,
|
||||
'remote_etag' => $remoteEvent->etag,
|
||||
'summary' => $parsedEvent->summary,
|
||||
'description' => $parsedEvent->description,
|
||||
'location' => $parsedEvent->location,
|
||||
'starts_at' => $parsedEvent->startsAt,
|
||||
'ends_at' => $parsedEvent->endsAt,
|
||||
'attendees' => $parsedEvent->attendees,
|
||||
'synced_at' => Carbon::now(),
|
||||
'deleted_at' => null,
|
||||
];
|
||||
|
||||
if (! $event) {
|
||||
return CalendarEvent::query()->create($attributes);
|
||||
}
|
||||
|
||||
$event->fill($attributes);
|
||||
$event->save();
|
||||
|
||||
return $event;
|
||||
}
|
||||
|
||||
private function syncReminders(CalendarEvent $event, ParsedCalendarEvent $parsedEvent): int
|
||||
{
|
||||
$seenReminderKeys = [];
|
||||
$scheduledReminders = 0;
|
||||
|
||||
foreach ($parsedEvent->alarms as $index => $alarm) {
|
||||
if ($alarm->action !== 'DISPLAY') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$remindAt = $this->remindAt($parsedEvent, $alarm);
|
||||
|
||||
if ($remindAt === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$reminderKey = sha1($alarm->action.'|'.$alarm->trigger.'|'.$index);
|
||||
$seenReminderKeys[] = $reminderKey;
|
||||
$reminder = CalendarReminder::query()
|
||||
->where('calendar_event_id', $event->id)
|
||||
->where('reminder_key', $reminderKey)
|
||||
->first();
|
||||
|
||||
$attributes = [
|
||||
'action' => $alarm->action,
|
||||
'trigger_minutes' => $alarm->triggerMinutes,
|
||||
'remind_at' => $remindAt,
|
||||
];
|
||||
|
||||
if (! $reminder) {
|
||||
CalendarReminder::query()->create(array_merge($attributes, [
|
||||
'calendar_event_id' => $event->id,
|
||||
'reminder_key' => $reminderKey,
|
||||
'status' => 'pending',
|
||||
]));
|
||||
$scheduledReminders++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! in_array($reminder->status, ['sent', 'sending', 'uncertain', 'skipped'], true)) {
|
||||
$reminder->update(array_merge($attributes, [
|
||||
'status' => 'pending',
|
||||
'last_error' => null,
|
||||
]));
|
||||
$scheduledReminders++;
|
||||
}
|
||||
}
|
||||
|
||||
CalendarReminder::query()
|
||||
->where('calendar_event_id', $event->id)
|
||||
->whereNotIn('reminder_key', $seenReminderKeys ?: [''])
|
||||
->whereIn('status', ['pending', 'failed'])
|
||||
->update([
|
||||
'status' => 'cancelled',
|
||||
'last_error' => 'Rappel absent de la derniere synchronisation.',
|
||||
]);
|
||||
|
||||
return $scheduledReminders;
|
||||
}
|
||||
|
||||
private function remindAt(ParsedCalendarEvent $event, ParsedCalendarAlarm $alarm): ?Carbon
|
||||
{
|
||||
if ($alarm->absoluteRemindAt !== null) {
|
||||
return $alarm->absoluteRemindAt;
|
||||
}
|
||||
|
||||
if ($event->startsAt === null || $alarm->triggerMinutes === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $event->startsAt->copy()->addMinutes($alarm->triggerMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $seenExternalIds
|
||||
*/
|
||||
private function cancelMissingEvents(array $seenExternalIds): int
|
||||
{
|
||||
$events = CalendarEvent::query()
|
||||
->where('source', 'caldav')
|
||||
->whereNull('deleted_at')
|
||||
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||
->get();
|
||||
|
||||
foreach ($events as $event) {
|
||||
$event->update(['deleted_at' => Carbon::now()]);
|
||||
$event->reminders()
|
||||
->whereIn('status', ['pending', 'failed'])
|
||||
->update([
|
||||
'status' => 'cancelled',
|
||||
'last_error' => 'Evenement absent de la derniere synchronisation.',
|
||||
]);
|
||||
}
|
||||
|
||||
return $events->count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use DateTimeZone;
|
||||
use RuntimeException;
|
||||
use Sabre\VObject\Component\VCalendar;
|
||||
use Sabre\VObject\Component\VEvent;
|
||||
use Sabre\VObject\Reader;
|
||||
|
||||
class CalendarOccurrenceExpander
|
||||
{
|
||||
public function expand(string $ical, CarbonInterface $from, CarbonInterface $to): string
|
||||
{
|
||||
if (! preg_match('/^(RRULE|RDATE|RECURRENCE-ID)[;:]/mi', $ical)) {
|
||||
return $ical;
|
||||
}
|
||||
|
||||
$calendar = Reader::read($ical);
|
||||
if (! $calendar instanceof VCalendar) {
|
||||
throw new RuntimeException('La source agenda ne contient pas un calendrier iCalendar.');
|
||||
}
|
||||
|
||||
$additionalDates = clone $calendar;
|
||||
$additionalUids = [];
|
||||
|
||||
foreach ($calendar->select('VEVENT') as $event) {
|
||||
// A cancelled detached occurrence may contain only UID and RECURRENCE-ID.
|
||||
// It must still suppress the original occurrence during expansion.
|
||||
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
|
||||
$start = clone $event->{'RECURRENCE-ID'};
|
||||
$start->name = 'DTSTART';
|
||||
$event->add($start);
|
||||
}
|
||||
|
||||
// VObject chooses RDATE instead of RRULE when both are present.
|
||||
// Expand their union separately, then deduplicate by occurrence identity.
|
||||
if (isset($event->RRULE, $event->RDATE)) {
|
||||
$additionalUids[] = (string) $event->UID;
|
||||
unset($event->RDATE);
|
||||
}
|
||||
}
|
||||
|
||||
$timezone = new DateTimeZone((string) config('app.timezone', 'UTC'));
|
||||
$expanded = $calendar->expand($from, $to, $timezone);
|
||||
|
||||
if ($additionalUids !== []) {
|
||||
foreach ($additionalDates->select('VEVENT') as $event) {
|
||||
if (! in_array((string) $event->UID, $additionalUids, true)) {
|
||||
$additionalDates->remove($event);
|
||||
} else {
|
||||
unset($event->RRULE);
|
||||
if (! isset($event->DTSTART) && isset($event->{'RECURRENCE-ID'})) {
|
||||
$start = clone $event->{'RECURRENCE-ID'};
|
||||
$start->name = 'DTSTART';
|
||||
$event->add($start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$seen = [];
|
||||
foreach ($expanded->select('VEVENT') as $event) {
|
||||
$seen[$this->identity($event)] = true;
|
||||
}
|
||||
foreach ($additionalDates->expand($from, $to, $timezone)->select('VEVENT') as $event) {
|
||||
$key = $this->identity($event);
|
||||
if (! isset($seen[$key])) {
|
||||
$expanded->add(clone $event);
|
||||
$seen[$key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $expanded->serialize();
|
||||
}
|
||||
|
||||
private function identity(VEvent $event): string
|
||||
{
|
||||
return (string) $event->UID.'|'.(string) $event->{'RECURRENCE-ID'};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use App\Models\CalendarReminder;
|
||||
use App\Models\Contact;
|
||||
use App\Models\User;
|
||||
use App\Services\Recipients\RecipientResolver;
|
||||
use App\Services\Sms\SmsCampaignSender;
|
||||
use App\Services\Sms\SmsMessageLength;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CalendarReminderSender
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RecipientResolver $recipientResolver,
|
||||
private readonly SmsCampaignSender $campaignSender,
|
||||
private readonly SmsMessageLength $smsMessageLength,
|
||||
) {}
|
||||
|
||||
public function sendDue(?Carbon $now = null, int $limit = 50): int
|
||||
{
|
||||
$now ??= Carbon::now();
|
||||
$dueAt = $now->copy()->utc()->format('Y-m-d H:i:s');
|
||||
$sent = 0;
|
||||
|
||||
CalendarReminder::query()
|
||||
->with('event')
|
||||
->where('status', 'pending')
|
||||
->whereNotNull('remind_at')
|
||||
->where('remind_at', '<=', $dueAt)
|
||||
->orderBy('remind_at')
|
||||
->limit($limit)
|
||||
->get()
|
||||
->each(function (CalendarReminder $reminder) use (&$sent, $now): void {
|
||||
if ($this->sendReminder($reminder, $now)) {
|
||||
$sent++;
|
||||
}
|
||||
});
|
||||
|
||||
return $sent;
|
||||
}
|
||||
|
||||
private function sendReminder(CalendarReminder $reminder, Carbon $now): bool
|
||||
{
|
||||
$reminder = DB::transaction(function () use ($reminder): ?CalendarReminder {
|
||||
$fresh = CalendarReminder::query()
|
||||
->whereKey($reminder->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $fresh || $fresh->status !== 'pending') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fresh->update(['status' => 'sending']);
|
||||
|
||||
return $fresh->load('event');
|
||||
});
|
||||
|
||||
if (! $reminder || ! $reminder->event || $reminder->event->deleted_at !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rawStartsAt = $reminder->event->getRawOriginal('starts_at');
|
||||
$rawRemindAt = $reminder->getRawOriginal('remind_at');
|
||||
|
||||
if ($rawStartsAt !== null && $rawRemindAt !== null) {
|
||||
$startsAt = Carbon::parse((string) $rawStartsAt, 'UTC');
|
||||
$remindAt = Carbon::parse((string) $rawRemindAt, 'UTC');
|
||||
|
||||
if ($remindAt->lessThan($startsAt) && $startsAt->lessThanOrEqualTo($now)) {
|
||||
$reminder->update([
|
||||
'status' => 'skipped',
|
||||
'last_error' => 'Rappel expire : evenement deja commence.',
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$resolution = $this->recipientResolver->resolve(
|
||||
$this->contactIdsForReminder($reminder),
|
||||
$this->configuredIds('relais_sms.caldav.default_group_ids'),
|
||||
);
|
||||
|
||||
if ($resolution->recipients === []) {
|
||||
$reminder->update([
|
||||
'status' => 'skipped',
|
||||
'last_error' => 'Aucun destinataire SMS valide pour ce rappel.',
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$maxRecipients = (int) config('relais_sms.default_settings.max_sms_per_campaign', 100);
|
||||
|
||||
if (count($resolution->recipients) > $maxRecipients) {
|
||||
$reminder->update([
|
||||
'status' => 'failed',
|
||||
'last_error' => 'La selection depasse la limite de '.$maxRecipients.' SMS.',
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$user = $this->user();
|
||||
|
||||
if ($user === null) {
|
||||
$reminder->update([
|
||||
'status' => 'failed',
|
||||
'last_error' => 'Aucun utilisateur applicatif disponible.',
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$campaign = $this->campaignSender->send($user, $this->message($reminder), $resolution->recipients);
|
||||
|
||||
$reminder->update([
|
||||
'sms_campaign_id' => $campaign->id,
|
||||
'status' => in_array($campaign->status, ['failed', 'uncertain'], true) ? $campaign->status : 'sent',
|
||||
'last_error' => $campaign->error_message,
|
||||
'sent_at' => in_array($campaign->status, ['failed', 'uncertain'], true) ? null : Carbon::now(),
|
||||
]);
|
||||
|
||||
return in_array($campaign->status, ['sent', 'partial'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function contactIdsForReminder(CalendarReminder $reminder): array
|
||||
{
|
||||
$ids = $this->configuredIds('relais_sms.caldav.default_contact_ids');
|
||||
$attendeeEmails = collect($reminder->event->attendees ?? [])
|
||||
->pluck('email')
|
||||
->filter()
|
||||
->map(fn (string $email): string => strtolower($email))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if ($attendeeEmails !== []) {
|
||||
$ids = array_merge($ids, Contact::query()
|
||||
->whereIn(DB::raw('lower(email)'), $attendeeEmails)
|
||||
->pluck('id')
|
||||
->all());
|
||||
}
|
||||
|
||||
return array_values(array_unique(array_map('intval', $ids)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function configuredIds(string $key): array
|
||||
{
|
||||
return collect(config($key, []))
|
||||
->map(fn (mixed $id): int => (int) $id)
|
||||
->filter(fn (int $id): bool => $id > 0)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
private function user(): ?User
|
||||
{
|
||||
$userId = (int) config('relais_sms.caldav.reminder_user_id');
|
||||
|
||||
if ($userId > 0) {
|
||||
return User::query()->find($userId);
|
||||
}
|
||||
|
||||
return User::query()->orderBy('id')->first();
|
||||
}
|
||||
|
||||
private function message(CalendarReminder $reminder): string
|
||||
{
|
||||
$event = $reminder->event;
|
||||
$rawStartsAt = $event->getRawOriginal('starts_at');
|
||||
$startsAt = $rawStartsAt === null
|
||||
? 'date inconnue'
|
||||
: Carbon::parse((string) $rawStartsAt, 'UTC')
|
||||
->timezone((string) config('relais_sms.caldav.display_timezone'))
|
||||
->format('d/m/Y H:i');
|
||||
$titlePrefix = 'Rappel : ';
|
||||
$title = trim((string) ($event->summary ?: 'Evenement'));
|
||||
$title = $this->smsMessageLength->truncateBetween(
|
||||
$titlePrefix,
|
||||
$title,
|
||||
"\n".$startsAt,
|
||||
);
|
||||
$coreLines = [$titlePrefix.$title, $startsAt];
|
||||
$header = '';
|
||||
$footer = '';
|
||||
|
||||
$configuredHeader = trim($this->configuredText('relais_sms.caldav.reminder_message_header'));
|
||||
if ($configuredHeader !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $configuredHeader))) {
|
||||
$header = $configuredHeader;
|
||||
}
|
||||
|
||||
$configuredFooter = trim($this->configuredText('relais_sms.caldav.reminder_message_footer'));
|
||||
if ($configuredFooter !== '' && $this->smsMessageLength->fitsInOneSms($this->assembleMessage($coreLines, $header, $configuredFooter))) {
|
||||
$footer = $configuredFooter;
|
||||
}
|
||||
|
||||
$location = trim(preg_replace('/\s+/', ' ', (string) $event->location) ?? '');
|
||||
if ($location !== '' && $this->fitsWithOptionalParts($coreLines, [$location], $header, $footer)) {
|
||||
$coreLines[] = $location;
|
||||
}
|
||||
|
||||
$description = $this->description((string) $event->description);
|
||||
if ($description !== '') {
|
||||
$prefix = collect([$header, ...$coreLines])
|
||||
->filter(fn (string $part): bool => $part !== '')
|
||||
->implode("\n")."\n";
|
||||
$suffix = $footer === '' ? '' : "\n".$footer;
|
||||
$description = $this->smsMessageLength->truncateBetween($prefix, $description, $suffix);
|
||||
|
||||
if ($description !== '') {
|
||||
$coreLines[] = $description;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->assembleMessage($coreLines, $header, $footer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $coreLines
|
||||
* @param array<int, string> $optionalLines
|
||||
*/
|
||||
private function fitsWithOptionalParts(array $coreLines, array $optionalLines, string $header, string $footer): bool
|
||||
{
|
||||
return $this->smsMessageLength->fitsInOneSms($this->assembleMessage([...$coreLines, ...$optionalLines], $header, $footer));
|
||||
}
|
||||
|
||||
/** @param array<int, string> $coreLines */
|
||||
private function assembleMessage(array $coreLines, string $header = '', string $footer = ''): string
|
||||
{
|
||||
return collect([
|
||||
$header,
|
||||
...$coreLines,
|
||||
$footer,
|
||||
])->map(fn (string $part): string => trim($part))
|
||||
->filter()
|
||||
->implode("\n");
|
||||
}
|
||||
|
||||
private function description(string $description): string
|
||||
{
|
||||
$description = trim(preg_replace('/\s+/', ' ', $description) ?? '');
|
||||
|
||||
if ($description === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$maxLength = max(1, (int) config('relais_sms.caldav.reminder_description_max_length', 120));
|
||||
|
||||
return Str::limit($description, $maxLength, '[...]');
|
||||
}
|
||||
|
||||
private function configuredText(string $key): string
|
||||
{
|
||||
return str_replace('\n', "\n", (string) config($key, ''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
class CalendarRemoteEvent
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $href,
|
||||
public readonly ?string $etag,
|
||||
public readonly string $ical,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class ICalendarParser
|
||||
{
|
||||
/**
|
||||
* @return array<int, ParsedCalendarEvent>
|
||||
*/
|
||||
public function parse(string $ical, ?CarbonInterface $from = null, ?CarbonInterface $to = null): array
|
||||
{
|
||||
$ical = (new CalendarOccurrenceExpander)->expand(
|
||||
$ical,
|
||||
$from ?? Carbon::now()->subDay(),
|
||||
$to ?? Carbon::now()->addDays((int) config('relais_sms.caldav.lookahead_days', 90)),
|
||||
);
|
||||
$lines = $this->unfoldLines($ical);
|
||||
$events = [];
|
||||
$eventLines = null;
|
||||
$alarmLines = null;
|
||||
$alarms = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$upper = strtoupper($line);
|
||||
|
||||
if ($upper === 'BEGIN:VEVENT') {
|
||||
$eventLines = [];
|
||||
$alarms = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($upper === 'END:VEVENT') {
|
||||
if ($eventLines !== null) {
|
||||
$event = $this->parseEvent($eventLines, $alarms);
|
||||
if (! $event->cancelled) {
|
||||
$events[] = $event;
|
||||
}
|
||||
}
|
||||
|
||||
$eventLines = null;
|
||||
$alarmLines = null;
|
||||
$alarms = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($eventLines === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($upper === 'BEGIN:VALARM') {
|
||||
$alarmLines = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($upper === 'END:VALARM') {
|
||||
if ($alarmLines !== null) {
|
||||
$alarms[] = $this->parseAlarm($alarmLines);
|
||||
}
|
||||
|
||||
$alarmLines = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($alarmLines !== null) {
|
||||
$alarmLines[] = $line;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$eventLines[] = $line;
|
||||
}
|
||||
|
||||
return array_values(array_filter($events, fn (ParsedCalendarEvent $event): bool => $event->uid !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $lines
|
||||
* @param array<int, ParsedCalendarAlarm> $alarms
|
||||
*/
|
||||
private function parseEvent(array $lines, array $alarms): ParsedCalendarEvent
|
||||
{
|
||||
$uid = '';
|
||||
$summary = null;
|
||||
$description = null;
|
||||
$location = null;
|
||||
$startsAt = null;
|
||||
$endsAt = null;
|
||||
$attendees = [];
|
||||
$recurrenceId = null;
|
||||
$cancelled = false;
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$property = $this->parseProperty($line);
|
||||
$name = strtoupper($property['name']);
|
||||
|
||||
match ($name) {
|
||||
'UID' => $uid = $this->decodeText($property['value']),
|
||||
'SUMMARY' => $summary = $this->decodeText($property['value']),
|
||||
'DESCRIPTION' => $description = $this->decodeText($property['value']),
|
||||
'LOCATION' => $location = $this->decodeText($property['value']),
|
||||
'DTSTART' => $startsAt = $this->parseDateTime($property['value'], $property['params']),
|
||||
'DTEND' => $endsAt = $this->parseDateTime($property['value'], $property['params']),
|
||||
'RECURRENCE-ID' => $recurrenceId = $this->parseDateTime($property['value'], $property['params']),
|
||||
'STATUS' => $cancelled = strtoupper($property['value']) === 'CANCELLED',
|
||||
'ATTENDEE', 'ORGANIZER' => $attendees[] = $this->parseAttendee($property['value'], $property['params']),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
return new ParsedCalendarEvent(
|
||||
uid: $uid,
|
||||
summary: $summary,
|
||||
description: $description,
|
||||
location: $location,
|
||||
startsAt: $startsAt,
|
||||
endsAt: $endsAt,
|
||||
attendees: array_values(array_filter(
|
||||
$attendees,
|
||||
fn (array $attendee): bool => $attendee['email'] !== '',
|
||||
)),
|
||||
alarms: $alarms,
|
||||
recurrenceId: $recurrenceId,
|
||||
cancelled: $cancelled,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $lines
|
||||
*/
|
||||
private function parseAlarm(array $lines): ParsedCalendarAlarm
|
||||
{
|
||||
$action = '';
|
||||
$trigger = '';
|
||||
$triggerMinutes = null;
|
||||
$absoluteRemindAt = null;
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$property = $this->parseProperty($line);
|
||||
$name = strtoupper($property['name']);
|
||||
|
||||
if ($name === 'ACTION') {
|
||||
$action = strtoupper($property['value']);
|
||||
}
|
||||
|
||||
if ($name === 'TRIGGER') {
|
||||
$trigger = $property['value'];
|
||||
|
||||
if (strtoupper((string) ($property['params']['VALUE'] ?? '')) === 'DATE-TIME') {
|
||||
$absoluteRemindAt = $this->parseDateTime($property['value'], $property['params']);
|
||||
} else {
|
||||
$triggerMinutes = $this->parseDurationMinutes($property['value']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ParsedCalendarAlarm(
|
||||
action: $action,
|
||||
trigger: $trigger,
|
||||
triggerMinutes: $triggerMinutes,
|
||||
absoluteRemindAt: $absoluteRemindAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{name: string, params: array<string, string>, value: string}
|
||||
*/
|
||||
private function parseProperty(string $line): array
|
||||
{
|
||||
[$left, $value] = $this->splitPropertyValue($line);
|
||||
$parts = $this->splitOutsideQuotes($left, ';');
|
||||
$name = array_shift($parts) ?: '';
|
||||
$params = [];
|
||||
|
||||
foreach ($parts as $part) {
|
||||
[$key, $paramValue] = array_pad(explode('=', $part, 2), 2, '');
|
||||
|
||||
if ($key !== '') {
|
||||
$params[strtoupper($key)] = trim($paramValue, '"');
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'name' => $name,
|
||||
'params' => $params,
|
||||
'value' => $value,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A CalDAV parameter can contain a URI, for example
|
||||
* MEMBER="mailto:circle+id@example.test". The colon in that quoted URI is
|
||||
* not the separator between the property metadata and its value.
|
||||
*
|
||||
* @return array{string, string}
|
||||
*/
|
||||
private function splitPropertyValue(string $line): array
|
||||
{
|
||||
$quoted = false;
|
||||
|
||||
for ($index = 0, $length = strlen($line); $index < $length; $index++) {
|
||||
if ($line[$index] === '"') {
|
||||
$quoted = ! $quoted;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line[$index] === ':' && ! $quoted) {
|
||||
return [substr($line, 0, $index), substr($line, $index + 1)];
|
||||
}
|
||||
}
|
||||
|
||||
return [$line, ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function splitOutsideQuotes(string $value, string $delimiter): array
|
||||
{
|
||||
$parts = [];
|
||||
$part = '';
|
||||
$quoted = false;
|
||||
|
||||
for ($index = 0, $length = strlen($value); $index < $length; $index++) {
|
||||
$character = $value[$index];
|
||||
|
||||
if ($character === '"') {
|
||||
$quoted = ! $quoted;
|
||||
}
|
||||
|
||||
if ($character === $delimiter && ! $quoted) {
|
||||
$parts[] = $part;
|
||||
$part = '';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$part .= $character;
|
||||
}
|
||||
|
||||
$parts[] = $part;
|
||||
|
||||
return $parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $params
|
||||
* @return array{email: string, name: ?string}
|
||||
*/
|
||||
private function parseAttendee(string $value, array $params): array
|
||||
{
|
||||
$email = preg_replace('/^mailto:/i', '', trim($value)) ?? '';
|
||||
|
||||
return [
|
||||
'email' => strtolower($email),
|
||||
'name' => isset($params['CN']) ? $this->decodeText($params['CN']) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
private function parseDateTime(string $value, array $params): ?Carbon
|
||||
{
|
||||
$value = trim($value);
|
||||
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$timezone = $params['TZID'] ?? config('app.timezone', 'UTC');
|
||||
|
||||
if (str_ends_with($value, 'Z')) {
|
||||
return Carbon::createFromFormat('Ymd\THis\Z', $value, 'UTC')?->utc();
|
||||
}
|
||||
|
||||
if (str_contains($value, 'T')) {
|
||||
return Carbon::createFromFormat('Ymd\THis', $value, $timezone)?->utc();
|
||||
}
|
||||
|
||||
return Carbon::createFromFormat('Ymd', $value, $timezone)?->startOfDay()->utc();
|
||||
}
|
||||
|
||||
private function parseDurationMinutes(string $value): ?int
|
||||
{
|
||||
$value = strtoupper(trim($value));
|
||||
|
||||
if (! preg_match('/^([+-])?P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/', $value, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$sign = ($matches[1] ?? '') === '-' ? -1 : 1;
|
||||
$days = (int) ($matches[2] ?? 0);
|
||||
$hours = (int) ($matches[3] ?? 0);
|
||||
$minutes = (int) ($matches[4] ?? 0);
|
||||
$seconds = (int) ($matches[5] ?? 0);
|
||||
|
||||
return $sign * (($days * 24 * 60) + ($hours * 60) + $minutes + (int) ceil($seconds / 60));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function unfoldLines(string $ical): array
|
||||
{
|
||||
$rawLines = preg_split('/\r\n|\n|\r/', $ical) ?: [];
|
||||
$lines = [];
|
||||
|
||||
foreach ($rawLines as $line) {
|
||||
if ($line === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((str_starts_with($line, ' ') || str_starts_with($line, "\t")) && $lines !== []) {
|
||||
$lines[array_key_last($lines)] .= substr($line, 1);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$lines[] = $line;
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
private function decodeText(string $value): string
|
||||
{
|
||||
return str_replace(
|
||||
['\\n', '\\N', '\\,', '\\;', '\\\\'],
|
||||
["\n", "\n", ',', ';', '\\'],
|
||||
$value,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class ParsedCalendarAlarm
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $action,
|
||||
public readonly string $trigger,
|
||||
public readonly ?int $triggerMinutes,
|
||||
public readonly ?Carbon $absoluteRemindAt,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Calendar;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class ParsedCalendarEvent
|
||||
{
|
||||
/**
|
||||
* @param array<int, array{email: string, name: ?string}> $attendees
|
||||
* @param array<int, ParsedCalendarAlarm> $alarms
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $uid,
|
||||
public readonly ?string $summary,
|
||||
public readonly ?string $description,
|
||||
public readonly ?string $location,
|
||||
public readonly ?Carbon $startsAt,
|
||||
public readonly ?Carbon $endsAt,
|
||||
public readonly array $attendees,
|
||||
public readonly array $alarms,
|
||||
public readonly ?Carbon $recurrenceId = null,
|
||||
public readonly bool $cancelled = false,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
use App\Contracts\CardDav\CardDavClientInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use RuntimeException;
|
||||
use SimpleXMLElement;
|
||||
use Throwable;
|
||||
|
||||
class CardDavClient implements CardDavClientInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientInterface $http,
|
||||
) {}
|
||||
|
||||
public function fetchCards(): array
|
||||
{
|
||||
try {
|
||||
$cards = $this->fetchCardsWithReport();
|
||||
|
||||
if ($cards !== []) {
|
||||
return $cards;
|
||||
}
|
||||
} catch (GuzzleException|RuntimeException) {
|
||||
// Some CardDAV servers restrict addressbook-query. Fall back to PROPFIND + GET.
|
||||
}
|
||||
|
||||
return $this->fetchCardsWithPropfind();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CardDavRemoteCard>
|
||||
*/
|
||||
private function fetchCardsWithReport(): array
|
||||
{
|
||||
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
|
||||
$username = (string) config('relais_sms.carddav.username');
|
||||
$password = (string) config('relais_sms.carddav.password');
|
||||
|
||||
$this->ensureConfigured($url, $username, $password);
|
||||
|
||||
$response = $this->http->request('REPORT', $url, [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/xml; charset=utf-8',
|
||||
'Depth' => '1',
|
||||
],
|
||||
'body' => <<<'XML'
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<c:addressbook-query xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
|
||||
<d:prop>
|
||||
<d:getetag />
|
||||
<c:address-data />
|
||||
</d:prop>
|
||||
</c:addressbook-query>
|
||||
XML,
|
||||
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||
]);
|
||||
|
||||
return $this->parseReport((string) $response->getBody());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CardDavRemoteCard>
|
||||
*/
|
||||
private function fetchCardsWithPropfind(): array
|
||||
{
|
||||
$url = rtrim((string) config('relais_sms.carddav.url'), '/').'/';
|
||||
$username = (string) config('relais_sms.carddav.username');
|
||||
$password = (string) config('relais_sms.carddav.password');
|
||||
|
||||
$this->ensureConfigured($url, $username, $password);
|
||||
|
||||
$response = $this->http->request('PROPFIND', $url, [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/xml; charset=utf-8',
|
||||
'Depth' => '1',
|
||||
],
|
||||
'body' => <<<'XML'
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<d:propfind xmlns:d="DAV:">
|
||||
<d:prop>
|
||||
<d:getetag />
|
||||
</d:prop>
|
||||
</d:propfind>
|
||||
XML,
|
||||
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||
]);
|
||||
|
||||
$entries = $this->parsePropfind((string) $response->getBody(), $url);
|
||||
$cards = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$cardResponse = $this->http->request('GET', $entry['url'], [
|
||||
'auth' => [$username, $password],
|
||||
'headers' => [
|
||||
'Accept' => 'text/vcard,text/x-vcard,text/plain,*/*',
|
||||
],
|
||||
'timeout' => (float) config('relais_sms.carddav.timeout'),
|
||||
]);
|
||||
|
||||
$cards[] = new CardDavRemoteCard(
|
||||
href: $entry['href'],
|
||||
etag: $entry['etag'],
|
||||
vcard: (string) $cardResponse->getBody(),
|
||||
);
|
||||
}
|
||||
|
||||
return $cards;
|
||||
}
|
||||
|
||||
private function ensureConfigured(string $url, string $username, string $password): void
|
||||
{
|
||||
if ($url === '/' || $username === '' || $password === '') {
|
||||
throw new RuntimeException('Configuration CardDAV incomplete.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CardDavRemoteCard>
|
||||
*/
|
||||
private function parseReport(string $xml): array
|
||||
{
|
||||
try {
|
||||
$document = new SimpleXMLElement($xml);
|
||||
} catch (Throwable $exception) {
|
||||
throw new RuntimeException('Reponse CardDAV REPORT illisible.', previous: $exception);
|
||||
}
|
||||
|
||||
$document->registerXPathNamespace('d', 'DAV:');
|
||||
$responses = $document->xpath('//d:response') ?: [];
|
||||
$cards = [];
|
||||
|
||||
foreach ($responses as $response) {
|
||||
$response->registerXPathNamespace('d', 'DAV:');
|
||||
$response->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:carddav');
|
||||
|
||||
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||
$cardNodes = $response->xpath('.//c:address-data') ?: [];
|
||||
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||
$vcard = (string) ($cardNodes[0] ?? '');
|
||||
|
||||
if ($href === '' || trim($vcard) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||
$cards[] = new CardDavRemoteCard(
|
||||
href: $href,
|
||||
etag: trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||
vcard: $vcard,
|
||||
);
|
||||
}
|
||||
|
||||
return $cards;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{href: string, etag: ?string, url: string}>
|
||||
*/
|
||||
private function parsePropfind(string $xml, string $baseUrl): array
|
||||
{
|
||||
try {
|
||||
$document = new SimpleXMLElement($xml);
|
||||
} catch (Throwable $exception) {
|
||||
throw new RuntimeException('Reponse CardDAV PROPFIND illisible.', previous: $exception);
|
||||
}
|
||||
|
||||
$document->registerXPathNamespace('d', 'DAV:');
|
||||
$responses = $document->xpath('//d:response') ?: [];
|
||||
$entries = [];
|
||||
|
||||
foreach ($responses as $response) {
|
||||
$response->registerXPathNamespace('d', 'DAV:');
|
||||
$hrefNodes = $response->xpath('./d:href') ?: [];
|
||||
$href = trim((string) ($hrefNodes[0] ?? ''));
|
||||
|
||||
if ($href === '' || ! str_ends_with(strtolower(parse_url($href, PHP_URL_PATH) ?: $href), '.vcf')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$etagNodes = $response->xpath('.//d:getetag') ?: [];
|
||||
$entries[] = [
|
||||
'href' => $href,
|
||||
'etag' => trim((string) ($etagNodes[0] ?? ''), '"') ?: null,
|
||||
'url' => $this->absoluteUrl($baseUrl, $href),
|
||||
];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
private function absoluteUrl(string $baseUrl, string $href): string
|
||||
{
|
||||
if (parse_url($href, PHP_URL_SCHEME)) {
|
||||
return $href;
|
||||
}
|
||||
|
||||
$base = parse_url($baseUrl);
|
||||
|
||||
if (! isset($base['scheme'], $base['host'])) {
|
||||
throw new RuntimeException('URL CardDAV invalide.');
|
||||
}
|
||||
|
||||
$port = isset($base['port']) ? ':'.$base['port'] : '';
|
||||
$path = str_starts_with($href, '/') ? $href : rtrim((string) ($base['path'] ?? ''), '/').'/'.$href;
|
||||
|
||||
return $base['scheme'].'://'.$base['host'].$port.$path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
use App\Contracts\CardDav\CardDavClientInterface;
|
||||
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||
use App\Models\Contact;
|
||||
use App\Models\ContactGroup;
|
||||
use App\Models\SourceSyncRun;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class CardDavContactSyncService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CardDavClientInterface $client,
|
||||
private readonly VCardParser $parser,
|
||||
private readonly PhoneNumberNormalizerInterface $phoneNumberNormalizer,
|
||||
) {}
|
||||
|
||||
public function sync(): SourceSyncRun
|
||||
{
|
||||
$run = SourceSyncRun::query()->create([
|
||||
'source' => 'carddav',
|
||||
'status' => 'running',
|
||||
'started_at' => Carbon::now(),
|
||||
]);
|
||||
|
||||
try {
|
||||
$cards = $this->client->fetchCards();
|
||||
|
||||
DB::transaction(function () use ($run, $cards): void {
|
||||
$seenContactExternalIds = [];
|
||||
$seenGroupExternalIds = [];
|
||||
$syncedContacts = 0;
|
||||
|
||||
foreach ($cards as $card) {
|
||||
$parsedCard = $this->parser->parse($card->vcard);
|
||||
$externalId = $this->externalId($parsedCard, $card);
|
||||
$seenContactExternalIds[] = $externalId;
|
||||
|
||||
$contact = $this->upsertContact($externalId, $card, $parsedCard);
|
||||
$this->replacePhoneNumbers($contact, $parsedCard);
|
||||
|
||||
$groupIds = [];
|
||||
|
||||
foreach ($parsedCard->categories as $category) {
|
||||
$group = $this->upsertGroup($category);
|
||||
$groupIds[] = $group->id;
|
||||
$seenGroupExternalIds[] = (string) $group->external_id;
|
||||
}
|
||||
|
||||
$this->syncCardDavGroupMemberships($contact, $groupIds);
|
||||
$syncedContacts++;
|
||||
}
|
||||
|
||||
$deletedContacts = $this->deleteMissingContacts($seenContactExternalIds);
|
||||
$this->deleteMissingGroups(array_values(array_unique($seenGroupExternalIds)));
|
||||
|
||||
$run->update([
|
||||
'status' => 'success',
|
||||
'finished_at' => Carbon::now(),
|
||||
'fetched_contacts' => count($cards),
|
||||
'synced_contacts' => $syncedContacts,
|
||||
'deleted_contacts' => $deletedContacts,
|
||||
'message' => $syncedContacts.' contact(s) CardDAV synchronise(s).',
|
||||
]);
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
$run->update([
|
||||
'status' => 'failed',
|
||||
'finished_at' => Carbon::now(),
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return $run->refresh();
|
||||
}
|
||||
|
||||
private function upsertContact(string $externalId, CardDavRemoteCard $card, ParsedVCard $parsedCard): Contact
|
||||
{
|
||||
$contact = Contact::withTrashed()
|
||||
->where('source', 'carddav')
|
||||
->where('external_id', $externalId)
|
||||
->first();
|
||||
|
||||
$attributes = [
|
||||
'source' => 'carddav',
|
||||
'external_id' => $externalId,
|
||||
'remote_url' => $card->href,
|
||||
'remote_etag' => $card->etag,
|
||||
'first_name' => $parsedCard->firstName,
|
||||
'last_name' => $this->lastName($parsedCard),
|
||||
'organization' => $parsedCard->organization,
|
||||
'email' => $parsedCard->email,
|
||||
'synced_at' => Carbon::now(),
|
||||
];
|
||||
|
||||
if (! $contact) {
|
||||
return Contact::query()->create($attributes);
|
||||
}
|
||||
|
||||
$contact->fill($attributes);
|
||||
$contact->deleted_at = null;
|
||||
$contact->save();
|
||||
|
||||
return $contact;
|
||||
}
|
||||
|
||||
private function replacePhoneNumbers(Contact $contact, ParsedVCard $parsedCard): void
|
||||
{
|
||||
$contact->phoneNumbers()->delete();
|
||||
$defaultCountry = (string) config('relais_sms.default_settings.default_country');
|
||||
|
||||
foreach ($parsedCard->phoneNumbers as $index => $phoneNumber) {
|
||||
$result = $this->phoneNumberNormalizer->normalize($phoneNumber->rawNumber, $defaultCountry);
|
||||
|
||||
$contact->phoneNumbers()->create([
|
||||
'label' => $phoneNumber->label,
|
||||
'raw_number' => $result->rawNumber,
|
||||
'normalized_number' => $result->normalizedNumber,
|
||||
'country' => $result->country,
|
||||
'is_valid' => $result->isValid,
|
||||
'is_mobile' => $result->isMobile,
|
||||
'is_primary' => $index === 0,
|
||||
'validation_error' => $result->error,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function upsertGroup(string $category): ContactGroup
|
||||
{
|
||||
$externalId = Str::slug($category);
|
||||
$slug = 'carddav-'.$externalId;
|
||||
$group = ContactGroup::withTrashed()
|
||||
->where('source', 'carddav')
|
||||
->where('external_id', $externalId)
|
||||
->first();
|
||||
|
||||
$attributes = [
|
||||
'source' => 'carddav',
|
||||
'external_id' => $externalId,
|
||||
'name' => $category,
|
||||
'slug' => $slug,
|
||||
'synced_at' => Carbon::now(),
|
||||
];
|
||||
|
||||
if (! $group) {
|
||||
return ContactGroup::query()->create($attributes);
|
||||
}
|
||||
|
||||
$group->fill($attributes);
|
||||
$group->deleted_at = null;
|
||||
$group->save();
|
||||
|
||||
return $group;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $groupIds
|
||||
*/
|
||||
private function syncCardDavGroupMemberships(Contact $contact, array $groupIds): void
|
||||
{
|
||||
$currentCardDavGroupIds = $contact->groups()
|
||||
->where('contact_groups.source', 'carddav')
|
||||
->pluck('contact_groups.id')
|
||||
->all();
|
||||
|
||||
if ($currentCardDavGroupIds !== []) {
|
||||
$contact->groups()->detach($currentCardDavGroupIds);
|
||||
}
|
||||
|
||||
if ($groupIds !== []) {
|
||||
$contact->groups()->syncWithoutDetaching($groupIds);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $seenExternalIds
|
||||
*/
|
||||
private function deleteMissingContacts(array $seenExternalIds): int
|
||||
{
|
||||
$contacts = Contact::query()
|
||||
->where('source', 'carddav')
|
||||
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||
->get();
|
||||
|
||||
foreach ($contacts as $contact) {
|
||||
$cardDavGroupIds = $contact->groups()
|
||||
->where('contact_groups.source', 'carddav')
|
||||
->pluck('contact_groups.id')
|
||||
->all();
|
||||
|
||||
if ($cardDavGroupIds !== []) {
|
||||
$contact->groups()->detach($cardDavGroupIds);
|
||||
}
|
||||
|
||||
$contact->delete();
|
||||
}
|
||||
|
||||
return $contacts->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $seenExternalIds
|
||||
*/
|
||||
private function deleteMissingGroups(array $seenExternalIds): void
|
||||
{
|
||||
ContactGroup::query()
|
||||
->where('source', 'carddav')
|
||||
->whereNotIn('external_id', $seenExternalIds ?: [''])
|
||||
->delete();
|
||||
}
|
||||
|
||||
private function externalId(ParsedVCard $parsedCard, CardDavRemoteCard $card): string
|
||||
{
|
||||
return $parsedCard->uid ?: sha1($card->href);
|
||||
}
|
||||
|
||||
private function lastName(ParsedVCard $parsedCard): string
|
||||
{
|
||||
if ($parsedCard->lastName) {
|
||||
return $parsedCard->lastName;
|
||||
}
|
||||
|
||||
if ($parsedCard->fullName) {
|
||||
return $parsedCard->fullName;
|
||||
}
|
||||
|
||||
if ($parsedCard->organization) {
|
||||
return $parsedCard->organization;
|
||||
}
|
||||
|
||||
return 'Contact CardDAV';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
readonly class CardDavRemoteCard
|
||||
{
|
||||
public function __construct(
|
||||
public string $href,
|
||||
public ?string $etag,
|
||||
public string $vcard,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
readonly class ParsedVCard
|
||||
{
|
||||
/**
|
||||
* @param array<int, ParsedVCardPhoneNumber> $phoneNumbers
|
||||
* @param array<int, string> $categories
|
||||
*/
|
||||
public function __construct(
|
||||
public ?string $uid,
|
||||
public ?string $fullName,
|
||||
public ?string $firstName,
|
||||
public ?string $lastName,
|
||||
public ?string $organization,
|
||||
public ?string $email,
|
||||
public array $phoneNumbers,
|
||||
public array $categories,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
readonly class ParsedVCardPhoneNumber
|
||||
{
|
||||
public function __construct(
|
||||
public string $rawNumber,
|
||||
public ?string $label,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CardDav;
|
||||
|
||||
class VCardParser
|
||||
{
|
||||
public function parse(string $contents): ParsedVCard
|
||||
{
|
||||
$uid = null;
|
||||
$fullName = null;
|
||||
$firstName = null;
|
||||
$lastName = null;
|
||||
$organization = null;
|
||||
$email = null;
|
||||
$phoneNumbers = [];
|
||||
$categories = [];
|
||||
|
||||
foreach ($this->parseLines($contents) as $line) {
|
||||
[$name, $params, $value] = $line;
|
||||
|
||||
match ($name) {
|
||||
'UID' => $uid = $uid ?? $this->cleanValue($value),
|
||||
'FN' => $fullName = $fullName ?? $this->cleanValue($value),
|
||||
'N' => [$lastName, $firstName] = $this->parseStructuredName($value, $lastName, $firstName),
|
||||
'ORG' => $organization = $organization ?? $this->cleanValue($this->splitEscaped($value, ';')[0] ?? ''),
|
||||
'EMAIL' => $email = $email ?? $this->cleanValue($value),
|
||||
'TEL' => $phoneNumbers[] = new ParsedVCardPhoneNumber($this->cleanValue($value), $this->phoneLabel($params)),
|
||||
'CATEGORIES' => $categories = array_merge($categories, $this->parseCategories($value)),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
$categories = array_values(array_unique(array_filter($categories)));
|
||||
|
||||
return new ParsedVCard(
|
||||
uid: $uid,
|
||||
fullName: $fullName,
|
||||
firstName: $firstName,
|
||||
lastName: $lastName,
|
||||
organization: $organization,
|
||||
email: $email,
|
||||
phoneNumbers: array_values(array_filter(
|
||||
$phoneNumbers,
|
||||
fn (ParsedVCardPhoneNumber $phoneNumber): bool => $phoneNumber->rawNumber !== '',
|
||||
)),
|
||||
categories: $categories,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{0: string, 1: array<string, array<int, string>>, 2: string}>
|
||||
*/
|
||||
private function parseLines(string $contents): array
|
||||
{
|
||||
$contents = str_replace(["\r\n", "\r"], "\n", $contents);
|
||||
$contents = preg_replace("/\n[ \t]/", '', $contents) ?? $contents;
|
||||
$lines = [];
|
||||
|
||||
foreach (explode("\n", $contents) as $line) {
|
||||
$line = trim($line);
|
||||
|
||||
if ($line === '' || ! str_contains($line, ':')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$left, $value] = explode(':', $line, 2);
|
||||
$propertyParts = explode(';', $left);
|
||||
$name = strtoupper((string) array_shift($propertyParts));
|
||||
|
||||
if ($name === 'BEGIN' || $name === 'END' || $name === 'VERSION') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = [];
|
||||
|
||||
foreach ($propertyParts as $part) {
|
||||
if (str_contains($part, '=')) {
|
||||
[$paramName, $paramValue] = explode('=', $part, 2);
|
||||
$paramName = strtoupper($paramName);
|
||||
$params[$paramName] = array_merge(
|
||||
$params[$paramName] ?? [],
|
||||
array_map('strtoupper', $this->splitEscaped($paramValue, ',')),
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$params['TYPE'][] = strtoupper($part);
|
||||
}
|
||||
|
||||
$lines[] = [$name, $params, $value];
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?string}
|
||||
*/
|
||||
private function parseStructuredName(string $value, ?string $currentLastName, ?string $currentFirstName): array
|
||||
{
|
||||
$parts = $this->splitEscaped($value, ';');
|
||||
$lastName = $this->cleanValue($parts[0] ?? '') ?: $currentLastName;
|
||||
$firstName = $this->cleanValue($parts[1] ?? '') ?: $currentFirstName;
|
||||
|
||||
return [$lastName, $firstName];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function parseCategories(string $value): array
|
||||
{
|
||||
return array_map(
|
||||
fn (string $category): string => $this->cleanValue($category),
|
||||
$this->splitEscaped($value, ','),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array<int, string>> $params
|
||||
*/
|
||||
private function phoneLabel(array $params): ?string
|
||||
{
|
||||
$types = array_filter($params['TYPE'] ?? []);
|
||||
|
||||
if ($types === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return implode(', ', array_map(
|
||||
fn (string $type): string => ucfirst(strtolower($type)),
|
||||
array_unique($types),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function splitEscaped(string $value, string $separator): array
|
||||
{
|
||||
$parts = [];
|
||||
$buffer = '';
|
||||
$escaped = false;
|
||||
|
||||
foreach (str_split($value) as $char) {
|
||||
if ($escaped) {
|
||||
$buffer .= '\\'.$char;
|
||||
$escaped = false;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '\\') {
|
||||
$escaped = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === $separator) {
|
||||
$parts[] = $buffer;
|
||||
$buffer = '';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$buffer .= $char;
|
||||
}
|
||||
|
||||
if ($escaped) {
|
||||
$buffer .= '\\';
|
||||
}
|
||||
|
||||
$parts[] = $buffer;
|
||||
|
||||
return $parts;
|
||||
}
|
||||
|
||||
private function cleanValue(string $value): string
|
||||
{
|
||||
$value = str_replace(
|
||||
['\n', '\N', '\;', '\,', '\\\\'],
|
||||
["\n", "\n", ';', ',', '\\'],
|
||||
trim($value),
|
||||
);
|
||||
|
||||
return trim($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Phone;
|
||||
|
||||
use App\Contracts\PhoneNumberNormalizerInterface;
|
||||
use libphonenumber\NumberParseException;
|
||||
use libphonenumber\PhoneNumberFormat;
|
||||
use libphonenumber\PhoneNumberType;
|
||||
use libphonenumber\PhoneNumberUtil;
|
||||
|
||||
class LibPhoneNumberNormalizer implements PhoneNumberNormalizerInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PhoneNumberUtil $phoneNumberUtil,
|
||||
) {}
|
||||
|
||||
public function normalize(string $rawNumber, string $defaultCountry): PhoneNumberResult
|
||||
{
|
||||
$rawNumber = trim($rawNumber);
|
||||
$defaultCountry = strtoupper(trim($defaultCountry));
|
||||
|
||||
if ($rawNumber === '') {
|
||||
return new PhoneNumberResult($rawNumber, null, null, false, false, 'Numero vide.');
|
||||
}
|
||||
|
||||
try {
|
||||
$number = $this->phoneNumberUtil->parse($rawNumber, $defaultCountry);
|
||||
} catch (NumberParseException $exception) {
|
||||
return new PhoneNumberResult($rawNumber, null, null, false, false, $exception->getMessage());
|
||||
}
|
||||
|
||||
$isValid = $this->phoneNumberUtil->isValidNumber($number);
|
||||
$normalizedNumber = $isValid
|
||||
? $this->phoneNumberUtil->format($number, PhoneNumberFormat::E164)
|
||||
: null;
|
||||
$country = $this->phoneNumberUtil->getRegionCodeForNumber($number);
|
||||
$mobileRegex = (string) config('relais_sms.default_settings.mobile_phone_regex');
|
||||
$numberType = $this->phoneNumberUtil->getNumberType($number);
|
||||
$isMobile = $isValid && (
|
||||
in_array($numberType, [PhoneNumberType::MOBILE, PhoneNumberType::FIXED_LINE_OR_MOBILE], true)
|
||||
|| ($mobileRegex !== '' && (
|
||||
preg_match($mobileRegex, $rawNumber) === 1
|
||||
|| ($normalizedNumber !== null && preg_match($mobileRegex, $normalizedNumber) === 1)
|
||||
))
|
||||
);
|
||||
|
||||
return new PhoneNumberResult(
|
||||
rawNumber: $rawNumber,
|
||||
normalizedNumber: $normalizedNumber,
|
||||
country: $country,
|
||||
isValid: $isValid,
|
||||
isMobile: $isMobile,
|
||||
error: $isValid ? null : 'Numero invalide.',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Phone;
|
||||
|
||||
final readonly class PhoneNumberResult
|
||||
{
|
||||
public function __construct(
|
||||
public string $rawNumber,
|
||||
public ?string $normalizedNumber,
|
||||
public ?string $country,
|
||||
public bool $isValid,
|
||||
public bool $isMobile,
|
||||
public ?string $error = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Recipients;
|
||||
|
||||
final readonly class RecipientResolutionResult
|
||||
{
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @param array<int, array<string, mixed>> $excluded
|
||||
*/
|
||||
public function __construct(
|
||||
public array $recipients,
|
||||
public array $excluded,
|
||||
public int $selectedContactCount,
|
||||
public int $selectedGroupCount,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function summary(): array
|
||||
{
|
||||
return [
|
||||
'selected_contacts' => $this->selectedContactCount,
|
||||
'selected_groups' => $this->selectedGroupCount,
|
||||
'ready_numbers' => count($this->recipients),
|
||||
'excluded_total' => count($this->excluded),
|
||||
'opt_out' => $this->countExcludedReason('opt_out'),
|
||||
'missing_phone' => $this->countExcludedReason('missing_phone'),
|
||||
'invalid' => $this->countExcludedReason('invalid'),
|
||||
'non_mobile' => $this->countExcludedReason('non_mobile'),
|
||||
'duplicate' => $this->countExcludedReason('duplicate'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function excludedByReason(string $reason): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->excluded,
|
||||
fn (array $entry): bool => ($entry['reason'] ?? null) === $reason,
|
||||
));
|
||||
}
|
||||
|
||||
private function countExcludedReason(string $reason): int
|
||||
{
|
||||
return count($this->excludedByReason($reason));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Recipients;
|
||||
|
||||
use App\Models\Contact;
|
||||
use App\Models\ContactGroup;
|
||||
use App\Models\ContactPhoneNumber;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class RecipientResolver
|
||||
{
|
||||
/**
|
||||
* @param array<int, int|string> $contactIds
|
||||
* @param array<int, int|string> $groupIds
|
||||
*/
|
||||
public function resolve(array $contactIds, array $groupIds): RecipientResolutionResult
|
||||
{
|
||||
$directContactIds = $this->cleanIds($contactIds);
|
||||
$selectedGroupIds = $this->cleanIds($groupIds);
|
||||
|
||||
$groups = ContactGroup::query()
|
||||
->with(['contacts' => fn ($query) => $query->select('contacts.id')])
|
||||
->whereKey($selectedGroupIds)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
/** @var array<int, array<int, string>> $groupNamesByContactId */
|
||||
$groupNamesByContactId = [];
|
||||
|
||||
foreach ($groups as $group) {
|
||||
foreach ($group->contacts as $contact) {
|
||||
$groupNamesByContactId[$contact->id][] = $group->name;
|
||||
}
|
||||
}
|
||||
|
||||
$selectedContactIds = $directContactIds
|
||||
->merge($groups->flatMap(fn (ContactGroup $group): Collection => $group->contacts->pluck('id')))
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
$contacts = Contact::query()
|
||||
->with([
|
||||
'groups',
|
||||
'phoneNumbers' => fn ($query) => $query
|
||||
->orderByDesc('is_primary')
|
||||
->orderBy('id'),
|
||||
])
|
||||
->whereKey($selectedContactIds)
|
||||
->orderBy('last_name')
|
||||
->orderBy('first_name')
|
||||
->get();
|
||||
|
||||
$recipients = [];
|
||||
$excluded = [];
|
||||
$seenNumbers = [];
|
||||
|
||||
foreach ($contacts as $contact) {
|
||||
$selection = $this->selectionLabels($contact, $directContactIds, $groupNamesByContactId[$contact->id] ?? []);
|
||||
|
||||
if ($contact->sms_opt_out) {
|
||||
$excluded[] = $this->excludedEntry($contact, 'opt_out', null, $selection);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($contact->phoneNumbers->isEmpty()) {
|
||||
$excluded[] = $this->excludedEntry($contact, 'missing_phone', null, $selection);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($contact->phoneNumbers as $phoneNumber) {
|
||||
if (! $phoneNumber->is_valid || $phoneNumber->normalized_number === null) {
|
||||
$excluded[] = $this->excludedEntry($contact, 'invalid', $phoneNumber, $selection);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $phoneNumber->hasDetectedMobileNumber()) {
|
||||
$excluded[] = $this->excludedEntry($contact, 'non_mobile', $phoneNumber, $selection);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($seenNumbers[$phoneNumber->normalized_number])) {
|
||||
$excluded[] = $this->excludedEntry(
|
||||
$contact,
|
||||
'duplicate',
|
||||
$phoneNumber,
|
||||
$selection,
|
||||
['duplicate_of' => $seenNumbers[$phoneNumber->normalized_number]],
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry = [
|
||||
'contact_id' => $contact->id,
|
||||
'contact_name' => $contact->displayName(),
|
||||
'phone_number_id' => $phoneNumber->id,
|
||||
'number' => $phoneNumber->normalized_number,
|
||||
'raw_number' => $phoneNumber->raw_number,
|
||||
'label' => $phoneNumber->label,
|
||||
'selection' => $selection,
|
||||
];
|
||||
|
||||
$recipients[] = $entry;
|
||||
$seenNumbers[$phoneNumber->normalized_number] = $entry['contact_name'];
|
||||
}
|
||||
}
|
||||
|
||||
return new RecipientResolutionResult(
|
||||
recipients: $recipients,
|
||||
excluded: $excluded,
|
||||
selectedContactCount: $contacts->count(),
|
||||
selectedGroupCount: $groups->count(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int|string> $ids
|
||||
* @return Collection<int, int>
|
||||
*/
|
||||
private function cleanIds(array $ids): Collection
|
||||
{
|
||||
return collect($ids)
|
||||
->map(fn (int|string $id): int => (int) $id)
|
||||
->filter(fn (int $id): bool => $id > 0)
|
||||
->unique()
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, int> $directContactIds
|
||||
* @param array<int, string> $groupNames
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function selectionLabels(Contact $contact, Collection $directContactIds, array $groupNames): array
|
||||
{
|
||||
$selection = $groupNames;
|
||||
|
||||
if ($directContactIds->contains($contact->id)) {
|
||||
array_unshift($selection, 'Selection directe');
|
||||
}
|
||||
|
||||
return array_values(array_unique($selection));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $selection
|
||||
* @param array<string, mixed> $extra
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function excludedEntry(
|
||||
Contact $contact,
|
||||
string $reason,
|
||||
?ContactPhoneNumber $phoneNumber,
|
||||
array $selection,
|
||||
array $extra = [],
|
||||
): array {
|
||||
return array_merge([
|
||||
'contact_id' => $contact->id,
|
||||
'contact_name' => $contact->displayName(),
|
||||
'contact_source' => $contact->source,
|
||||
'phone_number_id' => $phoneNumber?->id,
|
||||
'reason' => $reason,
|
||||
'number' => $phoneNumber?->normalized_number,
|
||||
'raw_number' => $phoneNumber?->raw_number,
|
||||
'label' => $phoneNumber?->label,
|
||||
'selection' => $selection,
|
||||
], $extra);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
class OvhShortCodeMessage
|
||||
{
|
||||
public function prepare(string $message): string
|
||||
{
|
||||
// Keep visible labels of Markdown/HTML links, but never their target.
|
||||
$message = preg_replace('~\[([^\]\r\n]*)\]\(https?://[^\s)]+\)~iu', '$1', $message) ?? $message;
|
||||
$message = preg_replace('~<a\b[^>]*>(.*?)</a>~isu', '$1', $message) ?? $message;
|
||||
$message = preg_replace('~https?://[^\s<>"\']+|(?<![\pL\pN_@])www\.[^\s<>"\']+~iu', '', $message) ?? $message;
|
||||
// Also remove bare domain links, without eating email addresses or dates.
|
||||
$message = preg_replace('~(?<![\pL\pN_@.-])(?:[\pL\pN](?:[\pL\pN-]*[\pL\pN])?\.)+[\pL]{2,63}(?::\d+)?(?:[/\?#][^\s<>"\']*)?(?![\pL\pN_@-])~iu', '', $message) ?? $message;
|
||||
$message = preg_replace('/[ \t]+/u', ' ', $message) ?? $message;
|
||||
$message = preg_replace('/ *\R */u', "\n", $message) ?? $message;
|
||||
$message = preg_replace('/\n{3,}/', "\n\n", $message) ?? $message;
|
||||
|
||||
return trim($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Contracts\Sms\SmsProviderInterface;
|
||||
use App\Models\SmsCampaign;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
class OvhSmsProvider implements SmsProviderInterface
|
||||
{
|
||||
private ?int $serverTimestamp = null;
|
||||
|
||||
private int $timestampFetchedAt = 0;
|
||||
|
||||
public function __construct(private readonly ClientInterface $client) {}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
*/
|
||||
public function send(SmsCampaign $campaign, array $recipients): SmsSendResult
|
||||
{
|
||||
$payload = $this->payload($campaign, $recipients);
|
||||
$serviceName = $this->serviceName();
|
||||
$path = '/sms/'.rawurlencode($serviceName).'/jobs';
|
||||
// Keep the exact request even if the process loses OVH's response.
|
||||
if ($campaign->exists) {
|
||||
$campaign->update([
|
||||
'provider_service_name' => $serviceName,
|
||||
'request_payload' => $payload,
|
||||
'message' => $payload['message'],
|
||||
]);
|
||||
}
|
||||
$response = $this->request('POST', $path, $payload);
|
||||
|
||||
if (! isset($response['ids']) || ! is_array($response['ids'])
|
||||
|| count($response['ids']) + count($this->stringList($response['invalidReceivers'] ?? [])) < count($recipients)) {
|
||||
throw new SmsProviderException('Reponse OVH incomplete : envoi a verifier.', $response, outcomeUnknown: true);
|
||||
}
|
||||
|
||||
return new SmsSendResult(
|
||||
serviceName: $serviceName,
|
||||
providerJobId: $this->stringValue($response['id'] ?? $response['jobId'] ?? null),
|
||||
requestPayload: $payload,
|
||||
responsePayload: $response,
|
||||
providerMessageIds: $this->stringList($response['ids'] ?? []),
|
||||
failedNumbers: $this->stringList($response['invalidReceivers'] ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array<int, array<string, mixed>> */
|
||||
public function outgoing(SmsCampaign $campaign): array
|
||||
{
|
||||
if (! $campaign->provider_tag) {
|
||||
throw new SmsProviderException('Verification impossible sans reference de campagne OVH.');
|
||||
}
|
||||
|
||||
$path = '/sms/'.rawurlencode($campaign->provider_service_name ?: $this->serviceName()).'/outgoing';
|
||||
$ids = $this->request('GET', $path.'?'.http_build_query(['tag' => $campaign->provider_tag]));
|
||||
$messages = [];
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$messages[] = $this->request('GET', $path.'/'.rawurlencode((string) $id));
|
||||
}
|
||||
|
||||
return $messages;
|
||||
}
|
||||
|
||||
private function serviceName(): string
|
||||
{
|
||||
$configured = trim((string) config('relais_sms.ovh.sms_service_name', ''));
|
||||
|
||||
if ($configured !== '') {
|
||||
return $configured;
|
||||
}
|
||||
|
||||
$services = $this->request('GET', '/sms');
|
||||
$service = $services[0] ?? null;
|
||||
|
||||
if (! is_string($service) || $service === '') {
|
||||
throw new SmsProviderException('Aucun service SMS OVH disponible pour ces identifiants.', [
|
||||
'services' => $services,
|
||||
]);
|
||||
}
|
||||
|
||||
return $service;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payload(SmsCampaign $campaign, array $recipients): array
|
||||
{
|
||||
$shortCode = (bool) config('relais_sms.ovh.sms_short_code');
|
||||
$sender = trim((string) config('relais_sms.ovh.sms_sender', ''));
|
||||
|
||||
if ($shortCode && $sender !== '') {
|
||||
throw new SmsProviderException('OVH_SMS_SHORT_CODE=true est incompatible avec OVH_SMS_SENDER.');
|
||||
}
|
||||
|
||||
if (! $shortCode && $sender === '') {
|
||||
throw new SmsProviderException('Configurer OVH_SMS_SENDER pour utiliser OVH_SMS_SHORT_CODE=false.');
|
||||
}
|
||||
|
||||
$message = $shortCode ? (new OvhShortCodeMessage)->prepare($campaign->message) : $campaign->message;
|
||||
|
||||
if (trim($message) === '') {
|
||||
throw new SmsProviderException('Le SMS est vide apres retrait des liens interdits par OVH en numero court.');
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'message' => $message,
|
||||
'receivers' => array_values(array_map(
|
||||
fn (array $recipient): string => (string) $recipient['number'],
|
||||
$recipients,
|
||||
)),
|
||||
'noStopClause' => (bool) config('relais_sms.ovh.sms_no_stop_clause'),
|
||||
'tag' => $campaign->provider_tag,
|
||||
];
|
||||
|
||||
if ($sender !== '') {
|
||||
$payload['sender'] = $sender;
|
||||
} elseif ($shortCode) {
|
||||
$payload['senderForResponse'] = true;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $payload
|
||||
* @return array<string, mixed>|array<int, mixed>
|
||||
*/
|
||||
private function request(string $method, string $path, ?array $payload = null): array
|
||||
{
|
||||
$body = $payload === null ? '' : json_encode($payload, JSON_THROW_ON_ERROR);
|
||||
$url = $this->baseUrl().$path;
|
||||
$timestamp = $this->timestamp();
|
||||
|
||||
try {
|
||||
$response = $this->client->request($method, $url, [
|
||||
'headers' => [
|
||||
'Content-Type' => 'application/json',
|
||||
'X-Ovh-Application' => $this->requiredConfig('application_key'),
|
||||
'X-Ovh-Consumer' => $this->requiredConfig('consumer_key'),
|
||||
'X-Ovh-Signature' => $this->signature($method, $url, $body, $timestamp),
|
||||
'X-Ovh-Timestamp' => (string) $timestamp,
|
||||
],
|
||||
'body' => $body,
|
||||
'timeout' => $method === 'POST'
|
||||
? (float) config('relais_sms.ovh.send_timeout', 60)
|
||||
: (float) config('relais_sms.ovh.timeout', 20),
|
||||
'connect_timeout' => 10,
|
||||
'allow_redirects' => false,
|
||||
]);
|
||||
} catch (RequestException $exception) {
|
||||
$responsePayload = $this->decode((string) $exception->getResponse()?->getBody());
|
||||
$message = $responsePayload['message'] ?? $exception->getMessage();
|
||||
|
||||
throw new SmsProviderException((string) $message, $responsePayload,
|
||||
outcomeUnknown: $method === 'POST' && ($exception->getResponse() === null || $exception->getResponse()->getStatusCode() >= 500));
|
||||
} catch (GuzzleException $exception) {
|
||||
throw new SmsProviderException($exception->getMessage(), outcomeUnknown: $method === 'POST');
|
||||
}
|
||||
|
||||
return $this->decode((string) $response->getBody());
|
||||
}
|
||||
|
||||
private function timestamp(): int
|
||||
{
|
||||
if ($this->serverTimestamp !== null) {
|
||||
return $this->serverTimestamp + time() - $this->timestampFetchedAt;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->client->request('GET', $this->baseUrl().'/auth/time', [
|
||||
'timeout' => (float) config('relais_sms.ovh.timeout', 20),
|
||||
]);
|
||||
|
||||
$this->timestampFetchedAt = time();
|
||||
|
||||
return $this->serverTimestamp = (int) trim((string) $response->getBody());
|
||||
} catch (GuzzleException) {
|
||||
return time();
|
||||
}
|
||||
}
|
||||
|
||||
private function signature(string $method, string $url, string $body, int $timestamp): string
|
||||
{
|
||||
return '$1$'.sha1(implode('+', [
|
||||
$this->requiredConfig('application_secret'),
|
||||
$this->requiredConfig('consumer_key'),
|
||||
strtoupper($method),
|
||||
$url,
|
||||
$body,
|
||||
(string) $timestamp,
|
||||
]));
|
||||
}
|
||||
|
||||
private function baseUrl(): string
|
||||
{
|
||||
return match ((string) config('relais_sms.ovh.endpoint', 'ovh-eu')) {
|
||||
'ovh-ca' => 'https://ca.api.ovh.com/1.0',
|
||||
'ovh-eu' => 'https://eu.api.ovh.com/1.0',
|
||||
default => throw new SmsProviderException('Endpoint OVH non pris en charge : utiliser ovh-eu ou ovh-ca.'),
|
||||
};
|
||||
}
|
||||
|
||||
private function requiredConfig(string $key): string
|
||||
{
|
||||
$value = trim((string) config('relais_sms.ovh.'.$key, ''));
|
||||
|
||||
if ($value === '') {
|
||||
throw new SmsProviderException('Configuration OVH incomplete : '.$key.'.');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|array<int, mixed>
|
||||
*/
|
||||
private function decode(string $body): array
|
||||
{
|
||||
if (trim($body) === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$decoded = json_decode($body, true);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
private function stringValue(mixed $value): ?string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function stringList(mixed $values): array
|
||||
{
|
||||
if (! is_array($values)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_map('strval', $values));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Models\CalendarReminder;
|
||||
use App\Models\SmsCampaign;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class SmsCampaignReconciler
|
||||
{
|
||||
public function __construct(private readonly OvhSmsProvider $provider) {}
|
||||
|
||||
public function reconcile(SmsCampaign $campaign): SmsCampaign
|
||||
{
|
||||
try {
|
||||
$messages = $this->provider->outgoing($campaign);
|
||||
} catch (SmsProviderException $exception) {
|
||||
Log::warning('SMS campaign verification unavailable.', [
|
||||
'sms_campaign_id' => $campaign->id,
|
||||
'reason' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
return $campaign;
|
||||
}
|
||||
|
||||
return $this->applyOutgoing($campaign, $messages);
|
||||
}
|
||||
|
||||
/** @param array<int, array<string, mixed>> $messages */
|
||||
public function applyOutgoing(SmsCampaign $campaign, array $messages): SmsCampaign
|
||||
{
|
||||
return DB::transaction(function () use ($campaign, $messages): SmsCampaign {
|
||||
$campaign = SmsCampaign::query()->lockForUpdate()->findOrFail($campaign->id);
|
||||
|
||||
if (! in_array($campaign->status, ['uncertain', 'sending'], true)) {
|
||||
return $campaign;
|
||||
}
|
||||
|
||||
$byNumber = [];
|
||||
foreach ($messages as $message) {
|
||||
if (($message['tag'] ?? null) !== $campaign->provider_tag
|
||||
|| ($message['message'] ?? null) !== $campaign->message
|
||||
|| empty($message['id']) || empty($message['receiver'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$byNumber[(string) $message['receiver']] = $message;
|
||||
}
|
||||
|
||||
foreach ($campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->get() as $delivery) {
|
||||
$message = $byNumber[$delivery->number] ?? null;
|
||||
if ($message === null) {
|
||||
$delivery->update(['status' => 'uncertain']);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// "sent" records acceptance by OVH, not delivery to the handset.
|
||||
$delivery->update([
|
||||
'status' => 'sent',
|
||||
'provider_message_id' => (string) $message['id'],
|
||||
'provider_response' => $message,
|
||||
'error_message' => null,
|
||||
'sent_at' => $message['sentAt'] ?? $message['creationDatetime'] ?? now(),
|
||||
]);
|
||||
}
|
||||
|
||||
$sentCount = $campaign->deliveries()->where('status', 'sent')->count();
|
||||
$failedCount = $campaign->deliveries()->where('status', 'failed')->count();
|
||||
$unconfirmed = $campaign->deliveries()->whereIn('status', ['uncertain', 'queued'])->exists();
|
||||
$status = $unconfirmed ? 'uncertain' : ($failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent');
|
||||
$campaign->update([
|
||||
'status' => $status,
|
||||
'sent_count' => $sentCount,
|
||||
'failed_count' => $failedCount,
|
||||
'sent_at' => $campaign->deliveries()->where('status', 'sent')->min('sent_at'),
|
||||
'response_payload' => ['verification' => 'OVH outgoing history', 'confirmed_recipients' => $sentCount],
|
||||
'error_message' => $unconfirmed
|
||||
? 'Certains envois restent a verifier chez OVH. Aucun renvoi automatique ; ne pas renvoyer cette campagne.'
|
||||
: null,
|
||||
]);
|
||||
|
||||
CalendarReminder::query()->where('sms_campaign_id', $campaign->id)->where('status', 'uncertain')->update([
|
||||
'status' => $status === 'uncertain' ? 'uncertain' : ($sentCount > 0 ? 'sent' : 'failed'),
|
||||
'last_error' => $campaign->error_message,
|
||||
'sent_at' => $campaign->sent_at,
|
||||
]);
|
||||
|
||||
Log::info('SMS campaign verified against OVH history.', [
|
||||
'sms_campaign_id' => $campaign->id,
|
||||
'sent_count' => $sentCount,
|
||||
'status' => $status,
|
||||
]);
|
||||
|
||||
return $campaign->fresh(['deliveries', 'user']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Contracts\Sms\SmsProviderInterface;
|
||||
use App\Models\ContactGroup;
|
||||
use App\Models\SmsCampaign;
|
||||
use App\Models\SmsDelivery;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class SmsCampaignSender
|
||||
{
|
||||
public function __construct(private readonly SmsProviderInterface $provider) {}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @param array<int, int|string> $selectedContactIds
|
||||
* @param array<int, int|string> $selectedGroupIds
|
||||
*/
|
||||
public function send(
|
||||
User $user,
|
||||
string $message,
|
||||
array $recipients,
|
||||
array $selectedContactIds = [],
|
||||
array $selectedGroupIds = [],
|
||||
): SmsCampaign {
|
||||
$campaign = $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'sending');
|
||||
|
||||
return $this->sendExistingCampaign($campaign, $recipients);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @param array<int, int|string> $selectedContactIds
|
||||
* @param array<int, int|string> $selectedGroupIds
|
||||
*/
|
||||
public function schedule(
|
||||
User $user,
|
||||
string $message,
|
||||
array $recipients,
|
||||
array $selectedContactIds,
|
||||
array $selectedGroupIds,
|
||||
CarbonInterface $scheduledAt,
|
||||
): SmsCampaign {
|
||||
return $this->createCampaign($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, 'scheduled', $scheduledAt);
|
||||
}
|
||||
|
||||
public function sendScheduled(SmsCampaign $campaign): ?SmsCampaign
|
||||
{
|
||||
$campaign = DB::transaction(function () use ($campaign): ?SmsCampaign {
|
||||
$fresh = SmsCampaign::query()
|
||||
->whereKey($campaign->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $fresh || $fresh->status !== 'scheduled') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fresh->update(['status' => 'sending']);
|
||||
|
||||
Log::info('SMS campaign status changed from scheduled to sending.', [
|
||||
'sms_campaign_id' => $fresh->id,
|
||||
'scheduled_at' => $fresh->scheduled_at?->toIso8601String(),
|
||||
]);
|
||||
|
||||
return $fresh->fresh(['deliveries', 'user']);
|
||||
});
|
||||
|
||||
if ($campaign === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->sendExistingCampaign($campaign, $this->recipientsFromDeliveries($campaign));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @param array<int, int|string> $selectedContactIds
|
||||
* @param array<int, int|string> $selectedGroupIds
|
||||
*/
|
||||
private function createCampaign(
|
||||
User $user,
|
||||
string $message,
|
||||
array $recipients,
|
||||
array $selectedContactIds,
|
||||
array $selectedGroupIds,
|
||||
string $status,
|
||||
?CarbonInterface $scheduledAt = null,
|
||||
): SmsCampaign {
|
||||
$selectedContactIds = $this->cleanIds($selectedContactIds);
|
||||
$selectedGroupIds = $this->cleanIds($selectedGroupIds);
|
||||
$selectedGroupNames = ContactGroup::query()
|
||||
->whereKey($selectedGroupIds)
|
||||
->orderBy('name')
|
||||
->pluck('name')
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return $this->createResolvedCampaign(
|
||||
$user,
|
||||
$message,
|
||||
$recipients,
|
||||
$selectedContactIds,
|
||||
$selectedGroupIds,
|
||||
$selectedGroupNames,
|
||||
$status,
|
||||
$scheduledAt,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
* @param array<int, int> $selectedContactIds
|
||||
* @param array<int, int> $selectedGroupIds
|
||||
* @param array<int, string> $selectedGroupNames
|
||||
*/
|
||||
private function createResolvedCampaign(
|
||||
User $user,
|
||||
string $message,
|
||||
array $recipients,
|
||||
array $selectedContactIds,
|
||||
array $selectedGroupIds,
|
||||
array $selectedGroupNames,
|
||||
string $status,
|
||||
?CarbonInterface $scheduledAt,
|
||||
): SmsCampaign {
|
||||
return DB::transaction(function () use ($user, $message, $recipients, $selectedContactIds, $selectedGroupIds, $selectedGroupNames, $status, $scheduledAt): SmsCampaign {
|
||||
$attributes = [
|
||||
'user_id' => $user->id,
|
||||
'provider' => (string) config('relais_sms.default_settings.active_sms_provider', 'ovh'),
|
||||
'status' => $status,
|
||||
'message' => $message,
|
||||
'recipients_count' => count($recipients),
|
||||
'selected_contact_ids' => $selectedContactIds,
|
||||
'selected_group_ids' => $selectedGroupIds,
|
||||
'selected_group_names' => $selectedGroupNames,
|
||||
];
|
||||
|
||||
if ($scheduledAt !== null) {
|
||||
$attributes['scheduled_at'] = $scheduledAt;
|
||||
}
|
||||
|
||||
$campaign = SmsCampaign::query()->create($attributes);
|
||||
$campaign->update(['provider_tag' => 'relais-sms-campaign-'.$campaign->id]);
|
||||
|
||||
foreach ($recipients as $recipient) {
|
||||
$campaign->deliveries()->create([
|
||||
'contact_id' => $recipient['contact_id'] ?? null,
|
||||
'contact_phone_number_id' => $recipient['phone_number_id'] ?? null,
|
||||
'contact_name' => (string) $recipient['contact_name'],
|
||||
'number' => (string) $recipient['number'],
|
||||
'status' => 'queued',
|
||||
]);
|
||||
}
|
||||
|
||||
return $campaign;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $recipients
|
||||
*/
|
||||
private function sendExistingCampaign(SmsCampaign $campaign, array $recipients): SmsCampaign
|
||||
{
|
||||
try {
|
||||
$result = $this->provider->send($campaign, $recipients);
|
||||
} catch (SmsProviderException $exception) {
|
||||
$status = $exception->outcomeUnknown ? 'uncertain' : 'failed';
|
||||
$message = $exception->outcomeUnknown
|
||||
? 'OVH n a pas confirme la reponse. Les SMS peuvent avoir ete envoyes. Verification automatique au prochain passage du cron ; ne pas renvoyer cette campagne.'
|
||||
: $exception->getMessage();
|
||||
|
||||
DB::transaction(function () use ($campaign, $exception, $status, $message, $recipients): void {
|
||||
$campaign->deliveries()->update(['status' => $status, 'error_message' => $message]);
|
||||
$campaign->update([
|
||||
'status' => $status,
|
||||
'failed_count' => $exception->outcomeUnknown ? 0 : count($recipients),
|
||||
'response_payload' => $exception->responsePayload,
|
||||
'error_message' => $message,
|
||||
]);
|
||||
});
|
||||
|
||||
Log::warning('SMS provider request failed.', [
|
||||
'sms_campaign_id' => $campaign->id,
|
||||
'outcome_unknown' => $exception->outcomeUnknown,
|
||||
'reason' => $exception->getMessage(),
|
||||
]);
|
||||
|
||||
return $campaign->fresh(['deliveries', 'user']);
|
||||
}
|
||||
|
||||
$failedNumbers = array_flip($result->failedNumbers);
|
||||
$sentCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($campaign->deliveries()->orderBy('id')->get()->values() as $index => $delivery) {
|
||||
$failed = isset($failedNumbers[$delivery->number]);
|
||||
|
||||
$delivery->update([
|
||||
'status' => $failed ? 'failed' : 'sent',
|
||||
'provider_message_id' => $result->providerMessageIds[$index] ?? null,
|
||||
'provider_response' => $result->responsePayload,
|
||||
'error_message' => $failed ? 'Numero refuse par OVH.' : null,
|
||||
'sent_at' => $failed ? null : now(),
|
||||
]);
|
||||
|
||||
$failed ? $failedCount++ : $sentCount++;
|
||||
}
|
||||
|
||||
$campaign->update([
|
||||
'status' => $failedCount > 0 ? ($sentCount > 0 ? 'partial' : 'failed') : 'sent',
|
||||
'sent_count' => $sentCount,
|
||||
'failed_count' => $failedCount,
|
||||
'provider_service_name' => $result->serviceName,
|
||||
'provider_job_id' => $result->providerJobId,
|
||||
'message' => (string) ($result->requestPayload['message'] ?? $campaign->message),
|
||||
'request_payload' => $result->requestPayload,
|
||||
'response_payload' => $result->responsePayload,
|
||||
'sent_at' => $sentCount > 0 ? now() : null,
|
||||
]);
|
||||
|
||||
return $campaign->fresh(['deliveries', 'user']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function recipientsFromDeliveries(SmsCampaign $campaign): array
|
||||
{
|
||||
return $campaign->deliveries()
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (SmsDelivery $delivery): array => [
|
||||
'contact_id' => $delivery->contact_id,
|
||||
'phone_number_id' => $delivery->contact_phone_number_id,
|
||||
'contact_name' => $delivery->contact_name,
|
||||
'number' => $delivery->number,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int|string> $ids
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function cleanIds(array $ids): array
|
||||
{
|
||||
return collect($ids)
|
||||
->map(fn (int|string $id): int => (int) $id)
|
||||
->filter(fn (int $id): bool => $id > 0)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use App\Models\AppSetting;
|
||||
|
||||
class SmsMessageComposer
|
||||
{
|
||||
/**
|
||||
* @return array{header: string, footer: string}
|
||||
*/
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'header' => AppSetting::string('sms_message_header'),
|
||||
'footer' => AppSetting::string('sms_message_footer'),
|
||||
];
|
||||
}
|
||||
|
||||
public function compose(string $body, bool $includeHeader = true, bool $includeFooter = true): string
|
||||
{
|
||||
$settings = $this->settings();
|
||||
$parts = [];
|
||||
|
||||
if ($includeHeader && $settings['header'] !== '') {
|
||||
$parts[] = $settings['header'];
|
||||
}
|
||||
|
||||
if (trim($body) !== '') {
|
||||
$parts[] = trim($body);
|
||||
}
|
||||
|
||||
if ($includeFooter && $settings['footer'] !== '') {
|
||||
$parts[] = $settings['footer'];
|
||||
}
|
||||
|
||||
return implode("\n", $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
class SmsMessageLength
|
||||
{
|
||||
private const GSM_BASIC = "@\u{00A3}$\u{00A5}\u{00E8}\u{00E9}\u{00F9}\u{00EC}\u{00F2}\u{00C7}\n\u{00D8}\u{00F8}\r\u{00C5}\u{00E5}\u{0394}_\u{03A6}\u{0393}\u{039B}\u{03A9}\u{03A0}\u{03A8}\u{03A3}\u{0398}\u{039E}\u{00C6}\u{00E6}\u{00DF}\u{00C9} !\"#\u{00A4}%&'()*+,-./0123456789:;<=>?\u{00A1}ABCDEFGHIJKLMNOPQRSTUVWXYZ\u{00C4}\u{00D6}\u{00D1}\u{00DC}\u{00A7}\u{00BF}abcdefghijklmnopqrstuvwxyz\u{00E4}\u{00F6}\u{00F1}\u{00FC}\u{00E0}";
|
||||
|
||||
private const GSM_EXTENDED = "^{}\\[~]|\u{20AC}";
|
||||
|
||||
public function fitsInOneSms(string $message): bool
|
||||
{
|
||||
return $this->units($message) <= $this->singleSmsCapacity($message);
|
||||
}
|
||||
|
||||
public function units(string $message): int
|
||||
{
|
||||
if (! $this->usesGsmAlphabet($message)) {
|
||||
return intdiv(strlen(mb_convert_encoding($message, 'UTF-16BE', 'UTF-8')), 2);
|
||||
}
|
||||
|
||||
return array_sum(array_map(
|
||||
fn (string $character): int => str_contains(self::GSM_EXTENDED, $character) ? 2 : 1,
|
||||
mb_str_split($message),
|
||||
));
|
||||
}
|
||||
|
||||
public function singleSmsCapacity(string $message): int
|
||||
{
|
||||
return $this->usesGsmAlphabet($message) ? 160 : 70;
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate a value so that prefix + value + suffix still fits in one SMS.
|
||||
*/
|
||||
public function truncateBetween(string $prefix, string $value, string $suffix, string $marker = '[...]'): string
|
||||
{
|
||||
if ($this->fitsInOneSms($prefix.$value.$suffix)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$truncated = '';
|
||||
|
||||
foreach (mb_str_split($value) as $character) {
|
||||
if (! $this->fitsInOneSms($prefix.$truncated.$character.$marker.$suffix)) {
|
||||
break;
|
||||
}
|
||||
|
||||
$truncated .= $character;
|
||||
}
|
||||
|
||||
if ($this->fitsInOneSms($prefix.$truncated.$marker.$suffix)) {
|
||||
return rtrim($truncated).$marker;
|
||||
}
|
||||
|
||||
return rtrim($truncated);
|
||||
}
|
||||
|
||||
private function usesGsmAlphabet(string $message): bool
|
||||
{
|
||||
foreach (mb_str_split($message) as $character) {
|
||||
if (! str_contains(self::GSM_BASIC, $character) && ! str_contains(self::GSM_EXTENDED, $character)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class SmsProviderException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed>|null $responsePayload
|
||||
*/
|
||||
public function __construct(
|
||||
string $message,
|
||||
public readonly ?array $responsePayload = null,
|
||||
public readonly bool $outcomeUnknown = false,
|
||||
) {
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Sms;
|
||||
|
||||
class SmsSendResult
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $requestPayload
|
||||
* @param array<string, mixed> $responsePayload
|
||||
* @param array<int, string> $providerMessageIds
|
||||
* @param array<int, string> $failedNumbers
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $serviceName,
|
||||
public readonly ?string $providerJobId,
|
||||
public readonly array $requestPayload,
|
||||
public readonly array $responsePayload,
|
||||
public readonly array $providerMessageIds = [],
|
||||
public readonly array $failedNumbers = [],
|
||||
) {}
|
||||
}
|
||||
Reference in New Issue
Block a user