From 11b70c9f9f8be9dd53ffec645e469deb11f60a35 Mon Sep 17 00:00:00 2001 From: Instinct Agent Date: Thu, 3 Dec 2026 21:21:42 +0200 Subject: [PATCH] Automation phase D: panel tab --- CHANGELOG.md | 3 + README.md | 4 +- config/rehla.php | 3 + docs/ar/README.md | 4 +- resources/lang/ar/rehla.php | 47 +++++ resources/lang/en/rehla.php | 47 +++++ resources/views/automation/_form.blade.php | 98 ++++++++++ resources/views/automation/create.blade.php | 12 ++ resources/views/automation/edit.blade.php | 13 ++ resources/views/automation/index.blade.php | 84 +++++++++ resources/views/automation/preview.blade.php | 39 ++++ resources/views/layout.blade.php | 3 + routes/web.php | 12 ++ .../Controllers/AutomationRuleController.php | 176 ++++++++++++++++++ tests/Feature/AutomationPanelTest.php | 107 +++++++++++ 15 files changed, 650 insertions(+), 2 deletions(-) create mode 100644 resources/views/automation/_form.blade.php create mode 100644 resources/views/automation/create.blade.php create mode 100644 resources/views/automation/edit.blade.php create mode 100644 resources/views/automation/index.blade.php create mode 100644 resources/views/automation/preview.blade.php create mode 100644 src/Http/Controllers/AutomationRuleController.php create mode 100644 tests/Feature/AutomationPanelTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f2c4e3..7b578c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +### 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. + ### Added (automation, phase C: rules and engine) - `rehla:automate [--dry-run] [--rule=]`: finds users matching a rule, runs the guards and queues messages. Conditions: `inactive_for`, `step_not_started_for`, `step_started_not_finished_for`, with thresholds in hours, days or weeks. - Rules in `rehla.automation.rules` (config) and the new `rehla_automation_rules` table (run `rehla:install` or `migrate`). Placeholders `{name}`, `{step}`, `{journey}`, `{days_inactive}`, plus a Meta template parameter mapping. diff --git a/README.md b/README.md index 49ca248..40b28be 100644 --- a/README.md +++ b/README.md @@ -209,4 +209,6 @@ php artisan rehla:automate --rule=stuck-profile Guards, in order, each skip counted with its reason: valid phone, consent (and no opt-out), quiet hours, cooldown, manual lock, already queued, max sends per user, then global limits. All are in `rehla.automation`: `quiet_hours` (default 21:00 to 09:00, app timezone, optional per-user timezone column), `cooldown_hours` (72, or per rule), `manual_lock_hours` (2: an admin's open WhatsApp draft blocks automation), `limits` (`per_hour`, `per_day`, `per_run`; 0 turns one off). Just before sending, the job cancels the message if an admin messaged that user by hand in the meantime. -The panel tab and hardening come in the next releases, so do not point automation at real users yet. +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. diff --git a/config/rehla.php b/config/rehla.php index be60cf5..b57daea 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -63,6 +63,9 @@ 'path' => 'rehla', 'middleware' => ['web'], 'gate' => 'viewRehla', + // Show the Automation tab (rules, dry-run preview, history). false + // hides it and closes its routes; rules still work from config. + 'automation_tab' => true, ], /* diff --git a/docs/ar/README.md b/docs/ar/README.md index 11f8d53..e8da52a 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -209,4 +209,6 @@ php artisan rehla:automate --rule=stuck-profile الحمايات بالترتيب، وكل تخطّي بيتعدّ بسببه: رقم صالح، الموافقة (ومفيش إيقاف)، ساعات الهدوء، فترة الانتظار، قفل اليدوي، مستني في الطابور، أقصى عدد رسائل للمستخدم، وبعدين الحدود العامة. كلها في `rehla.automation`: `quiet_hours` (الافتراضي 21:00 لـ09:00 بتوقيت التطبيق، وعمود توقيت لكل مستخدم اختياري)، و`cooldown_hours` (72، أو لكل قاعدة)، و`manual_lock_hours` (2: مسودة واتساب مفتوحة عند أدمن بتوقّف الأتمتة)، و`limits` (`per_hour` و`per_day` و`per_run`؛ 0 بيقفل الحد). قبل الإرسال مباشرة، الـjob بيلغي الرسالة لو أدمن بعت للمستخدم يدوي في الوقت ده. -تاب البانل والتقوية جايين في الإصدارات الجاية، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين. +في البانل تاب **الأتمتة**: قواعد من الداتابيز (إضافة وتعديل وتشغيل وإيقاف وحذف)، وقواعد الكونفيج (للقراءة بس)، ومعاينة تجريبية لكل قاعدة (مين هيتبعتله دلوقتي ومين اتخطّى وليه)، وآخر 50 رسالة تلقائية مع حالة التسليم. اختياري: خلّي `rehla.panel.automation_tab` بـ `false` عشان تخفيه وتقفل مساراته. وكل اللي بيعمله ممكن من الكونفيج و`rehla:automate`. + +التقوية وقايمة المراجعة الأخيرة جايين في الإصدار الجاي، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين. diff --git a/resources/lang/ar/rehla.php b/resources/lang/ar/rehla.php index 36a3bcd..ed13323 100644 --- a/resources/lang/ar/rehla.php +++ b/resources/lang/ar/rehla.php @@ -6,6 +6,7 @@ 'panel_title' => 'رحلة المستخدمين', 'nav_dashboard' => 'جدول الرحلة', 'nav_templates' => 'قوالب الرسائل', + 'nav_automation' => 'الأتمتة', 'filter_label' => 'لم يزر الموقع منذ', 'days_unit' => 'يوم/أيام', 'filter_apply' => 'تصفية', @@ -91,4 +92,50 @@ 'unknown_step' => 'هذه الخطوة غير معرّفة في الرحلة المختارة.', 'step_needs_journey' => 'اختر الرحلة عند ربط القالب بخطوة.', ], + 'automation' => [ + 'title' => 'الأتمتة', + 'new' => 'قاعدة جديدة', + 'create' => 'إنشاء قاعدة', + 'edit' => 'تعديل القاعدة', + 'rules' => 'القواعد', + 'history' => 'الرسائل التلقائية (آخر 50)', + 'name' => 'الاسم', + 'condition' => 'الشرط', + 'status' => 'الحالة', + 'when' => 'الوقت', + 'user' => 'المستخدم', + 'message' => 'الرسالة', + 'on' => 'شغّالة', + 'off' => 'موقوفة', + 'turn_on' => 'شغّلها', + 'turn_off' => 'أوقفها', + 'enabled' => 'القاعدة شغّالة', + 'from_config' => 'من الكونفيج', + 'preview' => 'معاينة (تجربة)', + 'preview_hint' => 'مفيش حاجة بتتبعت. ده بيوريك مين هيتبعتله دلوقتي ومين اتخطّى وليه.', + 'would_send' => 'هيتبعت لـ :count مستخدم', + 'nobody' => 'مفيش حد مطابق دلوقتي.', + 'skipped' => 'المتخطّين', + 'empty' => 'مفيش قواعد لسه.', + 'no_history' => 'مفيش رسائل تلقائية لسه.', + 'confirm_delete' => 'تمسح القاعدة دي؟', + 'disabled_notice' => 'الأتمتة مقفولة (rehla.automation.enabled). القواعد محفوظة بس مفيش حاجة هتتبعت.', + 'provider_hint' => 'المزوّد: :provider', + 'any_step' => 'الخطوة المستحقة عليه', + 'after' => 'بعد', + 'template' => 'قالب الرسالة', + 'message_or' => 'أو اكتب الرسالة', + 'placeholders' => 'تقدر تستخدم {name} و{step} و{journey} و{days_inactive}.', + 'cooldown' => 'ساعات الانتظار (فاضي = الافتراضي العام)', + 'max_sends' => 'أقصى عدد رسائل للمستخدم من القاعدة دي', + 'meta' => 'قالب ميتا (الاسم، اللغة، المتغيرات بالترتيب)', + 'meta_hint' => 'مطلوب للرسائل برّه نافذة الـ24 ساعة. المتغيرات بتملا {{1}} و{{2}} بالترتيب.', + 'needs_message' => 'اختار قالب أو اكتب رسالة.', + 'conditions' => [ + 'inactive_for' => 'مدخلش من', + 'step_not_started_for' => 'الخطوة لسه مبدأهاش من', + 'step_started_not_finished_for' => 'بدأ الخطوة ومخلصهاش من', + ], + 'units' => ['hours' => 'ساعة', 'days' => 'يوم', 'weeks' => 'أسبوع'], + ], ]; diff --git a/resources/lang/en/rehla.php b/resources/lang/en/rehla.php index 7d00c48..5f7265a 100644 --- a/resources/lang/en/rehla.php +++ b/resources/lang/en/rehla.php @@ -6,6 +6,7 @@ 'panel_title' => 'User journeys', 'nav_dashboard' => 'Journey table', 'nav_templates' => 'Message templates', + 'nav_automation' => 'Automation', 'filter_label' => 'No visit for at least', 'days_unit' => 'day(s)', 'filter_apply' => 'Filter', @@ -91,4 +92,50 @@ '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.', ], + 'automation' => [ + 'title' => 'Automation', + 'new' => 'New rule', + 'create' => 'Create rule', + 'edit' => 'Edit rule', + 'rules' => 'Rules', + 'history' => 'Automatic sends (latest 50)', + 'name' => 'Name', + 'condition' => 'Condition', + 'status' => 'Status', + 'when' => 'When', + 'user' => 'User', + 'message' => 'Message', + 'on' => 'On', + 'off' => 'Off', + 'turn_on' => 'Turn on', + 'turn_off' => 'Turn off', + 'enabled' => 'Rule is on', + 'from_config' => 'config', + 'preview' => 'Preview (dry run)', + 'preview_hint' => 'Nothing is sent. This shows who would be messaged right now and why others are skipped.', + 'would_send' => 'Would message :count user(s)', + 'nobody' => 'Nobody matches right now.', + 'skipped' => 'Skipped', + 'empty' => 'No rules yet.', + 'no_history' => 'No automatic messages yet.', + 'confirm_delete' => 'Delete this rule?', + 'disabled_notice' => 'Automation is off (rehla.automation.enabled). Rules are kept but nothing will be sent.', + 'provider_hint' => 'Provider: :provider', + 'any_step' => 'The step they are due on', + 'after' => 'After', + 'template' => 'Message template', + 'message_or' => 'Or write the message', + 'placeholders' => 'You can use {name}, {step}, {journey}, {days_inactive}.', + 'cooldown' => 'Cooldown hours (empty = the global default)', + 'max_sends' => 'Max messages per user from this rule', + 'meta' => 'Meta template (name, language, placeholders in order)', + 'meta_hint' => 'Needed to message users outside the 24-hour window. Placeholders fill {{1}}, {{2}} in order.', + 'needs_message' => 'Pick a template or write a message.', + 'conditions' => [ + 'inactive_for' => 'No visit for', + 'step_not_started_for' => 'Step not started for', + 'step_started_not_finished_for' => 'Step started, not finished for', + ], + 'units' => ['hours' => 'hour(s)', 'days' => 'day(s)', 'weeks' => 'week(s)'], + ], ]; diff --git a/resources/views/automation/_form.blade.php b/resources/views/automation/_form.blade.php new file mode 100644 index 0000000..4ce2826 --- /dev/null +++ b/resources/views/automation/_form.blade.php @@ -0,0 +1,98 @@ +@php($registry = app(\Rehla\Services\JourneyRegistry::class)) +@php($templates = \Rehla\Models\RehlaTemplate::query()->orderBy('title')->get()) +@php($rule = $rule ?? null) +@php($hours = (int) ($rule->after_hours ?? 48)) +@php($unit = $hours % 168 === 0 ? 'weeks' : ($hours % 24 === 0 ? 'days' : 'hours')) +@php($value = $unit === 'weeks' ? intdiv($hours, 168) : ($unit === 'days' ? intdiv($hours, 24) : $hours)) +@php($meta = $rule->provider_template ?? []) + +@if($errors->any()) +
+ @foreach($errors->all() as $error) +
{{ $error }}
+ @endforeach +
+@endif + +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + + +
+ +
+ + +
+ +
+ + + {{ __('rehla::rehla.automation.placeholders') }} +
+ +
+ + +
+ +
+ + +
+ +
+ + + + + {{ __('rehla::rehla.automation.meta_hint') }} +
+ +
+ +
diff --git a/resources/views/automation/create.blade.php b/resources/views/automation/create.blade.php new file mode 100644 index 0000000..c12cc8a --- /dev/null +++ b/resources/views/automation/create.blade.php @@ -0,0 +1,12 @@ +@extends('rehla::layout') + +@section('title', __('rehla::rehla.automation.create')) + +@section('content') +

{{ __('rehla::rehla.automation.create') }}

+
+ @csrf + @include('rehla::automation._form') + +
+@endsection diff --git a/resources/views/automation/edit.blade.php b/resources/views/automation/edit.blade.php new file mode 100644 index 0000000..6cf71c1 --- /dev/null +++ b/resources/views/automation/edit.blade.php @@ -0,0 +1,13 @@ +@extends('rehla::layout') + +@section('title', __('rehla::rehla.automation.edit')) + +@section('content') +

{{ __('rehla::rehla.automation.edit') }}

+
+ @method('PUT') + @csrf + @include('rehla::automation._form') + +
+@endsection diff --git a/resources/views/automation/index.blade.php b/resources/views/automation/index.blade.php new file mode 100644 index 0000000..4c0487d --- /dev/null +++ b/resources/views/automation/index.blade.php @@ -0,0 +1,84 @@ +@extends('rehla::layout') + +@section('title', __('rehla::rehla.automation.title')) + +@section('content') + @unless($automationEnabled) +
{{ __('rehla::rehla.automation.disabled_notice') }}
+ @endunless + +
+ {{ __('rehla::rehla.automation.new') }} + {{ __('rehla::rehla.automation.provider_hint', ['provider' => $provider]) }} +
+ +

{{ __('rehla::rehla.automation.rules') }}

+ + + + + + + + + + + @foreach($configRules as $rule) + + + + + + + @endforeach + @foreach($dbRules as $rule) + + + + + + + @endforeach + @if(count($configRules) + count($dbRules) === 0) + + @endif + +
{{ __('rehla::rehla.automation.name') }}{{ __('rehla::rehla.automation.condition') }}{{ __('rehla::rehla.automation.status') }}{{ __('rehla::rehla.templates.actions') }}
{{ $rule->name }} {{ __('rehla::rehla.automation.from_config') }}{{ __('rehla::rehla.automation.conditions.'.$rule->condition) }} · {{ $rule->journey }}{{ $rule->step ? ' / '.$rule->step : '' }} · {{ $rule->afterHours }}h{{ __('rehla::rehla.automation.on') }}{{ __('rehla::rehla.automation.preview') }}
{{ $rule->name }}{{ __('rehla::rehla.automation.conditions.'.$rule->condition) }} · {{ $rule->journey }}{{ $rule->step ? ' / '.$rule->step : '' }} · {{ $rule->after_hours }}h{{ $rule->enabled ? __('rehla::rehla.automation.on') : __('rehla::rehla.automation.off') }} + {{ __('rehla::rehla.automation.preview') }} + {{ __('rehla::rehla.automation.edit') }} +
+ @csrf + +
+
+ @csrf + @method('DELETE') + +
+
{{ __('rehla::rehla.automation.empty') }}
+ +

{{ __('rehla::rehla.automation.history') }}

+ + + + + + + + + + + @forelse($history as $row) + + + + + + + @empty + + @endforelse + +
{{ __('rehla::rehla.automation.when') }}{{ __('rehla::rehla.automation.user') }}{{ __('rehla::rehla.automation.status') }}{{ __('rehla::rehla.automation.message') }}
{{ $row->created_at?->format('Y-m-d H:i') }}#{{ $row->trackable_id }}{{ $row->status }}{{ $row->delivery_status ? ' / '.$row->delivery_status : '' }}{{ $row->skip_reason ? ' ('.$row->skip_reason.')' : '' }}{{ $row->error_message ? ': '.$row->error_message : '' }}{{ \Illuminate\Support\Str::limit($row->message, 120) }}
{{ __('rehla::rehla.automation.no_history') }}
+@endsection diff --git a/resources/views/automation/preview.blade.php b/resources/views/automation/preview.blade.php new file mode 100644 index 0000000..d1c7ecc --- /dev/null +++ b/resources/views/automation/preview.blade.php @@ -0,0 +1,39 @@ +@extends('rehla::layout') + +@section('title', __('rehla::rehla.automation.preview')) + +@section('content') +

← {{ __('rehla::rehla.automation.title') }}

+

{{ __('rehla::rehla.automation.preview') }}: {{ $key }}

+

{{ __('rehla::rehla.automation.preview_hint') }}

+ + @if(isset($report->skipped['automation_disabled'])) +
{{ __('rehla::rehla.automation.disabled_notice') }}
+ @endif + +

{{ __('rehla::rehla.automation.would_send', ['count' => count($report->sends)]) }}

+ + + @forelse($shown as $send) + + + + + + @empty + + @endforelse + +
{{ $names[$send['user']] ?? '#'.$send['user'] }}{{ $send['step'] ?? '—' }}{{ $send['message'] }}
{{ __('rehla::rehla.automation.nobody') }}
+ + @if($report->skipped !== []) +

{{ __('rehla::rehla.automation.skipped') }}

+ + + @foreach($report->skipped as $reason => $count) + + @endforeach + +
{{ $reason }}{{ $count }}
+ @endif +@endsection diff --git a/resources/views/layout.blade.php b/resources/views/layout.blade.php index 98f9176..d552d78 100644 --- a/resources/views/layout.blade.php +++ b/resources/views/layout.blade.php @@ -61,6 +61,9 @@ {{ __('rehla::rehla.panel_title') }} {{ __('rehla::rehla.nav_dashboard') }} {{ __('rehla::rehla.nav_templates') }} + @if(config('rehla.panel.automation_tab', true)) + {{ __('rehla::rehla.nav_automation') }} + @endif
@yield('content') diff --git a/routes/web.php b/routes/web.php index 362c69d..a129166 100644 --- a/routes/web.php +++ b/routes/web.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\Route; +use Rehla\Http\Controllers\AutomationRuleController; use Rehla\Http\Controllers\DashboardController; use Rehla\Http\Controllers\FollowUpController; use Rehla\Http\Controllers\TemplateController; @@ -17,3 +18,14 @@ Route::get('/templates/{template}/edit', [TemplateController::class, 'edit'])->name('templates.edit'); Route::put('/templates/{template}', [TemplateController::class, 'update'])->name('templates.update'); Route::delete('/templates/{template}', [TemplateController::class, 'destroy'])->name('templates.destroy'); + +if ((bool) config('rehla.panel.automation_tab', true)) { + Route::get('/automation', [AutomationRuleController::class, 'index'])->name('automation.index'); + Route::get('/automation/rules/create', [AutomationRuleController::class, 'create'])->name('automation.create'); + Route::post('/automation/rules', [AutomationRuleController::class, 'store'])->name('automation.store'); + Route::get('/automation/rules/{rule}/edit', [AutomationRuleController::class, 'edit'])->whereNumber('rule')->name('automation.edit'); + Route::put('/automation/rules/{rule}', [AutomationRuleController::class, 'update'])->whereNumber('rule')->name('automation.update'); + Route::post('/automation/rules/{rule}/toggle', [AutomationRuleController::class, 'toggle'])->whereNumber('rule')->name('automation.toggle'); + Route::delete('/automation/rules/{rule}', [AutomationRuleController::class, 'destroy'])->whereNumber('rule')->name('automation.destroy'); + Route::get('/automation/preview/{key}', [AutomationRuleController::class, 'preview'])->where('key', '[A-Za-z0-9:_\-]+')->name('automation.preview'); +} diff --git a/src/Http/Controllers/AutomationRuleController.php b/src/Http/Controllers/AutomationRuleController.php new file mode 100644 index 0000000..fb0b6b5 --- /dev/null +++ b/src/Http/Controllers/AutomationRuleController.php @@ -0,0 +1,176 @@ + 1, 'days' => 24, 'weeks' => 168]; + + public function index(RuleRepository $repository): View + { + return view('rehla::automation.index', [ + 'dbRules' => RehlaAutomationRule::query()->orderBy('id')->get(), + 'configRules' => array_values(array_filter($repository->all(), static fn (Rule $r): bool => $r->id === null)), + 'history' => RehlaFollowUp::query() + ->where('source', RehlaFollowUp::SOURCE_AUTOMATION) + ->latest('id') + ->limit(50) + ->get(), + 'automationEnabled' => (bool) Config::get('rehla.automation.enabled', false), + 'provider' => (string) Config::get('rehla.automation.provider', 'log'), + ]); + } + + public function create(): View + { + return view('rehla::automation.create'); + } + + public function store(Request $request, JourneyRegistry $journeys): RedirectResponse + { + RehlaAutomationRule::query()->create($this->validated($request, $journeys)); + + return redirect()->route('rehla.automation.index'); + } + + public function edit(RehlaAutomationRule $rule): View + { + return view('rehla::automation.edit', ['rule' => $rule]); + } + + public function update(Request $request, RehlaAutomationRule $rule, JourneyRegistry $journeys): RedirectResponse + { + $rule->update($this->validated($request, $journeys)); + + return redirect()->route('rehla.automation.index'); + } + + public function toggle(RehlaAutomationRule $rule): RedirectResponse + { + $rule->update(['enabled' => ! $rule->enabled]); + + return redirect()->route('rehla.automation.index'); + } + + public function destroy(RehlaAutomationRule $rule): RedirectResponse + { + $rule->delete(); + + return redirect()->route('rehla.automation.index'); + } + + /** Dry run of one rule: who would be messaged now, and why others are skipped. */ + public function preview(string $key, AutomationEngine $engine): View + { + $report = $engine->run(true, $key); + /** @var class-string $userModel */ + $userModel = (string) Config::get('rehla.user_model', 'App\\Models\\User'); + $nameAttribute = (string) Config::get('rehla.name_attribute', 'name'); + $shown = array_slice($report->sends, 0, 50); + $names = []; + + if (class_exists($userModel) && is_subclass_of($userModel, Model::class) && $shown !== []) { + foreach ($userModel::query()->whereKey(array_column($shown, 'user'))->get() as $user) { + $name = $user->getAttribute($nameAttribute); + $names[$user->getKey()] = is_string($name) ? $name : (string) $user->getKey(); + } + } + + return view('rehla::automation.preview', [ + 'key' => $key, + 'report' => $report, + 'shown' => $shown, + 'names' => $names, + ]); + } + + /** + * @return array + * + * @throws ValidationException + */ + private function validated(Request $request, JourneyRegistry $journeys): array + { + /** @var array $data */ + $data = $request->validate([ + 'name' => ['required', 'string', 'max:190'], + 'journey' => ['required', 'string', 'max:100'], + 'step' => ['nullable', 'string', 'max:100'], + 'condition' => ['required', ValidationRule::in(Rule::CONDITIONS)], + 'after_value' => ['required', 'integer', 'min:1', 'max:100000'], + 'after_unit' => ['required', ValidationRule::in(array_keys(self::UNITS))], + 'template_id' => ['nullable', 'integer', 'exists:rehla_templates,id'], + 'message' => ['nullable', 'string', 'max:5000'], + 'cooldown_hours' => ['nullable', 'integer', 'min:0', 'max:100000'], + 'max_sends_per_user' => ['required', 'integer', 'min:1', 'max:100'], + 'enabled' => ['nullable', 'boolean'], + 'meta_template' => ['nullable', 'string', 'max:190'], + 'meta_language' => ['nullable', 'string', 'max:16'], + 'meta_params' => ['nullable', 'string', 'max:500'], + ]); + + $journey = (string) $data['journey']; + $step = isset($data['step']) && $data['step'] !== '' ? (string) $data['step'] : null; + + if (! $journeys->exists($journey)) { + throw ValidationException::withMessages(['journey' => __('rehla::rehla.validation.unknown_journey')]); + } + + if ($step !== null && ! $journeys->hasStep($journey, $step)) { + throw ValidationException::withMessages(['step' => __('rehla::rehla.validation.unknown_step')]); + } + + $templateId = isset($data['template_id']) && $data['template_id'] !== '' ? (int) $data['template_id'] : null; + $message = isset($data['message']) && trim((string) $data['message']) !== '' ? (string) $data['message'] : null; + + if ($templateId === null && $message === null) { + throw ValidationException::withMessages(['message' => __('rehla::rehla.automation.needs_message')]); + } + + $providerTemplate = null; + $metaName = trim((string) ($data['meta_template'] ?? '')); + + if ($metaName !== '') { + $params = array_values(array_filter(array_map('trim', explode(',', (string) ($data['meta_params'] ?? ''))), static fn (string $p): bool => $p !== '')); + $providerTemplate = [ + 'name' => $metaName, + 'language' => trim((string) ($data['meta_language'] ?? '')) ?: null, + 'params' => $params, + ]; + } + + return [ + 'name' => (string) $data['name'], + 'enabled' => $request->boolean('enabled'), + 'journey' => $journey, + 'step' => $step, + 'condition' => (string) $data['condition'], + 'after_hours' => (int) $data['after_value'] * self::UNITS[(string) $data['after_unit']], + 'template_id' => $templateId, + 'message' => $message, + 'provider_template' => $providerTemplate, + 'cooldown_hours' => isset($data['cooldown_hours']) && $data['cooldown_hours'] !== '' ? (int) $data['cooldown_hours'] : null, + 'max_sends_per_user' => (int) $data['max_sends_per_user'], + ]; + } +} diff --git a/tests/Feature/AutomationPanelTest.php b/tests/Feature/AutomationPanelTest.php new file mode 100644 index 0000000..1cb0bd1 --- /dev/null +++ b/tests/Feature/AutomationPanelTest.php @@ -0,0 +1,107 @@ + 'Stuck profile', 'journey' => 'default', 'step' => 'profile', + 'condition' => 'step_started_not_finished_for', 'after_value' => 2, 'after_unit' => 'days', + 'message' => 'Hi {name}', 'max_sends_per_user' => 1, 'enabled' => 1, + ]; +} + +it('is closed to non-admins', function () { + $this->get('/rehla/automation')->assertForbidden(); +}); + +it('lists config and database rules and the automatic history', function () { + $this->allowPanel(); + config()->set('rehla.automation.enabled', true); + RehlaAutomationRule::query()->create(['name' => 'DB rule', 'journey' => 'default', 'condition' => 'inactive_for', 'after_hours' => 72, 'message' => 'x']); + RehlaFollowUp::query()->create(['trackable_type' => 'u', 'trackable_id' => 7, 'message' => 'auto hello', 'status' => 'sent', 'source' => 'automation', 'delivery_status' => 'read']); + + $this->get('/rehla/automation')->assertOk() + ->assertSee('DB rule')->assertSee('auto hello')->assertSee('sent / read'); +}); + +it('warns when automation is switched off', function () { + $this->allowPanel(); + + $this->get('/rehla/automation')->assertOk()->assertSee('rehla.automation.enabled'); +}); + +it('creates a rule converting the time unit to hours', function () { + $this->allowPanel(); + + $this->post('/rehla/automation/rules', ruleInput(['meta_template' => 'nudge_v1', 'meta_language' => 'ar', 'meta_params' => 'name, step'])) + ->assertRedirect('/rehla/automation'); + + $rule = RehlaAutomationRule::query()->firstOrFail(); + expect($rule->after_hours)->toBe(48)->and($rule->enabled)->toBeTrue() + ->and($rule->provider_template)->toBe(['name' => 'nudge_v1', 'language' => 'ar', 'params' => ['name', 'step']]); + + $this->post('/rehla/automation/rules', ruleInput(['name' => 'w', 'after_value' => 1, 'after_unit' => 'weeks'])); + expect(RehlaAutomationRule::query()->where('name', 'w')->value('after_hours'))->toBe(168); +}); + +it('rejects a rule without a message, with an unknown journey or step', function () { + $this->allowPanel(); + + $this->post('/rehla/automation/rules', ruleInput(['message' => '']))->assertSessionHasErrors('message'); + $this->post('/rehla/automation/rules', ruleInput(['journey' => 'nope']))->assertSessionHasErrors('journey'); + $this->post('/rehla/automation/rules', ruleInput(['step' => 'nope']))->assertSessionHasErrors('step'); + $this->post('/rehla/automation/rules', ruleInput(['condition' => 'nope']))->assertSessionHasErrors('condition'); + + expect(RehlaAutomationRule::query()->count())->toBe(0); +}); + +it('edits, toggles and deletes a rule', function () { + $this->allowPanel(); + $rule = RehlaAutomationRule::query()->create(['name' => 'R', 'journey' => 'default', 'condition' => 'inactive_for', 'after_hours' => 24, 'message' => 'x']); + + $this->get("/rehla/automation/rules/{$rule->id}/edit")->assertOk()->assertSee('value="1"', false); + $this->put("/rehla/automation/rules/{$rule->id}", ruleInput(['name' => 'Renamed', 'enabled' => 0]))->assertRedirect(); + expect($rule->fresh()->name)->toBe('Renamed')->and($rule->fresh()->enabled)->toBeFalse(); + + $this->post("/rehla/automation/rules/{$rule->id}/toggle")->assertRedirect(); + expect($rule->fresh()->enabled)->toBeTrue(); + + $this->delete("/rehla/automation/rules/{$rule->id}")->assertRedirect(); + expect(RehlaAutomationRule::query()->count())->toBe(0); +}); + +it('shows the create form', function () { + $this->allowPanel(); + + $this->get('/rehla/automation/rules/create')->assertOk()->assertSee('Complete the profile'); +}); + +it('previews a rule without sending anything', function () { + $this->allowPanel(); + config()->set('rehla.automation.enabled', true); + config()->set('rehla.consent.required', false); + config()->set('rehla.automation.quiet_hours', ['start' => '00:00', 'end' => '00:00']); + $user = $this->makeUser(['phone' => '01070645696', 'name' => 'Sara']); + RehlaStepProgress::query()->create([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'journey' => 'default', + 'step' => 'profile', 'status' => 'started', 'started_at' => now()->subDays(5), + ]); + $rule = RehlaAutomationRule::query()->create([ + 'name' => 'R', 'journey' => 'default', 'condition' => 'step_started_not_finished_for', 'after_hours' => 24, 'message' => 'Hi {name}', + ]); + + $this->get("/rehla/automation/preview/db:{$rule->id}")->assertOk() + ->assertSee('Would message 1 user(s)')->assertSee('Hi Sara'); + + expect(RehlaFollowUp::query()->where('source', 'automation')->count())->toBe(0); +}); + +it('links the Automation tab in the nav', function () { + $this->allowPanel(); + $this->get('/rehla')->assertOk()->assertSee('/rehla/automation', false); +});