diff --git a/CHANGELOG.md b/CHANGELOG.md index 8eaab66..7d7683c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +### Added +- `rehla.follow_up.confirm_sent` (default `true`). Set it to `false` to skip the "did you actually send it?" step; opening WhatsApp then records the follow-up as sent immediately. +- `php artisan rehla:install`: publishes the config if missing and runs only Rehla's migrations (idempotent, `--force` for production). + +### Changed +- The panel answers 503 with a clear message when the Rehla tables are missing, and the `rehla.activity` middleware logs and continues instead of failing the host request when tracking cannot write. + ### Changed - Follow-ups now distinguish "WhatsApp opened" from "admin confirmed sent". Opening WhatsApp records an `opened` (unconfirmed) follow-up. After opening, the modal asks "Did you actually send it?" and lets the admin correct the text. Only `sent` records feed the Last follow-up column and the recent-follow-up warning. Abandoned drafts are kept in the history as "Not sent". - Only the admin who opened a draft can confirm it, and only once. diff --git a/README.md b/README.md index bb96a5d..8ca866c 100644 --- a/README.md +++ b/README.md @@ -23,10 +23,13 @@ On top of that table sits a re-engagement flow: a WhatsApp button per user that ```bash composer require elbanbydev/rehla -php artisan vendor:publish --tag=rehla-config -php artisan migrate +php artisan rehla:install ``` +`rehla:install` publishes `config/rehla.php` (if missing) and creates the Rehla tables. Run it again any time; it only applies what is pending. + +Rehla registers its migrations itself, so no `vendor:publish` is needed for them: your normal deploy step `php artisan migrate` picks them up too. Composer cannot run migrations on `composer require` (Laravel packages have no install hook, and running database changes from a Composer script would be unsafe), so one of those two commands has to run once. If the tables are missing, the panel answers with a clear message and the tracking middleware stays quiet instead of breaking your site. + ## Define your journey In `config/rehla.php`: @@ -106,7 +109,7 @@ Set `rehla.phone_attribute` (default `phone`) and `rehla.name_attribute` (defaul When several people have follow-up permission, nobody should message the same user twice. So Rehla records every follow-up the moment the admin confirms the WhatsApp modal: who sent it, when, the exact message, and what it was about (the template title is snapshotted, so the record survives template edits and deletions). -The table's **Last follow-up** column sits next to **Last visit**, and each row's **(i)** button opens the full history popup: every message ever sent to that user, newest first. Recording is best-effort and never blocks opening WhatsApp. +The table's **Last follow-up** column sits next to **Last visit**, and each row's **(i)** button opens the full history popup: every message ever sent to that user, newest first. Recording is best-effort and never blocks opening WhatsApp. Set `rehla.follow_up.confirm_sent` to `false` to skip the confirm step: opening WhatsApp then records the follow-up as sent right away. Opening WhatsApp is not the same as sending. The record starts as unconfirmed; after the admin comes back, the modal asks "Did you actually send it?" (with a chance to fix the text). Only confirmed sends count as the last follow-up and trigger the "followed up recently" warning. Abandoned drafts stay in the history labelled "Not sent". diff --git a/config/rehla.php b/config/rehla.php index 069576c..492c401 100644 --- a/config/rehla.php +++ b/config/rehla.php @@ -68,10 +68,15 @@ /* | Follow-up guard. If the user was followed up within this many hours, | the WhatsApp modal shows a warning (it never blocks sending). - | Set 0 to turn the warning off. + | Set 0 to turn the warning off. `confirm_sent` is explained below. */ 'follow_up' => [ 'warn_within_hours' => 24, + + // true: after opening WhatsApp the modal asks "did you actually send + // it?" and only confirmed sends count as the last follow-up. + // false: opening WhatsApp records the follow-up as sent right away. + 'confirm_sent' => true, ], /* diff --git a/docs/ar/README.md b/docs/ar/README.md index d06089a..882c18f 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -23,10 +23,13 @@ ```bash composer require elbanbydev/rehla -php artisan vendor:publish --tag=rehla-config -php artisan migrate +php artisan rehla:install ``` +الأمر `rehla:install` بينشر `config/rehla.php` (لو مش موجود) وبيعمل جداول Rehla. تقدر تشغله تاني في أي وقت، بيطبق بس اللي لسه ماتطبقش. + +Rehla بيسجّل الـ migrations بتاعته بنفسه، فمفيش `vendor:publish` ليهم: أمر النشر العادي `php artisan migrate` بياخدهم برضه. Composer مبيقدرش يشغّل migrations وقت `composer require` (باكيدجات لارافل ملهاش install hook، وتشغيل تغييرات داتابيز من سكريبت Composer مش آمن)، فلازم واحد من الأمرين يتشغل مرة واحدة. لو الجداول ناقصة، اللوحة بترد برسالة واضحة، والـ middleware بتاع التتبع بيسكت بدل ما يوقّع موقعك. + ## عرّف الرحلة بتاعتك في `config/rehla.php`: @@ -106,7 +109,7 @@ Gate::define('viewRehla', fn (User $user) => $user->isAdmin()); لما يكون أكتر من واحد معاهم صلاحية المتابعة، محدش المفروض يبعت لنفس المستخدم مرتين. عشان كده رحلة بيسجّل كل متابعة لحظة ما الأدمن يأكد نافذة الواتساب: مين بعت، إمتى، نص الرسالة بالظبط، والموضوع (عنوان القالب بيتسجّل كـ snapshot، فالسجل بيفضل سليم حتى لو القالب اتعدّل أو اتمسح). -عمود **آخر متابعة** جنب **آخر زيارة** في الجدول، وزرار **(i)** في كل صف بيفتح نافذة سجل كامل: كل رسالة اتبعتت للمستخدم ده، الأحدث الأول. التسجيل بيحصل على أساس best-effort ولا يمنع فتح واتساب أبداً. +عمود **آخر متابعة** جنب **آخر زيارة** في الجدول، وزرار **(i)** في كل صف بيفتح نافذة سجل كامل: كل رسالة اتبعتت للمستخدم ده، الأحدث الأول. التسجيل بيحصل على أساس best-effort ولا يمنع فتح واتساب أبداً. ظبط `rehla.follow_up.confirm_sent` على `false` لو عاوز تتخطى خطوة التأكيد: فتح واتساب وقتها بيسجّل المتابعة «اتبعتت» على طول. فتح واتساب مش معناه إن الرسالة اتبعتت. السجل بيبدأ "غير مؤكد"، ولما الأدمن يرجع النافذة بتسأله "بعتّها فعلاً؟" (وممكن يصحح النص). المتابعات المؤكدة بس هي اللي بتتحسب "آخر متابعة" وبتطلّع تحذير "اتابع قريب". المسودات اللي اتساب بتفضل في السجل بعلامة "ماتبعتتش". diff --git a/resources/lang/ar/rehla.php b/resources/lang/ar/rehla.php index 6606c0b..771a051 100644 --- a/resources/lang/ar/rehla.php +++ b/resources/lang/ar/rehla.php @@ -19,6 +19,7 @@ 'last_visit' => 'آخر زيارة', 'last_followup' => 'آخر متابعة', 'never_followup' => 'لسه', + 'missing_tables' => 'جداول Rehla مش موجودة. شغّل: php artisan rehla:install', 'confirm' => [ 'question' => 'بعتّها فعلاً على واتساب؟', 'actual_text' => 'النص اللي بعتّه فعلاً', diff --git a/resources/lang/en/rehla.php b/resources/lang/en/rehla.php index f2e1d8f..7db0374 100644 --- a/resources/lang/en/rehla.php +++ b/resources/lang/en/rehla.php @@ -19,6 +19,7 @@ 'last_visit' => 'Last visit', 'last_followup' => 'Last follow-up', 'never_followup' => 'Never', + 'missing_tables' => 'Rehla tables are missing. Run: php artisan rehla:install', 'confirm' => [ 'question' => 'Did you actually send it in WhatsApp?', 'actual_text' => 'The text you actually sent', diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php index 74012c1..0b240f5 100644 --- a/resources/views/dashboard.blade.php +++ b/resources/views/dashboard.blade.php @@ -167,6 +167,7 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} var confirmMessageEl = document.getElementById('rehla-confirm-message'); var storeUrl = @json(route('rehla.follow-ups.store')); var historyUrl = @json(route('rehla.follow-ups.index')); + var confirmSent = @json($confirmSent); var confirmUrl = @json(route('rehla.follow-ups.confirm', ['id' => '__ID__'])); var csrfToken = (document.querySelector('meta[name="csrf-token"]') || {}).content || ''; @php($rehlaJsLabels = ['by' => __('rehla::rehla.history.by'), 'about' => __('rehla::rehla.history.about'), 'empty' => __('rehla::rehla.history.empty'), 'loading' => __('rehla::rehla.history.loading'), 'recent' => __('rehla::rehla.modal.recent_warning'), 'status' => ['sent' => __('rehla::rehla.history.status.sent'), 'opened' => __('rehla::rehla.history.status.opened'), 'not_sent' => __('rehla::rehla.history.status.not_sent')]]) @@ -266,6 +267,13 @@ function syncMessage() { window.open('https://wa.me/' + number + '?text=' + encodeURIComponent(message), '_blank', 'noopener'); + if (!confirmSent) { + pendingRecord.then(function () { + window.location.reload(); + }); + return; + } + confirmMessageEl.value = message; composeEl.hidden = true; confirmEl.hidden = false; diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php new file mode 100644 index 0000000..b0f4f67 --- /dev/null +++ b/src/Console/InstallCommand.php @@ -0,0 +1,38 @@ +laravel->configPath('rehla.php'))) { + $this->callSilently('vendor:publish', ['--tag' => 'rehla-config']); + $this->info('Published config/rehla.php'); + } + + $path = realpath(__DIR__.'/../../database/migrations'); + + if ($path === false) { + $this->error('Rehla migrations directory not found.'); + + return self::FAILURE; + } + + return $this->call('migrate', [ + '--path' => $path, + '--realpath' => true, + '--force' => (bool) $this->option('force'), + ]); + } +} diff --git a/src/Http/Controllers/DashboardController.php b/src/Http/Controllers/DashboardController.php index 23ddf9e..2b92ac7 100644 --- a/src/Http/Controllers/DashboardController.php +++ b/src/Http/Controllers/DashboardController.php @@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Schema; use Illuminate\View\View; use Rehla\Exceptions\ConfigurationException; use Rehla\Models\RehlaActivity; @@ -26,6 +27,8 @@ public function __invoke( ProgressQuery $progress, TemplateSuggester $suggester, ): View { + abort_unless(Schema::hasTable('rehla_step_progress'), 503, __('rehla::rehla.missing_tables')); + $validated = $request->validate([ 'journey' => ['nullable', 'string', 'max:100'], 'absent_days' => ['nullable', 'integer', 'min:0', 'max:3650'], @@ -132,6 +135,7 @@ public function __invoke( 'phones' => $phones, 'lastSeen' => $lastSeen, 'lastFollowUps' => $lastFollowUps, + 'confirmSent' => (bool) config('rehla.follow_up.confirm_sent', true), 'warnWithinHours' => max(0, (int) config('rehla.follow_up.warn_within_hours', 24)), 'nameAttribute' => $nameAttribute, 'userColumns' => $userColumns, diff --git a/src/Http/Controllers/FollowUpController.php b/src/Http/Controllers/FollowUpController.php index 2ce3a07..26437f4 100644 --- a/src/Http/Controllers/FollowUpController.php +++ b/src/Http/Controllers/FollowUpController.php @@ -64,6 +64,8 @@ public function store(Request $request, JourneyRegistry $journeys): JsonResponse $senderName = is_string($name) ? $name : null; } + $confirmSent = (bool) config('rehla.follow_up.confirm_sent', true); + $followUp = RehlaFollowUp::query()->create([ 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->getKey(), @@ -76,10 +78,11 @@ public function store(Request $request, JourneyRegistry $journeys): JsonResponse 'step' => $step, 'message' => $data['message'], 'channel' => 'whatsapp', - 'status' => RehlaFollowUp::STATUS_OPENED, + 'status' => $confirmSent ? RehlaFollowUp::STATUS_OPENED : RehlaFollowUp::STATUS_SENT, + 'sent_at' => $confirmSent ? null : now(), ]); - return response()->json(['ok' => true, 'id' => $followUp->getKey()]); + return response()->json(['ok' => true, 'id' => $followUp->getKey(), 'status' => $followUp->status]); } /** diff --git a/src/Http/Middleware/RecordActivity.php b/src/Http/Middleware/RecordActivity.php index 2c2e0b3..d150712 100644 --- a/src/Http/Middleware/RecordActivity.php +++ b/src/Http/Middleware/RecordActivity.php @@ -6,6 +6,7 @@ use Closure; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\QueryException; use Illuminate\Http\Request; use Rehla\Services\ProgressTracker; use Symfony\Component\HttpFoundation\Response; @@ -33,7 +34,13 @@ public function handle(Request $request, Closure $next): Response if ($user instanceof Model) { $throttle = (int) config('rehla.activity.throttle_seconds', 300); - $this->tracker->touch($user, $throttle); + try { + $this->tracker->touch($user, $throttle); + } catch (QueryException $e) { + // Tracking must never break the host app's request (for + // example before the Rehla tables exist). Log and carry on. + report($e); + } } return $response; diff --git a/src/RehlaServiceProvider.php b/src/RehlaServiceProvider.php index bccc5ea..7d17467 100644 --- a/src/RehlaServiceProvider.php +++ b/src/RehlaServiceProvider.php @@ -10,6 +10,7 @@ use Illuminate\Routing\Router; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; +use Rehla\Console\InstallCommand; use Rehla\Console\ReportCommand; use Rehla\Http\Middleware\AuthorizePanel; use Rehla\Http\Middleware\RecordActivity; @@ -46,7 +47,7 @@ public function register(): void public function boot(): void { if ($this->app->runningInConsole()) { - $this->commands([ReportCommand::class]); + $this->commands([InstallCommand::class, ReportCommand::class]); $this->publishes([ __DIR__.'/../config/rehla.php' => $this->app->configPath('rehla.php'), diff --git a/tests/Feature/FollowUpTest.php b/tests/Feature/FollowUpTest.php index 233c528..0803abd 100644 --- a/tests/Feature/FollowUpTest.php +++ b/tests/Feature/FollowUpTest.php @@ -279,3 +279,33 @@ $this->postJson('/rehla/follow-ups/1/confirm', ['outcome' => 'sent'])->assertForbidden(); }); + +it('records the follow-up as sent right away when confirmation is turned off', function () { + config()->set('rehla.follow_up.confirm_sent', false); + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi']) + ->assertOk()->assertJson(['status' => 'sent']); + + $followUp = RehlaFollowUp::query()->sole(); + expect($followUp->status)->toBe('sent')->and($followUp->sent_at)->not->toBeNull(); +}); + +it('keeps asking for confirmation by default', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi']) + ->assertOk()->assertJson(['status' => 'opened']); +}); + +it('tells the page whether to show the confirm step', function () { + $this->allowPanel(); + $this->makeUser(['phone' => '01070645696']); + + $this->get('/rehla')->assertOk()->assertSee('var confirmSent = true', false); + + config()->set('rehla.follow_up.confirm_sent', false); + $this->get('/rehla')->assertOk()->assertSee('var confirmSent = false', false); +}); diff --git a/tests/Feature/InstallTest.php b/tests/Feature/InstallTest.php new file mode 100644 index 0000000..94a115b --- /dev/null +++ b/tests/Feature/InstallTest.php @@ -0,0 +1,51 @@ +where('migration', 'like', '%rehla%')->delete(); +} + +it('creates the tables with rehla:install and can run again', function () { + dropRehlaTables(); + expect(Schema::hasTable('rehla_follow_ups'))->toBeFalse(); + + $this->artisan('rehla:install')->assertSuccessful(); + + expect(Schema::hasTable('rehla_step_progress'))->toBeTrue() + ->and(Schema::hasTable('rehla_activity'))->toBeTrue() + ->and(Schema::hasTable('rehla_templates'))->toBeTrue() + ->and(Schema::hasTable('rehla_follow_ups'))->toBeTrue() + ->and(Schema::hasColumn('rehla_follow_ups', 'status'))->toBeTrue(); + + $this->artisan('rehla:install')->assertSuccessful(); +}); + +it('shows a clear message instead of crashing when the tables are missing', function () { + $this->allowPanel(); + dropRehlaTables(); + + $this->get('/rehla')->assertStatus(503); +}); + +it('never breaks the host request when tracking fails', function () { + $user = $this->makeUser(); + Schema::dropIfExists('rehla_activity'); + + $request = Request::create('/'); + $request->setUserResolver(static fn () => $user); + + $response = app(RecordActivity::class)->handle($request, static fn () => response('ok')); + + expect($response->getStatusCode())->toBe(200); +});