Sync Ladill Events to the Mail utility calendar.

Events upsert calendar entries by stable external_ref keys, prefer the
owner's linked mailbox, and Meet skips mail sync for events-sourced rooms
so linked virtual sessions appear only once on the calendar.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-04 11:48:37 +00:00
co-authored by Cursor
parent c875a64fe4
commit 9cdfc331b0
10 changed files with 475 additions and 0 deletions
@@ -0,0 +1,203 @@
<?php
namespace App\Services\Events;
use App\Models\QrCode;
use App\Models\User;
use App\Services\Identity\IdentityClient;
use App\Services\Integrations\MailCalendarClient;
use Carbon\CarbonInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
class EventMailCalendarSyncService
{
public function __construct(
private readonly MailCalendarClient $mail,
private readonly IdentityClient $identity,
) {}
public function sync(QrCode $event, User $owner): QrCode
{
if ($event->type !== QrCode::TYPE_EVENT || ! $this->mail->isConfigured()) {
return $event;
}
$mailbox = $this->resolveMailbox($owner);
if ($mailbox === null) {
return $event;
}
$entries = $this->entriesFor($event);
$previous = (array) data_get($event->payload, 'calendar_sync.items', []);
$synced = [];
foreach ($entries as $entry) {
$result = $this->mail->upsertEvent(array_merge($entry, [
'mailbox_email' => $mailbox,
]));
if ($result && isset($result['id'])) {
$synced[$entry['external_ref']] = (int) $result['id'];
}
}
foreach ($previous as $externalRef => $eventId) {
if (! isset($synced[$externalRef]) && is_numeric($eventId)) {
$this->mail->deleteEvent((int) $eventId, $mailbox, (string) $externalRef);
}
}
if ($entries === [] && $previous !== []) {
foreach ($previous as $externalRef => $eventId) {
if (is_numeric($eventId)) {
$this->mail->deleteEvent((int) $eventId, $mailbox, (string) $externalRef);
}
}
}
$payload = (array) ($event->payload ?? []);
$payload['calendar_sync'] = ['items' => $synced];
$event->payload = $payload;
$event->save();
Log::info('Events mail calendar synced', [
'event_id' => $event->id,
'entries' => count($synced),
]);
return $event->fresh();
}
/**
* @return list<array<string, mixed>>
*/
public function entriesFor(QrCode $event): array
{
$content = $event->content();
$format = (string) ($content['format'] ?? 'in_person');
$sessions = array_values(array_filter(
(array) ($content['virtual_sessions'] ?? []),
fn ($session) => is_array($session) && trim((string) ($session['title'] ?? '')) !== '',
));
$entries = [];
if (in_array($format, ['virtual', 'hybrid'], true) && $sessions !== []) {
foreach ($sessions as $session) {
$entry = $this->sessionEntry($event, $content, $session);
if ($entry !== null) {
$entries[] = $entry;
}
}
if ($format === 'hybrid' && filled($content['starts_at'] ?? null)) {
$entries[] = $this->mainEventEntry($event, $content, ' (in person)');
}
return $entries;
}
if (filled($content['starts_at'] ?? null)) {
$entries[] = $this->mainEventEntry($event, $content);
}
return $entries;
}
/**
* @param array<string, mixed> $content
* @param array<string, mixed> $session
* @return array<string, mixed>|null
*/
private function sessionEntry(QrCode $event, array $content, array $session): ?array
{
$sessionId = trim((string) ($session['id'] ?? ''));
if ($sessionId === '') {
return null;
}
$starts = $this->parseDate($session['scheduled_at'] ?? $content['starts_at'] ?? null);
if ($starts === null) {
return null;
}
$duration = max(15, (int) ($session['duration_minutes'] ?? 60));
$joinUrl = trim((string) ($session['join_url'] ?? ''));
$description = trim((string) ($content['description'] ?? ''));
return [
'external_ref' => $this->sessionExternalRef($event->id, $sessionId),
'title' => trim((string) ($session['title'] ?? $content['name'] ?? $event->label)),
'body' => $description !== '' ? $description : null,
'starts_at' => $starts->toIso8601String(),
'ends_at' => $starts->copy()->addMinutes($duration)->toIso8601String(),
'join_url' => $joinUrl !== '' ? $joinUrl : $event->publicUrl(),
];
}
/**
* @param array<string, mixed> $content
* @return array<string, mixed>
*/
private function mainEventEntry(QrCode $event, array $content, string $titleSuffix = ''): array
{
$starts = $this->parseDate($content['starts_at'] ?? null) ?? now();
$ends = $this->parseDate($content['ends_at'] ?? null) ?? $starts->copy()->addHours(2);
$name = trim((string) ($content['name'] ?? $event->label));
$location = trim((string) ($content['location'] ?? ''));
$body = trim((string) ($content['description'] ?? ''));
if ($location !== '') {
$body = $body !== '' ? $body."\n\n".$location : $location;
}
return [
'external_ref' => $this->eventExternalRef($event->id),
'title' => $name.$titleSuffix,
'body' => $body !== '' ? $body : null,
'starts_at' => $starts->toIso8601String(),
'ends_at' => $ends->toIso8601String(),
'join_url' => $event->publicUrl(),
];
}
private function eventExternalRef(int $eventId): string
{
return 'events:'.$eventId;
}
private function sessionExternalRef(int $eventId, string $sessionId): string
{
return 'events:'.$eventId.':session:'.$sessionId;
}
private function parseDate(mixed $value): ?CarbonInterface
{
if ($value === null || $value === '') {
return null;
}
try {
return Carbon::parse($value);
} catch (\Throwable) {
return null;
}
}
private function resolveMailbox(User $user): ?string
{
try {
$status = $this->identity->mailboxLinkStatus($user->public_id);
$linked = strtolower(trim((string) ($status['linked_mailbox'] ?? '')));
if (filter_var($linked, FILTER_VALIDATE_EMAIL)) {
return $linked;
}
} catch (\Throwable) {
// Fall back to the account email.
}
$email = strtolower(trim((string) $user->email));
return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Services\Integrations;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class MailCalendarClient
{
public function isConfigured(): bool
{
return filled(config('mail_calendar.api_key')) && filled(config('mail_calendar.api_url'));
}
/**
* @param array<string, mixed> $payload
* @return array<string, mixed>|null
*/
public function upsertEvent(array $payload): ?array
{
if (! $this->isConfigured()) {
return null;
}
try {
$response = Http::withToken((string) config('mail_calendar.api_key'))
->acceptJson()
->asJson()
->connectTimeout(10)
->timeout(15)
->post($this->baseUrl().'/calendar/events', $payload);
} catch (ConnectionException $e) {
Log::warning('Events mail calendar upsert failed', ['error' => $e->getMessage()]);
return null;
}
if (! $response->successful()) {
Log::warning('Events mail calendar upsert failed', [
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
$data = $response->json('data');
return is_array($data) ? $data : null;
}
public function deleteEvent(int $eventId, string $mailboxEmail, string $externalRef): bool
{
if (! $this->isConfigured()) {
return false;
}
try {
$response = Http::withToken((string) config('mail_calendar.api_key'))
->acceptJson()
->connectTimeout(10)
->timeout(15)
->delete($this->baseUrl().'/calendar/events/'.$eventId, [
'mailbox_email' => strtolower(trim($mailboxEmail)),
'external_ref' => $externalRef,
]);
} catch (ConnectionException $e) {
Log::warning('Events mail calendar delete failed', ['error' => $e->getMessage()]);
return false;
}
return $response->successful();
}
protected function baseUrl(): string
{
return rtrim((string) config('mail_calendar.api_url'), '/');
}
}
+3
View File
@@ -20,6 +20,7 @@ class QrCodeManagerService
private QrImageGeneratorService $imageGenerator,
private QrPayloadValidator $payloadValidator,
private \App\Services\Meet\EventMeetSyncService $meetSync,
private \App\Services\Events\EventMailCalendarSyncService $mailCalendar,
) {}
public function walletFor(User $user): QrWallet
@@ -165,6 +166,7 @@ class QrCodeManagerService
if ($type === QrCode::TYPE_EVENT) {
$qrCode = $this->meetSync->sync($qrCode->fresh(), $user);
$qrCode = $this->mailCalendar->sync($qrCode->fresh(), $user);
}
return $qrCode->fresh(['document']);
@@ -305,6 +307,7 @@ class QrCodeManagerService
if ($qrCode->type === QrCode::TYPE_EVENT) {
$qrCode = $this->meetSync->sync($qrCode->fresh(), $qrCode->user);
$qrCode = $this->mailCalendar->sync($qrCode->fresh(), $qrCode->user);
}
if ($qrCode->type === QrCode::TYPE_ITINERARY) {