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 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).
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
53 changes: 53 additions & 0 deletions config/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?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
{
/** Existing rows keep working: they become source "manual". */
public function up(): void
{
Schema::table('rehla_follow_ups', function (Blueprint $table): void {
$table->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',
]);
});
}
};
22 changes: 22 additions & 0 deletions docs/ar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 والقواعد وتاب البانل جايين في الإصدارات الجاية، فلسه متوجهوش على مستخدمين حقيقيين.
6 changes: 6 additions & 0 deletions resources/lang/ar/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@
'sent' => 'أيوه بعتّها',
],
'history' => [
'automatic' => 'تلقائي',
'status' => [
'queued' => 'في الانتظار',
'failed' => 'فشلت',
'simulated' => 'تجريبي',
'cancelled' => 'اتلغت',

'sent' => 'اتبعتت',
'opened' => 'غير مؤكدة',
'not_sent' => 'ماتبعتتش',
Expand Down
6 changes: 6 additions & 0 deletions resources/lang/en/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
5 changes: 4 additions & 1 deletion resources/views/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
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) {
Expand Down Expand Up @@ -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);
}
Expand Down
101 changes: 101 additions & 0 deletions src/Automation/FollowUpSender.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

declare(strict_types=1);

namespace Rehla\Automation;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Rehla\Exceptions\AutomationException;
use Rehla\Jobs\SendAutomatedFollowUp;
use Rehla\Models\RehlaFollowUp;
use Rehla\Services\WhatsAppLink;

/**
* Queues one automatic WhatsApp message and records it in the same
* follow-up log the manual flow uses. The job does the actual sending.
*/
final class FollowUpSender
{
public function __construct(private readonly ProviderManager $providers) {}

/**
* @param array{
* template_id?: int|null,
* template_title?: string|null,
* journey?: string|null,
* step?: string|null,
* rule_id?: int|null,
* idempotency_key?: string|null,
* provider_template?: array{name: string, language?: string|null, params?: list<string>}|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;
}
}
21 changes: 21 additions & 0 deletions src/Automation/OutboundMessage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Rehla\Automation;

final readonly class OutboundMessage
{
/**
* @param string $phone digits only, international format, no "+"
* @param list<string> $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,
) {}
}
Loading
Loading