Add per-customer SMS and Bird Integrations for patient messaging.
Deploy Ladill Care / deploy (push) Successful in 37s
Deploy Ladill Care / deploy (push) Successful in 37s
Patient SMS/email now use encrypted tenant keys via the platform relay instead of shared platform Care API keys. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+4
-2
@@ -44,14 +44,16 @@ IDENTITY_API_KEY_CARE=
|
||||
MEET_API_URL=https://meet.ladill.com/api/service/v1
|
||||
MEET_API_KEY_CARE=
|
||||
|
||||
# Ladill SMS (patient messaging — management API on ladill.com)
|
||||
# Ladill SMS (patient messaging uses customer keys via Integrations; platform key optional)
|
||||
SMS_PLATFORM_API_URL=https://ladill.com/api
|
||||
SMS_API_KEY_CARE=
|
||||
SMS_CUSTOMER_RELAY_URL=https://ladill.com/api/sms
|
||||
SMS_DEFAULT_SENDER_ID=Ladill
|
||||
|
||||
# Ladill Bird / SMTP (patient email — management API on ladill.com)
|
||||
# Ladill Bird / SMTP (patient email uses customer keys via Integrations)
|
||||
SMTP_PLATFORM_API_URL=https://ladill.com/api/smtp
|
||||
SMTP_API_KEY_CARE=
|
||||
SMTP_CUSTOMER_RELAY_URL=https://ladill.com/api/smtp
|
||||
CARE_SMTP_FROM=care@ladill.com
|
||||
CARE_SMTP_FROM_NAME="Ladill Care"
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Care;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
|
||||
use App\Services\Care\AuditLogger;
|
||||
use App\Services\Care\CarePermissions;
|
||||
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;
|
||||
|
||||
class IntegrationsController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
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');
|
||||
|
||||
return view('care.integrations.edit', [
|
||||
'organization' => $organization,
|
||||
'canManage' => $canManage,
|
||||
'credential' => $credentials->forOrganization($organization),
|
||||
]);
|
||||
}
|
||||
|
||||
public function saveSms(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
|
||||
$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'],
|
||||
);
|
||||
|
||||
AuditLogger::record(
|
||||
$this->ownerRef($request),
|
||||
($result['ok'] ?? false) ? 'integrations.sms_connected' : 'integrations.sms_failed',
|
||||
$organization->id,
|
||||
$this->ownerRef($request),
|
||||
\App\Models\Organization::class,
|
||||
$organization->id,
|
||||
['prefix' => substr(trim($data['sms_api_key']), 0, 16)],
|
||||
);
|
||||
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
return back()->withInput()->with('error', $result['error'] ?? 'Could not save SMS credentials.');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Ladill SMS connected. Outbound patient SMS 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);
|
||||
|
||||
AuditLogger::record(
|
||||
$this->ownerRef($request),
|
||||
'integrations.sms_disconnected',
|
||||
$organization->id,
|
||||
$this->ownerRef($request),
|
||||
\App\Models\Organization::class,
|
||||
$organization->id,
|
||||
);
|
||||
|
||||
return back()->with('success', 'Ladill SMS disconnected.');
|
||||
}
|
||||
|
||||
public function saveBird(Request $request, MessagingCredentialsService $credentials): RedirectResponse
|
||||
{
|
||||
$this->authorizeAbility($request, 'settings.manage');
|
||||
$organization = $this->organization($request);
|
||||
|
||||
$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,
|
||||
);
|
||||
|
||||
AuditLogger::record(
|
||||
$this->ownerRef($request),
|
||||
($result['ok'] ?? false) ? 'integrations.bird_connected' : 'integrations.bird_failed',
|
||||
$organization->id,
|
||||
$this->ownerRef($request),
|
||||
\App\Models\Organization::class,
|
||||
$organization->id,
|
||||
['prefix' => substr(trim($data['bird_api_key']), 0, 16)],
|
||||
);
|
||||
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
return back()->withInput()->with('error', $result['error'] ?? 'Could not save Bird credentials.');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Ladill Bird connected. Outbound patient email 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);
|
||||
|
||||
AuditLogger::record(
|
||||
$this->ownerRef($request),
|
||||
'integrations.bird_disconnected',
|
||||
$organization->id,
|
||||
$this->ownerRef($request),
|
||||
\App\Models\Organization::class,
|
||||
$organization->id,
|
||||
);
|
||||
|
||||
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'] ?? []);
|
||||
}
|
||||
}
|
||||
@@ -93,9 +93,13 @@ class PatientController extends Controller
|
||||
$dashboard = $this->patients->dashboard($patient);
|
||||
$canManage = app(\App\Services\Care\CarePermissions::class)
|
||||
->can($this->member($request), 'patients.manage');
|
||||
$credential = app(\App\Services\Messaging\MessagingCredentialsService::class)
|
||||
->forOrganization($this->organization($request));
|
||||
|
||||
return view('care.patients.show', array_merge($dashboard, [
|
||||
'canManage' => $canManage,
|
||||
'messagingSmsReady' => $credential->hasValidSms(),
|
||||
'messagingEmailReady' => $credential->hasValidBird(),
|
||||
'genders' => config('care.genders'),
|
||||
'allergySeverities' => config('care.allergy_severities'),
|
||||
'documentTypes' => config('care.document_types'),
|
||||
|
||||
@@ -5,10 +5,11 @@ namespace App\Http\Controllers\Care;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
|
||||
use App\Models\Patient;
|
||||
use App\Services\Billing\PlatformEmailClient;
|
||||
use App\Services\Billing\PlatformSmsClient;
|
||||
use App\Services\Care\AuditLogger;
|
||||
use App\Services\Care\OrganizationResolver;
|
||||
use App\Services\Messaging\CustomerEmailClient;
|
||||
use App\Services\Messaging\CustomerSmsClient;
|
||||
use App\Services\Messaging\MessagingCredentialsService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -16,8 +17,12 @@ class PatientMessageController extends Controller
|
||||
{
|
||||
use ScopesToAccount;
|
||||
|
||||
public function sendEmail(Request $request, Patient $patient, PlatformEmailClient $email): RedirectResponse
|
||||
{
|
||||
public function sendEmail(
|
||||
Request $request,
|
||||
Patient $patient,
|
||||
MessagingCredentialsService $credentials,
|
||||
CustomerEmailClient $email,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'patients.manage');
|
||||
$this->authorizePatient($request, $patient);
|
||||
|
||||
@@ -25,6 +30,16 @@ class PatientMessageController extends Controller
|
||||
return back()->with('error', 'This patient has no valid email on file.');
|
||||
}
|
||||
|
||||
$credential = $credentials->forOrganization($this->organization($request));
|
||||
if (! $credential->hasValidBird()) {
|
||||
return back()->with('error', 'Connect Ladill Bird in Integrations before sending patient email.');
|
||||
}
|
||||
|
||||
$apiKey = $credential->birdApiKey();
|
||||
if (! $apiKey) {
|
||||
return back()->with('error', 'Bird credentials could not be decrypted. Reconnect Bird in Integrations.');
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'subject' => ['required', 'string', 'max:200'],
|
||||
'body' => ['required', 'string', 'max:5000'],
|
||||
@@ -32,7 +47,15 @@ class PatientMessageController extends Controller
|
||||
|
||||
$owner = $this->ownerRef($request);
|
||||
$html = nl2br(e($data['body']));
|
||||
$sent = $email->send($owner, (string) $patient->email, $data['subject'], $html, $data['body']);
|
||||
$sent = $email->send(
|
||||
$apiKey,
|
||||
(string) $credential->bird_from_email,
|
||||
$credential->bird_from_name,
|
||||
(string) $patient->email,
|
||||
$data['subject'],
|
||||
$html,
|
||||
$data['body'],
|
||||
);
|
||||
|
||||
AuditLogger::record(
|
||||
$owner,
|
||||
@@ -55,8 +78,12 @@ class PatientMessageController extends Controller
|
||||
return back()->with('success', 'Email sent to '.$patient->email);
|
||||
}
|
||||
|
||||
public function sendSms(Request $request, Patient $patient, PlatformSmsClient $sms): RedirectResponse
|
||||
{
|
||||
public function sendSms(
|
||||
Request $request,
|
||||
Patient $patient,
|
||||
MessagingCredentialsService $credentials,
|
||||
CustomerSmsClient $sms,
|
||||
): RedirectResponse {
|
||||
$this->authorizeAbility($request, 'patients.manage');
|
||||
$this->authorizePatient($request, $patient);
|
||||
|
||||
@@ -64,12 +91,22 @@ class PatientMessageController extends Controller
|
||||
return back()->with('error', 'This patient has no phone number on file.');
|
||||
}
|
||||
|
||||
$credential = $credentials->forOrganization($this->organization($request));
|
||||
if (! $credential->hasValidSms()) {
|
||||
return back()->with('error', 'Connect Ladill SMS in Integrations before sending patient SMS.');
|
||||
}
|
||||
|
||||
$apiKey = $credential->smsApiKey();
|
||||
if (! $apiKey) {
|
||||
return back()->with('error', 'SMS credentials could not be decrypted. Reconnect SMS in Integrations.');
|
||||
}
|
||||
|
||||
$data = $request->validate([
|
||||
'message' => ['required', 'string', 'max:480'],
|
||||
]);
|
||||
|
||||
$owner = $this->ownerRef($request);
|
||||
$sent = $sms->send($owner, (string) $patient->phone, $data['message']);
|
||||
$sent = $sms->send($apiKey, (string) $patient->phone, $data['message'], (string) $credential->sms_sender_id);
|
||||
|
||||
AuditLogger::record(
|
||||
$owner,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<?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 = 'care_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 $casts = [
|
||||
'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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,6 @@
|
||||
return [
|
||||
'platform_api_url' => env('SMS_PLATFORM_API_URL', 'https://ladill.com/api'),
|
||||
'platform_api_key' => env('SMS_API_KEY_CARE'),
|
||||
'customer_relay_url' => env('SMS_CUSTOMER_RELAY_URL', 'https://ladill.com/api/sms'),
|
||||
'default_sender_id' => env('SMS_DEFAULT_SENDER_ID', 'Ladill'),
|
||||
];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
return [
|
||||
'platform_api_url' => env('SMTP_PLATFORM_API_URL', 'https://ladill.com/api/smtp'),
|
||||
'platform_api_key' => env('SMTP_API_KEY_CARE'),
|
||||
'customer_relay_url' => env('SMTP_CUSTOMER_RELAY_URL', 'https://ladill.com/api/smtp'),
|
||||
'from' => env('CARE_SMTP_FROM', 'care@ladill.com'),
|
||||
'from_name' => env('CARE_SMTP_FROM_NAME', 'Ladill Care'),
|
||||
];
|
||||
|
||||
@@ -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('care_messaging_credentials', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('owner_ref')->index();
|
||||
$table->foreignId('organization_id')->constrained('care_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('care_messaging_credentials');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
<x-app-layout title="Integrations">
|
||||
<x-settings.page title="Messaging integrations">
|
||||
<p class="text-sm text-slate-600">
|
||||
Connect your own <a href="https://sms.ladill.com" target="_blank" rel="noopener" class="text-teal-700 underline">Ladill SMS</a>
|
||||
and <a href="https://bird.ladill.com" target="_blank" rel="noopener" class="text-teal-700 underline">Ladill Bird</a>
|
||||
API keys so patient messages bill your wallets and send under your brand.
|
||||
</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">You can view integrations, but only admins can change credentials.</p>
|
||||
@endif
|
||||
|
||||
<div class="mt-6 space-y-6">
|
||||
<x-settings.card title="Ladill SMS" description="Paste an SMS API key (lsk_sms_live_…) and an approved sender ID from sms.ladill.com.">
|
||||
@if ($credential->hasValidSms())
|
||||
<div class="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
|
||||
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="mb-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800">
|
||||
{{ $credential->sms_last_error ?: 'SMS credentials are invalid.' }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($canManage)
|
||||
<form method="POST" action="{{ route('care.integrations.sms.save') }}" class="space-y-4">
|
||||
@csrf
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-slate-700">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">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-slate-700">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">
|
||||
<p class="mt-1 text-xs text-slate-500">Must match an approved sender ID on your SMS service (or the platform default).</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="submit" class="btn-primary">Validate & save</button>
|
||||
</div>
|
||||
</form>
|
||||
@if ($credential->sms_api_key_encrypted || $credential->hasValidSms())
|
||||
<form method="POST" action="{{ route('care.integrations.sms.disconnect') }}" class="mt-3" onsubmit="return confirm('Disconnect Ladill SMS?')">
|
||||
@csrf
|
||||
<button type="submit" class="text-sm text-rose-700 hover:underline">Disconnect SMS</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
</x-settings.card>
|
||||
|
||||
<x-settings.card title="Ladill Bird" description="Paste a Bird API key (lsk_live_…) plus a from address on a verified domain from bird.ladill.com.">
|
||||
@if ($credential->hasValidBird())
|
||||
<div class="mb-4 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
|
||||
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="mb-4 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800">
|
||||
{{ $credential->bird_last_error ?: 'Bird credentials are invalid.' }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($canManage)
|
||||
<form method="POST" action="{{ route('care.integrations.bird.save') }}" class="space-y-4">
|
||||
@csrf
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-slate-700">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">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-slate-700">From email</label>
|
||||
<input type="email" name="bird_from_email" required
|
||||
value="{{ old('bird_from_email', $credential->bird_from_email) }}"
|
||||
placeholder="clinic@yourdomain.com"
|
||||
class="mt-1 w-full rounded-lg border-slate-300 text-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-slate-700">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">
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="submit" class="btn-primary">Validate & save</button>
|
||||
</div>
|
||||
</form>
|
||||
@if ($credential->bird_api_key_encrypted || $credential->hasValidBird())
|
||||
<form method="POST" action="{{ route('care.integrations.bird.disconnect') }}" class="mt-3" onsubmit="return confirm('Disconnect Ladill Bird?')">
|
||||
@csrf
|
||||
<button type="submit" class="text-sm text-rose-700 hover:underline">Disconnect Bird</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
</x-settings.card>
|
||||
</div>
|
||||
|
||||
<p class="mt-6 text-sm text-slate-500">
|
||||
<a href="{{ route('care.settings') }}" class="text-teal-700 underline">← Back to facility settings</a>
|
||||
</p>
|
||||
</x-settings.page>
|
||||
</x-app-layout>
|
||||
@@ -137,7 +137,18 @@
|
||||
@if ($canManage)
|
||||
<section class="rounded-2xl border border-slate-200 bg-white p-6" x-data="{ tab: 'sms' }">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wide text-slate-500">Message patient</h2>
|
||||
<p class="mt-1 text-xs text-slate-500">SMS uses Ladill SMS credits. Email uses Ladill Bird credits.</p>
|
||||
<p class="mt-1 text-xs text-slate-500">Uses your connected Ladill SMS / Bird credentials. <a href="{{ route('care.integrations') }}" class="text-teal-700 underline">Manage integrations</a></p>
|
||||
@if (! ($messagingSmsReady ?? false) || ! ($messagingEmailReady ?? false))
|
||||
<p class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
|
||||
@if (! ($messagingSmsReady ?? false) && ! ($messagingEmailReady ?? false))
|
||||
Connect SMS and Bird in Integrations before messaging patients.
|
||||
@elseif (! ($messagingSmsReady ?? false))
|
||||
Connect Ladill SMS in Integrations to enable SMS.
|
||||
@else
|
||||
Connect Ladill Bird in Integrations to enable email.
|
||||
@endif
|
||||
</p>
|
||||
@endif
|
||||
<div class="mt-4 flex gap-1 rounded-xl bg-slate-100 p-1 text-sm">
|
||||
<button type="button" @click="tab = 'sms'" :class="tab === 'sms' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-500'" class="flex-1 rounded-lg px-3 py-1.5 font-medium">SMS</button>
|
||||
<button type="button" @click="tab = 'email'" :class="tab === 'email' ? 'bg-white shadow-sm text-slate-900' : 'text-slate-500'" class="flex-1 rounded-lg px-3 py-1.5 font-medium">Email</button>
|
||||
@@ -148,7 +159,7 @@
|
||||
<p class="text-xs text-slate-500">To: {{ $patient->phone ?: 'no phone on file' }}</p>
|
||||
<textarea name="message" rows="3" maxlength="480" placeholder="Text message" required class="block w-full rounded-xl border-slate-300 text-sm focus:border-sky-500 focus:ring-sky-500">{{ old('message') }}</textarea>
|
||||
<div class="text-right">
|
||||
<button type="submit" class="btn-primary" @if(! $patient->phone) disabled @endif>Send SMS</button>
|
||||
<button type="submit" class="btn-primary" @if(! $patient->phone || ! ($messagingSmsReady ?? false)) disabled @endif>Send SMS</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -158,7 +169,7 @@
|
||||
<input type="text" name="subject" value="{{ old('subject') }}" placeholder="Subject" required class="block w-full rounded-xl border-slate-300 text-sm focus:border-sky-500 focus:ring-sky-500">
|
||||
<textarea name="body" rows="4" placeholder="Message" required class="block w-full rounded-xl border-slate-300 text-sm focus:border-sky-500 focus:ring-sky-500">{{ old('body') }}</textarea>
|
||||
<div class="text-right">
|
||||
<button type="submit" class="btn-primary" @if(! $patient->email) disabled @endif>Send email</button>
|
||||
<button type="submit" class="btn-primary" @if(! $patient->email || ! ($messagingEmailReady ?? false)) disabled @endif>Send email</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
@@ -41,6 +41,10 @@
|
||||
</x-settings.card>
|
||||
|
||||
@if ($canManage)
|
||||
<x-settings.card title="Messaging" description="Connect your Ladill SMS and Bird API keys for patient messaging.">
|
||||
<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="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'))>
|
||||
|
||||
@@ -23,6 +23,7 @@ use App\Http\Controllers\Care\QueueController;
|
||||
use App\Http\Controllers\Care\ProController;
|
||||
use App\Http\Controllers\Care\ReportController;
|
||||
use App\Http\Controllers\Care\ServiceQueueController;
|
||||
use App\Http\Controllers\Care\IntegrationsController;
|
||||
use App\Http\Controllers\Care\SettingsController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
@@ -137,6 +138,13 @@ Route::middleware(['auth', 'platform.session'])->group(function () {
|
||||
Route::get('/settings', [SettingsController::class, 'edit'])->name('care.settings');
|
||||
Route::put('/settings', [SettingsController::class, 'update'])->name('care.settings.update');
|
||||
|
||||
Route::get('/integrations', [IntegrationsController::class, 'edit'])->name('care.integrations');
|
||||
Route::post('/integrations/sms', [IntegrationsController::class, 'saveSms'])->name('care.integrations.sms.save');
|
||||
Route::post('/integrations/sms/disconnect', [IntegrationsController::class, 'disconnectSms'])->name('care.integrations.sms.disconnect');
|
||||
Route::post('/integrations/bird', [IntegrationsController::class, 'saveBird'])->name('care.integrations.bird.save');
|
||||
Route::post('/integrations/bird/disconnect', [IntegrationsController::class, 'disconnectBird'])->name('care.integrations.bird.disconnect');
|
||||
Route::post('/integrations/sms/senders', [IntegrationsController::class, 'previewSenders'])->name('care.integrations.sms.senders');
|
||||
|
||||
Route::get('/pro', [ProController::class, 'index'])->name('care.pro.index');
|
||||
Route::post('/pro/subscribe', [ProController::class, 'subscribe'])->name('care.pro.subscribe');
|
||||
Route::post('/pro/subscribe-enterprise', [ProController::class, 'subscribeEnterprise'])->name('care.pro.subscribe-enterprise');
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
<?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\Patient;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CareMessagingIntegrationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected User $user;
|
||||
|
||||
protected Organization $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutMiddleware(EnsurePlatformSession::class);
|
||||
|
||||
$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 Clinic',
|
||||
'slug' => 'test-clinic-msg',
|
||||
'timezone' => 'UTC',
|
||||
'settings' => ['onboarded' => true, 'facility_type' => 'clinic'],
|
||||
]);
|
||||
|
||||
Member::create([
|
||||
'owner_ref' => $this->user->public_id,
|
||||
'organization_id' => $this->organization->id,
|
||||
'user_ref' => $this->user->public_id,
|
||||
'role' => 'hospital_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(): void
|
||||
{
|
||||
$this->actingAs($this->user)
|
||||
->get(route('care.integrations'))
|
||||
->assertOk()
|
||||
->assertSee('Ladill SMS')
|
||||
->assertSee('Ladill Bird');
|
||||
}
|
||||
|
||||
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',
|
||||
'brand_name' => 'Clinic',
|
||||
]),
|
||||
'*/api/sms/senders' => Http::response([
|
||||
'data' => [['id' => 1, 'sender_id' => 'ClinicA', 'is_default' => true]],
|
||||
'default_sender' => 'Ladill',
|
||||
]),
|
||||
]);
|
||||
|
||||
$plain = 'lsk_sms_live_'.str_repeat('a', 32);
|
||||
|
||||
$this->actingAs($this->user)
|
||||
->post(route('care.integrations.sms.save'), [
|
||||
'sms_api_key' => $plain,
|
||||
'sms_sender_id' => 'ClinicA',
|
||||
])
|
||||
->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('ClinicA', $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('care.integrations.sms.save'), [
|
||||
'sms_api_key' => 'lsk_sms_live_'.str_repeat('b', 32),
|
||||
'sms_sender_id' => 'ClinicA',
|
||||
])
|
||||
->assertRedirect()
|
||||
->assertSessionHas('error');
|
||||
}
|
||||
|
||||
public function test_patient_sms_requires_credentials(): void
|
||||
{
|
||||
$patient = Patient::create([
|
||||
'uuid' => (string) \Illuminate\Support\Str::uuid(),
|
||||
'owner_ref' => $this->user->public_id,
|
||||
'organization_id' => $this->organization->id,
|
||||
'branch_id' => Branch::first()->id,
|
||||
'patient_number' => 'LC-MSG-00001',
|
||||
'first_name' => 'Ada',
|
||||
'last_name' => 'Lovelace',
|
||||
'phone' => '+233201111111',
|
||||
]);
|
||||
|
||||
$this->actingAs($this->user)
|
||||
->post(route('care.patients.sms', $patient), ['message' => 'Hello'])
|
||||
->assertRedirect()
|
||||
->assertSessionHas('error');
|
||||
}
|
||||
|
||||
public function test_patient_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' => 'ClinicA',
|
||||
'sms_status' => MessagingCredential::STATUS_VALID,
|
||||
'sms_validated_at' => now(),
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'*/api/sms/send' => Http::response(['success' => true, 'message_id' => 1]),
|
||||
]);
|
||||
|
||||
$patient = Patient::create([
|
||||
'uuid' => (string) \Illuminate\Support\Str::uuid(),
|
||||
'owner_ref' => $this->user->public_id,
|
||||
'organization_id' => $this->organization->id,
|
||||
'branch_id' => Branch::first()->id,
|
||||
'patient_number' => 'LC-MSG-00002',
|
||||
'first_name' => 'Ada',
|
||||
'last_name' => 'Lovelace',
|
||||
'phone' => '+233201111111',
|
||||
]);
|
||||
|
||||
$this->actingAs($this->user)
|
||||
->post(route('care.patients.sms', $patient), ['message' => 'Hello patient'])
|
||||
->assertRedirect()
|
||||
->assertSessionHas('success');
|
||||
|
||||
Http::assertSent(function ($request) use ($plain) {
|
||||
return str_contains($request->url(), '/api/sms/send')
|
||||
&& $request->hasHeader('Authorization', 'Bearer '.$plain)
|
||||
&& $request['sender_id'] === 'ClinicA'
|
||||
&& $request['text'] === 'Hello patient';
|
||||
});
|
||||
}
|
||||
|
||||
public function test_patient_email_uses_customer_bird_key(): 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' => 'clinic@example.test',
|
||||
'bird_from_name' => 'Clinic',
|
||||
'bird_status' => MessagingCredential::STATUS_VALID,
|
||||
'bird_validated_at' => now(),
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'*/api/smtp/send' => Http::response(['success' => true, 'message_id' => 'x']),
|
||||
]);
|
||||
|
||||
$patient = Patient::create([
|
||||
'uuid' => (string) \Illuminate\Support\Str::uuid(),
|
||||
'owner_ref' => $this->user->public_id,
|
||||
'organization_id' => $this->organization->id,
|
||||
'branch_id' => Branch::first()->id,
|
||||
'patient_number' => 'LC-MSG-00003',
|
||||
'first_name' => 'Ada',
|
||||
'last_name' => 'Lovelace',
|
||||
'email' => 'ada@example.com',
|
||||
]);
|
||||
|
||||
$this->actingAs($this->user)
|
||||
->post(route('care.patients.email', $patient), [
|
||||
'subject' => 'Hi',
|
||||
'body' => 'Body text',
|
||||
])
|
||||
->assertRedirect()
|
||||
->assertSessionHas('success');
|
||||
|
||||
Http::assertSent(function ($request) use ($plain) {
|
||||
return str_contains($request->url(), '/api/smtp/send')
|
||||
&& $request->hasHeader('Authorization', 'Bearer '.$plain)
|
||||
&& $request['from'] === 'clinic@example.test'
|
||||
&& $request['from_name'] === 'Clinic';
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@ 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\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -141,19 +143,23 @@ class CarePatientTest extends TestCase
|
||||
->assertSee('Message patient');
|
||||
}
|
||||
|
||||
public function test_can_send_patient_sms_via_platform_api(): void
|
||||
public function test_can_send_patient_sms_via_customer_relay(): void
|
||||
{
|
||||
config([
|
||||
'sms.platform_api_url' => 'https://ladill.test/api',
|
||||
'sms.platform_api_key' => 'test-sms-care-key',
|
||||
'sms.default_sender_id' => 'Ladill',
|
||||
$plain = 'lsk_sms_live_'.str_repeat('e', 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' => 'ClinicA',
|
||||
'sms_status' => MessagingCredential::STATUS_VALID,
|
||||
'sms_validated_at' => now(),
|
||||
]);
|
||||
|
||||
config(['sms.customer_relay_url' => 'https://ladill.test/api/sms']);
|
||||
|
||||
\Illuminate\Support\Facades\Http::fake([
|
||||
'ladill.test/api/sms/services*' => \Illuminate\Support\Facades\Http::response([
|
||||
'data' => [['id' => 9, 'name' => 'Ladill Care']],
|
||||
]),
|
||||
'ladill.test/api/sms/messages/send' => \Illuminate\Support\Facades\Http::response([
|
||||
'ladill.test/api/sms/send' => \Illuminate\Support\Facades\Http::response([
|
||||
'success' => true,
|
||||
'segments' => 1,
|
||||
]),
|
||||
@@ -180,17 +186,24 @@ class CarePatientTest extends TestCase
|
||||
$this->assertDatabaseHas('care_audit_logs', ['action' => 'patient.sms_sent']);
|
||||
}
|
||||
|
||||
public function test_can_send_patient_email_via_platform_api(): void
|
||||
public function test_can_send_patient_email_via_customer_relay(): void
|
||||
{
|
||||
config([
|
||||
'smtp.platform_api_url' => 'https://ladill.test/api/smtp',
|
||||
'smtp.platform_api_key' => 'test-smtp-care-key',
|
||||
'smtp.from' => 'care@ladill.com',
|
||||
'smtp.from_name' => 'Ladill Care',
|
||||
$plain = 'lsk_live_'.str_repeat('f', 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' => 'care@example.test',
|
||||
'bird_from_name' => 'Ladill Care',
|
||||
'bird_status' => MessagingCredential::STATUS_VALID,
|
||||
'bird_validated_at' => now(),
|
||||
]);
|
||||
|
||||
config(['smtp.customer_relay_url' => 'https://ladill.test/api/smtp']);
|
||||
|
||||
\Illuminate\Support\Facades\Http::fake([
|
||||
'ladill.test/api/smtp/messages/send' => \Illuminate\Support\Facades\Http::response([
|
||||
'ladill.test/api/smtp/send' => \Illuminate\Support\Facades\Http::response([
|
||||
'success' => true,
|
||||
'message_id' => 'msg-1',
|
||||
]),
|
||||
|
||||
Reference in New Issue
Block a user