diff --git a/CHANGELOG.md b/CHANGELOG.md index 65edd9b..0f2c4e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### 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. +- Guards, all configurable: quiet hours (optional per-user timezone), cooldown, manual lock, max sends per user, hourly/daily/per-run limits, no double queueing. The send job cancels if an admin messaged the user by hand meanwhile. + ### 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`. diff --git a/README.md b/README.md index 49f117e..49ca248 100644 --- a/README.md +++ b/README.md @@ -175,4 +175,38 @@ Webhook (delivery status and STOP replies). It is only registered when the meta 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. + +### Rules and the engine + +Rules say who gets which message and when. Define them in `rehla.automation.rules` (code, always available) or in the `rehla_automation_rules` table (the panel tab comes in the next release). Both run together. + +```php +'rules' => [ + 'stuck-profile' => [ + 'journey' => 'default', + 'step' => 'profile', // optional; omit for "the step they are due on" + 'condition' => 'step_started_not_finished_for', + 'after_days' => 2, // or after_hours / after_weeks + 'message' => 'Hi {name}, finish "{step}" in {journey}', // or 'template_id' => 3 + 'max_sends_per_user' => 1, + // Meta: approved template name; params are placeholder names filling {{1}}, {{2}} + // 'provider_template' => ['name' => 'nudge_v1', 'language' => 'ar', 'params' => ['name', 'step']], + ], +], +``` + +Conditions: `inactive_for` (no visit for the time), `step_not_started_for` (the step they are due on has not started, counted from their last completed step or registration), `step_started_not_finished_for`. Placeholders: `{name}`, `{step}`, `{journey}`, `{days_inactive}`. + +Run it from the scheduler (every 5 to 15 minutes) and start with a dry run: + +```php +Schedule::command('rehla:automate')->everyTenMinutes(); +``` +```bash +php artisan rehla:automate --dry-run # who would be messaged, who is skipped and why +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. diff --git a/config/rehla.php b/config/rehla.php index 10398c4..be60cf5 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -125,6 +125,34 @@ ], ], + // 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 + 'limits' => [ + 'per_hour' => 60, + 'per_day' => 500, + 'per_run' => 100, + ], + // No automatic sends in this window (local time; may cross midnight). + // user_timezone_attribute: a user column holding an IANA timezone. + 'quiet_hours' => [ + 'start' => '21:00', + 'end' => '09:00', + 'timezone' => null, // null = app timezone + 'user_timezone_attribute' => null, + ], + // User column used as "registered at" when nothing else is known. + 'registered_attribute' => 'created_at', + + // Rules in code. Each: journey, condition (inactive_for, + // step_not_started_for, step_started_not_finished_for), one of + // after_hours / after_days / after_weeks, message (with {name}, + // {step}, {journey}, {days_inactive}) or template_id, optional step, + // cooldown_hours, max_sends_per_user (default 1), provider_template + // ['name' => ..., 'language' => ..., 'params' => ['name', 'step']]. + // Rules created in the panel (database) run alongside these. + 'rules' => [], + // Where queued sends run. null = the app defaults. 'queue' => ['connection' => null, 'name' => null], diff --git a/database/migrations/2026_01_01_000008_create_rehla_automation_rules_table.php b/database/migrations/2026_01_01_000008_create_rehla_automation_rules_table.php new file mode 100644 index 0000000..0809b40 --- /dev/null +++ b/database/migrations/2026_01_01_000008_create_rehla_automation_rules_table.php @@ -0,0 +1,37 @@ +id(); + $table->string('name'); + $table->boolean('enabled')->default(true); + $table->string('journey'); + $table->string('step')->nullable(); + $table->string('condition', 48); + $table->unsignedInteger('after_hours'); + $table->foreignId('template_id')->nullable(); + $table->text('message')->nullable(); + $table->json('provider_template')->nullable(); + $table->unsignedInteger('cooldown_hours')->nullable(); + $table->unsignedSmallInteger('max_sends_per_user')->default(1); + $table->string('created_by')->nullable(); + $table->timestamps(); + + $table->index(['enabled', 'journey'], 'rehla_rules_enabled_journey'); + }); + } + + public function down(): void + { + Schema::dropIfExists('rehla_automation_rules'); + } +}; diff --git a/docs/ar/README.md b/docs/ar/README.md index e32969c..11f8d53 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -175,4 +175,38 @@ Rehla::consent()->optOut($user); // وكمان بيلغي الرسائل في البانل المستخدمين اللي عملوا إيقاف عليهم علامة "أوقف الرسائل"، والمودال بيطلب تأكيد صريح قبل رسالة يدوية ليهم. -القواعد وتاب البانل والتقوية جايين في الإصدارات الجاية، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين. + +### القواعد والمحرّك + +القواعد بتحدد مين ياخد أنهي رسالة وإمتى. عرّفها في `rehla.automation.rules` (في الكود، متاحة دايماً) أو في جدول `rehla_automation_rules` (تاب البانل جاي في الإصدار الجاي). الاتنين بيشتغلوا مع بعض. + +```php +'rules' => [ + 'stuck-profile' => [ + 'journey' => 'default', + 'step' => 'profile', // اختياري؛ من غيره = الخطوة المستحقة عليه + 'condition' => 'step_started_not_finished_for', + 'after_days' => 2, // أو after_hours / after_weeks + 'message' => 'أهلاً {name}، كمّل "{step}" في {journey}', // أو 'template_id' => 3 + 'max_sends_per_user' => 1, + // ميتا: اسم القالب المعتمد؛ params أسماء المتغيرات اللي بتملا {{1}} و{{2}} + // 'provider_template' => ['name' => 'nudge_v1', 'language' => 'ar', 'params' => ['name', 'step']], + ], +], +``` + +الشروط: `inactive_for` (مدخلش المدة دي)، و`step_not_started_for` (الخطوة المستحقة عليه لسه مبدأهاش، من آخر خطوة خلصها أو من التسجيل)، و`step_started_not_finished_for`. المتغيرات: `{name}` و`{step}` و`{journey}` و`{days_inactive}`. + +شغّله من الـscheduler (كل 5 لـ15 دقيقة) وابدأ بتجربة: + +```php +Schedule::command('rehla:automate')->everyTenMinutes(); +``` +```bash +php artisan rehla:automate --dry-run # مين هيتبعتله ومين اتخطّى وليه +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 بيلغي الرسالة لو أدمن بعت للمستخدم يدوي في الوقت ده. + +تاب البانل والتقوية جايين في الإصدارات الجاية، فلسه متوجّهش الإرسال التلقائي على مستخدمين حقيقيين. diff --git a/src/Automation/AutomationEngine.php b/src/Automation/AutomationEngine.php new file mode 100644 index 0000000..c8c1d77 --- /dev/null +++ b/src/Automation/AutomationEngine.php @@ -0,0 +1,413 @@ +skip('*', '*', 'automation_disabled'); + + return $report; + } + + /** @var class-string $userModel */ + $userModel = (string) Config::get('rehla.user_model', 'App\\Models\\User'); + + if (! class_exists($userModel) || ! is_subclass_of($userModel, Model::class)) { + return $report; + } + + $hourly = $this->limit('rehla.automation.limits.per_hour'); + $daily = $this->limit('rehla.automation.limits.per_day'); + $usedHour = $this->automaticSince($now->copy()->subHour()); + $usedDay = $this->automaticSince($now->copy()->subDay()); + $perRun = $this->limit('rehla.automation.limits.per_run'); + $queuedThisRun = 0; + + foreach ($this->rules->all() as $rule) { + if ($onlyRule !== null && $onlyRule !== $rule->key && $onlyRule !== $rule->name) { + continue; + } + + if (! $this->journeys->exists($rule->journey)) { + $report->skip($rule->key, '*', 'unknown_journey'); + + continue; + } + + $userModel::query()->chunkById(200, function ($users) use ( + $rule, $report, $now, $dryRun, $hourly, $daily, $perRun, &$usedHour, &$usedDay, &$queuedThisRun, + ): bool { + $ids = $users->modelKeys(); + $progress = $this->progressFor($ids, $users->first(), $rule->journey); + $activity = RehlaActivity::query() + ->where('trackable_type', $users->first()?->getMorphClass()) + ->whereIn('trackable_id', $ids) + ->pluck('last_seen_at', 'trackable_id'); + $followUps = RehlaFollowUp::query() + ->where('trackable_type', $users->first()?->getMorphClass()) + ->whereIn('trackable_id', $ids) + ->get() + ->groupBy('trackable_id'); + + foreach ($users as $user) { + $id = $user->getKey(); + $match = $this->match($rule, $user, $progress[$id] ?? [], $activity[$id] ?? null, $now); + + if ($match === null) { + continue; + } + + $reason = $this->guard($rule, $user, $followUps[$id] ?? collect(), $now); + + if ($reason === null && $hourly !== null && $usedHour >= $hourly) { + $reason = 'rate_limit_hour'; + } + + if ($reason === null && $daily !== null && $usedDay >= $daily) { + $reason = 'rate_limit_day'; + } + + if ($reason === null && $perRun !== null && $queuedThisRun >= $perRun) { + $reason = 'rate_limit_run'; + } + + if ($reason !== null) { + $report->skip($rule->key, $id, $reason); + + continue; + } + + $message = $this->render($rule, $user, $match); + $sendNumber = $this->previousSends($rule, $followUps[$id] ?? collect()) + 1; + + if (! $dryRun) { + try { + $this->sender->queue($user, $message, [ + 'template_id' => $rule->templateId, + 'journey' => $rule->journey, + 'step' => $match['step'], + 'rule_id' => $rule->id, + 'idempotency_key' => "{$rule->key}:user:{$id}:{$match['step']}:{$sendNumber}", + 'provider_template' => $this->providerTemplate($rule, $user, $match), + ]); + } catch (AutomationException $e) { + $report->skip($rule->key, $id, 'send_refused'); + + continue; + } + } + + $usedHour++; + $usedDay++; + $queuedThisRun++; + $report->send($rule->key, $id, $match['step'], $message); + } + + return true; + }); + } + + return $report; + } + + /** + * @param array $ids + * @return array> + */ + private function progressFor(array $ids, ?Model $sample, string $journey): array + { + if ($sample === null) { + return []; + } + + $out = []; + + foreach (RehlaStepProgress::query() + ->where('trackable_type', $sample->getMorphClass()) + ->whereIn('trackable_id', $ids) + ->where('journey', $journey) + ->get() as $row) { + $out[$row->trackable_id][] = $row; + } + + return $out; + } + + /** + * Does this user match the rule's condition? Returns the step they are + * due on and the days figure for templates, or null. + * + * @param list $rows + * @return array{step: string|null, days: int}|null + */ + private function match(Rule $rule, Model $user, array $rows, mixed $lastSeen, CarbonInterface $now): ?array + { + $cutoff = $now->copy()->subHours($rule->afterHours); + $status = []; + $completedAt = null; + + foreach ($rows as $row) { + $status[$row->step] = $row; + + if ($row->status === StepStatus::Completed && $row->completed_at !== null + && ($completedAt === null || $row->completed_at->gt($completedAt))) { + $completedAt = $row->completed_at; + } + } + + $started = []; + $notStarted = []; + + foreach ($this->journeys->stepKeys($rule->journey) as $step) { + $row = $status[$step] ?? null; + + if ($row?->status === StepStatus::Started) { + $started[] = $step; + } elseif ($row?->status !== StepStatus::Completed) { + $notStarted[] = $step; + } + } + + $registered = $this->registeredAt($user); + + if ($rule->condition === Rule::INACTIVE_FOR) { + $pending = $rule->step !== null + ? (in_array($rule->step, $started, true) || in_array($rule->step, $notStarted, true) ? $rule->step : null) + : ($started[0] ?? $notStarted[0] ?? null); + + if ($pending === null) { + return null; + } + + $seen = $lastSeen instanceof CarbonInterface ? $lastSeen : $registered; + + return $seen !== null && $seen->lte($cutoff) + ? ['step' => $pending, 'days' => (int) $seen->diffInDays($now, true)] + : null; + } + + if ($rule->condition === Rule::STEP_NOT_STARTED_FOR) { + $due = $rule->step ?? ($notStarted[0] ?? null); + + if ($due === null || ! in_array($due, $notStarted, true) || in_array($due, $started, true)) { + return null; + } + + $since = $completedAt ?? $registered; + + return $since !== null && $since->lte($cutoff) + ? ['step' => $due, 'days' => (int) $since->diffInDays($now, true)] + : null; + } + + $step = $rule->step ?? ($started[0] ?? null); + + if ($step === null || ! in_array($step, $started, true)) { + return null; + } + + $startedAt = ($status[$step] ?? null)?->started_at; + + return $startedAt !== null && $startedAt->lte($cutoff) + ? ['step' => $step, 'days' => (int) $startedAt->diffInDays($now, true)] + : null; + } + + private function registeredAt(Model $user): ?CarbonInterface + { + $value = $user->getAttribute((string) Config::get('rehla.automation.registered_attribute', 'created_at')); + + return $value instanceof CarbonInterface ? $value : null; + } + + /** + * The guards, in order. Returns the skip reason, or null to send. + * + * @param Collection $history + */ + private function guard(Rule $rule, Model $user, $history, CarbonInterface $now): ?string + { + $phone = $user->getAttribute((string) Config::get('rehla.phone_attribute', 'phone')); + + if (WhatsAppLink::normalizeNumber(is_string($phone) ? $phone : null, (string) Config::get('rehla.whatsapp.default_country_code', '')) === null) { + return 'no_phone'; + } + + if (! $this->consent->allows($user)) { + return $this->consent->isOptedOut($user) ? 'opted_out' : 'no_consent'; + } + + if ($this->inQuietHours($user, $now)) { + return 'quiet_hours'; + } + + $cooldown = $rule->cooldownHours ?? (int) Config::get('rehla.automation.cooldown_hours', 72); + $lock = (int) Config::get('rehla.automation.manual_lock_hours', 2); + + foreach ($history as $row) { + if ($row->status === RehlaFollowUp::STATUS_QUEUED && $row->source === RehlaFollowUp::SOURCE_AUTOMATION) { + return 'already_queued'; + } + + if ($row->status === RehlaFollowUp::STATUS_SENT && $row->created_at->gt($now->copy()->subHours($cooldown))) { + return 'cooldown'; + } + + if ($row->status === RehlaFollowUp::STATUS_OPENED && $row->created_at->gt($now->copy()->subHours($lock))) { + return 'manual_lock'; + } + } + + if ($this->previousSends($rule, $history) >= $rule->maxSendsPerUser) { + return 'max_sends'; + } + + return null; + } + + /** + * @param Collection $history + */ + private function previousSends(Rule $rule, $history): int + { + return $history->filter( + fn (RehlaFollowUp $row): bool => $row->source === RehlaFollowUp::SOURCE_AUTOMATION + && str_starts_with((string) $row->idempotency_key, $rule->key.':') + && ! in_array($row->status, [RehlaFollowUp::STATUS_CANCELLED, RehlaFollowUp::STATUS_FAILED], true), + )->count(); + } + + private function inQuietHours(Model $user, CarbonInterface $now): bool + { + $start = Config::get('rehla.automation.quiet_hours.start', '21:00'); + $end = Config::get('rehla.automation.quiet_hours.end', '09:00'); + + if (! is_string($start) || ! is_string($end) || $start === $end) { + return false; + } + + $configured = Config::get('rehla.automation.quiet_hours.timezone'); + $timezone = is_string($configured) && $configured !== '' ? $configured : (string) Config::get('app.timezone', 'UTC'); + $attribute = Config::get('rehla.automation.quiet_hours.user_timezone_attribute'); + + if (is_string($attribute) && $attribute !== '') { + $own = $user->getAttribute($attribute); + + if (is_string($own) && in_array($own, timezone_identifiers_list(), true)) { + $timezone = $own; + } + } + + $local = $now->copy()->setTimezone($timezone)->format('H:i'); + + return $start < $end + ? $local >= $start && $local < $end + : $local >= $start || $local < $end; + } + + /** + * @param array{step: string|null, days: int} $match + * @return array + */ + private function values(Rule $rule, Model $user, array $match): array + { + $name = $user->getAttribute((string) Config::get('rehla.name_attribute', 'name')); + $step = $match['step']; + + return [ + 'name' => is_string($name) ? $name : '', + 'step' => $step !== null ? $this->journeys->steps($rule->journey)[$step] ?? $step : '', + 'journey' => $this->journeys->label($rule->journey), + 'days_inactive' => (string) $match['days'], + ]; + } + + /** @param array{step: string|null, days: int} $match */ + private function render(Rule $rule, Model $user, array $match): string + { + $text = $rule->message; + + if ($text === null && $rule->templateId !== null) { + $text = RehlaTemplate::query()->find($rule->templateId)?->content; + } + + $text ??= ''; + + foreach ($this->values($rule, $user, $match) as $key => $value) { + $text = str_replace('{'.$key.'}', $value, $text); + } + + return $text; + } + + /** + * @param array{step: string|null, days: int} $match + * @return array{name: string, language?: string|null, params?: list}|null + */ + private function providerTemplate(Rule $rule, Model $user, array $match): ?array + { + if ($rule->providerTemplate === null) { + return null; + } + + $values = $this->values($rule, $user, $match); + $params = []; + + foreach ($rule->providerTemplate['params'] ?? [] as $placeholder) { + $params[] = $values[trim($placeholder, '{}')] ?? ''; + } + + return ['name' => $rule->providerTemplate['name'], 'language' => $rule->providerTemplate['language'] ?? null, 'params' => $params]; + } + + private function limit(string $key): ?int + { + $value = Config::get($key); + + return is_numeric($value) && (int) $value > 0 ? (int) $value : null; + } + + private function automaticSince(CarbonInterface $since): int + { + return RehlaFollowUp::query() + ->where('source', RehlaFollowUp::SOURCE_AUTOMATION) + ->whereNotIn('status', [RehlaFollowUp::STATUS_CANCELLED]) + ->where('created_at', '>=', $since) + ->count(); + } +} diff --git a/src/Automation/Rule.php b/src/Automation/Rule.php new file mode 100644 index 0000000..c8b157d --- /dev/null +++ b/src/Automation/Rule.php @@ -0,0 +1,121 @@ +}|null $providerTemplate + */ + public function __construct( + public readonly string $key, + public readonly ?int $id, + public readonly string $name, + public readonly string $journey, + public readonly ?string $step, + public readonly string $condition, + public readonly int $afterHours, + public readonly ?int $templateId, + public readonly ?string $message, + public readonly ?array $providerTemplate, + public readonly ?int $cooldownHours, + public readonly int $maxSendsPerUser, + ) { + if (! in_array($condition, self::CONDITIONS, true)) { + throw new InvalidArgumentException("Unknown rule condition [{$condition}]."); + } + + if ($afterHours < 1) { + throw new InvalidArgumentException('A rule needs a positive time threshold.'); + } + } + + /** + * Config shape: name, journey, condition, and the threshold as + * after_hours, after_days or after_weeks (first one set wins). + * + * @param array $data + */ + public static function fromConfig(string $key, array $data): self + { + $hours = match (true) { + isset($data['after_hours']) => (int) $data['after_hours'], + isset($data['after_days']) => (int) $data['after_days'] * 24, + isset($data['after_weeks']) => (int) $data['after_weeks'] * 168, + default => 0, + }; + + $template = $data['provider_template'] ?? null; + + return new self( + 'config:'.$key, + null, + is_string($data['name'] ?? null) ? $data['name'] : $key, + (string) ($data['journey'] ?? ''), + isset($data['step']) && is_string($data['step']) && $data['step'] !== '' ? $data['step'] : null, + (string) ($data['condition'] ?? ''), + $hours, + isset($data['template_id']) ? (int) $data['template_id'] : null, + isset($data['message']) && is_string($data['message']) ? $data['message'] : null, + self::cleanTemplate($template), + isset($data['cooldown_hours']) ? (int) $data['cooldown_hours'] : null, + max(1, (int) ($data['max_sends_per_user'] ?? 1)), + ); + } + + public static function fromModel(RehlaAutomationRule $rule): self + { + return new self( + 'db:'.$rule->id, + $rule->id, + $rule->name, + $rule->journey, + $rule->step !== '' ? $rule->step : null, + $rule->condition, + $rule->after_hours, + $rule->template_id, + $rule->message, + self::cleanTemplate($rule->provider_template), + $rule->cooldown_hours, + max(1, $rule->max_sends_per_user), + ); + } + + /** @return array{name: string, language?: string|null, params?: list}|null */ + private static function cleanTemplate(mixed $template): ?array + { + if (! is_array($template) || ! is_string($template['name'] ?? null) || $template['name'] === '') { + return null; + } + + $params = []; + + foreach ((array) ($template['params'] ?? []) as $param) { + if (is_string($param)) { + $params[] = $param; + } + } + + return [ + 'name' => $template['name'], + 'language' => is_string($template['language'] ?? null) ? $template['language'] : null, + 'params' => $params, + ]; + } +} diff --git a/src/Automation/RuleRepository.php b/src/Automation/RuleRepository.php new file mode 100644 index 0000000..a55e4b6 --- /dev/null +++ b/src/Automation/RuleRepository.php @@ -0,0 +1,45 @@ + */ + public function all(): array + { + $rules = []; + + foreach ((array) Config::get('rehla.automation.rules', []) as $key => $data) { + if (! is_array($data) || ($data['enabled'] ?? true) === false) { + continue; + } + + try { + $rules[] = Rule::fromConfig((string) $key, $data); + } catch (InvalidArgumentException $e) { + report($e); + } + } + + try { + foreach (RehlaAutomationRule::query()->where('enabled', true)->orderBy('id')->get() as $model) { + $rules[] = Rule::fromModel($model); + } + } catch (Throwable) { + // The table does not exist yet (migration not run): config rules still work. + } + + return $rules; + } +} diff --git a/src/Automation/RunReport.php b/src/Automation/RunReport.php new file mode 100644 index 0000000..f531000 --- /dev/null +++ b/src/Automation/RunReport.php @@ -0,0 +1,33 @@ + */ + public array $sends = []; + + /** @var array reason => how many users */ + public array $skipped = []; + + /** @var list */ + public array $skips = []; + + public function __construct(public readonly bool $dryRun) {} + + public function send(string $rule, int|string $user, ?string $step, string $message): void + { + $this->sends[] = ['rule' => $rule, 'user' => $user, 'step' => $step, 'message' => $message]; + } + + public function skip(string $rule, int|string $user, string $reason): void + { + $this->skipped[$reason] = ($this->skipped[$reason] ?? 0) + 1; + $this->skips[] = ['rule' => $rule, 'user' => $user, 'reason' => $reason]; + } +} diff --git a/src/Console/AutomateCommand.php b/src/Console/AutomateCommand.php new file mode 100644 index 0000000..3843ffb --- /dev/null +++ b/src/Console/AutomateCommand.php @@ -0,0 +1,48 @@ +option('rule'); + $dry = (bool) $this->option('dry-run'); + $report = $engine->run($dry, is_string($only) && $only !== '' ? $only : null); + + if (isset($report->skipped['automation_disabled'])) { + $this->warn('Automation is disabled (rehla.automation.enabled). Nothing was done.'); + + return self::SUCCESS; + } + + $this->info(($dry ? 'Dry run: would queue ' : 'Queued ').count($report->sends).' message(s).'); + + foreach ($report->sends as $send) { + $this->line(" [{$send['rule']}] user {$send['user']} step ".($send['step'] ?? '-')); + + if ($dry) { + $this->line(' '.$send['message']); + } + } + + foreach ($report->skipped as $reason => $count) { + $this->line(" skipped {$count}: {$reason}"); + } + + return self::SUCCESS; + } +} diff --git a/src/Jobs/SendAutomatedFollowUp.php b/src/Jobs/SendAutomatedFollowUp.php index 3ea9982..0634fa3 100644 --- a/src/Jobs/SendAutomatedFollowUp.php +++ b/src/Jobs/SendAutomatedFollowUp.php @@ -48,6 +48,23 @@ public function handle(ProviderManager $providers, ConsentManager $consent): voi return; } + if ($followUp->source === RehlaFollowUp::SOURCE_AUTOMATION && $followUp->rule_id !== null || str_contains((string) $followUp->idempotency_key, ':user:')) { + // An admin may have messaged this user by hand while this waited. + $manual = RehlaFollowUp::query() + ->where('trackable_type', $followUp->trackable_type) + ->where('trackable_id', $followUp->trackable_id) + ->where('source', '!=', RehlaFollowUp::SOURCE_AUTOMATION) + ->whereIn('status', [RehlaFollowUp::STATUS_SENT, RehlaFollowUp::STATUS_OPENED]) + ->where('created_at', '>=', $followUp->created_at) + ->exists(); + + if ($manual) { + $followUp->forceFill(['status' => RehlaFollowUp::STATUS_CANCELLED, 'skip_reason' => 'manual_sent'])->save(); + + return; + } + } + $payload = $followUp->payload ?? []; $phone = $payload['phone'] ?? null; diff --git a/src/Models/RehlaAutomationRule.php b/src/Models/RehlaAutomationRule.php new file mode 100644 index 0000000..cbc8ff5 --- /dev/null +++ b/src/Models/RehlaAutomationRule.php @@ -0,0 +1,42 @@ +|null $provider_template + * @property int|null $cooldown_hours + * @property int $max_sends_per_user + * @property string|null $created_by + */ +final class RehlaAutomationRule extends Model +{ + protected $table = 'rehla_automation_rules'; + + /** @var list */ + protected $fillable = [ + 'name', 'enabled', 'journey', 'step', 'condition', 'after_hours', 'template_id', + 'message', 'provider_template', 'cooldown_hours', 'max_sends_per_user', 'created_by', + ]; + + /** @var array */ + protected $casts = [ + 'enabled' => 'boolean', + 'after_hours' => 'integer', + 'provider_template' => 'array', + 'cooldown_hours' => 'integer', + 'max_sends_per_user' => 'integer', + ]; +} diff --git a/src/RehlaServiceProvider.php b/src/RehlaServiceProvider.php index 65a1c1a..d493067 100644 --- a/src/RehlaServiceProvider.php +++ b/src/RehlaServiceProvider.php @@ -12,6 +12,7 @@ use Illuminate\Support\ServiceProvider; use Rehla\Automation\FollowUpSender; use Rehla\Automation\ProviderManager; +use Rehla\Console\AutomateCommand; use Rehla\Console\InstallCommand; use Rehla\Console\ReportCommand; use Rehla\Http\Middleware\AuthorizePanel; @@ -54,7 +55,7 @@ public function register(): void public function boot(): void { if ($this->app->runningInConsole()) { - $this->commands([InstallCommand::class, ReportCommand::class]); + $this->commands([InstallCommand::class, ReportCommand::class, AutomateCommand::class]); $this->publishes([ __DIR__.'/../config/rehla.php' => $this->app->configPath('rehla.php'), diff --git a/tests/Feature/AutomationEngineTest.php b/tests/Feature/AutomationEngineTest.php new file mode 100644 index 0000000..3b6f9b8 --- /dev/null +++ b/tests/Feature/AutomationEngineTest.php @@ -0,0 +1,246 @@ +set('rehla.automation.enabled', true); + config()->set('rehla.consent.required', false); + config()->set('rehla.app_timezone', 'UTC'); + config()->set('app.timezone', 'UTC'); + config()->set('rehla.automation.rules', [ + 'nudge' => [ + 'journey' => 'default', + 'condition' => 'step_started_not_finished_for', + 'after_days' => 2, + 'message' => 'Hi {name}, finish "{step}" in {journey}', + ], + ]); + Carbon::setTestNow('2026-03-10 12:00:00'); +}); + +afterEach(fn () => Carbon::setTestNow()); + +function stuckUser(object $test, array $attrs = [], string $startedAt = '2026-03-07 10:00:00'): Model +{ + static $n = 0; + $n++; + $user = FixtureUser::query()->create($attrs + ['phone' => '01070645696', 'name' => 'S'.$n, 'email' => "s{$n}@example.com", 'password' => 'x']); + RehlaStepProgress::query()->create([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, + 'journey' => 'default', 'step' => 'profile', 'status' => 'started', 'started_at' => $startedAt, + ]); + + return $user; +} + +it('queues a rendered message for a user stuck on a step', function () { + $user = stuckUser($this, ['name' => 'Sara']); + + $report = app(AutomationEngine::class)->run(); + + expect($report->sends)->toHaveCount(1) + ->and($report->sends[0]['message'])->toBe('Hi Sara, finish "Complete the profile" in Main journey'); + $row = RehlaFollowUp::query()->firstOrFail(); + expect($row->status)->toBe('queued')->and($row->source)->toBe('automation') + ->and($row->step)->toBe('profile')->and($row->trackable_id)->toBe($user->id); + Bus::assertDispatched(SendAutomatedFollowUp::class); +}); + +it('does nothing in a dry run', function () { + stuckUser($this); + + $report = app(AutomationEngine::class)->run(dryRun: true); + + expect($report->sends)->toHaveCount(1)->and(RehlaFollowUp::query()->count())->toBe(0); +}); + +it('ignores users who have not waited long enough', function () { + stuckUser($this, [], '2026-03-09 10:00:00'); + + expect(app(AutomationEngine::class)->run()->sends)->toBe([]); +}); + +it('never queues the same user twice for a rule (max sends and overlap)', function () { + stuckUser($this); + + app(AutomationEngine::class)->run(); + $second = app(AutomationEngine::class)->run(); + + expect($second->sends)->toBe([])->and($second->skipped)->toHaveKey('already_queued') + ->and(RehlaFollowUp::query()->count())->toBe(1); +}); + +it('respects the max sends per user once earlier ones are done', function () { + $user = stuckUser($this); + app(AutomationEngine::class)->run(); + RehlaFollowUp::query()->update(['status' => 'simulated']); + + $report = app(AutomationEngine::class)->run(); + + expect($report->skipped)->toHaveKey('max_sends'); +}); + +it('skips users without a phone, consent, or after an opt-out', function () { + stuckUser($this, ['phone' => null]); + $optedOut = stuckUser($this); + Rehla::consent()->optOut($optedOut); + + $report = app(AutomationEngine::class)->run(); + expect($report->skipped)->toMatchArray(['no_phone' => 1, 'opted_out' => 1]); + + config()->set('rehla.consent.required', true); + stuckUser($this); + expect(app(AutomationEngine::class)->run(dryRun: true)->skipped)->toHaveKey('no_consent'); +}); + +it('stays quiet during quiet hours and honours changed hours', function () { + stuckUser($this); + Carbon::setTestNow('2026-03-10 22:30:00'); + + expect(app(AutomationEngine::class)->run()->skipped)->toHaveKey('quiet_hours'); + + config()->set('rehla.automation.quiet_hours', ['start' => '01:00', 'end' => '05:00']); + expect(app(AutomationEngine::class)->run(dryRun: true)->sends)->toHaveCount(1); +}); + +it('uses a per-user timezone when configured', function () { + config()->set('rehla.automation.quiet_hours.user_timezone_attribute', 'name'); + stuckUser($this, ['name' => 'Asia/Tokyo']); // 12:00 UTC = 21:00 in Tokyo + + expect(app(AutomationEngine::class)->run()->skipped)->toHaveKey('quiet_hours'); +}); + +it('waits out the cooldown after a sent follow-up and the lock after an open draft', function () { + $user = stuckUser($this); + $row = fn (string $status, string $at) => RehlaFollowUp::query()->forceCreate([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'x', + 'status' => $status, 'source' => 'manual', 'created_at' => $at, + ]); + + $sent = $row('sent', '2026-03-08 12:00:00'); + expect(app(AutomationEngine::class)->run(dryRun: true)->skipped)->toHaveKey('cooldown'); + + config()->set('rehla.automation.cooldown_hours', 24); + expect(app(AutomationEngine::class)->run(dryRun: true)->sends)->toHaveCount(1); + + $sent->delete(); + $row('opened', '2026-03-10 11:00:00'); + expect(app(AutomationEngine::class)->run(dryRun: true)->skipped)->toHaveKey('manual_lock'); +}); + +it('applies the global rate limits', function () { + config()->set('rehla.automation.limits.per_run', 2); + foreach (range(1, 4) as $_) { + stuckUser($this); + } + + $report = app(AutomationEngine::class)->run(); + + expect($report->sends)->toHaveCount(2)->and($report->skipped)->toMatchArray(['rate_limit_run' => 2]); +}); + +it('does nothing while automation is disabled', function () { + config()->set('rehla.automation.enabled', false); + stuckUser($this); + + expect(app(AutomationEngine::class)->run()->skipped)->toHaveKey('automation_disabled'); +}); + +it('matches inactive users by last visit, falling back to registration', function () { + config()->set('rehla.automation.rules', ['gone' => [ + 'journey' => 'default', 'condition' => 'inactive_for', 'after_weeks' => 1, 'message' => '{days_inactive} days', + ]]); + $away = $this->makeUser(['phone' => '01070645696']); + RehlaActivity::query()->create(['trackable_type' => $away->getMorphClass(), 'trackable_id' => $away->id, 'last_seen_at' => '2026-03-01 08:00:00']); + $recent = $this->makeUser(['phone' => '01070645696']); + RehlaActivity::query()->create(['trackable_type' => $recent->getMorphClass(), 'trackable_id' => $recent->id, 'last_seen_at' => '2026-03-09 08:00:00']); + + $report = app(AutomationEngine::class)->run(dryRun: true); + + expect($report->sends)->toHaveCount(1) + ->and($report->sends[0]['user'])->toBe($away->id) + ->and($report->sends[0]['message'])->toBe('9 days'); +}); + +it('matches a step that was never started, counted from the last completed step', function () { + config()->set('rehla.automation.rules', ['idle' => [ + 'journey' => 'default', 'condition' => 'step_not_started_for', 'after_hours' => 48, 'message' => '{step}', + ]]); + $user = $this->makeUser(['phone' => '01070645696']); + RehlaStepProgress::query()->create([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'journey' => 'default', + 'step' => 'account', 'status' => 'completed', 'started_at' => '2026-03-01', 'completed_at' => '2026-03-05 10:00:00', + ]); + + $report = app(AutomationEngine::class)->run(dryRun: true); + + expect($report->sends)->toHaveCount(1)->and($report->sends[0]['message'])->toBe('Complete the profile'); +}); + +it('runs database rules, using a template and a Meta template mapping', function () { + config()->set('rehla.automation.rules', []); + $template = RehlaTemplate::query()->create(['title' => 't', 'content' => 'Hello {name}', 'type' => 'encourage_start']); + RehlaAutomationRule::query()->create([ + 'name' => 'db', 'journey' => 'default', 'condition' => 'step_started_not_finished_for', 'after_hours' => 24, + 'template_id' => $template->id, + 'provider_template' => ['name' => 'nudge_v1', 'language' => 'ar', 'params' => ['name', 'step']], + ]); + stuckUser($this, ['name' => 'Omar']); + + app(AutomationEngine::class)->run(); + + $row = RehlaFollowUp::query()->firstOrFail(); + expect($row->message)->toBe('Hello Omar') + ->and($row->rule_id)->not->toBeNull() + ->and($row->payload['template_name'])->toBe('nudge_v1') + ->and($row->payload['template_params'])->toBe(['Omar', 'Complete the profile']); +}); + +it('ignores disabled and invalid rules without crashing', function () { + config()->set('rehla.automation.rules', [ + 'bad' => ['journey' => 'default', 'condition' => 'nope', 'after_days' => 1], + 'off' => ['enabled' => false, 'journey' => 'default', 'condition' => 'inactive_for', 'after_days' => 1], + ]); + stuckUser($this); + + expect(app(AutomationEngine::class)->run()->sends)->toBe([]); +}); + +it('cancels a queued send when an admin messaged the user meanwhile', function () { + $user = stuckUser($this); + app(AutomationEngine::class)->run(); + RehlaFollowUp::query()->create([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'm', + 'status' => 'sent', 'source' => 'manual', + ]); + $row = RehlaFollowUp::query()->where('source', 'automation')->firstOrFail(); + + (new SendAutomatedFollowUp($row->id))->handle(app(ProviderManager::class), app(ConsentManager::class)); + + expect($row->fresh()->status)->toBe('cancelled')->and($row->fresh()->skip_reason)->toBe('manual_sent'); +}); + +it('has an artisan command with dry run', function () { + stuckUser($this); + + $this->artisan('rehla:automate --dry-run')->expectsOutputToContain('would queue 1')->assertSuccessful(); + expect(RehlaFollowUp::query()->count())->toBe(0); + + $this->artisan('rehla:automate')->expectsOutputToContain('Queued 1')->assertSuccessful(); +}); diff --git a/tests/Feature/InstallTest.php b/tests/Feature/InstallTest.php index a9b2669..1036acb 100644 --- a/tests/Feature/InstallTest.php +++ b/tests/Feature/InstallTest.php @@ -9,7 +9,7 @@ function dropRehlaTables(): void { - foreach (['rehla_consents', 'rehla_follow_ups', 'rehla_templates', 'rehla_activity', 'rehla_step_progress'] as $table) { + foreach (['rehla_automation_rules', 'rehla_consents', 'rehla_follow_ups', 'rehla_templates', 'rehla_activity', 'rehla_step_progress'] as $table) { Schema::dropIfExists($table); }