From af62f624b581b45264d9fe39efc806f2f3848004 Mon Sep 17 00:00:00 2001 From: Instinct Agent Date: Thu, 3 Dec 2026 21:24:33 +0200 Subject: [PATCH] Automation phase E: hardening, prune, checklist --- CHANGELOG.md | 7 ++++ README.md | 12 +++++- config/rehla.php | 7 ++++ docs/ar/README.md | 12 +++++- src/Automation/AutomationEngine.php | 36 +++++++++++++++-- src/Automation/FollowUpSender.php | 56 ++++++++++++++++---------- src/Console/PruneCommand.php | 39 ++++++++++++++++++ src/RehlaServiceProvider.php | 3 +- tests/Feature/AutomationEngineTest.php | 55 +++++++++++++++++++++++++ 9 files changed, 197 insertions(+), 30 deletions(-) create mode 100644 src/Console/PruneCommand.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b578c7..d5a8d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 40b28be..5b24e5d 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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). diff --git a/config/rehla.php b/config/rehla.php index b57daea..cd49043 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -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 diff --git a/docs/ar/README.md b/docs/ar/README.md index e8da52a..1e84b59 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -141,7 +141,7 @@ composer check # pint --test, phpstan level 8, pest MIT. شوف [LICENSE.md](../../LICENSE.md). -## الإرسال التلقائي على واتساب (اختياري، تحت التنفيذ) +## الإرسال التلقائي على واتساب (اختياري) المتابعة اليدوية زي ما هي. الإرسال التلقائي طبقة منفصلة واختيارية و**مقفولة افتراضياً**. كل إعداد موجود في `config/rehla.php` والـ env الأول، وإظهار أي حاجة منها في البانل قرارك أنت. @@ -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). diff --git a/src/Automation/AutomationEngine.php b/src/Automation/AutomationEngine.php index c8c1d77..454fa6d 100644 --- a/src/Automation/AutomationEngine.php +++ b/src/Automation/AutomationEngine.php @@ -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; @@ -44,6 +45,10 @@ public function run(bool $dryRun = false, ?string $onlyRule = null, ?CarbonInter return $report; } + if (! $dryRun) { + $this->cancelStale($now); + } + /** @var class-string $userModel */ $userModel = (string) Config::get('rehla.user_model', 'App\\Models\\User'); @@ -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'); @@ -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); } /** @@ -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); diff --git a/src/Automation/FollowUpSender.php b/src/Automation/FollowUpSender.php index cbeabcd..c318537 100644 --- a/src/Automation/FollowUpSender.php +++ b/src/Automation/FollowUpSender.php @@ -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; @@ -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'); diff --git a/src/Console/PruneCommand.php b/src/Console/PruneCommand.php new file mode 100644 index 0000000..7eb7dbd --- /dev/null +++ b/src/Console/PruneCommand.php @@ -0,0 +1,39 @@ +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; + } +} diff --git a/src/RehlaServiceProvider.php b/src/RehlaServiceProvider.php index d493067..47aef7a 100644 --- a/src/RehlaServiceProvider.php +++ b/src/RehlaServiceProvider.php @@ -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; @@ -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'), diff --git a/tests/Feature/AutomationEngineTest.php b/tests/Feature/AutomationEngineTest.php index 3b6f9b8..9094f00 100644 --- a/tests/Feature/AutomationEngineTest.php +++ b/tests/Feature/AutomationEngineTest.php @@ -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; @@ -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); +});