diff --git a/.env.example b/.env.example index f5602b1..4bf914a 100644 --- a/.env.example +++ b/.env.example @@ -42,6 +42,10 @@ BILLING_API_KEY_FRONTDESK= IDENTITY_API_URL=https://ladill.com/api IDENTITY_API_KEY_FRONTDESK= +# Per-customer Ladill SMS / Bird relay (host alert integrations) +SMS_CUSTOMER_RELAY_URL=https://ladill.com/api/sms +SMTP_CUSTOMER_RELAY_URL=https://ladill.com/api/smtp + # Afia AI assistant (uses platform relay via IDENTITY_API_KEY when AFIA_API_KEY is unset) AFIA_ENABLED=true # AFIA_API_KEY= diff --git a/app/Http/Controllers/Frontdesk/IntegrationController.php b/app/Http/Controllers/Frontdesk/IntegrationController.php index 26ef122..2f0928a 100644 --- a/app/Http/Controllers/Frontdesk/IntegrationController.php +++ b/app/Http/Controllers/Frontdesk/IntegrationController.php @@ -5,6 +5,9 @@ namespace App\Http\Controllers\Frontdesk; use App\Http\Controllers\Controller; use App\Http\Controllers\Frontdesk\Concerns\ScopesToAccount; use App\Models\WebhookEndpoint; +use App\Services\Messaging\CustomerSmsClient; +use App\Services\Messaging\MessagingCredentialsService; +use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\View\View; @@ -13,7 +16,7 @@ class IntegrationController extends Controller { use ScopesToAccount; - public function edit(Request $request): View + public function edit(Request $request, MessagingCredentialsService $credentials): View { $this->authorizeAbility($request, 'settings.view'); $organization = $this->organization($request); @@ -40,6 +43,7 @@ class IntegrationController extends Controller 'webhookEvents' => config('frontdesk.webhook_events', []), 'integrations' => config('frontdesk.integrations', []), 'icalUrl' => $this->signedIcalUrl($organization->id, $this->ownerRef($request)), + 'credential' => $credentials->forOrganization($organization), ]); } @@ -84,6 +88,96 @@ class IntegrationController extends Controller return back()->with('success', 'Integration settings saved.'); } + public function saveSms(Request $request, MessagingCredentialsService $credentials): RedirectResponse + { + $this->authorizeAbility($request, 'settings.manage'); + $organization = $this->organization($request); + + if (! app(\App\Services\Frontdesk\PlanService::class)->hasFeature($organization, 'integrations')) { + return back()->with('error', 'Messaging integrations require Frontdesk Pro.'); + } + + $data = $request->validate([ + 'sms_api_key' => ['required', 'string', 'max:200'], + 'sms_sender_id' => ['required', 'string', 'max:11'], + ]); + + $result = $credentials->validateAndSaveSms( + $organization, + $data['sms_api_key'], + $data['sms_sender_id'], + ); + + if (! ($result['ok'] ?? false)) { + return back()->withInput()->with('error', $result['error'] ?? 'Could not save SMS credentials.'); + } + + return back()->with('success', 'Ladill SMS connected. Host alerts will use your key and sender ID.'); + } + + public function disconnectSms(Request $request, MessagingCredentialsService $credentials): RedirectResponse + { + $this->authorizeAbility($request, 'settings.manage'); + $organization = $this->organization($request); + $credentials->disconnectSms($organization); + + return back()->with('success', 'Ladill SMS disconnected.'); + } + + public function saveBird(Request $request, MessagingCredentialsService $credentials): RedirectResponse + { + $this->authorizeAbility($request, 'settings.manage'); + $organization = $this->organization($request); + + if (! app(\App\Services\Frontdesk\PlanService::class)->hasFeature($organization, 'integrations')) { + return back()->with('error', 'Messaging integrations require Frontdesk Pro.'); + } + + $data = $request->validate([ + 'bird_api_key' => ['required', 'string', 'max:200'], + 'bird_from_email' => ['required', 'email', 'max:255'], + 'bird_from_name' => ['nullable', 'string', 'max:100'], + ]); + + $result = $credentials->validateAndSaveBird( + $organization, + $data['bird_api_key'], + $data['bird_from_email'], + $data['bird_from_name'] ?? null, + ); + + if (! ($result['ok'] ?? false)) { + return back()->withInput()->with('error', $result['error'] ?? 'Could not save Bird credentials.'); + } + + return back()->with('success', 'Ladill Bird connected. Host email alerts will use your key and from address.'); + } + + public function disconnectBird(Request $request, MessagingCredentialsService $credentials): RedirectResponse + { + $this->authorizeAbility($request, 'settings.manage'); + $organization = $this->organization($request); + $credentials->disconnectBird($organization); + + return back()->with('success', 'Ladill Bird disconnected.'); + } + + public function previewSenders(Request $request, CustomerSmsClient $sms): JsonResponse + { + $this->authorizeAbility($request, 'settings.manage'); + + $data = $request->validate([ + 'sms_api_key' => ['required', 'string', 'max:200'], + ]); + + $result = $sms->senders(trim($data['sms_api_key'])); + if (! ($result['ok'] ?? false)) { + return response()->json(['error' => $result['error'] ?? 'Could not load senders.'], 422); + } + + return response()->json($result['data'] ?? []); + } + protected function signedIcalUrl(int $organizationId, string $ownerRef): string { $token = hash_hmac('sha256', "{$organizationId}:{$ownerRef}", (string) config('app.key')); diff --git a/app/Jobs/DispatchCampaignJob.php b/app/Jobs/DispatchCampaignJob.php index 8728351..30c7865 100644 --- a/app/Jobs/DispatchCampaignJob.php +++ b/app/Jobs/DispatchCampaignJob.php @@ -7,6 +7,9 @@ use App\Models\CampaignRecipient; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; +/** + * Campaign batch dispatch — orphaned until Campaign model exists. + */ class DispatchCampaignJob implements ShouldQueue { use Queueable; diff --git a/app/Jobs/SendCampaignMessageJob.php b/app/Jobs/SendCampaignMessageJob.php index 61c480b..b11ed93 100644 --- a/app/Jobs/SendCampaignMessageJob.php +++ b/app/Jobs/SendCampaignMessageJob.php @@ -15,6 +15,10 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Support\Facades\DB; +/** + * Campaign delivery job — orphaned until Campaign / CampaignRecipient models exist. + * Wire to CustomerSmsClient / CustomerEmailClient + MessagingCredentialsService when campaigns ship. + */ class SendCampaignMessageJob implements ShouldQueue { use Queueable; diff --git a/app/Models/MessagingCredential.php b/app/Models/MessagingCredential.php new file mode 100644 index 0000000..25731a1 --- /dev/null +++ b/app/Models/MessagingCredential.php @@ -0,0 +1,100 @@ + 'datetime', + 'bird_validated_at' => 'datetime', + ]; + } + + public function organization(): BelongsTo + { + return $this->belongsTo(Organization::class); + } + + public function hasValidSms(): bool + { + return $this->sms_status === self::STATUS_VALID + && filled($this->sms_api_key_encrypted) + && filled($this->sms_sender_id); + } + + public function hasValidBird(): bool + { + return $this->bird_status === self::STATUS_VALID + && filled($this->bird_api_key_encrypted) + && filled($this->bird_from_email); + } + + public function smsApiKey(): ?string + { + if (! filled($this->sms_api_key_encrypted)) { + return null; + } + + try { + return Crypt::decryptString($this->sms_api_key_encrypted); + } catch (\Throwable) { + return null; + } + } + + public function birdApiKey(): ?string + { + if (! filled($this->bird_api_key_encrypted)) { + return null; + } + + try { + return Crypt::decryptString($this->bird_api_key_encrypted); + } catch (\Throwable) { + return null; + } + } + + public static function encryptKey(string $plain): string + { + return Crypt::encryptString($plain); + } +} diff --git a/app/Services/Frontdesk/NotificationBillingService.php b/app/Services/Frontdesk/NotificationBillingService.php index 97387b8..da643a1 100644 --- a/app/Services/Frontdesk/NotificationBillingService.php +++ b/app/Services/Frontdesk/NotificationBillingService.php @@ -4,6 +4,7 @@ namespace App\Services\Frontdesk; use App\Models\Organization; use App\Services\Billing\BillingClient; +use App\Services\Messaging\MessagingCredentialsService; use Illuminate\Support\Str; class NotificationBillingService @@ -13,10 +14,25 @@ class NotificationBillingService protected NotificationPricingService $pricing, protected NotificationUsageService $usage, protected PlanService $plans, + protected MessagingCredentialsService $credentials, ) {} + public function usesCustomerEmail(Organization $organization): bool + { + return $this->credentials->forOrganization($organization)->hasValidBird(); + } + + public function usesCustomerSms(Organization $organization): bool + { + return $this->credentials->forOrganization($organization)->hasValidSms(); + } + public function emailCostMinor(Organization $organization): int { + if ($this->usesCustomerEmail($organization)) { + return 0; + } + $allowance = $this->plans->freeEmailsPerMonth($organization); if ($allowance === null || $this->usage->emailCountThisMonth($organization) < $allowance) { return 0; @@ -27,6 +43,10 @@ class NotificationBillingService public function canAffordEmail(Organization $organization): bool { + if ($this->usesCustomerEmail($organization)) { + return true; + } + $cost = $this->emailCostMinor($organization); if ($cost <= 0) { return true; @@ -37,6 +57,10 @@ class NotificationBillingService public function canAffordSms(Organization $organization, string $message): bool { + if ($this->usesCustomerSms($organization)) { + return true; + } + $cost = $this->pricing->smsCostMinor($message); if ($cost <= 0) { return true; @@ -47,9 +71,16 @@ class NotificationBillingService /** * Debit after a successful send. Returns false if the wallet could not be charged. + * Customer relay keys bill the Ladill SMS/Bird wallet directly — never double-debit Frontdesk. */ public function chargeEmail(Organization $organization, string $reference, string $description): bool { + if ($this->usesCustomerEmail($organization)) { + $this->usage->recordEmail($organization, 0); + + return true; + } + $cost = $this->emailCostMinor($organization); if ($cost <= 0) { $this->usage->recordEmail($organization, 0); @@ -68,6 +99,12 @@ class NotificationBillingService public function chargeSms(Organization $organization, string $message, string $reference, string $description): bool { + if ($this->usesCustomerSms($organization)) { + $this->usage->recordSms($organization, 0); + + return true; + } + $cost = $this->pricing->smsCostMinor($message); if ($cost <= 0) { $this->usage->recordSms($organization, 0); diff --git a/app/Services/Frontdesk/NotificationDispatcher.php b/app/Services/Frontdesk/NotificationDispatcher.php index d64cad6..6813d5b 100644 --- a/app/Services/Frontdesk/NotificationDispatcher.php +++ b/app/Services/Frontdesk/NotificationDispatcher.php @@ -10,15 +10,17 @@ use App\Models\User; use App\Models\Visitor; use App\Models\Visit; use App\Notifications\FrontdeskAlertNotification; -use App\Services\Comms\EmailService; -use App\Services\Comms\SmsService; +use App\Services\Messaging\CustomerEmailClient; +use App\Services\Messaging\CustomerSmsClient; +use App\Services\Messaging\MessagingCredentialsService; use Illuminate\Support\Facades\Log; class NotificationDispatcher { public function __construct( - protected EmailService $email, - protected SmsService $sms, + protected MessagingCredentialsService $credentials, + protected CustomerEmailClient $customerEmail, + protected CustomerSmsClient $customerSms, protected NotificationPreferenceService $preferences, protected NotificationBillingService $billing, ) {} @@ -194,40 +196,94 @@ class NotificationDispatcher ): bool { $notified = false; $reference = $visit ? 'visit-'.$visit->id.'-'.($event ?? 'alert') : 'host-'.$host->id; + $credential = $this->credentials->forOrganization($organization); if (in_array('email', $channels, true) && $host->email) { - if (! $this->billing->canAffordEmail($organization)) { - Log::info('Frontdesk host email skipped — insufficient wallet balance', [ + if (! $credential->hasValidBird()) { + Log::info('Frontdesk host email skipped — Ladill Bird not connected', [ 'host_id' => $host->id, 'organization_id' => $organization->id, ]); } else { - try { - $this->email->send($host->email, $title, $message); - if ($this->billing->chargeEmail($organization, $reference, "Host alert: {$title}")) { - $notified = true; + $apiKey = $credential->birdApiKey(); + if (! $apiKey) { + Log::info('Frontdesk host email skipped — Bird credentials could not be decrypted', [ + 'host_id' => $host->id, + 'organization_id' => $organization->id, + ]); + } elseif (! $this->billing->canAffordEmail($organization)) { + Log::info('Frontdesk host email skipped — insufficient wallet balance', [ + 'host_id' => $host->id, + 'organization_id' => $organization->id, + ]); + } else { + try { + $html = nl2br(e($message)); + $sent = $this->customerEmail->send( + $apiKey, + (string) $credential->bird_from_email, + $credential->bird_from_name, + (string) $host->email, + $title, + $html, + $message, + ); + + if (! $sent) { + Log::warning('Frontdesk host email failed', [ + 'host_id' => $host->id, + 'error' => $this->customerEmail->lastError(), + ]); + } elseif ($this->billing->chargeEmail($organization, $reference, "Host alert: {$title}")) { + $notified = true; + } + } catch (\Throwable $e) { + Log::warning('Frontdesk host email failed', ['host_id' => $host->id, 'error' => $e->getMessage()]); } - } catch (\Throwable $e) { - Log::warning('Frontdesk host email failed', ['host_id' => $host->id, 'error' => $e->getMessage()]); } } } if (in_array('sms', $channels, true) && $host->phone) { $smsBody = "{$title}: {$message}"; - if (! $this->billing->canAffordSms($organization, $smsBody)) { - Log::info('Frontdesk host SMS skipped — insufficient wallet balance', [ + + if (! $credential->hasValidSms()) { + Log::info('Frontdesk host SMS skipped — Ladill SMS not connected', [ 'host_id' => $host->id, 'organization_id' => $organization->id, ]); } else { - try { - $this->sms->send($host->phone, $smsBody); - if ($this->billing->chargeSms($organization, $smsBody, $reference, "Host SMS: {$title}")) { - $notified = true; + $apiKey = $credential->smsApiKey(); + if (! $apiKey) { + Log::info('Frontdesk host SMS skipped — SMS credentials could not be decrypted', [ + 'host_id' => $host->id, + 'organization_id' => $organization->id, + ]); + } elseif (! $this->billing->canAffordSms($organization, $smsBody)) { + Log::info('Frontdesk host SMS skipped — insufficient wallet balance', [ + 'host_id' => $host->id, + 'organization_id' => $organization->id, + ]); + } else { + try { + $sent = $this->customerSms->send( + $apiKey, + (string) $host->phone, + $smsBody, + (string) $credential->sms_sender_id, + ); + + if (! $sent) { + Log::warning('Frontdesk host SMS failed', [ + 'host_id' => $host->id, + 'error' => $this->customerSms->lastError(), + ]); + } elseif ($this->billing->chargeSms($organization, $smsBody, $reference, "Host SMS: {$title}")) { + $notified = true; + } + } catch (\Throwable $e) { + Log::warning('Frontdesk host SMS failed', ['host_id' => $host->id, 'error' => $e->getMessage()]); } - } catch (\Throwable $e) { - Log::warning('Frontdesk host SMS failed', ['host_id' => $host->id, 'error' => $e->getMessage()]); } } } diff --git a/app/Services/Messaging/CustomerEmailClient.php b/app/Services/Messaging/CustomerEmailClient.php new file mode 100644 index 0000000..12c58e0 --- /dev/null +++ b/app/Services/Messaging/CustomerEmailClient.php @@ -0,0 +1,92 @@ +lastError; + } + + private function base(): string + { + return rtrim((string) config('smtp.customer_relay_url', 'https://ladill.com/api/smtp'), '/'); + } + + /** @return array{ok: bool, data?: array, error?: string, status?: int} */ + public function me(string $apiKey): array + { + try { + $res = Http::withToken($apiKey)->acceptJson()->timeout(15) + ->get($this->base().'/me'); + + if ($res->status() === 401) { + return ['ok' => false, 'error' => 'Invalid Bird API key.', 'status' => 401]; + } + + if ($res->failed()) { + return [ + 'ok' => false, + 'error' => (string) ($res->json('error') ?: 'Could not validate Bird credentials.'), + 'status' => $res->status(), + ]; + } + + return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()]; + } catch (\Throwable $e) { + Log::warning('Customer Bird meta request failed', ['error' => $e->getMessage()]); + + return ['ok' => false, 'error' => 'Could not reach Ladill Bird. Please try again.']; + } + } + + public function send( + string $apiKey, + string $from, + ?string $fromName, + string $to, + string $subject, + string $html, + ?string $text = null, + ): bool { + $this->lastError = null; + + try { + $res = Http::withToken($apiKey)->acceptJson()->timeout(30) + ->post($this->base().'/send', array_filter([ + 'from' => $from, + 'from_name' => $fromName, + 'to' => [$to], + 'subject' => $subject, + 'html' => $html, + 'text' => $text, + ], fn ($value) => $value !== null && $value !== '')); + + if ($res->status() === 402) { + $this->lastError = (string) ($res->json('error') ?: 'Insufficient Bird email credits. Top up Bird and try again.'); + + return false; + } + + if ($res->failed()) { + $this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The email could not be sent.'); + Log::warning('Customer email send failed', ['status' => $res->status()]); + + return false; + } + + return (bool) ($res->json('success') ?? true); + } catch (\Throwable $e) { + $this->lastError = 'Could not reach the email service. Please try again.'; + Log::warning('Customer email send error', ['error' => $e->getMessage()]); + + return false; + } + } +} diff --git a/app/Services/Messaging/CustomerSmsClient.php b/app/Services/Messaging/CustomerSmsClient.php new file mode 100644 index 0000000..37d5274 --- /dev/null +++ b/app/Services/Messaging/CustomerSmsClient.php @@ -0,0 +1,94 @@ +lastError; + } + + private function base(): string + { + return rtrim((string) config('sms.customer_relay_url', 'https://ladill.com/api/sms'), '/'); + } + + /** @return array{ok: bool, data?: array, error?: string, status?: int} */ + public function me(string $apiKey): array + { + return $this->get($apiKey, '/me'); + } + + /** @return array{ok: bool, data?: array, error?: string, status?: int} */ + public function senders(string $apiKey): array + { + return $this->get($apiKey, '/senders'); + } + + public function send(string $apiKey, string $to, string $text, string $senderId): bool + { + $this->lastError = null; + + try { + $res = Http::withToken($apiKey)->acceptJson()->timeout(30) + ->post($this->base().'/send', [ + 'to' => $to, + 'text' => $text, + 'sender_id' => $senderId, + ]); + + if ($res->status() === 402) { + $this->lastError = (string) ($res->json('error') ?: 'Insufficient SMS credit. Top up your Ladill SMS wallet and try again.'); + + return false; + } + + if ($res->failed()) { + $this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The SMS could not be sent.'); + Log::warning('Customer SMS send failed', ['status' => $res->status()]); + + return false; + } + + return (bool) ($res->json('success') ?? true); + } catch (\Throwable $e) { + $this->lastError = 'Could not reach the SMS service. Please try again.'; + Log::warning('Customer SMS send error', ['error' => $e->getMessage()]); + + return false; + } + } + + /** @return array{ok: bool, data?: array, error?: string, status?: int} */ + private function get(string $apiKey, string $path): array + { + try { + $res = Http::withToken($apiKey)->acceptJson()->timeout(15) + ->get($this->base().$path); + + if ($res->status() === 401) { + return ['ok' => false, 'error' => 'Invalid SMS API key.', 'status' => 401]; + } + + if ($res->failed()) { + return [ + 'ok' => false, + 'error' => (string) ($res->json('error') ?: 'Could not validate SMS credentials.'), + 'status' => $res->status(), + ]; + } + + return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()]; + } catch (\Throwable $e) { + Log::warning('Customer SMS meta request failed', ['path' => $path, 'error' => $e->getMessage()]); + + return ['ok' => false, 'error' => 'Could not reach Ladill SMS. Please try again.']; + } + } +} diff --git a/app/Services/Messaging/MessagingCredentialsService.php b/app/Services/Messaging/MessagingCredentialsService.php new file mode 100644 index 0000000..f5e2e57 --- /dev/null +++ b/app/Services/Messaging/MessagingCredentialsService.php @@ -0,0 +1,167 @@ +firstOrCreate( + ['organization_id' => $organization->id], + ['owner_ref' => $organization->owner_ref], + ); + } + + /** + * @return array{ok: bool, error?: string, credential?: MessagingCredential, senders?: list} + */ + public function validateAndSaveSms(Organization $organization, string $apiKey, string $senderId): array + { + $apiKey = trim($apiKey); + $senderId = trim($senderId); + + if (! str_starts_with($apiKey, 'lsk_sms_live_')) { + return ['ok' => false, 'error' => 'SMS API keys must start with lsk_sms_live_.']; + } + + if ($senderId === '' || strlen($senderId) > 11) { + return ['ok' => false, 'error' => 'Sender ID must be 1–11 characters.']; + } + + $me = $this->sms->me($apiKey); + if (! ($me['ok'] ?? false)) { + $credential = $this->forOrganization($organization); + $credential->update([ + 'sms_status' => MessagingCredential::STATUS_INVALID, + 'sms_last_error' => $me['error'] ?? 'Invalid SMS API key.', + ]); + + return ['ok' => false, 'error' => $me['error'] ?? 'Invalid SMS API key.', 'credential' => $credential]; + } + + $senders = $this->sms->senders($apiKey); + $approved = collect($senders['data']['data'] ?? [])->pluck('sender_id')->map(fn ($id) => (string) $id)->all(); + $defaultSender = (string) ($senders['data']['default_sender'] ?? ''); + + $allowed = array_values(array_unique(array_filter([...$approved, $defaultSender]))); + if ($allowed !== [] && ! in_array($senderId, $allowed, true)) { + $error = 'Sender ID is not approved for this SMS key. Approved: '.implode(', ', $allowed); + + $credential = $this->forOrganization($organization); + $credential->update([ + 'sms_status' => MessagingCredential::STATUS_INVALID, + 'sms_last_error' => $error, + ]); + + return ['ok' => false, 'error' => $error, 'credential' => $credential, 'senders' => $allowed]; + } + + $credential = $this->forOrganization($organization); + $credential->update([ + 'owner_ref' => $organization->owner_ref, + 'sms_api_key_encrypted' => MessagingCredential::encryptKey($apiKey), + 'sms_api_key_prefix' => substr($apiKey, 0, 16), + 'sms_sender_id' => $senderId, + 'sms_status' => MessagingCredential::STATUS_VALID, + 'sms_validated_at' => now(), + 'sms_last_error' => null, + ]); + + return ['ok' => true, 'credential' => $credential->fresh(), 'senders' => $allowed]; + } + + /** + * @return array{ok: bool, error?: string, credential?: MessagingCredential} + */ + public function validateAndSaveBird(Organization $organization, string $apiKey, string $fromEmail, ?string $fromName): array + { + $apiKey = trim($apiKey); + $fromEmail = strtolower(trim($fromEmail)); + $fromName = trim((string) $fromName); + + if (! str_starts_with($apiKey, 'lsk_live_') && ! str_starts_with($apiKey, 'lsk_acct_')) { + return ['ok' => false, 'error' => 'Bird API keys must start with lsk_live_ or lsk_acct_.']; + } + + if (! filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) { + return ['ok' => false, 'error' => 'Enter a valid from email address.']; + } + + $me = $this->email->me($apiKey); + if (! ($me['ok'] ?? false)) { + $credential = $this->forOrganization($organization); + $credential->update([ + 'bird_status' => MessagingCredential::STATUS_INVALID, + 'bird_last_error' => $me['error'] ?? 'Invalid Bird API key.', + ]); + + return ['ok' => false, 'error' => $me['error'] ?? 'Invalid Bird API key.', 'credential' => $credential]; + } + + $domains = collect($me['data']['verified_domains'] ?? [])->map(fn ($d) => strtolower((string) $d))->all(); + $fromDomain = strtolower((string) (explode('@', $fromEmail, 2)[1] ?? '')); + if ($domains !== [] && ! in_array($fromDomain, $domains, true)) { + $error = 'From email must use a verified Bird domain ('.implode(', ', $domains).').'; + $credential = $this->forOrganization($organization); + $credential->update([ + 'bird_status' => MessagingCredential::STATUS_INVALID, + 'bird_last_error' => $error, + ]); + + return ['ok' => false, 'error' => $error, 'credential' => $credential]; + } + + $credential = $this->forOrganization($organization); + $credential->update([ + 'owner_ref' => $organization->owner_ref, + 'bird_api_key_encrypted' => MessagingCredential::encryptKey($apiKey), + 'bird_api_key_prefix' => substr($apiKey, 0, 16), + 'bird_from_email' => $fromEmail, + 'bird_from_name' => $fromName !== '' ? $fromName : null, + 'bird_status' => MessagingCredential::STATUS_VALID, + 'bird_validated_at' => now(), + 'bird_last_error' => null, + ]); + + return ['ok' => true, 'credential' => $credential->fresh()]; + } + + public function disconnectSms(Organization $organization): MessagingCredential + { + $credential = $this->forOrganization($organization); + $credential->update([ + 'sms_api_key_encrypted' => null, + 'sms_api_key_prefix' => null, + 'sms_sender_id' => null, + 'sms_status' => null, + 'sms_validated_at' => null, + 'sms_last_error' => null, + ]); + + return $credential->fresh(); + } + + public function disconnectBird(Organization $organization): MessagingCredential + { + $credential = $this->forOrganization($organization); + $credential->update([ + 'bird_api_key_encrypted' => null, + 'bird_api_key_prefix' => null, + 'bird_from_email' => null, + 'bird_from_name' => null, + 'bird_status' => null, + 'bird_validated_at' => null, + 'bird_last_error' => null, + ]); + + return $credential->fresh(); + } +} diff --git a/config/sms.php b/config/sms.php new file mode 100644 index 0000000..539a89b --- /dev/null +++ b/config/sms.php @@ -0,0 +1,5 @@ + env('SMS_CUSTOMER_RELAY_URL', 'https://ladill.com/api/sms'), +]; diff --git a/config/smtp.php b/config/smtp.php new file mode 100644 index 0000000..73db440 --- /dev/null +++ b/config/smtp.php @@ -0,0 +1,5 @@ + env('SMTP_CUSTOMER_RELAY_URL', 'https://ladill.com/api/smtp'), +]; diff --git a/database/migrations/2026_07_12_100000_create_frontdesk_messaging_credentials_table.php b/database/migrations/2026_07_12_100000_create_frontdesk_messaging_credentials_table.php new file mode 100644 index 0000000..663745c --- /dev/null +++ b/database/migrations/2026_07_12_100000_create_frontdesk_messaging_credentials_table.php @@ -0,0 +1,38 @@ +id(); + $table->string('owner_ref')->index(); + $table->foreignId('organization_id')->constrained('frontdesk_organizations')->cascadeOnDelete(); + $table->text('sms_api_key_encrypted')->nullable(); + $table->string('sms_api_key_prefix', 32)->nullable(); + $table->string('sms_sender_id', 11)->nullable(); + $table->string('sms_status', 32)->nullable(); + $table->timestamp('sms_validated_at')->nullable(); + $table->text('sms_last_error')->nullable(); + $table->text('bird_api_key_encrypted')->nullable(); + $table->string('bird_api_key_prefix', 32)->nullable(); + $table->string('bird_from_email')->nullable(); + $table->string('bird_from_name')->nullable(); + $table->string('bird_status', 32)->nullable(); + $table->timestamp('bird_validated_at')->nullable(); + $table->text('bird_last_error')->nullable(); + $table->timestamps(); + + $table->unique('organization_id'); + }); + } + + public function down(): void + { + Schema::dropIfExists('frontdesk_messaging_credentials'); + } +}; diff --git a/resources/views/frontdesk/integrations/edit.blade.php b/resources/views/frontdesk/integrations/edit.blade.php index 803a194..5949457 100644 --- a/resources/views/frontdesk/integrations/edit.blade.php +++ b/resources/views/frontdesk/integrations/edit.blade.php @@ -1,6 +1,10 @@

Integrations

-

Connect Ladill apps and external systems.

+

Connect Ladill apps, messaging, and external systems.

+ + @if (! $canManage) +

You can view integrations, but only admins can change credentials.

+ @endif

Supported Ladill apps

@@ -12,6 +16,111 @@

Sibling apps authenticate with service API keys and can create visits via POST /api/visits with external_ref for idempotency.

+
+
+

Ladill SMS

+

+ Connect your Ladill SMS + API key so host SMS alerts bill your SMS wallet and send under your sender ID. +

+ + @if ($credential->hasValidSms()) +
+ Connected · key {{ $credential->sms_api_key_prefix }}… · sender {{ $credential->sms_sender_id }} + @if ($credential->sms_validated_at) + · validated {{ $credential->sms_validated_at->diffForHumans() }} + @endif +
+ @elseif ($credential->sms_status === \App\Models\MessagingCredential::STATUS_INVALID) +
+ {{ $credential->sms_last_error ?: 'SMS credentials are invalid.' }} +
+ @endif + + @if ($canManage) +
+ @csrf +
+ + +
+
+ + +

Must match an approved sender ID on your SMS service.

+
+ +
+ @if ($credential->sms_api_key_encrypted || $credential->hasValidSms()) +
+ @csrf + +
+ @endif + @endif +
+ +
+

Ladill Bird

+

+ Connect your Ladill Bird + API key so host email alerts bill your Bird wallet and send from your domain. +

+ + @if ($credential->hasValidBird()) +
+ Connected · key {{ $credential->bird_api_key_prefix }}… · from + {{ $credential->bird_from_name ? $credential->bird_from_name.' <'.$credential->bird_from_email.'>' : $credential->bird_from_email }} + @if ($credential->bird_validated_at) + · validated {{ $credential->bird_validated_at->diffForHumans() }} + @endif +
+ @elseif ($credential->bird_status === \App\Models\MessagingCredential::STATUS_INVALID) +
+ {{ $credential->bird_last_error ?: 'Bird credentials are invalid.' }} +
+ @endif + + @if ($canManage) +
+ @csrf +
+ + +
+
+ + +
+
+ + +
+ +
+ @if ($credential->bird_api_key_encrypted || $credential->hasValidBird()) +
+ @csrf + +
+ @endif + @endif +
+
+ @if ($canManage)
@csrf @method('PUT') @@ -39,12 +148,12 @@ - +
@endif -
+

Calendar feed (iCal)

Subscribe to scheduled visits in Outlook, Google Calendar, or Apple Calendar.

{{ $icalUrl }} diff --git a/routes/web.php b/routes/web.php index ec42d71..a738923 100644 --- a/routes/web.php +++ b/routes/web.php @@ -96,6 +96,11 @@ Route::middleware(['auth', 'platform.session'])->group(function () { Route::get('/integrations', [IntegrationController::class, 'edit'])->name('frontdesk.integrations.edit'); Route::put('/integrations', [IntegrationController::class, 'update'])->name('frontdesk.integrations.update'); + Route::post('/integrations/sms', [IntegrationController::class, 'saveSms'])->name('frontdesk.integrations.sms.save'); + Route::post('/integrations/sms/disconnect', [IntegrationController::class, 'disconnectSms'])->name('frontdesk.integrations.sms.disconnect'); + Route::post('/integrations/bird', [IntegrationController::class, 'saveBird'])->name('frontdesk.integrations.bird.save'); + Route::post('/integrations/bird/disconnect', [IntegrationController::class, 'disconnectBird'])->name('frontdesk.integrations.bird.disconnect'); + Route::post('/integrations/sms/senders', [IntegrationController::class, 'previewSenders'])->name('frontdesk.integrations.sms.senders'); Route::delete('/visits/{visit}', [ComplianceController::class, 'destroyVisit'])->name('frontdesk.visits.destroy'); diff --git a/tests/Feature/FrontdeskMessagingIntegrationsTest.php b/tests/Feature/FrontdeskMessagingIntegrationsTest.php new file mode 100644 index 0000000..9bb27be --- /dev/null +++ b/tests/Feature/FrontdeskMessagingIntegrationsTest.php @@ -0,0 +1,241 @@ +withoutMiddleware(EnsurePlatformSession::class); + + config(['billing.api_url' => 'https://billing.test']); + + $this->user = User::create([ + 'public_id' => 'test-user-msg-001', + 'name' => 'Test User', + 'email' => 'msg@example.com', + ]); + + $this->organization = Organization::create([ + 'owner_ref' => $this->user->public_id, + 'name' => 'Test Frontdesk', + 'slug' => 'test-frontdesk-msg', + 'settings' => [ + 'onboarded' => true, + 'plan' => 'pro', + 'plan_expires_at' => now()->addMonth()->toIso8601String(), + ], + ]); + + Member::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'user_ref' => $this->user->public_id, + 'role' => 'org_admin', + ]); + + Branch::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'name' => 'Main', + 'is_active' => true, + ]); + } + + public function test_integrations_page_loads_messaging_cards(): void + { + $this->actingAs($this->user) + ->get(route('frontdesk.integrations.edit')) + ->assertOk() + ->assertSee('Ladill SMS') + ->assertSee('Ladill Bird') + ->assertSee('Outbound webhooks'); + } + + public function test_saving_sms_credentials_encrypts_key(): void + { + Http::fake([ + '*/api/sms/me' => Http::response([ + 'api_key_prefix' => 'lsk_sms_live_abcd', + 'service_id' => 1, + 'status' => 'active', + ]), + '*/api/sms/senders' => Http::response([ + 'data' => [['id' => 1, 'sender_id' => 'FrontA', 'is_default' => true]], + 'default_sender' => 'Ladill', + ]), + ]); + + $plain = 'lsk_sms_live_'.str_repeat('a', 32); + + $this->actingAs($this->user) + ->post(route('frontdesk.integrations.sms.save'), [ + 'sms_api_key' => $plain, + 'sms_sender_id' => 'FrontA', + ]) + ->assertRedirect() + ->assertSessionHas('success'); + + $row = MessagingCredential::query()->where('organization_id', $this->organization->id)->first(); + $this->assertNotNull($row); + $this->assertNotSame($plain, $row->sms_api_key_encrypted); + $this->assertSame($plain, Crypt::decryptString($row->sms_api_key_encrypted)); + $this->assertSame(MessagingCredential::STATUS_VALID, $row->sms_status); + $this->assertSame('FrontA', $row->sms_sender_id); + } + + public function test_invalid_sms_key_is_rejected(): void + { + Http::fake([ + '*/api/sms/me' => Http::response(['error' => 'Invalid or missing API key.'], 401), + ]); + + $this->actingAs($this->user) + ->post(route('frontdesk.integrations.sms.save'), [ + 'sms_api_key' => 'lsk_sms_live_'.str_repeat('b', 32), + 'sms_sender_id' => 'FrontA', + ]) + ->assertRedirect() + ->assertSessionHas('error'); + } + + public function test_host_email_requires_bird_credentials(): void + { + Http::fake([ + 'billing.test/*' => Http::response(['affordable' => true, 'ok' => true]), + ]); + + $host = \App\Models\Host::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'name' => 'No Bird Host', + 'email' => 'nobird@example.com', + 'is_available' => true, + ]); + + $this->actingAs($this->user) + ->post(route('frontdesk.visits.store'), [ + 'full_name' => 'Guest', + 'host_id' => $host->id, + 'visitor_type' => 'visitor', + 'policies_accepted' => '1', + ]) + ->assertRedirect(); + + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/api/smtp/send')); + } + + public function test_host_email_uses_customer_bird_relay(): void + { + $plain = 'lsk_live_'.str_repeat('d', 32); + MessagingCredential::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'bird_api_key_encrypted' => Crypt::encryptString($plain), + 'bird_api_key_prefix' => substr($plain, 0, 16), + 'bird_from_email' => 'frontdesk@example.test', + 'bird_from_name' => 'Frontdesk', + 'bird_status' => MessagingCredential::STATUS_VALID, + 'bird_validated_at' => now(), + ]); + + Http::fake([ + 'billing.test/*' => Http::response(['affordable' => true, 'ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true, 'message_id' => 'x']), + ]); + + $host = \App\Models\Host::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'name' => 'Bird Host', + 'email' => 'host@example.com', + 'is_available' => true, + ]); + + $this->actingAs($this->user) + ->post(route('frontdesk.visits.store'), [ + 'full_name' => 'Guest', + 'host_id' => $host->id, + 'visitor_type' => 'visitor', + 'policies_accepted' => '1', + ]) + ->assertRedirect(); + + Http::assertSent(function ($request) use ($plain) { + return str_contains($request->url(), '/api/smtp/send') + && $request->hasHeader('Authorization', 'Bearer '.$plain) + && $request['from'] === 'frontdesk@example.test' + && $request['from_name'] === 'Frontdesk'; + }); + + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/debit')); + } + + public function test_host_sms_uses_customer_relay_key(): void + { + $plain = 'lsk_sms_live_'.str_repeat('c', 32); + MessagingCredential::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'sms_api_key_encrypted' => Crypt::encryptString($plain), + 'sms_api_key_prefix' => substr($plain, 0, 16), + 'sms_sender_id' => 'FrontA', + 'sms_status' => MessagingCredential::STATUS_VALID, + 'sms_validated_at' => now(), + ]); + + $this->organization->update([ + 'settings' => array_merge($this->organization->settings ?? [], [ + 'notification_channels' => ['sms'], + ]), + ]); + + Http::fake([ + 'billing.test/*' => Http::response(['affordable' => true, 'ok' => true]), + '*/api/sms/send' => Http::response(['success' => true, 'message_id' => 1]), + ]); + + $host = \App\Models\Host::create([ + 'owner_ref' => $this->user->public_id, + 'organization_id' => $this->organization->id, + 'name' => 'SMS Host', + 'phone' => '+233201111111', + 'is_available' => true, + ]); + + $this->actingAs($this->user) + ->post(route('frontdesk.visits.store'), [ + 'full_name' => 'Guest', + 'host_id' => $host->id, + 'visitor_type' => 'visitor', + 'policies_accepted' => '1', + ]) + ->assertRedirect(); + + Http::assertSent(function ($request) use ($plain) { + return str_contains($request->url(), '/api/sms/send') + && $request->hasHeader('Authorization', 'Bearer '.$plain) + && $request['sender_id'] === 'FrontA'; + }); + + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/debit')); + } +} diff --git a/tests/Feature/FrontdeskNotificationBillingTest.php b/tests/Feature/FrontdeskNotificationBillingTest.php index f21eee1..7fda0a3 100644 --- a/tests/Feature/FrontdeskNotificationBillingTest.php +++ b/tests/Feature/FrontdeskNotificationBillingTest.php @@ -6,14 +6,14 @@ use App\Http\Middleware\EnsurePlatformSession; use App\Models\Branch; use App\Models\Host; use App\Models\Member; +use App\Models\MessagingCredential; use App\Models\NotificationUsage; use App\Models\Organization; use App\Models\User; -use App\Models\Visit; use App\Notifications\FrontdeskAlertNotification; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Notification; use Tests\TestCase; @@ -25,6 +25,8 @@ class FrontdeskNotificationBillingTest extends TestCase protected Organization $organization; + protected string $birdKey; + protected function setUp(): void { parent::setUp(); @@ -63,14 +65,26 @@ class FrontdeskNotificationBillingTest extends TestCase 'name' => 'HQ', 'is_active' => true, ]); + + $this->birdKey = 'lsk_live_'.str_repeat('a', 32); + MessagingCredential::create([ + 'owner_ref' => $this->owner->public_id, + 'organization_id' => $this->organization->id, + 'bird_api_key_encrypted' => Crypt::encryptString($this->birdKey), + 'bird_api_key_prefix' => substr($this->birdKey, 0, 16), + 'bird_from_email' => 'notify@example.test', + 'bird_from_name' => 'Notify Org', + 'bird_status' => MessagingCredential::STATUS_VALID, + 'bird_validated_at' => now(), + ]); } public function test_host_email_notification_without_ladill_user_link(): void { - Mail::fake(); Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => true]), 'billing.test/debit' => Http::response(['ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true]), ]); $host = Host::create([ @@ -90,7 +104,8 @@ class FrontdeskNotificationBillingTest extends TestCase ]) ->assertRedirect(); - Mail::assertSent(\App\Mail\ContactMessageMail::class); + Http::assertSent(fn ($request) => str_contains($request->url(), '/api/smtp/send')); + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/debit')); $usage = NotificationUsage::where('organization_id', $this->organization->id)->first(); $this->assertNotNull($usage); @@ -98,12 +113,12 @@ class FrontdeskNotificationBillingTest extends TestCase $this->assertSame(0, $usage->email_charged_minor); } - public function test_paid_email_charges_wallet_after_free_allowance(): void + public function test_customer_email_skips_wallet_debit_after_free_allowance(): void { - Mail::fake(); Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => true]), 'billing.test/debit' => Http::response(['ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true]), ]); NotificationUsage::create([ @@ -132,16 +147,17 @@ class FrontdeskNotificationBillingTest extends TestCase ]) ->assertRedirect(); - Http::assertSent(fn ($request) => str_contains($request->url(), '/debit')); + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/debit')); $usage = NotificationUsage::where('organization_id', $this->organization->id)->first(); $this->assertSame(101, $usage->email_count); - $this->assertGreaterThan(0, $usage->email_charged_minor); + $this->assertSame(0, $usage->email_charged_minor); } - public function test_insufficient_balance_skips_host_email(): void + public function test_missing_bird_credentials_skips_host_email(): void { - Mail::fake(); + MessagingCredential::query()->where('organization_id', $this->organization->id)->delete(); + Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => false]), ]); @@ -169,15 +185,15 @@ class FrontdeskNotificationBillingTest extends TestCase ]) ->assertRedirect(); - Mail::assertNothingSent(); + Http::assertNotSent(fn ($request) => str_contains($request->url(), '/api/smtp/send')); } public function test_kiosk_returns_host_notified_flag(): void { - Mail::fake(); Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => true]), 'billing.test/debit' => Http::response(['ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true]), ]); $host = Host::create([ @@ -226,12 +242,12 @@ class FrontdeskNotificationBillingTest extends TestCase ->assertSee('Upgrade to Pro'); } - public function test_pro_plan_emails_are_unlimited(): void + public function test_pro_plan_emails_record_usage_without_wallet_debit(): void { - Mail::fake(); Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => true]), 'billing.test/debit' => Http::response(['ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true]), ]); $this->organization->update([ @@ -264,7 +280,7 @@ class FrontdeskNotificationBillingTest extends TestCase ]) ->assertRedirect(); - Mail::assertSent(\App\Mail\ContactMessageMail::class); + Http::assertSent(fn ($request) => str_contains($request->url(), '/api/smtp/send')); Http::assertNotSent(fn ($request) => str_contains($request->url(), '/debit')); $usage = NotificationUsage::where('organization_id', $this->organization->id)->first(); @@ -275,10 +291,10 @@ class FrontdeskNotificationBillingTest extends TestCase public function test_linked_user_still_gets_in_app_notification(): void { Notification::fake(); - Mail::fake(); Http::fake([ 'billing.test/can-afford*' => Http::response(['affordable' => true]), 'billing.test/debit' => Http::response(['ok' => true]), + '*/api/smtp/send' => Http::response(['success' => true]), ]); $linkedUser = User::create([