From 8273148f378ab3fec5e4fd45a7c25f01c126794b Mon Sep 17 00:00:00 2001 From: Instinct Date: Thu, 3 Dec 2026 18:55:48 +0200 Subject: [PATCH] Automation phase A: provider layer, queued sends, log columns --- CHANGELOG.md | 5 + README.md | 22 +++ config/rehla.php | 53 ++++++ ...tion_columns_to_rehla_follow_ups_table.php | 41 +++++ docs/ar/README.md | 22 +++ resources/lang/ar/rehla.php | 6 + resources/lang/en/rehla.php | 6 + resources/views/dashboard.blade.php | 5 +- src/Automation/FollowUpSender.php | 101 ++++++++++++ src/Automation/OutboundMessage.php | 21 +++ src/Automation/ProviderManager.php | 109 +++++++++++++ src/Automation/Providers/HttpProvider.php | 97 +++++++++++ src/Automation/Providers/LogProvider.php | 36 ++++ .../Providers/MetaCloudProvider.php | 99 +++++++++++ src/Automation/SendResult.php | 32 ++++ src/Automation/UrlGuard.php | 53 ++++++ src/Contracts/WhatsAppProvider.php | 20 +++ src/Exceptions/AutomationException.php | 38 +++++ src/Http/Controllers/FollowUpController.php | 2 + src/Jobs/SendAutomatedFollowUp.php | 118 ++++++++++++++ src/Models/RehlaFollowUp.php | 37 ++++- src/RehlaServiceProvider.php | 5 + tests/Feature/AutomatedSendTest.php | 154 ++++++++++++++++++ tests/Feature/AutomationProvidersTest.php | 136 ++++++++++++++++ 24 files changed, 1216 insertions(+), 2 deletions(-) create mode 100644 database/migrations/2026_01_01_000006_add_automation_columns_to_rehla_follow_ups_table.php create mode 100644 src/Automation/FollowUpSender.php create mode 100644 src/Automation/OutboundMessage.php create mode 100644 src/Automation/ProviderManager.php create mode 100644 src/Automation/Providers/HttpProvider.php create mode 100644 src/Automation/Providers/LogProvider.php create mode 100644 src/Automation/Providers/MetaCloudProvider.php create mode 100644 src/Automation/SendResult.php create mode 100644 src/Automation/UrlGuard.php create mode 100644 src/Contracts/WhatsAppProvider.php create mode 100644 src/Exceptions/AutomationException.php create mode 100644 src/Jobs/SendAutomatedFollowUp.php create mode 100644 tests/Feature/AutomatedSendTest.php create mode 100644 tests/Feature/AutomationProvidersTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d7683c..482e036 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### Added (automation, phase A: sending layer) +- `rehla.automation` config (off by default): provider contract with `meta` (WhatsApp Business Cloud API), generic `http` and `log` (dry run) drivers, custom drivers via `ProviderManager::extend`. +- `FollowUpSender::queue()` records an automatic follow-up (`source = automation`) and sends it on the queue, with retries for temporary failures, an idempotency key and failure reasons. +- Follow-up log columns for source, provider message id, delivery status, errors, attempts and payload (additive migration). History shows "Automatic" and the new statuses (queued, failed, dry run, cancelled). Dry-run and failed rows never count as the last follow-up. + ### Added - `rehla.follow_up.confirm_sent` (default `true`). Set it to `false` to skip the "did you actually send it?" step; opening WhatsApp then records the follow-up as sent immediately. - `php artisan rehla:install`: publishes the config if missing and runs only Rehla's migrations (idempotent, `--force` for production). diff --git a/README.md b/README.md index 8ca866c..6a516d8 100644 --- a/README.md +++ b/README.md @@ -139,3 +139,25 @@ composer check # pint --test, phpstan level 8, pest ## License MIT. See [LICENSE.md](LICENSE.md). + + +## Automatic WhatsApp sending (optional, in progress) + +Manual follow-up stays as it is. Automation is a separate, optional layer that is **off by default**. Every setting lives in `config/rehla.php` and env first; showing any of it in the panel is your choice. + +```env +REHLA_AUTOMATION_ENABLED=true +REHLA_AUTOMATION_PROVIDER=log # log (dry run), meta, http, or your own +REHLA_META_PHONE_NUMBER_ID=... +REHLA_META_ACCESS_TOKEN=... +``` + +Providers (`rehla.automation.providers`): +- `log`: dry run. Logs the message, sends nothing. Its rows are marked "Dry run" and never count as a real follow-up. Start here. +- `meta`: WhatsApp Business Cloud API. Outside the 24-hour customer service window Meta only accepts approved templates, so automatic nudges need a template name; free text only works inside the window. Meta bills per message by category, and you pay Meta, not Rehla. +- `http`: any service that takes an HTTP request. The body is a config array with `{phone}`, `{message}`, `{template}`, `{language}`, `{idempotency_key}` placeholders. HTTPS only, and private or loopback addresses are refused unless you turn that off for development. +- Your own: `app(Rehla\Automation\ProviderManager::class)->extend('acme', fn (array $config) => new AcmeProvider(...))`, then `'driver' => 'acme'` in config. + +Sends run on your queue (`rehla.automation.queue`), so run a queue worker. Temporary failures (timeouts, 429, 5xx) retry with the delays in `rehla.automation.retry.backoff_seconds` (seconds: 60 = a minute, 3600 = an hour); permanent ones are marked failed with the provider's reason. Every automatic send is recorded in the same follow-up history as manual ones, labelled "Automatic". + +This release adds the sending layer only (`Rehla\Automation\FollowUpSender::queue($user, $message)`). Consent and STOP handling, rules and the panel tab come in the next releases, so do not point it at real users yet. diff --git a/config/rehla.php b/config/rehla.php index 492c401..c190d60 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -79,6 +79,59 @@ 'confirm_sent' => true, ], + /* + | Automatic WhatsApp sending. Off by default. Everything here is code + | level and mandatory: credentials and numbers come from env or this file. + | Showing any of it in the panel is optional and up to you. + | + | provider: the name of an entry in `providers` below. + | "log" is a dry run: it logs the message and sends nothing. + | Meta only accepts free text inside the 24-hour customer service + | window, so automatic nudges need an approved template. + */ + 'automation' => [ + 'enabled' => (bool) env('REHLA_AUTOMATION_ENABLED', false), + 'provider' => env('REHLA_AUTOMATION_PROVIDER', 'log'), + + 'providers' => [ + 'log' => ['driver' => 'log', 'channel' => null], + + 'meta' => [ + 'driver' => 'meta', + 'phone_number_id' => env('REHLA_META_PHONE_NUMBER_ID'), + 'access_token' => env('REHLA_META_ACCESS_TOKEN'), + 'api_version' => env('REHLA_META_API_VERSION', 'v21.0'), + 'language' => env('REHLA_META_TEMPLATE_LANGUAGE', 'ar'), + 'timeout' => 15, + ], + + // Any service that takes an HTTP request. Body values may use + // {phone} {message} {template} {language} {idempotency_key}; + // a value of exactly {params} becomes the template parameter list. + 'http' => [ + 'driver' => 'http', + 'url' => env('REHLA_HTTP_URL'), + 'method' => 'POST', + 'headers' => [], + 'body' => ['to' => '{phone}', 'text' => '{message}'], + 'message_id_path' => 'id', + 'timeout' => 15, + 'allow_insecure' => false, + 'block_private_hosts' => true, + ], + ], + + // Where queued sends run. null = the app defaults. + 'queue' => ['connection' => null, 'name' => null], + + // Retries for temporary failures (timeouts, 429, 5xx). One entry + // per retry, in seconds: 60 = a minute, 3600 = an hour. + 'retry' => [ + 'max_attempts' => 3, + 'backoff_seconds' => [60, 300, 900], + ], + ], + /* | WhatsApp deep links. wa.me wants digits only, international format | without "+". Local numbers (leading 0) get the country code. diff --git a/database/migrations/2026_01_01_000006_add_automation_columns_to_rehla_follow_ups_table.php b/database/migrations/2026_01_01_000006_add_automation_columns_to_rehla_follow_ups_table.php new file mode 100644 index 0000000..d3bf97f --- /dev/null +++ b/database/migrations/2026_01_01_000006_add_automation_columns_to_rehla_follow_ups_table.php @@ -0,0 +1,41 @@ +string('source', 16)->default('manual')->after('status'); + $table->unsignedBigInteger('rule_id')->nullable()->after('source'); + $table->string('provider', 32)->nullable()->after('rule_id'); + $table->string('provider_message_id')->nullable()->after('provider'); + $table->string('delivery_status', 16)->nullable()->after('provider_message_id'); + $table->string('error_code', 64)->nullable()->after('delivery_status'); + $table->text('error_message')->nullable()->after('error_code'); + $table->unsignedSmallInteger('attempts')->default(0)->after('error_message'); + $table->string('skip_reason')->nullable()->after('attempts'); + $table->json('payload')->nullable()->after('skip_reason'); + $table->string('idempotency_key')->nullable()->unique('rehla_followups_idem_unique')->after('payload'); + $table->index('provider_message_id', 'rehla_followups_provider_msg_index'); + }); + } + + public function down(): void + { + Schema::table('rehla_follow_ups', function (Blueprint $table): void { + $table->dropUnique('rehla_followups_idem_unique'); + $table->dropIndex('rehla_followups_provider_msg_index'); + $table->dropColumn([ + 'source', 'rule_id', 'provider', 'provider_message_id', 'delivery_status', + 'error_code', 'error_message', 'attempts', 'skip_reason', 'payload', 'idempotency_key', + ]); + }); + } +}; diff --git a/docs/ar/README.md b/docs/ar/README.md index 882c18f..4ac2bbb 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -139,3 +139,25 @@ composer check # pint --test, phpstan level 8, pest ## الترخيص MIT. شوف [LICENSE.md](../../LICENSE.md). + + +## الإرسال التلقائي على واتساب (اختياري، تحت التنفيذ) + +المتابعة اليدوية زي ما هي. الإرسال التلقائي طبقة منفصلة واختيارية و**مقفولة افتراضياً**. كل إعداد موجود في `config/rehla.php` والـ env الأول، وإظهار أي حاجة منها في البانل قرارك أنت. + +```env +REHLA_AUTOMATION_ENABLED=true +REHLA_AUTOMATION_PROVIDER=log # log (تجريبي), meta, http, أو بتاعك +REHLA_META_PHONE_NUMBER_ID=... +REHLA_META_ACCESS_TOKEN=... +``` + +مقدّمو الخدمة (`rehla.automation.providers`): +- `log`: تجربة. بيسجّل الرسالة في اللوج ومبيبعتش حاجة. سجلاته بتتعلّم "تجريبي" ومبتتحسبش متابعة حقيقية. ابدأ بيه. +- `meta`: واجهة WhatsApp Business Cloud. برّه نافذة الـ24 ساعة ميتا بتقبل قوالب معتمدة بس، فالرسائل التلقائية محتاجة اسم قالب. النص الحر بيشتغل جوه النافذة بس. ميتا بتحاسب على كل رسالة حسب الفئة، وأنت بتدفع لميتا مش لـ Rehla. +- `http`: أي خدمة بتقبل طلب HTTP. الـ body مصفوفة في الكونفيج فيها `{phone}` و`{message}` و`{template}` و`{language}` و`{idempotency_key}`. HTTPS بس، والعناوين الخاصة والـ loopback مرفوضة إلا لو قفلت ده للتطوير. +- بتاعك: `app(Rehla\Automation\ProviderManager::class)->extend('acme', fn (array $config) => new AcmeProvider(...))` وبعدين `'driver' => 'acme'` في الكونفيج. + +الإرسال بيشتغل على الـ queue بتاعك (`rehla.automation.queue`)، فلازم يكون عندك queue worker شغال. الأعطال المؤقتة (timeout أو 429 أو 5xx) بتتعاد بالمهل في `rehla.automation.retry.backoff_seconds` (بالثواني: 60 = دقيقة، 3600 = ساعة)، والدائمة بتتعلّم فاشلة مع سبب المزوّد. كل إرسال تلقائي بيتسجّل في نفس سجل المتابعات زي اليدوي وعليه علامة "تلقائي". + +الإصدار ده فيه طبقة الإرسال بس (`Rehla\Automation\FollowUpSender::queue($user, $message)`). الموافقة ومعالجة STOP والقواعد وتاب البانل جايين في الإصدارات الجاية، فلسه متوجهوش على مستخدمين حقيقيين. diff --git a/resources/lang/ar/rehla.php b/resources/lang/ar/rehla.php index 771a051..85eb2fc 100644 --- a/resources/lang/ar/rehla.php +++ b/resources/lang/ar/rehla.php @@ -27,7 +27,13 @@ 'sent' => 'أيوه بعتّها', ], 'history' => [ + 'automatic' => 'تلقائي', 'status' => [ + 'queued' => 'في الانتظار', + 'failed' => 'فشلت', + 'simulated' => 'تجريبي', + 'cancelled' => 'اتلغت', + 'sent' => 'اتبعتت', 'opened' => 'غير مؤكدة', 'not_sent' => 'ماتبعتتش', diff --git a/resources/lang/en/rehla.php b/resources/lang/en/rehla.php index 7db0374..cfec183 100644 --- a/resources/lang/en/rehla.php +++ b/resources/lang/en/rehla.php @@ -27,7 +27,13 @@ 'sent' => 'Yes, I sent it', ], 'history' => [ + 'automatic' => 'Automatic', 'status' => [ + 'queued' => 'Queued', + 'failed' => 'Failed', + 'simulated' => 'Dry run', + 'cancelled' => 'Cancelled', + 'sent' => 'Sent', 'opened' => 'Unconfirmed', 'not_sent' => 'Not sent', diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php index 0b240f5..9e9f830 100644 --- a/resources/views/dashboard.blade.php +++ b/resources/views/dashboard.blade.php @@ -170,7 +170,7 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} var confirmSent = @json($confirmSent); var confirmUrl = @json(route('rehla.follow-ups.confirm', ['id' => '__ID__'])); var csrfToken = (document.querySelector('meta[name="csrf-token"]') || {}).content || ''; -@php($rehlaJsLabels = ['by' => __('rehla::rehla.history.by'), 'about' => __('rehla::rehla.history.about'), 'empty' => __('rehla::rehla.history.empty'), 'loading' => __('rehla::rehla.history.loading'), 'recent' => __('rehla::rehla.modal.recent_warning'), 'status' => ['sent' => __('rehla::rehla.history.status.sent'), 'opened' => __('rehla::rehla.history.status.opened'), 'not_sent' => __('rehla::rehla.history.status.not_sent')]]) +@php($rehlaJsLabels = ['by' => __('rehla::rehla.history.by'), 'about' => __('rehla::rehla.history.about'), 'empty' => __('rehla::rehla.history.empty'), 'loading' => __('rehla::rehla.history.loading'), 'recent' => __('rehla::rehla.modal.recent_warning'), 'automatic' => __('rehla::rehla.history.automatic'), 'status' => ['sent' => __('rehla::rehla.history.status.sent'), 'opened' => __('rehla::rehla.history.status.opened'), 'not_sent' => __('rehla::rehla.history.status.not_sent'), 'queued' => __('rehla::rehla.history.status.queued'), 'failed' => __('rehla::rehla.history.status.failed'), 'simulated' => __('rehla::rehla.history.status.simulated'), 'cancelled' => __('rehla::rehla.history.status.cancelled')]]) var labels = @json($rehlaJsLabels); function fillSelect(selectedId) { @@ -326,6 +326,9 @@ function renderHistory(items) { meta.className = 'followup-meta'; meta.dir = 'auto'; var bits = [item.ago, labels.status[item.status] || item.status]; + if (item.source === 'automation') { + bits.push(labels.automatic); + } if (item.sender_name) { bits.push(labels.by + ' ' + item.sender_name); } diff --git a/src/Automation/FollowUpSender.php b/src/Automation/FollowUpSender.php new file mode 100644 index 0000000..5be6d8b --- /dev/null +++ b/src/Automation/FollowUpSender.php @@ -0,0 +1,101 @@ +}|null, + * } $options + */ + public function queue(Model $user, string $message, array $options = []): RehlaFollowUp + { + if (! (bool) Config::get('rehla.automation.enabled', false)) { + throw AutomationException::disabled(); + } + + $key = $options['idempotency_key'] ?? null; + + if ($key !== null) { + $existing = RehlaFollowUp::query()->where('idempotency_key', $key)->first(); + + if ($existing !== null) { + return $existing; + } + } + + $phoneAttribute = (string) Config::get('rehla.phone_attribute', 'phone'); + $raw = $user->getAttribute($phoneAttribute); + $phone = WhatsAppLink::normalizeNumber( + is_string($raw) ? $raw : null, + (string) Config::get('rehla.whatsapp.default_country_code', ''), + ); + + if ($phone === null) { + throw AutomationException::noPhone(); + } + + $providerTemplate = $options['provider_template'] ?? null; + + $followUp = RehlaFollowUp::query()->create([ + 'trackable_type' => $user->getMorphClass(), + 'trackable_id' => $user->getKey(), + 'sender_name' => 'Automation', + 'template_id' => $options['template_id'] ?? null, + 'template_title' => $options['template_title'] ?? null, + 'journey' => $options['journey'] ?? null, + 'step' => $options['step'] ?? null, + 'message' => $message, + 'channel' => 'whatsapp', + 'status' => RehlaFollowUp::STATUS_QUEUED, + 'source' => RehlaFollowUp::SOURCE_AUTOMATION, + 'rule_id' => $options['rule_id'] ?? null, + 'provider' => $this->providers->defaultName(), + 'idempotency_key' => $key, + 'payload' => [ + 'phone' => $phone, + 'template_name' => $providerTemplate['name'] ?? null, + 'template_language' => $providerTemplate['language'] ?? null, + 'template_params' => $providerTemplate['params'] ?? [], + ], + ]); + + $job = new SendAutomatedFollowUp((int) $followUp->getKey()); + $connection = Config::get('rehla.automation.queue.connection'); + $queue = Config::get('rehla.automation.queue.name'); + + if (is_string($connection) && $connection !== '') { + $job->onConnection($connection); + } + + if (is_string($queue) && $queue !== '') { + $job->onQueue($queue); + } + + dispatch($job); + + return $followUp; + } +} diff --git a/src/Automation/OutboundMessage.php b/src/Automation/OutboundMessage.php new file mode 100644 index 0000000..40b0122 --- /dev/null +++ b/src/Automation/OutboundMessage.php @@ -0,0 +1,21 @@ + $templateParams ordered values for {{1}}, {{2}}, ... + */ + public function __construct( + public string $phone, + public string $body, + public ?string $templateName = null, + public ?string $templateLanguage = null, + public array $templateParams = [], + public ?string $idempotencyKey = null, + ) {} +} diff --git a/src/Automation/ProviderManager.php b/src/Automation/ProviderManager.php new file mode 100644 index 0000000..37850fc --- /dev/null +++ b/src/Automation/ProviderManager.php @@ -0,0 +1,109 @@ +): WhatsAppProvider> */ + private array $custom = []; + + /** @var array */ + private array $resolved = []; + + /** + * Register your own driver, then name it in + * rehla.automation.providers..driver. + * + * @param Closure(array): WhatsAppProvider $factory + */ + public function extend(string $driver, Closure $factory): void + { + $this->custom[$driver] = $factory; + $this->resolved = []; + } + + public function defaultName(): string + { + return (string) config('rehla.automation.provider', 'log'); + } + + public function driver(?string $name = null): WhatsAppProvider + { + $name ??= $this->defaultName(); + + return $this->resolved[$name] ??= $this->build($name); + } + + private function build(string $name): WhatsAppProvider + { + /** @var array|null $config */ + $config = config("rehla.automation.providers.{$name}"); + + if (! is_array($config)) { + throw AutomationException::unknownProvider($name); + } + + $driver = (string) ($config['driver'] ?? $name); + + if (isset($this->custom[$driver])) { + return ($this->custom[$driver])($config); + } + + return match ($driver) { + 'log' => new LogProvider(isset($config['channel']) ? (string) $config['channel'] : null), + 'meta' => new MetaCloudProvider( + $this->required($name, $config, 'phone_number_id'), + $this->required($name, $config, 'access_token'), + (string) ($config['api_version'] ?? 'v21.0'), + (string) ($config['language'] ?? 'ar'), + (int) ($config['timeout'] ?? 15), + ), + 'http' => new HttpProvider( + $this->required($name, $config, 'url'), + (string) ($config['method'] ?? 'POST'), + $this->stringMap($config['headers'] ?? []), + is_array($config['body'] ?? null) ? $config['body'] : [], + (int) ($config['timeout'] ?? 15), + isset($config['message_id_path']) ? (string) $config['message_id_path'] : null, + (bool) ($config['allow_insecure'] ?? false), + (bool) ($config['block_private_hosts'] ?? true), + ), + default => throw AutomationException::unknownDriver($driver), + }; + } + + /** @param array $config */ + private function required(string $provider, array $config, string $key): string + { + $value = $config[$key] ?? null; + + if (! is_string($value) || $value === '') { + throw AutomationException::missingSetting($provider, $key); + } + + return $value; + } + + /** @return array */ + private function stringMap(mixed $value): array + { + $out = []; + + foreach (is_array($value) ? $value : [] as $k => $v) { + if (is_string($k) && is_scalar($v)) { + $out[$k] = (string) $v; + } + } + + return $out; + } +} diff --git a/src/Automation/Providers/HttpProvider.php b/src/Automation/Providers/HttpProvider.php new file mode 100644 index 0000000..ce20d78 --- /dev/null +++ b/src/Automation/Providers/HttpProvider.php @@ -0,0 +1,97 @@ + $headers + * @param array $body + */ + public function __construct( + private readonly string $url, + private readonly string $method = 'POST', + private readonly array $headers = [], + private readonly array $body = [], + private readonly int $timeoutSeconds = 15, + private readonly ?string $messageIdPath = null, + private readonly bool $allowInsecure = false, + private readonly bool $blockPrivateHosts = true, + ) {} + + public function name(): string + { + return 'http'; + } + + public function send(OutboundMessage $message): SendResult + { + UrlGuard::assertSafe($this->url, $this->allowInsecure, $this->blockPrivateHosts); + + $payload = $this->render($this->body, $message); + + try { + $response = Http::withHeaders($this->headers) + ->acceptJson() + ->timeout($this->timeoutSeconds) + ->send(strtoupper($this->method), $this->url, ['json' => $payload]); + } catch (ConnectionException $e) { + return SendResult::failed('connection', $e->getMessage(), true); + } + + if ($response->successful()) { + $id = $this->messageIdPath !== null ? data_get($response->json(), $this->messageIdPath) : null; + + return SendResult::accepted(is_scalar($id) ? (string) $id : null); + } + + $status = $response->status(); + + return SendResult::failed((string) $status, 'HTTP '.$status, $status === 429 || $status >= 500); + } + + /** + * @param array $template + * @return array + */ + private function render(array $template, OutboundMessage $message): array + { + $out = []; + + foreach ($template as $key => $value) { + if (is_array($value)) { + /** @var array $value */ + $out[$key] = $this->render($value, $message); + } elseif ($value === '{params}') { + $out[$key] = $message->templateParams; + } elseif (is_string($value)) { + $out[$key] = strtr($value, [ + '{phone}' => $message->phone, + '{message}' => $message->body, + '{template}' => (string) $message->templateName, + '{language}' => (string) $message->templateLanguage, + '{idempotency_key}' => (string) $message->idempotencyKey, + ]); + } else { + $out[$key] = $value; + } + } + + return $out; + } +} diff --git a/src/Automation/Providers/LogProvider.php b/src/Automation/Providers/LogProvider.php new file mode 100644 index 0000000..f64bec0 --- /dev/null +++ b/src/Automation/Providers/LogProvider.php @@ -0,0 +1,36 @@ +channel)->info('Rehla dry run: WhatsApp message not sent', [ + 'to' => $message->phone, + 'template' => $message->templateName, + 'body' => $message->body, + ]); + + return SendResult::simulated('log-'.Str::uuid()->toString()); + } +} diff --git a/src/Automation/Providers/MetaCloudProvider.php b/src/Automation/Providers/MetaCloudProvider.php new file mode 100644 index 0000000..d90487a --- /dev/null +++ b/src/Automation/Providers/MetaCloudProvider.php @@ -0,0 +1,99 @@ +baseUrl, '/').'/'.$this->apiVersion.'/'.$this->phoneNumberId.'/messages'; + + try { + $response = Http::withToken($this->accessToken) + ->acceptJson() + ->asJson() + ->timeout($this->timeoutSeconds) + ->post($url, $this->payload($message)); + } catch (ConnectionException $e) { + return SendResult::failed('connection', $e->getMessage(), true); + } + + return $this->interpret($response); + } + + /** @return array */ + public function payload(OutboundMessage $message): array + { + $base = ['messaging_product' => 'whatsapp', 'recipient_type' => 'individual', 'to' => $message->phone]; + + if ($message->templateName === null) { + return $base + ['type' => 'text', 'text' => ['preview_url' => false, 'body' => $message->body]]; + } + + $template = [ + 'name' => $message->templateName, + 'language' => ['code' => $message->templateLanguage ?? $this->defaultLanguage], + ]; + + if ($message->templateParams !== []) { + $template['components'] = [[ + 'type' => 'body', + 'parameters' => array_map( + static fn (string $value): array => ['type' => 'text', 'text' => $value], + $message->templateParams, + ), + ]]; + } + + return $base + ['type' => 'template', 'template' => $template]; + } + + private function interpret(Response $response): SendResult + { + if ($response->successful()) { + $id = $response->json('messages.0.id'); + + return SendResult::accepted(is_string($id) ? $id : null); + } + + $code = $response->json('error.code'); + $text = $response->json('error.message'); + $status = $response->status(); + $retryable = $status === 429 || $status >= 500; + + return SendResult::failed( + is_scalar($code) ? (string) $code : (string) $status, + is_string($text) && $text !== '' ? $text : 'HTTP '.$status, + $retryable, + ); + } +} diff --git a/src/Automation/SendResult.php b/src/Automation/SendResult.php new file mode 100644 index 0000000..e5b5873 --- /dev/null +++ b/src/Automation/SendResult.php @@ -0,0 +1,32 @@ + $followUp->sender_name, 'channel' => $followUp->channel, 'status' => $followUp->status, + 'source' => $followUp->source, + 'delivery_status' => $followUp->delivery_status, 'at' => $followUp->created_at->toIso8601String(), 'ago' => $followUp->created_at->diffForHumans(), ])->values()->all(), diff --git a/src/Jobs/SendAutomatedFollowUp.php b/src/Jobs/SendAutomatedFollowUp.php new file mode 100644 index 0000000..cdc010f --- /dev/null +++ b/src/Jobs/SendAutomatedFollowUp.php @@ -0,0 +1,118 @@ +find($this->followUpId); + + if ($followUp === null || $followUp->status !== RehlaFollowUp::STATUS_QUEUED) { + return; + } + + $payload = $followUp->payload ?? []; + $phone = $payload['phone'] ?? null; + + if (! is_string($phone) || $phone === '') { + $this->markFailed($followUp, 'no_phone', 'No phone number was stored for this send.'); + + return; + } + + $followUp->increment('attempts'); + + try { + $provider = $providers->driver($followUp->provider); + /** @var list $params */ + $params = array_values(array_map('strval', (array) ($payload['template_params'] ?? []))); + $result = $provider->send(new OutboundMessage( + phone: $phone, + body: $followUp->message, + templateName: is_string($payload['template_name'] ?? null) ? $payload['template_name'] : null, + templateLanguage: is_string($payload['template_language'] ?? null) ? $payload['template_language'] : null, + templateParams: $params, + idempotencyKey: $followUp->idempotency_key, + )); + } catch (RehlaException $e) { + // Misconfiguration will not fix itself between retries. + $this->markFailed($followUp, 'configuration', $e->getMessage()); + + return; + } + + if ($result->accepted) { + $followUp->forceFill([ + 'status' => $result->simulated ? RehlaFollowUp::STATUS_SIMULATED : RehlaFollowUp::STATUS_SENT, + 'sent_at' => $result->simulated ? null : now(), + 'delivery_status' => $result->simulated ? 'simulated' : 'sent', + 'provider_message_id' => $result->messageId, + 'error_code' => null, + 'error_message' => null, + ])->save(); + + return; + } + + $max = max(1, (int) config('rehla.automation.retry.max_attempts', 3)); + $followUp->refresh(); + + if ($result->retryable && $followUp->attempts < $max) { + $followUp->forceFill([ + 'error_code' => $result->errorCode, + 'error_message' => $result->errorMessage, + ])->save(); + + $this->release($this->backoff($followUp->attempts)); + + return; + } + + $this->markFailed($followUp, $result->errorCode ?? 'failed', $result->errorMessage ?? 'The provider refused the message.'); + } + + private function backoff(int $attempt): int + { + /** @var list $steps */ + $steps = array_values((array) config('rehla.automation.retry.backoff_seconds', [60, 300, 900])); + + if ($steps === []) { + return 60; + } + + return max(1, (int) ($steps[min($attempt, count($steps)) - 1])); + } + + private function markFailed(RehlaFollowUp $followUp, string $code, string $message): void + { + $followUp->forceFill([ + 'status' => RehlaFollowUp::STATUS_FAILED, + 'delivery_status' => 'failed', + 'error_code' => $code, + 'error_message' => mb_substr($message, 0, 1000), + ])->save(); + } +} diff --git a/src/Models/RehlaFollowUp.php b/src/Models/RehlaFollowUp.php index 8ef1afe..e543ad4 100644 --- a/src/Models/RehlaFollowUp.php +++ b/src/Models/RehlaFollowUp.php @@ -24,6 +24,17 @@ * @property string $message * @property string $channel * @property string $status + * @property string $source + * @property int|null $rule_id + * @property string|null $provider + * @property string|null $provider_message_id + * @property string|null $delivery_status + * @property string|null $error_code + * @property string|null $error_message + * @property int $attempts + * @property string|null $skip_reason + * @property array|null $payload + * @property string|null $idempotency_key * @property Carbon|null $sent_at * @property Carbon $created_at */ @@ -46,6 +57,17 @@ final class RehlaFollowUp extends Model 'channel', 'status', 'sent_at', + 'source', + 'rule_id', + 'provider', + 'provider_message_id', + 'delivery_status', + 'error_code', + 'error_message', + 'attempts', + 'skip_reason', + 'payload', + 'idempotency_key', ]; public const STATUS_OPENED = 'opened'; @@ -54,10 +76,23 @@ final class RehlaFollowUp extends Model public const STATUS_NOT_SENT = 'not_sent'; + /** Automatic sends: waiting in the queue, refused for good, or a dry run. */ + public const STATUS_QUEUED = 'queued'; + + public const STATUS_FAILED = 'failed'; + + public const STATUS_SIMULATED = 'simulated'; + + public const STATUS_CANCELLED = 'cancelled'; + + public const SOURCE_MANUAL = 'manual'; + + public const SOURCE_AUTOMATION = 'automation'; + /** @return array */ protected function casts(): array { - return ['sent_at' => 'datetime']; + return ['sent_at' => 'datetime', 'payload' => 'array']; } /** @return MorphTo */ diff --git a/src/RehlaServiceProvider.php b/src/RehlaServiceProvider.php index 7d17467..28e7056 100644 --- a/src/RehlaServiceProvider.php +++ b/src/RehlaServiceProvider.php @@ -10,6 +10,8 @@ use Illuminate\Routing\Router; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; +use Rehla\Automation\FollowUpSender; +use Rehla\Automation\ProviderManager; use Rehla\Console\InstallCommand; use Rehla\Console\ReportCommand; use Rehla\Http\Middleware\AuthorizePanel; @@ -41,6 +43,9 @@ public function register(): void $app->make(JourneyRegistry::class), )); + $this->app->singleton(ProviderManager::class); + $this->app->singleton(FollowUpSender::class); + $this->app->singleton(TemplateSuggester::class, static fn (): TemplateSuggester => new TemplateSuggester); } diff --git a/tests/Feature/AutomatedSendTest.php b/tests/Feature/AutomatedSendTest.php new file mode 100644 index 0000000..4b0b885 --- /dev/null +++ b/tests/Feature/AutomatedSendTest.php @@ -0,0 +1,154 @@ +set('rehla.automation.enabled', true); + config()->set('rehla.automation.provider', 'meta'); + config()->set('rehla.automation.providers.meta.phone_number_id', '1'); + config()->set('rehla.automation.providers.meta.access_token', 't'); +}); + +function runJob(int $id): void +{ + (new SendAutomatedFollowUp($id))->handle(app(ProviderManager::class)); +} + +it('refuses to queue while automation is disabled', function () { + config()->set('rehla.automation.enabled', false); + + expect(fn () => app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi')) + ->toThrow(AutomationException::class, 'disabled'); +}); + +it('refuses users without a dialable number', function () { + expect(fn () => app(FollowUpSender::class)->queue($this->makeUser(['phone' => null]), 'hi')) + ->toThrow(AutomationException::class, 'phone'); +}); + +it('queues a row and dispatches the job on the configured queue', function () { + Bus::fake(); + config()->set('rehla.automation.queue.name', 'whatsapp'); + + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi', ['step' => 'profile']); + + expect($row->status)->toBe('queued') + ->and($row->source)->toBe('automation') + ->and($row->provider)->toBe('meta') + ->and($row->payload['phone'])->toBe('201070645696'); + + Bus::assertDispatched(SendAutomatedFollowUp::class, fn ($job) => $job->followUpId === $row->id && $job->queue === 'whatsapp'); +}); + +it('marks the row sent with the provider message id', function () { + Http::fake(['graph.facebook.com/*' => Http::response(['messages' => [['id' => 'wamid.1']]], 200)]); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + + runJob($row->id); + + $row->refresh(); + expect($row->status)->toBe('sent') + ->and($row->delivery_status)->toBe('sent') + ->and($row->provider_message_id)->toBe('wamid.1') + ->and($row->sent_at)->not->toBeNull() + ->and($row->attempts)->toBe(1); +}); + +it('keeps dry-run sends out of the real follow-up state', function () { + config()->set('rehla.automation.provider', 'log'); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + + runJob($row->id); + + $row->refresh(); + expect($row->status)->toBe('simulated')->and($row->sent_at)->toBeNull(); +}); + +it('does not retry permanent failures', function () { + Http::fake(['graph.facebook.com/*' => Http::response(['error' => ['code' => 131026, 'message' => 'undeliverable']], 400)]); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + + runJob($row->id); + + $row->refresh(); + expect($row->status)->toBe('failed') + ->and($row->error_code)->toBe('131026') + ->and($row->error_message)->toBe('undeliverable'); +}); + +it('retries temporary failures until the attempt limit, then fails', function () { + Http::fake(['graph.facebook.com/*' => Http::response([], 503)]); + config()->set('rehla.automation.retry.max_attempts', 2); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + + runJob($row->id); + expect($row->fresh()->status)->toBe('queued')->and($row->fresh()->attempts)->toBe(1); + + runJob($row->id); + expect($row->fresh()->status)->toBe('failed')->and($row->fresh()->attempts)->toBe(2); +}); + +it('is idempotent for the same key', function () { + Bus::fake(); + $user = $this->makeUser(['phone' => '01070645696']); + + $first = app(FollowUpSender::class)->queue($user, 'hi', ['idempotency_key' => 'rule-1:user-1:window-9']); + $second = app(FollowUpSender::class)->queue($user, 'hi', ['idempotency_key' => 'rule-1:user-1:window-9']); + + expect($second->id)->toBe($first->id)->and(RehlaFollowUp::query()->count())->toBe(1); + Bus::assertDispatchedTimes(SendAutomatedFollowUp::class, 1); +}); + +it('ignores a job whose row is already settled', function () { + Http::fake(); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + $row->forceFill(['status' => 'cancelled'])->save(); + + runJob($row->id); + + Http::assertNothingSent(); +}); + +it('fails the row on misconfiguration instead of retrying', function () { + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + config()->set('rehla.automation.providers.meta.access_token', null); + + runJob($row->id); + + expect($row->fresh()->status)->toBe('failed')->and($row->fresh()->error_code)->toBe('configuration'); +}); + +it('keeps automatic sends out of the last-follow-up column unless really sent', function () { + $this->allowPanel(); + config()->set('rehla.automation.provider', 'log'); + Bus::fake(); + $row = app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi'); + runJob($row->id); + + $this->get('/rehla')->assertOk()->assertDontSee('data-recent-followup="', false); +}); + +it('shows source and delivery status in the history', function () { + $this->allowPanel(); + $user = $this->makeUser(['phone' => '01070645696']); + Bus::fake(); + app(FollowUpSender::class)->queue($user, 'hi'); + + $item = $this->getJson('/rehla/follow-ups?user_id='.$user->id)->json('items.0'); + + expect($item['source'])->toBe('automation')->and($item['status'])->toBe('queued'); +}); diff --git a/tests/Feature/AutomationProvidersTest.php b/tests/Feature/AutomationProvidersTest.php new file mode 100644 index 0000000..fdaf8cb --- /dev/null +++ b/tests/Feature/AutomationProvidersTest.php @@ -0,0 +1,136 @@ + Http::response(['messages' => [['id' => 'wamid.ABC']]], 200)]); + + $provider = new MetaCloudProvider('1234567890', 'secret-token', 'v21.0', 'ar'); + $result = $provider->send(new OutboundMessage('201070645696', 'ignored', 'nudge_profile', 'ar', ['Ahmed', 'Profile'])); + + expect($result->accepted)->toBeTrue()->and($result->messageId)->toBe('wamid.ABC'); + + Http::assertSent(function ($request) { + $data = $request->data(); + + return $request->url() === 'https://graph.facebook.com/v21.0/1234567890/messages' + && $request->hasHeader('Authorization', 'Bearer secret-token') + && $data['to'] === '201070645696' + && $data['type'] === 'template' + && $data['template']['name'] === 'nudge_profile' + && $data['template']['language']['code'] === 'ar' + && $data['template']['components'][0]['parameters'][1]['text'] === 'Profile'; + }); +}); + +it('sends free text through Meta when no template is given', function () { + Http::fake(['graph.facebook.com/*' => Http::response(['messages' => [['id' => 'x']]], 200)]); + + (new MetaCloudProvider('1', 't'))->send(new OutboundMessage('201070645696', 'مرحبا')); + + Http::assertSent(fn ($request) => $request->data()['type'] === 'text' && $request->data()['text']['body'] === 'مرحبا'); +}); + +it('classifies Meta errors as retryable or permanent', function (int $status, bool $retryable) { + Http::fake(['graph.facebook.com/*' => Http::response(['error' => ['code' => 131049, 'message' => 'nope']], $status)]); + + $result = (new MetaCloudProvider('1', 't'))->send(new OutboundMessage('201070645696', 'x')); + + expect($result->accepted)->toBeFalse() + ->and($result->retryable)->toBe($retryable) + ->and($result->errorCode)->toBe('131049') + ->and($result->errorMessage)->toBe('nope'); +})->with([ + 'bad request' => [400, false], + 'unauthorized' => [401, false], + 'rate limited' => [429, true], + 'server error' => [503, true], +]); + +it('treats a connection failure as retryable', function () { + Http::fake(fn () => throw new ConnectionException('timeout')); + + $result = (new MetaCloudProvider('1', 't'))->send(new OutboundMessage('201070645696', 'x')); + + expect($result->retryable)->toBeTrue()->and($result->errorCode)->toBe('connection'); +}); + +it('renders the generic HTTP body placeholders and reads the message id path', function () { + Http::fake(['93.184.216.34/*' => Http::response(['data' => ['id' => 'abc-1']], 200)]); + + $provider = new HttpProvider( + url: 'https://93.184.216.34/send', + headers: ['X-Key' => 'k'], + body: ['to' => '{phone}', 'text' => '{message}', 'tpl' => ['name' => '{template}', 'vars' => '{params}']], + messageIdPath: 'data.id', + ); + + $result = $provider->send(new OutboundMessage('201070645696', 'hello', 'tpl_a', 'ar', ['A', 'B'])); + + expect($result->accepted)->toBeTrue()->and($result->messageId)->toBe('abc-1'); + + Http::assertSent(fn ($request) => $request->data() === [ + 'to' => '201070645696', 'text' => 'hello', 'tpl' => ['name' => 'tpl_a', 'vars' => ['A', 'B']], + ] && $request->hasHeader('X-Key', 'k')); +}); + +it('refuses unsafe provider URLs', function (string $url) { + expect(fn () => UrlGuard::assertSafe($url, false, true))->toThrow(AutomationException::class); +})->with([ + 'http' => ['http://93.184.216.34/x'], + 'loopback' => ['https://127.0.0.1/x'], + 'private 10' => ['https://10.0.0.5/x'], + 'private 192' => ['https://192.168.1.10/x'], + 'link local' => ['https://169.254.169.254/latest'], + 'no host' => ['https:///x'], +]); + +it('accepts a public https URL and honours the explicit dev overrides', function () { + UrlGuard::assertSafe('https://93.184.216.34/x', false, true); + UrlGuard::assertSafe('http://127.0.0.1/x', true, false); + + expect(true)->toBeTrue(); +}); + +it('builds providers from config and supports custom drivers', function () { + config()->set('rehla.automation.provider', 'meta'); + config()->set('rehla.automation.providers.meta.phone_number_id', '1'); + config()->set('rehla.automation.providers.meta.access_token', 't'); + $manager = app(ProviderManager::class); + + expect($manager->driver()->name())->toBe('meta')->and($manager->driver('log')->name())->toBe('log'); + + $manager->extend('acme', fn (array $config): WhatsAppProvider => new class implements WhatsAppProvider + { + public function name(): string + { + return 'acme'; + } + + public function send(OutboundMessage $message): SendResult + { + return SendResult::accepted('id'); + } + }); + config()->set('rehla.automation.providers.acme', ['driver' => 'acme']); + + expect($manager->driver('acme')->name())->toBe('acme'); +}); + +it('reports missing or unknown provider settings clearly', function () { + config()->set('rehla.automation.providers.meta.phone_number_id', null); + + expect(fn () => app(ProviderManager::class)->driver('meta'))->toThrow(AutomationException::class, 'phone_number_id') + ->and(fn () => app(ProviderManager::class)->driver('nope'))->toThrow(AutomationException::class, 'nope'); +});