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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

### Changed (automation, phase E: hardening)
- Placeholders expand in one pass (a user name containing `{step}` is no longer expanded); Meta template parameters are cleaned of newlines and repeated spaces.
- Two overlapping runs cannot double-queue: a race on the idempotency key returns the existing row.
- Queued sends whose job never ran are cancelled after `rehla.automation.stale_queued_hours` (default 24) so they cannot block the user.
- `php artisan rehla:prune [--days=]` and `rehla.automation.retention_days` delete old automatic rows (manual follow-ups and consent are never touched).
- README (EN and AR): go-live checklist.

### Added (automation, phase D: panel tab)
- Automation tab in the panel: manage database rules, see config rules, dry-run preview per rule, history of the latest 50 automatic sends. Hide it with `rehla.panel.automation_tab = false`. EN and AR.

Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ composer check # pint --test, phpstan level 8, pest
MIT. See [LICENSE.md](LICENSE.md).


## Automatic WhatsApp sending (optional, in progress)
## Automatic WhatsApp sending (optional)

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.

Expand Down Expand Up @@ -211,4 +211,12 @@ Guards, in order, each skip counted with its reason: valid phone, consent (and n

The panel has an **Automation** tab: rules from the database (add, edit, turn on or off, delete), config rules (read-only), a dry-run preview per rule (who would be messaged now, who is skipped and why) and the latest 50 automatic sends with delivery status. It is optional: set `rehla.panel.automation_tab` to `false` to hide it and close its routes. Everything it does is also possible from config and `rehla:automate`.

Hardening and the final checklist come in the next release, so do not point automation at real users yet.
### Before real users (checklist)

1. Start with `REHLA_AUTOMATION_PROVIDER=log` and `php artisan rehla:automate --dry-run`; read the preview in the Automation tab.
2. Collect opt-in (`Rehla::consent()->optIn($user)` when the user agrees), keep `rehla.consent.required` on.
3. Create and get your Meta templates approved in Meta Business Manager; map them with `provider_template`.
4. Set the webhook (verify token, app secret) so STOP replies and delivery status work, and test it with a number you own.
5. Run a queue worker and the scheduler (`rehla:automate` every 5 to 15 minutes).
6. Send to your own number first with a rule limited by `limits.per_run`.
7. Optional: `rehla.automation.retention_days` with `Schedule::command('rehla:prune')->daily()` to delete old automatic rows. Queued sends that never ran are cancelled after `stale_queued_hours` (24).
7 changes: 7 additions & 0 deletions config/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,13 @@
],
],

// A queued send whose job never ran (stopped worker, lost queue) is
// cancelled after this many hours so it cannot block the user. 0 = never.
'stale_queued_hours' => 24,
// `php artisan rehla:prune` deletes finished automatic sends older
// than this many days. null/0 = keep everything.
'retention_days' => null,

// Safety limits. All changeable; 0 or null turns a limit off.
'cooldown_hours' => 72, // no automatic message within this long after any sent follow-up
'manual_lock_hours' => 2, // an admin's open WhatsApp draft blocks automation this long
Expand Down
12 changes: 10 additions & 2 deletions docs/ar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ composer check # pint --test, phpstan level 8, pest
MIT. شوف [LICENSE.md](../../LICENSE.md).


## الإرسال التلقائي على واتساب (اختياري، تحت التنفيذ)
## الإرسال التلقائي على واتساب (اختياري)

المتابعة اليدوية زي ما هي. الإرسال التلقائي طبقة منفصلة واختيارية و**مقفولة افتراضياً**. كل إعداد موجود في `config/rehla.php` والـ env الأول، وإظهار أي حاجة منها في البانل قرارك أنت.

Expand Down Expand Up @@ -211,4 +211,12 @@ php artisan rehla:automate --rule=stuck-profile

في البانل تاب **الأتمتة**: قواعد من الداتابيز (إضافة وتعديل وتشغيل وإيقاف وحذف)، وقواعد الكونفيج (للقراءة بس)، ومعاينة تجريبية لكل قاعدة (مين هيتبعتله دلوقتي ومين اتخطّى وليه)، وآخر 50 رسالة تلقائية مع حالة التسليم. اختياري: خلّي `rehla.panel.automation_tab` بـ `false` عشان تخفيه وتقفل مساراته. وكل اللي بيعمله ممكن من الكونفيج و`rehla:automate`.

التقوية وقايمة المراجعة الأخيرة جايين في الإصدار الجاي، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين.
### قبل المستخدمين الحقيقيين (قايمة مراجعة)

1. ابدأ بـ `REHLA_AUTOMATION_PROVIDER=log` و`php artisan rehla:automate --dry-run`، واقرا المعاينة في تاب الأتمتة.
2. اجمع الموافقة (`Rehla::consent()->optIn($user)` لما المستخدم يوافق)، وسيب `rehla.consent.required` شغّال.
3. اعمل قوالب ميتا واعتمدها من Meta Business Manager، واربطها بـ `provider_template`.
4. فعّل الـ webhook (verify token وapp secret) عشان ردود STOP وحالة التسليم تشتغل، وجرّبه برقم بتاعك.
5. شغّل queue worker والـ scheduler (`rehla:automate` كل 5 لـ15 دقيقة).
6. ابعت لرقمك الأول بقاعدة محدودة بـ `limits.per_run`.
7. اختياري: `rehla.automation.retention_days` مع `Schedule::command('rehla:prune')->daily()` لمسح الصفوف التلقائية القديمة. والرسائل الواقفة في الطابور ومشتغلتش بتتلغي بعد `stale_queued_hours` (24).
36 changes: 33 additions & 3 deletions src/Automation/AutomationEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
Expand Down Expand Up @@ -44,6 +45,10 @@ public function run(bool $dryRun = false, ?string $onlyRule = null, ?CarbonInter
return $report;
}

if (! $dryRun) {
$this->cancelStale($now);
}

/** @var class-string<Model> $userModel */
$userModel = (string) Config::get('rehla.user_model', 'App\\Models\\User');

Expand Down Expand Up @@ -125,6 +130,11 @@ public function run(bool $dryRun = false, ?string $onlyRule = null, ?CarbonInter
'idempotency_key' => "{$rule->key}:user:{$id}:{$match['step']}:{$sendNumber}",
'provider_template' => $this->providerTemplate($rule, $user, $match),
]);
} catch (UniqueConstraintViolationException) {
// Another run queued this exact send first.
$report->skip($rule->key, $id, 'duplicate');

continue;
} catch (AutomationException $e) {
$report->skip($rule->key, $id, 'send_refused');

Expand Down Expand Up @@ -368,11 +378,14 @@ private function render(Rule $rule, Model $user, array $match): string

$text ??= '';

$pairs = [];

foreach ($this->values($rule, $user, $match) as $key => $value) {
$text = str_replace('{'.$key.'}', $value, $text);
$pairs['{'.$key.'}'] = $value;
}

return $text;
// One pass: a user's name that contains "{step}" is not expanded again.
return strtr($text, $pairs);
}

/**
Expand All @@ -389,12 +402,29 @@ private function providerTemplate(Rule $rule, Model $user, array $match): ?array
$params = [];

foreach ($rule->providerTemplate['params'] ?? [] as $placeholder) {
$params[] = $values[trim($placeholder, '{}')] ?? '';
// Meta rejects newlines, tabs and long runs of spaces in template parameters.
$params[] = trim((string) preg_replace('/\s+/u', ' ', $values[trim($placeholder, '{}')] ?? ''));
}

return ['name' => $rule->providerTemplate['name'], 'language' => $rule->providerTemplate['language'] ?? null, 'params' => $params];
}

/** A queued row whose job never ran (lost queue, stopped worker) would block the user forever. */
private function cancelStale(CarbonInterface $now): void
{
$hours = (int) Config::get('rehla.automation.stale_queued_hours', 24);

if ($hours < 1) {
return;
}

RehlaFollowUp::query()
->where('source', RehlaFollowUp::SOURCE_AUTOMATION)
->where('status', RehlaFollowUp::STATUS_QUEUED)
->where('created_at', '<', $now->copy()->subHours($hours))
->update(['status' => RehlaFollowUp::STATUS_CANCELLED, 'skip_reason' => 'stale']);
}

private function limit(string $key): ?int
{
$value = Config::get($key);
Expand Down
56 changes: 34 additions & 22 deletions src/Automation/FollowUpSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Rehla\Automation;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Config;
use Rehla\Exceptions\AutomationException;
use Rehla\Jobs\SendAutomatedFollowUp;
Expand Down Expand Up @@ -67,28 +68,39 @@ public function queue(Model $user, string $message, array $options = []): RehlaF

$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'] ?? [],
],
]);
try {
$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'] ?? [],
],
]);
} catch (UniqueConstraintViolationException $e) {
// Two runs raced on the same idempotency key: the other one won.
$existing = $key !== null ? RehlaFollowUp::query()->where('idempotency_key', $key)->first() : null;

if ($existing === null) {
throw $e;
}

return $existing;
}

$job = new SendAutomatedFollowUp((int) $followUp->getKey());
$connection = Config::get('rehla.automation.queue.connection');
Expand Down
39 changes: 39 additions & 0 deletions src/Console/PruneCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Rehla\Console;

use Illuminate\Console\Command;
use Rehla\Models\RehlaFollowUp;

final class PruneCommand extends Command
{
/** @var string */
protected $signature = 'rehla:prune {--days= : Delete finished automatic sends older than this many days}';

/** @var string */
protected $description = 'Delete old automatic follow-up rows (data retention). Manual follow-ups and consent records are never touched.';

public function handle(): int
{
$option = $this->option('days');
$days = is_numeric($option) ? (int) $option : (int) config('rehla.automation.retention_days', 0);

if ($days < 1) {
$this->warn('No retention period set. Pass --days=N or set rehla.automation.retention_days.');

return self::SUCCESS;
}

$deleted = RehlaFollowUp::query()
->where('source', RehlaFollowUp::SOURCE_AUTOMATION)
->whereNotIn('status', [RehlaFollowUp::STATUS_QUEUED])
->where('created_at', '<', now()->subDays($days))
->delete();

$this->info("Deleted {$deleted} automatic follow-up row(s) older than {$days} day(s).");

return self::SUCCESS;
}
}
3 changes: 2 additions & 1 deletion src/RehlaServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Rehla\Automation\ProviderManager;
use Rehla\Console\AutomateCommand;
use Rehla\Console\InstallCommand;
use Rehla\Console\PruneCommand;
use Rehla\Console\ReportCommand;
use Rehla\Http\Middleware\AuthorizePanel;
use Rehla\Http\Middleware\RecordActivity;
Expand Down Expand Up @@ -55,7 +56,7 @@ public function register(): void
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->commands([InstallCommand::class, ReportCommand::class, AutomateCommand::class]);
$this->commands([InstallCommand::class, ReportCommand::class, AutomateCommand::class, PruneCommand::class]);

$this->publishes([
__DIR__.'/../config/rehla.php' => $this->app->configPath('rehla.php'),
Expand Down
55 changes: 55 additions & 0 deletions tests/Feature/AutomationEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Bus;
use Rehla\Automation\AutomationEngine;
use Rehla\Automation\FollowUpSender;
use Rehla\Automation\ProviderManager;
use Rehla\Facades\Rehla;
use Rehla\Jobs\SendAutomatedFollowUp;
Expand Down Expand Up @@ -244,3 +245,57 @@ function stuckUser(object $test, array $attrs = [], string $startedAt = '2026-03

$this->artisan('rehla:automate')->expectsOutputToContain('Queued 1')->assertSuccessful();
});

it('expands placeholders once, so a name cannot inject another placeholder', function () {
stuckUser($this, ['name' => '{step}']);

$report = app(AutomationEngine::class)->run(dryRun: true);

expect($report->sends[0]['message'])->toBe('Hi {step}, finish "Complete the profile" in Main journey');
});

it('cleans Meta template parameters of newlines and extra spaces', function () {
config()->set('rehla.automation.rules.nudge.provider_template', ['name' => 'n', 'language' => 'ar', 'params' => ['name']]);
stuckUser($this, ['name' => "Sara\n\n Ali"]);

app(AutomationEngine::class)->run();

expect(RehlaFollowUp::query()->firstOrFail()->payload['template_params'])->toBe(['Sara Ali']);
});

it('cancels queued sends whose job never ran', function () {
stuckUser($this);
app(AutomationEngine::class)->run();
RehlaFollowUp::query()->update(['created_at' => '2026-03-08 12:00:00']);

$report = app(AutomationEngine::class)->run();

expect(RehlaFollowUp::query()->where('skip_reason', 'stale')->count())->toBe(1)
->and($report->sends)->toHaveCount(1); // the first one never went out, so the user is eligible again
});

it('returns the existing row when two runs race on one idempotency key', function () {
$user = stuckUser($this);
$sender = app(FollowUpSender::class);

$a = $sender->queue($user, 'hi', ['idempotency_key' => 'k1']);
$b = $sender->queue($user, 'hi', ['idempotency_key' => 'k1']);

expect($b->id)->toBe($a->id)->and(RehlaFollowUp::query()->count())->toBe(1);
});

it('prunes old automatic rows only, never manual ones or queued ones', function () {
$user = stuckUser($this);
$make = fn (string $source, string $status) => RehlaFollowUp::query()->forceCreate([
'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'm',
'status' => $status, 'source' => $source, 'created_at' => '2025-01-01 00:00:00',
]);
$make('automation', 'sent');
$make('automation', 'queued');
$make('manual', 'sent');

$this->artisan('rehla:prune')->expectsOutputToContain('No retention')->assertSuccessful();
$this->artisan('rehla:prune --days=30')->expectsOutputToContain('Deleted 1')->assertSuccessful();

expect(RehlaFollowUp::query()->count())->toBe(2);
});
Loading