Add settings-gated appointment notifications and fix Bird key validation.
Deploy Ladill Care / deploy (push) Successful in 58s

Patients can be SMS/email notified on booking and video schedule when enabled in Settings. Bird validation now accepts only lsk_live_ keys, strips paste artifacts, and surfaces the platform error.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
isaacclad
2026-07-13 13:31:28 +00:00
co-authored by Cursor
parent 7c33432dc9
commit d13d460e32
10 changed files with 625 additions and 15 deletions
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Appointment;
use App\Services\Care\AppointmentPatientNotifier;
use App\Services\Care\AuditLogger;
use App\Services\Meet\MeetClient;
use Illuminate\Http\RedirectResponse;
@@ -14,7 +15,7 @@ class AppointmentMeetController extends Controller
{
use ScopesToAccount;
public function schedule(Request $request, Appointment $appointment): RedirectResponse
public function schedule(Request $request, Appointment $appointment, AppointmentPatientNotifier $notifier): RedirectResponse
{
$this->authorizeAbility($request, 'appointments.manage');
$this->authorizeOwner($request, $appointment);
@@ -27,8 +28,14 @@ class AppointmentMeetController extends Controller
$appointment->loadMissing('patient');
$patient = $appointment->patient;
$owner = $this->ownerRef($request);
$organization = $this->organization($request);
$user = $request->user();
$inviteEmails = [];
if ($notifier->shouldInvitePatientEmailViaMeet($organization)) {
$inviteEmails = array_values(array_filter([(string) $patient->email]));
}
$response = MeetClient::for($owner)->createRoom([
'title' => 'Video visit — '.$patient->fullName(),
'description' => $appointment->reason,
@@ -42,7 +49,7 @@ class AppointmentMeetController extends Controller
'entity_type' => 'appointment',
'entity_id' => $appointment->uuid,
],
'invite_emails' => array_values(array_filter([$patient->email])),
'invite_emails' => $inviteEmails,
]);
$appointment->update([
@@ -52,20 +59,29 @@ class AppointmentMeetController extends Controller
AuditLogger::record($owner, 'appointment.meet_scheduled', $appointment->organization_id, $owner, Appointment::class, $appointment->id);
$notifier->notifyVideoScheduled($organization, $appointment->fresh(['patient', 'branch']));
return redirect()->route('care.appointments.show', $appointment)
->with('success', 'Video visit scheduled. The patient will receive a join link.');
->with('success', 'Video visit scheduled.'.($this->notifyHint($organization, $notifier)));
}
public function start(Request $request, Appointment $appointment): RedirectResponse
public function start(Request $request, Appointment $appointment, AppointmentPatientNotifier $notifier): RedirectResponse
{
$this->authorizeAbility($request, 'consultations.manage');
$this->authorizeOwner($request, $appointment);
$owner = $this->ownerRef($request);
$organization = $this->organization($request);
$appointment->loadMissing('patient');
$user = $request->user();
$createdRoom = false;
if (! $appointment->meet_room_uuid) {
$inviteEmails = [];
if ($notifier->shouldInvitePatientEmailViaMeet($organization)) {
$inviteEmails = array_values(array_filter([(string) $appointment->patient->email]));
}
$response = MeetClient::for($owner)->createRoom([
'title' => 'Video visit — '.$appointment->patient->fullName(),
'description' => $appointment->reason,
@@ -76,17 +92,34 @@ class AppointmentMeetController extends Controller
'entity_type' => 'appointment',
'entity_id' => $appointment->uuid,
],
'invite_emails' => array_values(array_filter([$appointment->patient->email])),
'invite_emails' => $inviteEmails,
]);
$appointment->update([
'meet_room_uuid' => data_get($response, 'room.uuid'),
'meet_join_url' => data_get($response, 'join_url'),
]);
$createdRoom = true;
}
if ($createdRoom) {
$notifier->notifyVideoScheduled($organization, $appointment->fresh(['patient', 'branch']));
}
$start = MeetClient::for($owner)->startRoom((string) $appointment->meet_room_uuid, $owner);
return redirect()->away((string) (data_get($start, 'join_url') ?: $appointment->meet_join_url));
}
private function notifyHint($organization, AppointmentPatientNotifier $notifier): string
{
$sms = $notifier->organizationWants($organization, AppointmentPatientNotifier::SETTING_VIDEO_SMS);
$email = $notifier->organizationWants($organization, AppointmentPatientNotifier::SETTING_VIDEO_EMAIL);
if ($sms || $email) {
return ' Patient notification settings will be applied.';
}
return ' Enable video notifications in Settings to alert the patient.';
}
}
@@ -5,8 +5,10 @@ namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Branch;
use App\Services\Care\AppointmentPatientNotifier;
use App\Services\Care\AuditLogger;
use App\Services\Care\CarePermissions;
use App\Services\Messaging\MessagingCredentialsService;
use App\Services\Queue\QueueClient;
use App\Support\OrganizationBranding;
use Illuminate\Http\RedirectResponse;
@@ -17,11 +19,12 @@ class SettingsController 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);
$canManage = app(CarePermissions::class)->can($this->member($request), 'settings.manage');
$credential = $credentials->forOrganization($organization);
$branchCount = Branch::owned($this->ownerRef($request))
->where('organization_id', $organization->id)
@@ -31,6 +34,8 @@ class SettingsController extends Controller
'organization' => $organization,
'canManage' => $canManage,
'branchCount' => $branchCount,
'messagingSmsReady' => $credential->hasValidSms(),
'messagingEmailReady' => $credential->hasValidBird(),
'facilityTypes' => [
'clinic' => 'Clinic',
'hospital' => 'Hospital',
@@ -53,6 +58,10 @@ class SettingsController extends Controller
'logo' => ['nullable', 'image', 'mimes:jpeg,png,jpg,webp,svg', 'max:2048'],
'remove_logo' => ['nullable', 'boolean'],
'queue_integration_enabled' => ['nullable', 'boolean'],
'notify_appointment_booked_sms' => ['nullable', 'boolean'],
'notify_appointment_booked_email' => ['nullable', 'boolean'],
'notify_video_scheduled_sms' => ['nullable', 'boolean'],
'notify_video_scheduled_email' => ['nullable', 'boolean'],
]);
$settings = $organization->settings ?? [];
@@ -60,9 +69,13 @@ class SettingsController extends Controller
$settings['facility_type'] = $validated['facility_type'];
$wantsQueue = $request->boolean('queue_integration_enabled');
$hadQueue = (bool) data_get($settings, 'queue_integration_enabled', false);
$settings['queue_integration_enabled'] = $wantsQueue;
$settings[AppointmentPatientNotifier::SETTING_BOOKED_SMS] = $request->boolean('notify_appointment_booked_sms');
$settings[AppointmentPatientNotifier::SETTING_BOOKED_EMAIL] = $request->boolean('notify_appointment_booked_email');
$settings[AppointmentPatientNotifier::SETTING_VIDEO_SMS] = $request->boolean('notify_video_scheduled_sms');
$settings[AppointmentPatientNotifier::SETTING_VIDEO_EMAIL] = $request->boolean('notify_video_scheduled_email');
if ($wantsQueue && $queue->configured()) {
$branch = Branch::owned($owner)->where('organization_id', $organization->id)->orderBy('name')->first();
try {
@@ -0,0 +1,241 @@
<?php
namespace App\Services\Care;
use App\Models\Appointment;
use App\Models\Organization;
use App\Models\Patient;
use App\Services\Messaging\CustomerEmailClient;
use App\Services\Messaging\CustomerSmsClient;
use App\Services\Messaging\MessagingCredentialsService;
use App\Support\OrganizationBranding;
use Illuminate\Support\Facades\Log;
class AppointmentPatientNotifier
{
public const SETTING_BOOKED_SMS = 'notify_appointment_booked_sms';
public const SETTING_BOOKED_EMAIL = 'notify_appointment_booked_email';
public const SETTING_VIDEO_SMS = 'notify_video_scheduled_sms';
public const SETTING_VIDEO_EMAIL = 'notify_video_scheduled_email';
public function __construct(
private MessagingCredentialsService $credentials,
private CustomerSmsClient $sms,
private CustomerEmailClient $email,
) {}
public function organizationWants(Organization $organization, string $setting): bool
{
return (bool) data_get($organization->settings, $setting, false);
}
public function notifyAppointmentBooked(Organization $organization, Appointment $appointment): void
{
$appointment->loadMissing(['patient', 'branch', 'practitioner']);
$patient = $appointment->patient;
if (! $patient) {
return;
}
$when = $appointment->scheduled_at?->timezone($organization->timezone)->format('D, d M Y \a\t H:i') ?? 'the scheduled time';
$branch = $appointment->branch?->name ?? $organization->name;
$practitioner = $appointment->practitioner?->name;
if ($this->organizationWants($organization, self::SETTING_BOOKED_SMS)) {
$parts = [
$organization->name.': appointment confirmed for '.$when.' at '.$branch.'.',
];
if ($practitioner) {
$parts[] = 'With '.$practitioner.'.';
}
$parts[] = 'Reply or call the clinic if you need to reschedule.';
$this->sendSms($organization, $patient, implode(' ', $parts), 'appointment.booked_sms');
}
if ($this->organizationWants($organization, self::SETTING_BOOKED_EMAIL)) {
$lines = [
'Hello '.$patient->fullName().',',
'',
'Your appointment at '.$organization->name.' has been scheduled.',
'',
'When: '.$when,
'Where: '.$branch,
];
if ($practitioner) {
$lines[] = 'With: '.$practitioner;
}
if ($appointment->reason) {
$lines[] = 'Reason: '.$appointment->reason;
}
$lines[] = '';
$lines[] = 'If you need to reschedule, please contact the clinic.';
$this->sendEmail(
$organization,
$patient,
'Appointment confirmed — '.$organization->name,
implode("\n", $lines),
'appointment.booked_email',
);
}
}
public function notifyVideoScheduled(Organization $organization, Appointment $appointment): void
{
$appointment->loadMissing(['patient', 'branch']);
$patient = $appointment->patient;
$joinUrl = (string) ($appointment->meet_join_url ?? '');
if (! $patient || $joinUrl === '') {
return;
}
$when = $appointment->scheduled_at?->timezone($organization->timezone)->format('D, d M Y \a\t H:i') ?? 'your appointment time';
if ($this->organizationWants($organization, self::SETTING_VIDEO_SMS)) {
$this->sendSms(
$organization,
$patient,
$organization->name.': video visit on '.$when.'. Join: '.$joinUrl,
'appointment.video_sms',
);
}
// Video email is delivered by Ladill Meet via invite_emails when the setting is on.
// Also send a Care-branded copy when Bird is connected so branding matches other notices.
if ($this->organizationWants($organization, self::SETTING_VIDEO_EMAIL)) {
$lines = [
'Hello '.$patient->fullName().',',
'',
'A video visit has been scheduled with '.$organization->name.'.',
'',
'When: '.$when,
'Join link: '.$joinUrl,
'',
'Open the link at the appointment time to join.',
];
$this->sendEmail(
$organization,
$patient,
'Video visit — '.$organization->name,
implode("\n", $lines),
'appointment.video_email',
);
}
}
/**
* When true, Meet should also email the patient join invite.
* Prefer Care-branded email when Bird is connected; otherwise fall back to Meet invites.
*/
public function shouldInvitePatientEmailViaMeet(Organization $organization): bool
{
if (! $this->organizationWants($organization, self::SETTING_VIDEO_EMAIL)) {
return false;
}
$credential = $this->credentials->forOrganization($organization);
// Avoid double emails when Care Bird can send the branded notice.
return ! $credential->hasValidBird();
}
private function sendSms(Organization $organization, Patient $patient, string $message, string $auditAction): void
{
$phone = trim((string) $patient->phone);
if ($phone === '') {
return;
}
try {
$credential = $this->credentials->forOrganization($organization);
if (! $credential->hasValidSms()) {
return;
}
$apiKey = $credential->smsApiKey();
if (! $apiKey) {
return;
}
$sent = $this->sms->send($apiKey, $phone, $message, (string) $credential->sms_sender_id);
AuditLogger::record(
$organization->owner_ref,
$sent ? $auditAction.'_sent' : $auditAction.'_failed',
$organization->id,
$organization->owner_ref,
Patient::class,
$patient->id,
[
'to' => $phone,
'error' => $sent ? null : $this->sms->lastError(),
],
);
} catch (\Throwable $e) {
Log::warning('Care appointment SMS notification failed', [
'organization_id' => $organization->id,
'patient_id' => $patient->id,
'error' => $e->getMessage(),
]);
}
}
private function sendEmail(
Organization $organization,
Patient $patient,
string $subject,
string $body,
string $auditAction,
): void {
$to = (string) $patient->email;
if (! filter_var($to, FILTER_VALIDATE_EMAIL)) {
return;
}
try {
$credential = $this->credentials->forOrganization($organization);
if (! $credential->hasValidBird()) {
return;
}
$apiKey = $credential->birdApiKey();
if (! $apiKey) {
return;
}
$html = OrganizationBranding::wrapEmailHtml(nl2br(e($body)), $organization);
$sent = $this->email->send(
$apiKey,
(string) $credential->bird_from_email,
$credential->bird_from_name,
$to,
$subject,
$html,
$body,
);
AuditLogger::record(
$organization->owner_ref,
$sent ? $auditAction.'_sent' : $auditAction.'_failed',
$organization->id,
$organization->owner_ref,
Patient::class,
$patient->id,
[
'to' => $to,
'subject' => $subject,
'error' => $sent ? null : $this->email->lastError(),
],
);
} catch (\Throwable $e) {
Log::warning('Care appointment email notification failed', [
'organization_id' => $organization->id,
'patient_id' => $patient->id,
'error' => $e->getMessage(),
]);
}
}
}
+5 -1
View File
@@ -18,6 +18,7 @@ class AppointmentService
{
public function __construct(
protected VisitService $visits,
protected AppointmentPatientNotifier $notifier,
) {}
public function queryForOrganization(string $ownerRef, int $organizationId): Builder
@@ -101,7 +102,10 @@ class AppointmentService
AuditLogger::record($ownerRef, 'appointment.created', $organization->id, $actorRef, Appointment::class, $appointment->id);
return $appointment->load(['patient', 'practitioner', 'branch']);
$appointment = $appointment->load(['patient', 'practitioner', 'branch']);
$this->notifier->notifyAppointmentBooked($organization, $appointment);
return $appointment;
}
/**
@@ -27,7 +27,15 @@ class CustomerEmailClient
->get($this->base().'/me');
if ($res->status() === 401) {
return ['ok' => false, 'error' => 'Invalid Bird API key.', 'status' => 401];
$platformError = trim((string) ($res->json('error') ?: ''));
return [
'ok' => false,
'error' => $platformError !== ''
? $platformError
: 'Invalid Bird API key. Use the HTTP API key from bird.ladill.com (starts with lsk_live_).',
'status' => 401,
];
}
if ($res->failed()) {
@@ -25,7 +25,7 @@ class MessagingCredentialsService
*/
public function validateAndSaveSms(Organization $organization, string $apiKey, string $senderId): array
{
$apiKey = trim($apiKey);
$apiKey = $this->sanitizeApiKey($apiKey);
$senderId = trim($senderId);
if (! str_starts_with($apiKey, 'lsk_sms_live_')) {
@@ -83,12 +83,13 @@ class MessagingCredentialsService
*/
public function validateAndSaveBird(Organization $organization, string $apiKey, string $fromEmail, ?string $fromName): array
{
$apiKey = trim($apiKey);
$apiKey = $this->sanitizeApiKey($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_.'];
// Platform SMTP relay only accepts HTTP API keys issued as lsk_live_…
if (! str_starts_with($apiKey, 'lsk_live_')) {
return ['ok' => false, 'error' => 'Bird API keys must start with lsk_live_. Copy the HTTP API key from bird.ladill.com (not the mailbox password).'];
}
if (! filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
@@ -97,13 +98,14 @@ class MessagingCredentialsService
$me = $this->email->me($apiKey);
if (! ($me['ok'] ?? false)) {
$error = $me['error'] ?? 'Invalid Bird API key.';
$credential = $this->forOrganization($organization);
$credential->update([
'bird_status' => MessagingCredential::STATUS_INVALID,
'bird_last_error' => $me['error'] ?? 'Invalid Bird API key.',
'bird_last_error' => $error,
]);
return ['ok' => false, 'error' => $me['error'] ?? 'Invalid Bird API key.', 'credential' => $credential];
return ['ok' => false, 'error' => $error, 'credential' => $credential];
}
$domains = collect($me['data']['verified_domains'] ?? [])->map(fn ($d) => strtolower((string) $d))->all();
@@ -164,4 +166,13 @@ class MessagingCredentialsService
return $credential->fresh();
}
private function sanitizeApiKey(string $apiKey): string
{
$apiKey = trim($apiKey);
// Strip zero-width / BOM / whitespace that often sneaks in on paste.
$cleaned = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}\s]+/u', '', $apiKey);
return is_string($cleaned) ? $cleaned : $apiKey;
}
}
@@ -87,6 +87,7 @@
<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">
<p class="mt-1 text-xs text-slate-500">Use the HTTP API key from <a href="https://bird.ladill.com" target="_blank" rel="noopener" class="underline">bird.ladill.com</a> (starts with <code>lsk_live_</code>). Do not use the mailbox password.</p>
</div>
<div>
<label class="block text-sm font-medium text-slate-700">From email</label>
@@ -53,6 +53,64 @@
<a href="{{ route('care.integrations') }}" class="text-sm font-medium text-teal-700 underline">Open messaging integrations </a>
</x-settings.card>
<x-settings.card title="Patient notifications" description="Automatically notify patients when appointments are booked or video visits are scheduled. Requires connected SMS / Bird credentials.">
<div class="space-y-4 text-sm">
<div>
<p class="font-medium text-slate-800">When an appointment is booked</p>
<div class="mt-2 space-y-2">
<label class="flex items-start gap-2">
<input type="checkbox" name="notify_appointment_booked_sms" value="1"
@checked(old('notify_appointment_booked_sms', data_get($organization->settings, 'notify_appointment_booked_sms')))
class="mt-0.5">
<span>
Send SMS confirmation
@unless ($messagingSmsReady)
<span class="block text-xs text-amber-700">Connect SMS in Integrations before this can send.</span>
@endunless
</span>
</label>
<label class="flex items-start gap-2">
<input type="checkbox" name="notify_appointment_booked_email" value="1"
@checked(old('notify_appointment_booked_email', data_get($organization->settings, 'notify_appointment_booked_email')))
class="mt-0.5">
<span>
Send email confirmation
@unless ($messagingEmailReady)
<span class="block text-xs text-amber-700">Connect Bird email in Integrations before this can send.</span>
@endunless
</span>
</label>
</div>
</div>
<div>
<p class="font-medium text-slate-800">When a video visit is scheduled</p>
<div class="mt-2 space-y-2">
<label class="flex items-start gap-2">
<input type="checkbox" name="notify_video_scheduled_sms" value="1"
@checked(old('notify_video_scheduled_sms', data_get($organization->settings, 'notify_video_scheduled_sms')))
class="mt-0.5">
<span>
Send SMS with join link
@unless ($messagingSmsReady)
<span class="block text-xs text-amber-700">Connect SMS in Integrations before this can send.</span>
@endunless
</span>
</label>
<label class="flex items-start gap-2">
<input type="checkbox" name="notify_video_scheduled_email" value="1"
@checked(old('notify_video_scheduled_email', data_get($organization->settings, 'notify_video_scheduled_email')))
class="mt-0.5">
<span>
Send email with join link
<span class="block text-xs text-slate-500">Uses Bird when connected; otherwise Meet emails the invite.</span>
</span>
</label>
</div>
</div>
</div>
</x-settings.card>
<x-settings.card title="Integrations" description="Manage service queues and counters in Care. You must also enable Care integration in Ladill Queue settings.">
<label class="flex items-center gap-2 text-sm">
<input type="checkbox" name="queue_integration_enabled" value="1" @checked(data_get($organization->settings, 'queue_integration_enabled'))>
@@ -0,0 +1,186 @@
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnsurePlatformSession;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Member;
use App\Models\MessagingCredential;
use App\Models\Organization;
use App\Models\Patient;
use App\Models\Practitioner;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class CareAppointmentNotificationTest extends TestCase
{
use RefreshDatabase;
protected User $user;
protected Organization $organization;
protected Branch $branch;
protected Patient $patient;
protected Practitioner $practitioner;
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware(EnsurePlatformSession::class);
$this->user = User::create([
'public_id' => 'test-user-notify',
'name' => 'Admin',
'email' => 'admin-notify@example.com',
]);
$this->organization = Organization::create([
'owner_ref' => $this->user->public_id,
'name' => 'Notify Clinic',
'slug' => 'notify-clinic',
'timezone' => 'UTC',
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'notify_appointment_booked_sms' => true,
'notify_appointment_booked_email' => true,
],
]);
Member::create([
'owner_ref' => $this->user->public_id,
'organization_id' => $this->organization->id,
'user_ref' => $this->user->public_id,
'role' => 'hospital_admin',
]);
$this->branch = Branch::create([
'owner_ref' => $this->user->public_id,
'organization_id' => $this->organization->id,
'name' => 'Main',
'is_active' => true,
]);
Department::create([
'owner_ref' => $this->user->public_id,
'branch_id' => $this->branch->id,
'name' => 'OPD',
'type' => 'outpatient',
'is_active' => true,
]);
$this->patient = Patient::create([
'uuid' => (string) \Illuminate\Support\Str::uuid(),
'owner_ref' => $this->user->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'patient_number' => 'LC-NOT-00001',
'first_name' => 'Kofi',
'last_name' => 'Mensah',
'phone' => '+233201111111',
'email' => 'kofi@example.com',
]);
$this->practitioner = Practitioner::create([
'owner_ref' => $this->user->public_id,
'organization_id' => $this->organization->id,
'branch_id' => $this->branch->id,
'name' => 'Dr. Asante',
'specialty' => 'GP',
'is_active' => true,
]);
$smsKey = 'lsk_sms_live_'.str_repeat('n', 32);
$birdKey = 'lsk_live_'.str_repeat('n', 32);
MessagingCredential::create([
'owner_ref' => $this->user->public_id,
'organization_id' => $this->organization->id,
'sms_api_key_encrypted' => Crypt::encryptString($smsKey),
'sms_api_key_prefix' => substr($smsKey, 0, 16),
'sms_sender_id' => 'Clinic',
'sms_status' => MessagingCredential::STATUS_VALID,
'sms_validated_at' => now(),
'bird_api_key_encrypted' => Crypt::encryptString($birdKey),
'bird_api_key_prefix' => substr($birdKey, 0, 16),
'bird_from_email' => 'clinic@example.test',
'bird_from_name' => 'Notify Clinic',
'bird_status' => MessagingCredential::STATUS_VALID,
'bird_validated_at' => now(),
]);
}
public function test_booking_sends_sms_and_email_when_enabled(): void
{
Http::fake([
'*/api/sms/send' => Http::response(['success' => true, 'message_id' => 1]),
'*/api/smtp/send' => Http::response(['success' => true, 'message_id' => 'x']),
]);
$this->actingAs($this->user)
->post(route('care.appointments.store'), [
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'practitioner_id' => $this->practitioner->id,
'scheduled_at' => now()->addDay()->format('Y-m-d\TH:i'),
'reason' => 'Check-up',
])
->assertRedirect();
Http::assertSent(fn ($request) => str_contains($request->url(), '/api/sms/send'));
Http::assertSent(fn ($request) => str_contains($request->url(), '/api/smtp/send'));
$this->assertDatabaseHas('care_audit_logs', ['action' => 'appointment.booked_sms_sent']);
$this->assertDatabaseHas('care_audit_logs', ['action' => 'appointment.booked_email_sent']);
}
public function test_booking_skips_notifications_when_disabled(): void
{
$this->organization->update([
'settings' => [
'onboarded' => true,
'facility_type' => 'clinic',
'notify_appointment_booked_sms' => false,
'notify_appointment_booked_email' => false,
],
]);
Http::fake();
$this->actingAs($this->user)
->post(route('care.appointments.store'), [
'branch_id' => $this->branch->id,
'patient_id' => $this->patient->id,
'practitioner_id' => $this->practitioner->id,
'scheduled_at' => now()->addDay()->format('Y-m-d\TH:i'),
])
->assertRedirect();
Http::assertNothingSent();
}
public function test_settings_can_persist_notification_toggles(): void
{
$this->actingAs($this->user)
->put(route('care.settings.update'), [
'name' => 'Notify Clinic',
'timezone' => 'UTC',
'facility_type' => 'clinic',
'notify_appointment_booked_sms' => '1',
'notify_video_scheduled_email' => '1',
])
->assertRedirect()
->assertSessionHas('success');
$this->organization->refresh();
$this->assertTrue((bool) data_get($this->organization->settings, 'notify_appointment_booked_sms'));
$this->assertFalse((bool) data_get($this->organization->settings, 'notify_appointment_booked_email'));
$this->assertTrue((bool) data_get($this->organization->settings, 'notify_video_scheduled_email'));
$this->assertFalse((bool) data_get($this->organization->settings, 'notify_video_scheduled_sms'));
}
}
@@ -218,4 +218,59 @@ class CareMessagingIntegrationsTest extends TestCase
&& $request['from_name'] === 'Clinic';
});
}
public function test_saving_bird_credentials_rejects_acct_prefix(): void
{
$this->actingAs($this->user)
->post(route('care.integrations.bird.save'), [
'bird_api_key' => 'lsk_acct_'.str_repeat('a', 32),
'bird_from_email' => 'clinic@example.test',
'bird_from_name' => 'Clinic',
])
->assertRedirect()
->assertSessionHas('error');
}
public function test_saving_bird_credentials_encrypts_live_key(): void
{
Http::fake([
'*/api/smtp/me' => Http::response([
'api_key_prefix' => 'lsk_live_abcd1234',
'status' => 'active',
'verified_domains' => ['example.test'],
]),
]);
$plain = 'lsk_live_'.str_repeat('e', 32);
$this->actingAs($this->user)
->post(route('care.integrations.bird.save'), [
'bird_api_key' => " {$plain}\n",
'bird_from_email' => 'clinic@example.test',
'bird_from_name' => 'Clinic',
])
->assertRedirect()
->assertSessionHas('success');
$row = MessagingCredential::query()->where('organization_id', $this->organization->id)->first();
$this->assertNotNull($row);
$this->assertSame($plain, Crypt::decryptString($row->bird_api_key_encrypted));
$this->assertSame(MessagingCredential::STATUS_VALID, $row->bird_status);
$this->assertSame('clinic@example.test', $row->bird_from_email);
}
public function test_saving_bird_credentials_surfaces_platform_401(): void
{
Http::fake([
'*/api/smtp/me' => Http::response(['error' => 'Invalid or missing API key.'], 401),
]);
$this->actingAs($this->user)
->post(route('care.integrations.bird.save'), [
'bird_api_key' => 'lsk_live_'.str_repeat('f', 32),
'bird_from_email' => 'clinic@example.test',
])
->assertRedirect()
->assertSessionHas('error', 'Invalid or missing API key.');
}
}