diff --git a/CHANGELOG.md b/CHANGELOG.md index 482e036..65edd9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### Added (automation, phase B: consent and webhook) +- Consent (`rehla.consent`): required by default. Sources `table` (`Rehla::consent()->optIn/optOut`), `attribute` or a custom `ConsentResolver`. Opting out cancels queued automatic sends; the job re-checks consent before sending. `Rehla::forget()` also deletes consent history. New table `rehla_consents` (run `php artisan rehla:install` or `migrate`). +- Meta webhook (opt-in by config): signature-checked delivery status updates that never move backwards, failure reasons, and STOP keyword handling in English and Arabic. Config: `rehla.webhooks`, `REHLA_META_VERIFY_TOKEN`, `REHLA_META_APP_SECRET`. +- Panel marks opted-out users and asks for an override before a manual follow-up. + ### 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. diff --git a/README.md b/README.md index 6a516d8..49f117e 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,8 @@ 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=... +REHLA_META_VERIFY_TOKEN=... # for the webhook +REHLA_META_APP_SECRET=... ``` Providers (`rehla.automation.providers`): @@ -160,4 +162,17 @@ Providers (`rehla.automation.providers`): 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. +Consent comes first. By default Rehla only sends to users who opted in (`rehla.consent.required`). Meta requires opt-in too: https://developers.facebook.com/docs/whatsapp/overview/getting-opt-in/ + +```php +Rehla::consent()->optIn($user, 'signup_form', 'ticked the box'); +Rehla::consent()->optOut($user); // also cancels their queued automatic sends +``` + +Where consent comes from (`rehla.consent.source`): `table` (the calls above, latest decision wins and the history is kept), `attribute` (a truthy column or accessor named in `attribute`), or `resolver` (an invokable class implementing `Rehla\Contracts\ConsentResolver`). An opt-out recorded through Rehla blocks sends with any source. Set `required` to `false` only if you collect consent elsewhere. `Rehla::forget($user)` deletes their consent history too. + +Webhook (delivery status and STOP replies). It is only registered when the meta provider has both `REHLA_META_VERIFY_TOKEN` and `REHLA_META_APP_SECRET`. Point Meta at `https://your-app/rehla/webhooks/meta` (`rehla.webhooks.path`, `rehla.webhooks.middleware`). Requests without a valid `X-Hub-Signature-256` are rejected. Delivery states only move forward (sent, delivered, read); a failure is recorded with Meta's error. A user who replies with a stop keyword (`rehla.webhooks.stop_keywords`, English and Arabic by default, whole-message match, Arabic hamza forms treated alike) is opted out; `start_keywords` and the optional `stop_reply` / `start_reply` are config too. Matching a number to a user needs `rehla.phone_attribute` to be a real column. Webhook reference: https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/ + +In the panel, opted-out users get an "Opted out" mark and the follow-up modal asks for an explicit override before a manual message to them. + +Rules, the panel tab and hardening come in the next releases, so do not point automation at real users yet. diff --git a/config/rehla.php b/config/rehla.php index c190d60..10398c4 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -103,6 +103,10 @@ 'api_version' => env('REHLA_META_API_VERSION', 'v21.0'), 'language' => env('REHLA_META_TEMPLATE_LANGUAGE', 'ar'), 'timeout' => 15, + // For the webhook below: the token you type in Meta's webhook + // setup, and your Meta app secret (checks the signature). + 'verify_token' => env('REHLA_META_VERIFY_TOKEN'), + 'app_secret' => env('REHLA_META_APP_SECRET'), ], // Any service that takes an HTTP request. Body values may use @@ -132,6 +136,39 @@ ], ], + /* + | Consent for automatic messages. Meta requires the user's opt-in. + | required: false lets automation message users without a record + | (an opt-out always blocks, whatever this says). + | source: "table" (Rehla::consent()->optIn($user)), "attribute" (a + | truthy column or accessor named in `attribute`), or "resolver" + | (an invokable class implementing Rehla\Contracts\ConsentResolver). + */ + 'consent' => [ + 'required' => true, + 'source' => 'table', + 'attribute' => null, + 'resolver' => null, + ], + + /* + | Meta webhook: delivery status updates and STOP replies. It is only + | registered when the meta provider has both verify_token and app_secret. + | Point Meta at https://your-app/. Matching a STOP reply to a user + | needs `phone_attribute` to be a real database column. + | Keywords match the whole message, case-insensitive; Arabic hamza forms + | are treated alike. stop_reply / start_reply: text answered after a + | match (allowed because the user just wrote to you); null = silent. + */ + 'webhooks' => [ + 'path' => 'rehla/webhooks/meta', + 'middleware' => ['api'], + 'stop_keywords' => ['stop', 'unsubscribe', 'إيقاف', 'توقف', 'إلغاء الاشتراك'], + 'start_keywords' => [], + 'stop_reply' => null, + 'start_reply' => null, + ], + /* | 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_000007_create_rehla_consents_table.php b/database/migrations/2026_01_01_000007_create_rehla_consents_table.php new file mode 100644 index 0000000..fdac292 --- /dev/null +++ b/database/migrations/2026_01_01_000007_create_rehla_consents_table.php @@ -0,0 +1,32 @@ +id(); + $table->string('trackable_type'); + $table->unsignedBigInteger('trackable_id'); + $table->string('channel', 24)->default('whatsapp'); + $table->string('status', 16); + $table->string('source', 64)->nullable(); + $table->text('evidence')->nullable(); + $table->timestamps(); + + $table->index(['trackable_type', 'trackable_id', 'channel', 'id'], 'rehla_consents_user_index'); + }); + } + + public function down(): void + { + Schema::dropIfExists('rehla_consents'); + } +}; diff --git a/docs/ar/README.md b/docs/ar/README.md index 4ac2bbb..e32969c 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -150,6 +150,8 @@ REHLA_AUTOMATION_ENABLED=true REHLA_AUTOMATION_PROVIDER=log # log (تجريبي), meta, http, أو بتاعك REHLA_META_PHONE_NUMBER_ID=... REHLA_META_ACCESS_TOKEN=... +REHLA_META_VERIFY_TOKEN=... # للـ webhook +REHLA_META_APP_SECRET=... ``` مقدّمو الخدمة (`rehla.automation.providers`): @@ -160,4 +162,17 @@ REHLA_META_ACCESS_TOKEN=... الإرسال بيشتغل على الـ queue بتاعك (`rehla.automation.queue`)، فلازم يكون عندك queue worker شغال. الأعطال المؤقتة (timeout أو 429 أو 5xx) بتتعاد بالمهل في `rehla.automation.retry.backoff_seconds` (بالثواني: 60 = دقيقة، 3600 = ساعة)، والدائمة بتتعلّم فاشلة مع سبب المزوّد. كل إرسال تلقائي بيتسجّل في نفس سجل المتابعات زي اليدوي وعليه علامة "تلقائي". -الإصدار ده فيه طبقة الإرسال بس (`Rehla\Automation\FollowUpSender::queue($user, $message)`). الموافقة ومعالجة STOP والقواعد وتاب البانل جايين في الإصدارات الجاية، فلسه متوجهوش على مستخدمين حقيقيين. +الموافقة الأول. افتراضياً Rehla بتبعت للمستخدمين اللي وافقوا بس (`rehla.consent.required`). وميتا كمان بتشترط الموافقة: https://developers.facebook.com/docs/whatsapp/overview/getting-opt-in/ + +```php +Rehla::consent()->optIn($user, 'signup_form', 'ticked the box'); +Rehla::consent()->optOut($user); // وكمان بيلغي الرسائل التلقائية الواقفة في الطابور +``` + +مصدر الموافقة (`rehla.consent.source`): `table` (النداءات اللي فوق، آخر قرار هو المعتمد والتاريخ محفوظ)، أو `attribute` (عمود أو accessor قيمته صحيحة، اسمه في `attribute`)، أو `resolver` (كلاس بيطبّق `Rehla\Contracts\ConsentResolver`). أي إيقاف متسجّل عن طريق Rehla بيمنع الإرسال مهما كان المصدر. خلّي `required` بـ `false` بس لو بتجمع الموافقة من مكان تاني. و`Rehla::forget($user)` بيمسح تاريخ الموافقة كمان. + +الـ webhook (حالة التسليم وردود STOP). بيتسجّل بس لما الـ meta يكون عنده `REHLA_META_VERIFY_TOKEN` و`REHLA_META_APP_SECRET`. وجّه ميتا على `https://your-app/rehla/webhooks/meta` (`rehla.webhooks.path` و`rehla.webhooks.middleware`). أي طلب من غير `X-Hub-Signature-256` صحيح بيترفض. حالات التسليم بتتحرك لقدّام بس (sent ثم delivered ثم read)، والفشل بيتسجّل مع سبب ميتا. المستخدم اللي يرد بكلمة إيقاف (`rehla.webhooks.stop_keywords`، عربي وإنجليزي افتراضياً، لازم الرسالة كلها تطابق، وأشكال الهمزة متساوية) بيتعمله إيقاف. و`start_keywords` و`stop_reply` / `start_reply` اختيارية وكلها في الكونفيج. مطابقة الرقم بمستخدم محتاجة `rehla.phone_attribute` يكون عمود حقيقي. مرجع ميتا: https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/ + +في البانل المستخدمين اللي عملوا إيقاف عليهم علامة "أوقف الرسائل"، والمودال بيطلب تأكيد صريح قبل رسالة يدوية ليهم. + +القواعد وتاب البانل والتقوية جايين في الإصدارات الجاية، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين. diff --git a/resources/lang/ar/rehla.php b/resources/lang/ar/rehla.php index 85eb2fc..36a3bcd 100644 --- a/resources/lang/ar/rehla.php +++ b/resources/lang/ar/rehla.php @@ -50,6 +50,7 @@ 'no_phone' => 'لا يوجد رقم محفوظ', 'empty_users' => 'لا يوجد مستخدمون مطابقون لهذه التصفية.', 'modal' => [ + 'optout_override' => 'المستخدم ده طلب إيقاف رسائل واتساب. علّم هنا لو عاوز تبعت برضه.', 'recent_warning' => 'حد كلّم المستخدم ده قريب. راجع السجل الأول.', 'title' => 'إرسال رسالة واتساب', 'name' => 'المستخدم', @@ -85,6 +86,7 @@ ], 'validation' => [ 'unknown_journey' => 'هذه الرحلة غير معرّفة في إعدادات rehla.journeys.', + 'opted_out' => 'المستخدم ده طلب إيقاف رسائل واتساب.', 'unknown_user' => 'هذا المستخدم غير موجود.', 'unknown_step' => 'هذه الخطوة غير معرّفة في الرحلة المختارة.', 'step_needs_journey' => 'اختر الرحلة عند ربط القالب بخطوة.', diff --git a/resources/lang/en/rehla.php b/resources/lang/en/rehla.php index cfec183..7d00c48 100644 --- a/resources/lang/en/rehla.php +++ b/resources/lang/en/rehla.php @@ -50,6 +50,7 @@ 'no_phone' => 'No number saved', 'empty_users' => 'No users match this filter.', 'modal' => [ + 'optout_override' => 'This user opted out of WhatsApp messages. Tick to send anyway.', 'recent_warning' => 'Someone already followed up with this user recently. Check the history first.', 'title' => 'Send a WhatsApp message', 'name' => 'User', @@ -85,6 +86,7 @@ ], 'validation' => [ 'unknown_journey' => 'This journey is not defined in the rehla.journeys config.', + 'opted_out' => 'This user opted out of WhatsApp messages.', 'unknown_user' => 'This user does not exist.', 'unknown_step' => 'This step is not defined in the chosen journey.', 'step_needs_journey' => 'Choose a journey when the template is tied to a step.', diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php index 9e9f830..696e776 100644 --- a/resources/views/dashboard.blade.php +++ b/resources/views/dashboard.blade.php @@ -76,6 +76,9 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} @if ($warnWithinHours > 0 && ($lastFollowUps[$user->getKey()] ?? null) !== null && $lastFollowUps[$user->getKey()]->gt(now()->subHours($warnWithinHours))) data-recent-followup="{{ $lastFollowUps[$user->getKey()]->diffForHumans() }}" @endif + @if (isset($optedOut[$user->getKey()])) + data-opted-out="1" + @endif data-name="{{ $user->getAttribute($nameAttribute) }}" data-number="{{ $phones[$user->getKey()] }}" data-suggested="{{ $suggestions[$user->getKey()] ?? '' }}"> @@ -120,6 +123,9 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}
+
@@ -155,6 +161,10 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} var overlay = document.getElementById('rehla-modal'); var nameEl = document.getElementById('rehla-modal-name'); var warningEl = document.getElementById('rehla-modal-warning'); + var optoutEl = document.getElementById('rehla-modal-optout'); + var optoutOverrideEl = document.getElementById('rehla-optout-override'); + var sendButtonEl = document.getElementById('rehla-modal-send'); + var optedOut = false; var numberEl = document.getElementById('rehla-modal-number'); var selectEl = document.getElementById('rehla-modal-template'); var messageEl = document.getElementById('rehla-modal-message'); @@ -209,6 +219,10 @@ function syncMessage() { confirmEl.hidden = true; nameEl.textContent = currentName; var recent = button.getAttribute('data-recent-followup'); + optedOut = button.getAttribute('data-opted-out') === '1'; + optoutEl.hidden = !optedOut; + optoutOverrideEl.checked = false; + sendButtonEl.disabled = optedOut; warningEl.hidden = !recent; warningEl.textContent = recent ? labels.recent + ' (' + recent + ')' : ''; numberEl.textContent = number; @@ -230,6 +244,10 @@ function syncMessage() { } }); + optoutOverrideEl.addEventListener('change', function () { + sendButtonEl.disabled = optedOut && !optoutOverrideEl.checked; + }); + document.getElementById('rehla-modal-send').addEventListener('click', function () { var message = messageEl.value; if (!number || !message) { @@ -255,7 +273,8 @@ function syncMessage() { message: message, template_id: selected ? selected.id : null, journey: selected ? selected.journey : null, - step: selected ? selected.step : null + step: selected ? selected.step : null, + override_opt_out: optedOut && optoutOverrideEl.checked }) }).then(function (response) { return response.ok ? response.json() : null; diff --git a/routes/webhooks.php b/routes/webhooks.php new file mode 100644 index 0000000..d5f6bbb --- /dev/null +++ b/routes/webhooks.php @@ -0,0 +1,9 @@ +name('rehla.webhooks.meta.verify'); +Route::post('/', [MetaWebhookController::class, 'receive'])->name('rehla.webhooks.meta.receive'); diff --git a/src/Automation/FollowUpSender.php b/src/Automation/FollowUpSender.php index 5be6d8b..cbeabcd 100644 --- a/src/Automation/FollowUpSender.php +++ b/src/Automation/FollowUpSender.php @@ -9,6 +9,7 @@ use Rehla\Exceptions\AutomationException; use Rehla\Jobs\SendAutomatedFollowUp; use Rehla\Models\RehlaFollowUp; +use Rehla\Services\ConsentManager; use Rehla\Services\WhatsAppLink; /** @@ -17,7 +18,10 @@ */ final class FollowUpSender { - public function __construct(private readonly ProviderManager $providers) {} + public function __construct( + private readonly ProviderManager $providers, + private readonly ConsentManager $consent, + ) {} /** * @param array{ @@ -36,6 +40,10 @@ public function queue(Model $user, string $message, array $options = []): RehlaF throw AutomationException::disabled(); } + if (! $this->consent->allows($user)) { + throw AutomationException::noConsent(); + } + $key = $options['idempotency_key'] ?? null; if ($key !== null) { diff --git a/src/Contracts/ConsentResolver.php b/src/Contracts/ConsentResolver.php new file mode 100644 index 0000000..da61244 --- /dev/null +++ b/src/Contracts/ConsentResolver.php @@ -0,0 +1,17 @@ + $phones, 'lastSeen' => $lastSeen, 'lastFollowUps' => $lastFollowUps, + 'optedOut' => app(ConsentManager::class)->optedOutAmong($userInstance, $ids), 'confirmSent' => (bool) config('rehla.follow_up.confirm_sent', true), 'warnWithinHours' => max(0, (int) config('rehla.follow_up.warn_within_hours', 24)), 'nameAttribute' => $nameAttribute, diff --git a/src/Http/Controllers/FollowUpController.php b/src/Http/Controllers/FollowUpController.php index 10488d3..80f0d34 100644 --- a/src/Http/Controllers/FollowUpController.php +++ b/src/Http/Controllers/FollowUpController.php @@ -11,6 +11,7 @@ use Rehla\Exceptions\ConfigurationException; use Rehla\Models\RehlaFollowUp; use Rehla\Models\RehlaTemplate; +use Rehla\Services\ConsentManager; use Rehla\Services\JourneyRegistry; final class FollowUpController @@ -28,6 +29,7 @@ public function store(Request $request, JourneyRegistry $journeys): JsonResponse 'template_id' => ['nullable', 'integer', 'exists:rehla_templates,id'], 'journey' => ['nullable', 'string', 'max:100'], 'step' => ['nullable', 'string', 'max:100'], + 'override_opt_out' => ['nullable', 'boolean'], ]); $user = $this->findUser((int) $data['user_id']); @@ -36,6 +38,10 @@ public function store(Request $request, JourneyRegistry $journeys): JsonResponse throw ValidationException::withMessages(['user_id' => __('rehla::rehla.validation.unknown_user')]); } + if (! $request->boolean('override_opt_out') && app(ConsentManager::class)->isOptedOut($user)) { + throw ValidationException::withMessages(['user_id' => __('rehla::rehla.validation.opted_out')]); + } + $journey = isset($data['journey']) && $data['journey'] !== '' ? $data['journey'] : null; $step = isset($data['step']) && $data['step'] !== '' ? $data['step'] : null; diff --git a/src/Http/Controllers/MetaWebhookController.php b/src/Http/Controllers/MetaWebhookController.php new file mode 100644 index 0000000..caa7a2e --- /dev/null +++ b/src/Http/Controllers/MetaWebhookController.php @@ -0,0 +1,231 @@ + 1, 'delivered' => 2, 'read' => 3]; + + public function verify(Request $request): Response + { + $token = (string) config('rehla.automation.providers.meta.verify_token', ''); + $given = $request->query('hub_verify_token', $request->query('hub.verify_token')); + $challenge = $request->query('hub_challenge', $request->query('hub.challenge')); + $mode = $request->query('hub_mode', $request->query('hub.mode')); + + if ($mode === 'subscribe' && $token !== '' && is_string($given) && hash_equals($token, $given) && is_scalar($challenge)) { + return response((string) $challenge, 200)->header('Content-Type', 'text/plain'); + } + + abort(403); + } + + public function receive(Request $request, ConsentManager $consent, ProviderManager $providers): Response + { + $secret = (string) config('rehla.automation.providers.meta.app_secret', ''); + $signature = (string) $request->header('X-Hub-Signature-256', ''); + $expected = 'sha256='.hash_hmac('sha256', $request->getContent(), $secret); + + abort_if($secret === '' || ! hash_equals($expected, $signature), 403); + + $payload = json_decode($request->getContent(), true); + + if (! is_array($payload)) { + return response('', 200); + } + + foreach ((array) ($payload['entry'] ?? []) as $entry) { + foreach ((array) (is_array($entry) ? ($entry['changes'] ?? []) : []) as $change) { + $value = is_array($change) ? ($change['value'] ?? null) : null; + + if (! is_array($value)) { + continue; + } + + foreach ((array) ($value['statuses'] ?? []) as $status) { + if (is_array($status)) { + $this->applyStatus($status); + } + } + + foreach ((array) ($value['messages'] ?? []) as $message) { + if (is_array($message)) { + $this->applyInbound($message, $consent, $providers); + } + } + } + } + + return response('', 200); + } + + /** @param array $status */ + private function applyStatus(array $status): void + { + $id = $status['id'] ?? null; + $state = $status['status'] ?? null; + + if (! is_string($id) || ! is_string($state)) { + return; + } + + $followUp = RehlaFollowUp::query()->where('provider_message_id', $id)->first(); + + if ($followUp === null) { + return; + } + + $current = $followUp->delivery_status; + + if ($state === 'failed') { + if (in_array($current, ['delivered', 'read'], true)) { + return; + } + + $error = is_array($status['errors'][0] ?? null) ? $status['errors'][0] : []; + $followUp->forceFill([ + 'status' => RehlaFollowUp::STATUS_FAILED, + 'delivery_status' => 'failed', + 'error_code' => isset($error['code']) && is_scalar($error['code']) ? (string) $error['code'] : null, + 'error_message' => isset($error['title']) && is_string($error['title']) ? mb_substr($error['title'], 0, 1000) : null, + ])->save(); + + return; + } + + if (! isset(self::RANK[$state])) { + return; + } + + // Webhooks can arrive out of order: never move backwards. + if ($current !== null && (self::RANK[$current] ?? 0) >= self::RANK[$state]) { + return; + } + + $followUp->forceFill(['delivery_status' => $state])->save(); + } + + /** @param array $message */ + private function applyInbound(array $message, ConsentManager $consent, ProviderManager $providers): void + { + $from = $message['from'] ?? null; + $text = is_array($message['text'] ?? null) ? ($message['text']['body'] ?? null) : null; + + if (! is_string($from) || ! is_string($text)) { + return; + } + + $normalized = $this->normalizeKeyword($text); + $stop = $this->keywords('rehla.webhooks.stop_keywords'); + $start = $this->keywords('rehla.webhooks.start_keywords'); + $isStop = in_array($normalized, $stop, true); + $isStart = in_array($normalized, $start, true); + + if (! $isStop && ! $isStart) { + return; + } + + $user = $this->findUser($from); + + if ($user === null) { + return; + } + + if ($isStop) { + $consent->optOut($user, 'whatsapp_reply', 'Inbound keyword: '.mb_substr($text, 0, 100)); + $this->reply($providers, $from, config('rehla.webhooks.stop_reply')); + + return; + } + + $consent->optIn($user, 'whatsapp_reply', 'Inbound keyword: '.mb_substr($text, 0, 100)); + $this->reply($providers, $from, config('rehla.webhooks.start_reply')); + } + + private function reply(ProviderManager $providers, string $to, mixed $text): void + { + if (! is_string($text) || trim($text) === '') { + return; + } + + // The user just wrote to us, so free text is allowed. Best effort. + try { + $providers->driver()->send(new OutboundMessage($to, $text)); + } catch (Throwable $e) { + report($e); + } + } + + /** @return list */ + private function keywords(string $key): array + { + $out = []; + + foreach ((array) config($key, []) as $word) { + if (is_string($word) && trim($word) !== '') { + $out[] = $this->normalizeKeyword($word); + } + } + + return $out; + } + + private function normalizeKeyword(string $text): string + { + $text = mb_strtolower(trim($text)); + $text = preg_replace('/[\p{P}\p{S}\s]+/u', ' ', $text) ?? $text; + $text = str_replace(['أ', 'إ', 'آ'], 'ا', trim($text)); + + return $text; + } + + private function findUser(string $from): ?Model + { + /** @var class-string $userModel */ + $userModel = (string) config('rehla.user_model', 'App\\Models\\User'); + + if (! class_exists($userModel) || ! is_subclass_of($userModel, Model::class)) { + return null; + } + + $digits = preg_replace('/\D+/', '', $from) ?? ''; + + if (strlen($digits) < 8) { + return null; + } + + $attribute = (string) config('rehla.phone_attribute', 'phone'); + $country = (string) config('rehla.whatsapp.default_country_code', ''); + $tail = substr($digits, -8); + + // The stored number may be local (0107...) or international (2010...): + // narrow by the last digits in SQL, confirm by normalising in PHP. + $candidates = $userModel::query()->where($attribute, 'like', '%'.$tail.'%')->limit(20)->get(); + + foreach ($candidates as $candidate) { + $stored = $candidate->getAttribute($attribute); + + if (WhatsAppLink::normalizeNumber(is_string($stored) ? $stored : null, $country) === $digits) { + return $candidate; + } + } + + return null; + } +} diff --git a/src/Jobs/SendAutomatedFollowUp.php b/src/Jobs/SendAutomatedFollowUp.php index cdc010f..3ea9982 100644 --- a/src/Jobs/SendAutomatedFollowUp.php +++ b/src/Jobs/SendAutomatedFollowUp.php @@ -6,6 +6,7 @@ use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; @@ -13,6 +14,7 @@ use Rehla\Automation\ProviderManager; use Rehla\Exceptions\RehlaException; use Rehla\Models\RehlaFollowUp; +use Rehla\Services\ConsentManager; final class SendAutomatedFollowUp implements ShouldQueue { @@ -26,7 +28,7 @@ final class SendAutomatedFollowUp implements ShouldQueue public function __construct(public readonly int $followUpId) {} - public function handle(ProviderManager $providers): void + public function handle(ProviderManager $providers, ConsentManager $consent): void { $followUp = RehlaFollowUp::query()->find($this->followUpId); @@ -34,6 +36,18 @@ public function handle(ProviderManager $providers): void return; } + $user = $followUp->trackable; + + if ($user instanceof Model && ! $consent->allows($user)) { + // Opted out (or consent withdrawn) while the message waited. + $followUp->forceFill([ + 'status' => RehlaFollowUp::STATUS_CANCELLED, + 'skip_reason' => $consent->isOptedOut($user) ? 'opted_out' : 'no_consent', + ])->save(); + + return; + } + $payload = $followUp->payload ?? []; $phone = $payload['phone'] ?? null; diff --git a/src/Models/RehlaConsent.php b/src/Models/RehlaConsent.php new file mode 100644 index 0000000..e7a4003 --- /dev/null +++ b/src/Models/RehlaConsent.php @@ -0,0 +1,37 @@ + */ + protected $fillable = ['trackable_type', 'trackable_id', 'channel', 'status', 'source', 'evidence']; + + /** @return MorphTo */ + public function trackable(): MorphTo + { + return $this->morphTo(); + } +} diff --git a/src/RehlaManager.php b/src/RehlaManager.php index 957b4f0..c0e0704 100644 --- a/src/RehlaManager.php +++ b/src/RehlaManager.php @@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Model; use Rehla\Data\UserProgress; use Rehla\Models\RehlaStepProgress; +use Rehla\Services\ConsentManager; use Rehla\Services\JourneyRegistry; use Rehla\Services\ProgressQuery; use Rehla\Services\ProgressTracker; @@ -54,6 +55,11 @@ public function forget(Model $user): void $this->tracker()->forget($user); } + public function consent(): ConsentManager + { + return $this->app->make(ConsentManager::class); + } + public function recordVisit(Model $user): void { $throttle = (int) $this->app->make(Config::class)->get('rehla.activity.throttle_seconds', 300); diff --git a/src/RehlaServiceProvider.php b/src/RehlaServiceProvider.php index 28e7056..65a1c1a 100644 --- a/src/RehlaServiceProvider.php +++ b/src/RehlaServiceProvider.php @@ -16,6 +16,7 @@ use Rehla\Console\ReportCommand; use Rehla\Http\Middleware\AuthorizePanel; use Rehla\Http\Middleware\RecordActivity; +use Rehla\Services\ConsentManager; use Rehla\Services\JourneyRegistry; use Rehla\Services\ProgressQuery; use Rehla\Services\ProgressTracker; @@ -45,6 +46,7 @@ public function register(): void $this->app->singleton(ProviderManager::class); $this->app->singleton(FollowUpSender::class); + $this->app->singleton(ConsentManager::class); $this->app->singleton(TemplateSuggester::class, static fn (): TemplateSuggester => new TemplateSuggester); } @@ -78,6 +80,24 @@ public function boot(): void $this->app->make(Router::class)->aliasMiddleware('rehla.activity', RecordActivity::class); $this->registerPanelRoutes(); + $this->registerWebhookRoutes(); + } + + private function registerWebhookRoutes(): void + { + $config = $this->app->make(Config::class); + + if ((string) $config->get('rehla.automation.providers.meta.verify_token', '') === '' + || (string) $config->get('rehla.automation.providers.meta.app_secret', '') === '') { + return; + } + + Route::group([ + 'prefix' => (string) $config->get('rehla.webhooks.path', 'rehla/webhooks/meta'), + 'middleware' => (array) $config->get('rehla.webhooks.middleware', ['api']), + ], function (): void { + $this->loadRoutesFrom(__DIR__.'/../routes/webhooks.php'); + }); } private function registerPanelRoutes(): void diff --git a/src/Services/ConsentManager.php b/src/Services/ConsentManager.php new file mode 100644 index 0000000..0c610ec --- /dev/null +++ b/src/Services/ConsentManager.php @@ -0,0 +1,144 @@ +record($user, RehlaConsent::OPTED_IN, $source, $evidence); + } + + /** Also cancels automatic messages still waiting in the queue. */ + public function optOut(Model $user, ?string $source = null, ?string $evidence = null): RehlaConsent + { + $consent = $this->record($user, RehlaConsent::OPTED_OUT, $source, $evidence); + + RehlaFollowUp::query() + ->whereMorphedTo('trackable', $user) + ->where('source', RehlaFollowUp::SOURCE_AUTOMATION) + ->where('status', RehlaFollowUp::STATUS_QUEUED) + ->update(['status' => RehlaFollowUp::STATUS_CANCELLED, 'skip_reason' => 'opted_out']); + + return $consent; + } + + /** The latest recorded decision: "opted_in", "opted_out" or null. */ + public function status(Model $user): ?string + { + $latest = RehlaConsent::query() + ->whereMorphedTo('trackable', $user) + ->where('channel', self::CHANNEL) + ->latest('id') + ->first(); + + return $latest?->status; + } + + public function isOptedOut(Model $user): bool + { + return $this->status($user) === RehlaConsent::OPTED_OUT; + } + + /** + * @param array $ids + * @return array ids whose latest decision is an opt-out + */ + public function optedOutAmong(Model $sample, array $ids): array + { + if ($ids === []) { + return []; + } + + $latest = []; + + $rows = RehlaConsent::query() + ->where('trackable_type', $sample->getMorphClass()) + ->whereIn('trackable_id', $ids) + ->where('channel', self::CHANNEL) + ->orderBy('id') + ->get(['trackable_id', 'status']); + + foreach ($rows as $row) { + $latest[$row->trackable_id] = $row->status; + } + + $out = []; + + foreach ($latest as $id => $status) { + if ($status === RehlaConsent::OPTED_OUT) { + $out[$id] = true; + } + } + + return $out; + } + + /** May this user get automatic messages, under the configured policy? */ + public function allows(Model $user): bool + { + $status = $this->status($user); + + if ($status === RehlaConsent::OPTED_OUT) { + return false; + } + + if (! (bool) config('rehla.consent.required', true)) { + return true; + } + + return match ((string) config('rehla.consent.source', 'table')) { + 'attribute' => $this->fromAttribute($user), + 'resolver' => $this->fromResolver($user), + default => $status === RehlaConsent::OPTED_IN, + }; + } + + private function fromAttribute(Model $user): bool + { + $attribute = config('rehla.consent.attribute'); + + return is_string($attribute) && $attribute !== '' && (bool) $user->getAttribute($attribute); + } + + private function fromResolver(Model $user): bool + { + $class = config('rehla.consent.resolver'); + + if (! is_string($class) || ! class_exists($class)) { + return false; + } + + $resolver = $this->app->make($class); + + return $resolver instanceof ConsentResolver && $resolver->hasConsent($user); + } + + private function record(Model $user, string $status, ?string $source, ?string $evidence): RehlaConsent + { + return RehlaConsent::query()->create([ + 'trackable_type' => $user->getMorphClass(), + 'trackable_id' => $user->getKey(), + 'channel' => self::CHANNEL, + 'status' => $status, + 'source' => $source, + 'evidence' => $evidence, + ]); + } +} diff --git a/src/Services/ProgressTracker.php b/src/Services/ProgressTracker.php index acec8a1..496e40d 100644 --- a/src/Services/ProgressTracker.php +++ b/src/Services/ProgressTracker.php @@ -11,6 +11,7 @@ use Rehla\Events\StepCompleted; use Rehla\Events\StepStarted; use Rehla\Models\RehlaActivity; +use Rehla\Models\RehlaConsent; use Rehla\Models\RehlaFollowUp; use Rehla\Models\RehlaStepProgress; @@ -141,6 +142,7 @@ public function forget(Model $user): void RehlaStepProgress::query()->whereMorphedTo('trackable', $user)->delete(); RehlaActivity::query()->whereMorphedTo('trackable', $user)->delete(); RehlaFollowUp::query()->whereMorphedTo('trackable', $user)->delete(); + RehlaConsent::query()->whereMorphedTo('trackable', $user)->delete(); } /** diff --git a/tests/Feature/AutomatedSendTest.php b/tests/Feature/AutomatedSendTest.php index 4b0b885..7d2debc 100644 --- a/tests/Feature/AutomatedSendTest.php +++ b/tests/Feature/AutomatedSendTest.php @@ -9,8 +9,10 @@ use Rehla\Exceptions\AutomationException; use Rehla\Jobs\SendAutomatedFollowUp; use Rehla\Models\RehlaFollowUp; +use Rehla\Services\ConsentManager; beforeEach(function () { + config()->set('rehla.consent.required', false); config()->set('rehla.automation.enabled', true); config()->set('rehla.automation.provider', 'meta'); config()->set('rehla.automation.providers.meta.phone_number_id', '1'); @@ -19,7 +21,7 @@ function runJob(int $id): void { - (new SendAutomatedFollowUp($id))->handle(app(ProviderManager::class)); + (new SendAutomatedFollowUp($id))->handle(app(ProviderManager::class), app(ConsentManager::class)); } it('refuses to queue while automation is disabled', function () { diff --git a/tests/Feature/ConsentTest.php b/tests/Feature/ConsentTest.php new file mode 100644 index 0000000..1f6c78b --- /dev/null +++ b/tests/Feature/ConsentTest.php @@ -0,0 +1,141 @@ +set('rehla.automation.enabled', true); +}); + +it('treats the latest decision as the current state', function () { + $user = $this->makeUser(); + expect(Rehla::consent()->status($user))->toBeNull(); + + Rehla::consent()->optIn($user, 'signup_form', 'ticked the box'); + expect(Rehla::consent()->status($user))->toBe('opted_in'); + + Rehla::consent()->optOut($user, 'whatsapp_reply'); + expect(Rehla::consent()->status($user))->toBe('opted_out') + ->and(RehlaConsent::query()->count())->toBe(2); + + Rehla::consent()->optIn($user); + expect(Rehla::consent()->status($user))->toBe('opted_in'); +}); + +it('requires an opt-in by default', function () { + $user = $this->makeUser(); + expect(Rehla::consent()->allows($user))->toBeFalse(); + + Rehla::consent()->optIn($user); + expect(Rehla::consent()->allows($user))->toBeTrue(); +}); + +it('lets the developer turn the requirement off, but an opt-out still blocks', function () { + config()->set('rehla.consent.required', false); + $user = $this->makeUser(); + expect(Rehla::consent()->allows($user))->toBeTrue(); + + Rehla::consent()->optOut($user); + expect(Rehla::consent()->allows($user))->toBeFalse(); +}); + +it('can read consent from a user attribute', function () { + config()->set('rehla.consent.source', 'attribute'); + config()->set('rehla.consent.attribute', 'name'); + $user = $this->makeUser(['name' => 'yes']); + + expect(Rehla::consent()->allows($user))->toBeTrue(); + + Rehla::consent()->optOut($user); + expect(Rehla::consent()->allows($user))->toBeFalse(); +}); + +it('can ask an app resolver', function () { + config()->set('rehla.consent.source', 'resolver'); + config()->set('rehla.consent.resolver', AlwaysConsents::class); + + expect(Rehla::consent()->allows($this->makeUser()))->toBeTrue(); +}); + +it('refuses to queue an automatic send without consent', function () { + expect(fn () => app(FollowUpSender::class)->queue($this->makeUser(['phone' => '01070645696']), 'hi')) + ->toThrow(AutomationException::class, 'opted in'); +}); + +it('cancels queued sends when the user opts out, and the job then sends nothing', function () { + Bus::fake(); + $user = $this->makeUser(['phone' => '01070645696']); + Rehla::consent()->optIn($user); + $row = app(FollowUpSender::class)->queue($user, 'hi'); + + Rehla::consent()->optOut($user, 'whatsapp_reply'); + + expect($row->fresh()->status)->toBe('cancelled')->and($row->fresh()->skip_reason)->toBe('opted_out'); + (new SendAutomatedFollowUp($row->id))->handle(app(ProviderManager::class), app(ConsentManager::class)); + expect($row->fresh()->status)->toBe('cancelled'); +}); + +it('stops a send in the job when consent was withdrawn without a record', function () { + Bus::fake(); + config()->set('rehla.consent.source', 'attribute'); + config()->set('rehla.consent.attribute', 'name'); + $user = $this->makeUser(['phone' => '01070645696', 'name' => 'yes']); + $row = app(FollowUpSender::class)->queue($user, 'hi'); + + $user->forceFill(['name' => ''])->save(); + (new SendAutomatedFollowUp($row->id))->handle(app(ProviderManager::class), app(ConsentManager::class)); + + expect($row->fresh()->status)->toBe('cancelled')->and($row->fresh()->skip_reason)->toBe('no_consent'); +}); + +it('forgetting a user deletes their consent history', function () { + $user = $this->makeUser(); + Rehla::consent()->optIn($user); + + Rehla::forget($user); + + expect(RehlaConsent::query()->count())->toBe(0); +}); + +it('blocks a manual follow-up to an opted-out user unless the admin overrides', function () { + $this->actingAs($this->makeUser()); + Gate::define('viewRehla', fn ($u = null) => $u !== null); + $user = $this->makeUser(['phone' => '01070645696']); + Rehla::consent()->optOut($user); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi']) + ->assertUnprocessable()->assertJsonValidationErrors('user_id'); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi', 'override_opt_out' => true]) + ->assertOk(); + + expect(RehlaFollowUp::query()->count())->toBe(1); +}); + +it('marks opted-out users in the panel', function () { + $this->allowPanel(); + $user = $this->makeUser(['phone' => '01070645696']); + Rehla::consent()->optOut($user); + + $this->get('/rehla')->assertOk()->assertSee('data-opted-out="1"', false); +}); + +final class AlwaysConsents implements ConsentResolver +{ + public function hasConsent(Model $user): bool + { + return true; + } +} diff --git a/tests/Feature/InstallTest.php b/tests/Feature/InstallTest.php index 94a115b..a9b2669 100644 --- a/tests/Feature/InstallTest.php +++ b/tests/Feature/InstallTest.php @@ -9,7 +9,7 @@ function dropRehlaTables(): void { - foreach (['rehla_follow_ups', 'rehla_templates', 'rehla_activity', 'rehla_step_progress'] as $table) { + foreach (['rehla_consents', 'rehla_follow_ups', 'rehla_templates', 'rehla_activity', 'rehla_step_progress'] as $table) { Schema::dropIfExists($table); } diff --git a/tests/Feature/MetaWebhookTest.php b/tests/Feature/MetaWebhookTest.php new file mode 100644 index 0000000..5841237 --- /dev/null +++ b/tests/Feature/MetaWebhookTest.php @@ -0,0 +1,104 @@ +call('POST', '/rehla/webhooks/meta', [], [], [], [ + 'CONTENT_TYPE' => 'application/json', + 'HTTP_X_HUB_SIGNATURE_256' => $sig, + ], (string) $body); +} + +function inbound(string $from, string $text): array +{ + return ['entry' => [['changes' => [['value' => ['messages' => [['from' => $from, 'text' => ['body' => $text]]]]]]]]]; +} + +function statusPayload(string $id, string $status, array $extra = []): array +{ + return ['entry' => [['changes' => [['value' => ['statuses' => [['id' => $id, 'status' => $status] + $extra]]]]]]]; +} + +function sentRow(object $user, string $wamid): RehlaFollowUp +{ + $row = RehlaFollowUp::query()->create([ + 'trackable_type' => $user::class, 'trackable_id' => $user->id, 'message' => 'hi', + 'status' => 'sent', 'source' => 'automation', 'provider_message_id' => $wamid, + ]); + + return $row; +} + +it('answers the subscription handshake only with the right token', function () { + $this->get('/rehla/webhooks/meta?hub_mode=subscribe&hub_verify_token=vt&hub_challenge=1234') + ->assertOk()->assertSee('1234'); + + $this->get('/rehla/webhooks/meta?hub_mode=subscribe&hub_verify_token=bad&hub_challenge=1234') + ->assertForbidden(); +}); + +it('rejects an unsigned or wrongly signed post', function () { + $this->postJson('/rehla/webhooks/meta', inbound('201070645696', 'STOP'))->assertForbidden(); + signedPost($this, inbound('201070645696', 'STOP'), 'wrong')->assertForbidden(); +}); + +it('opts a user out on an English STOP and an Arabic keyword', function (string $word) { + $user = $this->makeUser(['phone' => '01070645696']); + + signedPost($this, inbound('201070645696', $word))->assertOk(); + + expect(Rehla::consent()->isOptedOut($user))->toBeTrue(); +})->with(['STOP', ' Stop! ', 'إيقاف', 'ايقاف']); + +it('ignores ordinary replies and unknown numbers', function () { + $user = $this->makeUser(['phone' => '01070645696']); + + signedPost($this, inbound('201070645696', 'thanks, please stop by tomorrow'))->assertOk(); + signedPost($this, inbound('201999999999', 'STOP'))->assertOk(); + + expect(Rehla::consent()->status($user))->toBeNull(); +}); + +it('opts back in on a configured start keyword', function () { + config()->set('rehla.webhooks.start_keywords', ['start']); + $user = $this->makeUser(['phone' => '01070645696']); + Rehla::consent()->optOut($user); + + signedPost($this, inbound('201070645696', 'START'))->assertOk(); + + expect(Rehla::consent()->status($user))->toBe('opted_in'); +}); + +it('moves delivery status forward and never backwards', function () { + $row = sentRow($this->makeUser(['phone' => '01070645696']), 'wamid.1'); + + signedPost($this, statusPayload('wamid.1', 'read'))->assertOk(); + expect($row->fresh()->delivery_status)->toBe('read'); + + signedPost($this, statusPayload('wamid.1', 'delivered'))->assertOk(); + expect($row->fresh()->delivery_status)->toBe('read'); +}); + +it('records a failed delivery with its error', function () { + $row = sentRow($this->makeUser(['phone' => '01070645696']), 'wamid.2'); + + signedPost($this, statusPayload('wamid.2', 'failed', ['errors' => [['code' => 131026, 'title' => 'Undeliverable']]]))->assertOk(); + + $fresh = $row->fresh(); + expect($fresh->status)->toBe('failed')->and($fresh->error_code)->toBe('131026')->and($fresh->error_message)->toBe('Undeliverable'); +}); + +it('does not turn a delivered message into a failure', function () { + $row = sentRow($this->makeUser(['phone' => '01070645696']), 'wamid.3'); + signedPost($this, statusPayload('wamid.3', 'delivered'))->assertOk(); + signedPost($this, statusPayload('wamid.3', 'failed'))->assertOk(); + + expect($row->fresh()->status)->toBe('sent')->and($row->fresh()->delivery_status)->toBe('delivered'); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index d9e5efd..885fcb7 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -41,6 +41,8 @@ protected function defineEnvironment($app): void ], ]); $app['config']->set('rehla.panel.gate', 'viewRehla'); + $app['config']->set('rehla.automation.providers.meta.verify_token', 'vt'); + $app['config']->set('rehla.automation.providers.meta.app_secret', 'shh'); } protected function defineDatabaseMigrations(): void