Add per-customer SMS and Bird credentials to Frontdesk Integrations.
Deploy Ladill Frontdesk / deploy (push) Successful in 45s
Deploy Ladill Frontdesk / deploy (push) Successful in 45s
NotificationDispatcher sends via customer relay and skips Frontdesk wallet debit when tenant keys are configured. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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=
|
||||
|
||||
@@ -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'));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToOwner;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
class MessagingCredential extends Model
|
||||
{
|
||||
use BelongsToOwner;
|
||||
|
||||
public const STATUS_VALID = 'valid';
|
||||
|
||||
public const STATUS_INVALID = 'invalid';
|
||||
|
||||
protected $table = 'frontdesk_messaging_credentials';
|
||||
|
||||
protected $fillable = [
|
||||
'owner_ref',
|
||||
'organization_id',
|
||||
'sms_api_key_encrypted',
|
||||
'sms_api_key_prefix',
|
||||
'sms_sender_id',
|
||||
'sms_status',
|
||||
'sms_validated_at',
|
||||
'sms_last_error',
|
||||
'bird_api_key_encrypted',
|
||||
'bird_api_key_prefix',
|
||||
'bird_from_email',
|
||||
'bird_from_name',
|
||||
'bird_status',
|
||||
'bird_validated_at',
|
||||
'bird_last_error',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'sms_api_key_encrypted',
|
||||
'bird_api_key_encrypted',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'sms_validated_at' => '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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Messaging;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CustomerEmailClient
|
||||
{
|
||||
private ?string $lastError = null;
|
||||
|
||||
public function lastError(): ?string
|
||||
{
|
||||
return $this->lastError;
|
||||
}
|
||||
|
||||
private function base(): string
|
||||
{
|
||||
return rtrim((string) config('smtp.customer_relay_url', 'https://ladill.com/api/smtp'), '/');
|
||||
}
|
||||
|
||||
/** @return array{ok: bool, data?: array<string, mixed>, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Messaging;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CustomerSmsClient
|
||||
{
|
||||
private ?string $lastError = null;
|
||||
|
||||
public function lastError(): ?string
|
||||
{
|
||||
return $this->lastError;
|
||||
}
|
||||
|
||||
private function base(): string
|
||||
{
|
||||
return rtrim((string) config('sms.customer_relay_url', 'https://ladill.com/api/sms'), '/');
|
||||
}
|
||||
|
||||
/** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
|
||||
public function me(string $apiKey): array
|
||||
{
|
||||
return $this->get($apiKey, '/me');
|
||||
}
|
||||
|
||||
/** @return array{ok: bool, data?: array<string, mixed>, 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<string, mixed>, 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.'];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Messaging;
|
||||
|
||||
use App\Models\MessagingCredential;
|
||||
use App\Models\Organization;
|
||||
|
||||
class MessagingCredentialsService
|
||||
{
|
||||
public function __construct(
|
||||
private CustomerSmsClient $sms,
|
||||
private CustomerEmailClient $email,
|
||||
) {}
|
||||
|
||||
public function forOrganization(Organization $organization): MessagingCredential
|
||||
{
|
||||
return MessagingCredential::query()->firstOrCreate(
|
||||
['organization_id' => $organization->id],
|
||||
['owner_ref' => $organization->owner_ref],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{ok: bool, error?: string, credential?: MessagingCredential, senders?: list<string>}
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'customer_relay_url' => env('SMS_CUSTOMER_RELAY_URL', 'https://ladill.com/api/sms'),
|
||||
];
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'customer_relay_url' => env('SMTP_CUSTOMER_RELAY_URL', 'https://ladill.com/api/smtp'),
|
||||
];
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('frontdesk_messaging_credentials', function (Blueprint $table) {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,10 @@
|
||||
<x-app-layout title="Integrations">
|
||||
<h1 class="text-xl font-semibold text-slate-900 dark:text-slate-100">Integrations</h1>
|
||||
<p class="text-sm text-slate-500 dark:text-slate-400">Connect Ladill apps and external systems.</p>
|
||||
<p class="text-sm text-slate-500 dark:text-slate-400">Connect Ladill apps, messaging, and external systems.</p>
|
||||
|
||||
@if (! $canManage)
|
||||
<p class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-200">You can view integrations, but only admins can change credentials.</p>
|
||||
@endif
|
||||
|
||||
<section class="mt-6 rounded-2xl border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">Supported Ladill apps</h2>
|
||||
@@ -12,6 +16,111 @@
|
||||
<p class="mt-3 text-xs text-slate-500">Sibling apps authenticate with service API keys and can create visits via <code class="text-xs">POST /api/visits</code> with <code class="text-xs">external_ref</code> for idempotency.</p>
|
||||
</section>
|
||||
|
||||
<div class="mt-6 space-y-6 max-w-2xl">
|
||||
<section class="rounded-2xl border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">Ladill SMS</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
Connect your <a href="https://sms.ladill.com" target="_blank" rel="noopener" class="text-indigo-600 underline dark:text-indigo-400">Ladill SMS</a>
|
||||
API key so host SMS alerts bill your SMS wallet and send under your sender ID.
|
||||
</p>
|
||||
|
||||
@if ($credential->hasValidSms())
|
||||
<div class="mt-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-200">
|
||||
Connected · key {{ $credential->sms_api_key_prefix }}… · sender <strong>{{ $credential->sms_sender_id }}</strong>
|
||||
@if ($credential->sms_validated_at)
|
||||
· validated {{ $credential->sms_validated_at->diffForHumans() }}
|
||||
@endif
|
||||
</div>
|
||||
@elseif ($credential->sms_status === \App\Models\MessagingCredential::STATUS_INVALID)
|
||||
<div class="mt-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-200">
|
||||
{{ $credential->sms_last_error ?: 'SMS credentials are invalid.' }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($canManage)
|
||||
<form method="POST" action="{{ route('frontdesk.integrations.sms.save') }}" class="mt-4 space-y-4">
|
||||
@csrf
|
||||
<div>
|
||||
<label class="block text-sm font-medium">SMS API key</label>
|
||||
<input type="password" name="sms_api_key" autocomplete="off" required
|
||||
placeholder="lsk_sms_live_…"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm dark:border-slate-600 dark:bg-slate-800">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium">Sender ID</label>
|
||||
<input type="text" name="sms_sender_id" maxlength="11" required
|
||||
value="{{ old('sms_sender_id', $credential->sms_sender_id) }}"
|
||||
placeholder="Approved sender ID"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 text-sm dark:border-slate-600 dark:bg-slate-800">
|
||||
<p class="mt-1 text-xs text-slate-500">Must match an approved sender ID on your SMS service.</p>
|
||||
</div>
|
||||
<button type="submit" class="btn-primary">Validate & save SMS</button>
|
||||
</form>
|
||||
@if ($credential->sms_api_key_encrypted || $credential->hasValidSms())
|
||||
<form method="POST" action="{{ route('frontdesk.integrations.sms.disconnect') }}" class="mt-3" onsubmit="return confirm('Disconnect Ladill SMS?')">
|
||||
@csrf
|
||||
<button type="submit" class="text-sm text-rose-700 hover:underline dark:text-rose-400">Disconnect SMS</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<section class="rounded-2xl border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">Ladill Bird</h2>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
Connect your <a href="https://bird.ladill.com" target="_blank" rel="noopener" class="text-indigo-600 underline dark:text-indigo-400">Ladill Bird</a>
|
||||
API key so host email alerts bill your Bird wallet and send from your domain.
|
||||
</p>
|
||||
|
||||
@if ($credential->hasValidBird())
|
||||
<div class="mt-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-200">
|
||||
Connected · key {{ $credential->bird_api_key_prefix }}… · from
|
||||
<strong>{{ $credential->bird_from_name ? $credential->bird_from_name.' <'.$credential->bird_from_email.'>' : $credential->bird_from_email }}</strong>
|
||||
@if ($credential->bird_validated_at)
|
||||
· validated {{ $credential->bird_validated_at->diffForHumans() }}
|
||||
@endif
|
||||
</div>
|
||||
@elseif ($credential->bird_status === \App\Models\MessagingCredential::STATUS_INVALID)
|
||||
<div class="mt-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-200">
|
||||
{{ $credential->bird_last_error ?: 'Bird credentials are invalid.' }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($canManage)
|
||||
<form method="POST" action="{{ route('frontdesk.integrations.bird.save') }}" class="mt-4 space-y-4">
|
||||
@csrf
|
||||
<div>
|
||||
<label class="block text-sm font-medium">Bird API key</label>
|
||||
<input type="password" name="bird_api_key" autocomplete="off" required
|
||||
placeholder="lsk_live_…"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 font-mono text-sm dark:border-slate-600 dark:bg-slate-800">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium">From email</label>
|
||||
<input type="email" name="bird_from_email" required
|
||||
value="{{ old('bird_from_email', $credential->bird_from_email) }}"
|
||||
placeholder="frontdesk@yourdomain.com"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 text-sm dark:border-slate-600 dark:bg-slate-800">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium">From name</label>
|
||||
<input type="text" name="bird_from_name" maxlength="100"
|
||||
value="{{ old('bird_from_name', $credential->bird_from_name) }}"
|
||||
placeholder="{{ $organization->name }}"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 text-sm dark:border-slate-600 dark:bg-slate-800">
|
||||
</div>
|
||||
<button type="submit" class="btn-primary">Validate & save Bird</button>
|
||||
</form>
|
||||
@if ($credential->bird_api_key_encrypted || $credential->hasValidBird())
|
||||
<form method="POST" action="{{ route('frontdesk.integrations.bird.disconnect') }}" class="mt-3" onsubmit="return confirm('Disconnect Ladill Bird?')">
|
||||
@csrf
|
||||
<button type="submit" class="text-sm text-rose-700 hover:underline dark:text-rose-400">Disconnect Bird</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@if ($canManage)
|
||||
<form method="POST" action="{{ route('frontdesk.integrations.update') }}" class="mt-6 max-w-2xl space-y-6">
|
||||
@csrf @method('PUT')
|
||||
@@ -39,12 +148,12 @@
|
||||
</div>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-sm"><input type="checkbox" name="webhook_active" value="1" @checked(old('webhook_active', $webhook?->is_active ?? true))> Active</label>
|
||||
<button type="submit" class="btn-primary">Save integrations</button>
|
||||
<button type="submit" class="btn-primary">Save webhooks</button>
|
||||
</section>
|
||||
</form>
|
||||
@endif
|
||||
|
||||
<section class="mt-6 rounded-2xl border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
|
||||
<section class="mt-6 max-w-2xl rounded-2xl border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900">
|
||||
<h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">Calendar feed (iCal)</h2>
|
||||
<p class="mt-2 text-sm text-slate-600 dark:text-slate-300">Subscribe to scheduled visits in Outlook, Google Calendar, or Apple Calendar.</p>
|
||||
<code class="mt-3 block break-all rounded-lg bg-slate-50 p-3 text-xs dark:bg-slate-800">{{ $icalUrl }}</code>
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\EnsurePlatformSession;
|
||||
use App\Models\Branch;
|
||||
use App\Models\Member;
|
||||
use App\Models\MessagingCredential;
|
||||
use App\Models\Organization;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class FrontdeskMessagingIntegrationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected User $user;
|
||||
|
||||
protected Organization $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->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'));
|
||||
}
|
||||
}
|
||||
@@ -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([
|
||||
|
||||
Reference in New Issue
Block a user