Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`):
Expand All @@ -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.
37 changes: 37 additions & 0 deletions config/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<path>. 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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/** Append-only: the latest row per user and channel is the current state. */
public function up(): void
{
Schema::create('rehla_consents', function (Blueprint $table): void {
$table->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');
}
};
17 changes: 16 additions & 1 deletion docs/ar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`):
Expand All @@ -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/

في البانل المستخدمين اللي عملوا إيقاف عليهم علامة "أوقف الرسائل"، والمودال بيطلب تأكيد صريح قبل رسالة يدوية ليهم.

القواعد وتاب البانل والتقوية جايين في الإصدارات الجاية، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين.
2 changes: 2 additions & 0 deletions resources/lang/ar/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
'no_phone' => 'لا يوجد رقم محفوظ',
'empty_users' => 'لا يوجد مستخدمون مطابقون لهذه التصفية.',
'modal' => [
'optout_override' => 'المستخدم ده طلب إيقاف رسائل واتساب. علّم هنا لو عاوز تبعت برضه.',
'recent_warning' => 'حد كلّم المستخدم ده قريب. راجع السجل الأول.',
'title' => 'إرسال رسالة واتساب',
'name' => 'المستخدم',
Expand Down Expand Up @@ -85,6 +86,7 @@
],
'validation' => [
'unknown_journey' => 'هذه الرحلة غير معرّفة في إعدادات rehla.journeys.',
'opted_out' => 'المستخدم ده طلب إيقاف رسائل واتساب.',
'unknown_user' => 'هذا المستخدم غير موجود.',
'unknown_step' => 'هذه الخطوة غير معرّفة في الرحلة المختارة.',
'step_needs_journey' => 'اختر الرحلة عند ربط القالب بخطوة.',
Expand Down
2 changes: 2 additions & 0 deletions resources/lang/en/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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.',
Expand Down
21 changes: 20 additions & 1 deletion resources/views/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
@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()] ?? '' }}">
Expand Down Expand Up @@ -120,6 +123,9 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
<dd id="rehla-modal-number" dir="ltr"></dd>
</dl>
<div class="followup-warning" id="rehla-modal-warning" hidden></div>
<div class="followup-warning" id="rehla-modal-optout" hidden>
<label><input type="checkbox" id="rehla-optout-override"> {{ __('rehla::rehla.modal.optout_override') }}</label>
</div>
<div class="field">
<label for="rehla-modal-template">{{ __('rehla::rehla.modal.template') }}</label>
<select id="rehla-modal-template"></select>
Expand Down Expand Up @@ -155,6 +161,10 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
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');
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions routes/webhooks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Route;
use Rehla\Http\Controllers\MetaWebhookController;

Route::get('/', [MetaWebhookController::class, 'verify'])->name('rehla.webhooks.meta.verify');
Route::post('/', [MetaWebhookController::class, 'receive'])->name('rehla.webhooks.meta.receive');
10 changes: 9 additions & 1 deletion src/Automation/FollowUpSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Rehla\Exceptions\AutomationException;
use Rehla\Jobs\SendAutomatedFollowUp;
use Rehla\Models\RehlaFollowUp;
use Rehla\Services\ConsentManager;
use Rehla\Services\WhatsAppLink;

/**
Expand All @@ -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{
Expand All @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions src/Contracts/ConsentResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Rehla\Contracts;

use Illuminate\Database\Eloquent\Model;

/**
* For apps that already keep consent somewhere else. Name an invokable class
* implementing this in rehla.consent.resolver and set rehla.consent.source
* to "resolver".
*/
interface ConsentResolver
{
public function hasConsent(Model $user): bool;
}
5 changes: 5 additions & 0 deletions src/Exceptions/AutomationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public static function noPhone(): self
return new self('This user has no dialable phone number.');
}

public static function noConsent(): self
{
return new self('This user has not opted in to automatic WhatsApp messages (or has opted out).');
}

public static function unknownProvider(string $name): self
{
return new self("Rehla automation provider [{$name}] is not configured.");
Expand Down
1 change: 1 addition & 0 deletions src/Facades/Rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* @method static int reset(\Illuminate\Database\Eloquent\Model $user, ?string $journey = null, ?string $step = null)
* @method static \Rehla\Data\UserProgress progress(\Illuminate\Database\Eloquent\Model $user, ?string $journey = null)
* @method static void forget(\Illuminate\Database\Eloquent\Model $user)
* @method static \Rehla\Services\ConsentManager consent()
* @method static void recordVisit(\Illuminate\Database\Eloquent\Model $user)
*
* @see RehlaManager
Expand Down
Loading
Loading