From 84c4a7a2a38f77074785a52decc1d8b8b5b11089 Mon Sep 17 00:00:00 2001 From: Instinct Date: Thu, 3 Dec 2026 18:18:25 +0200 Subject: [PATCH] Confirm-sent step: only confirmed sends count as follow-ups --- CHANGELOG.md | 5 + README.md | 2 + ...5_add_status_to_rehla_follow_ups_table.php | 29 +++++ docs/ar/README.md | 2 + resources/lang/ar/rehla.php | 11 ++ resources/lang/en/rehla.php | 11 ++ resources/views/dashboard.blade.php | 83 ++++++++++--- routes/web.php | 1 + src/Http/Controllers/DashboardController.php | 3 +- src/Http/Controllers/FollowUpController.php | 45 +++++++ src/Models/RehlaFollowUp.php | 16 +++ tests/Feature/FollowUpTest.php | 110 +++++++++++++++++- 12 files changed, 299 insertions(+), 19 deletions(-) create mode 100644 database/migrations/2026_01_01_000005_add_status_to_rehla_follow_ups_table.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f25c8c2..8eaab66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +### 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. +- Existing rows are labelled "Unconfirmed" (the new `status` column defaults to `opened`); nothing is backfilled as sent. Run `php artisan migrate`. + ### Changed (breaking rename) - The package is now **Rehla**, matching its repository. It was named "Rihla" during pre-release development. Composer name `elbanbydev/rehla`, namespace `Rehla\`, config `config/rehla.php`, language namespace `rehla::`, facade `Rehla`, tables `rehla_*`, models `Rehla*`, env vars `REHLA_*`, routes `rehla.*`. Nothing was ever tagged or published under the old name, so there is no upgrade path to support. diff --git a/README.md b/README.md index eb50689..bb96a5d 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,8 @@ When several people have follow-up permission, nobody should message the same us 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. +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". + ## Housekeeping When your app deletes a user, drop their journey data too: diff --git a/database/migrations/2026_01_01_000005_add_status_to_rehla_follow_ups_table.php b/database/migrations/2026_01_01_000005_add_status_to_rehla_follow_ups_table.php new file mode 100644 index 0000000..588dd01 --- /dev/null +++ b/database/migrations/2026_01_01_000005_add_status_to_rehla_follow_ups_table.php @@ -0,0 +1,29 @@ +string('status', 16)->default('opened')->after('channel'); + $table->timestamp('sent_at')->nullable()->after('status'); + }); + } + + public function down(): void + { + Schema::table('rehla_follow_ups', function (Blueprint $table): void { + $table->dropColumn(['status', 'sent_at']); + }); + } +}; diff --git a/docs/ar/README.md b/docs/ar/README.md index 61b677c..d06089a 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -108,6 +108,8 @@ Gate::define('viewRehla', fn (User $user) => $user->isAdmin()); عمود **آخر متابعة** جنب **آخر زيارة** في الجدول، وزرار **(i)** في كل صف بيفتح نافذة سجل كامل: كل رسالة اتبعتت للمستخدم ده، الأحدث الأول. التسجيل بيحصل على أساس best-effort ولا يمنع فتح واتساب أبداً. +فتح واتساب مش معناه إن الرسالة اتبعتت. السجل بيبدأ "غير مؤكد"، ولما الأدمن يرجع النافذة بتسأله "بعتّها فعلاً؟" (وممكن يصحح النص). المتابعات المؤكدة بس هي اللي بتتحسب "آخر متابعة" وبتطلّع تحذير "اتابع قريب". المسودات اللي اتساب بتفضل في السجل بعلامة "ماتبعتتش". + ## تنضيف البيانات لما التطبيق يمسح مستخدم، امسح بيانات رحلته كمان: diff --git a/resources/lang/ar/rehla.php b/resources/lang/ar/rehla.php index 8662f81..6606c0b 100644 --- a/resources/lang/ar/rehla.php +++ b/resources/lang/ar/rehla.php @@ -19,7 +19,18 @@ 'last_visit' => 'آخر زيارة', 'last_followup' => 'آخر متابعة', 'never_followup' => 'لسه', + 'confirm' => [ + 'question' => 'بعتّها فعلاً على واتساب؟', + 'actual_text' => 'النص اللي بعتّه فعلاً', + 'not_sent' => 'ماتبعتتش', + 'sent' => 'أيوه بعتّها', + ], 'history' => [ + 'status' => [ + 'sent' => 'اتبعتت', + 'opened' => 'غير مؤكدة', + 'not_sent' => 'ماتبعتتش', + ], 'title' => 'سجل المتابعة', 'by' => 'بواسطة', 'about' => 'الموضوع', diff --git a/resources/lang/en/rehla.php b/resources/lang/en/rehla.php index e6f5e4c..f2e1d8f 100644 --- a/resources/lang/en/rehla.php +++ b/resources/lang/en/rehla.php @@ -19,7 +19,18 @@ 'last_visit' => 'Last visit', 'last_followup' => 'Last follow-up', 'never_followup' => 'Never', + 'confirm' => [ + 'question' => 'Did you actually send it in WhatsApp?', + 'actual_text' => 'The text you actually sent', + 'not_sent' => 'Not sent', + 'sent' => 'Yes, I sent it', + ], 'history' => [ + 'status' => [ + 'sent' => 'Sent', + 'opened' => 'Unconfirmed', + 'not_sent' => 'Not sent', + ], 'title' => 'Follow-up history', 'by' => 'By', 'about' => 'About', diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php index 6399aeb..74012c1 100644 --- a/resources/views/dashboard.blade.php +++ b/resources/views/dashboard.blade.php @@ -101,6 +101,18 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} @@ -148,10 +161,15 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }} var number = ''; var currentName = ''; var currentUserId = ''; + var pendingRecord = Promise.resolve(null); + var composeEl = document.getElementById('rehla-compose'); + var confirmEl = document.getElementById('rehla-confirm'); + var confirmMessageEl = document.getElementById('rehla-confirm-message'); var storeUrl = @json(route('rehla.follow-ups.store')); var historyUrl = @json(route('rehla.follow-ups.index')); + 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')]) +@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')]]) var labels = @json($rehlaJsLabels); function fillSelect(selectedId) { @@ -186,6 +204,8 @@ function syncMessage() { number = button.getAttribute('data-number') || ''; currentName = button.getAttribute('data-name') || ''; currentUserId = button.getAttribute('data-user-id') || ''; + composeEl.hidden = false; + confirmEl.hidden = true; nameEl.textContent = currentName; var recent = button.getAttribute('data-recent-followup'); warningEl.hidden = !recent; @@ -222,27 +242,60 @@ function syncMessage() { } }); - try { - fetch(storeUrl, { + pendingRecord = fetch(storeUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'X-CSRF-TOKEN': csrfToken + }, + body: JSON.stringify({ + user_id: currentUserId, + message: message, + template_id: selected ? selected.id : null, + journey: selected ? selected.journey : null, + step: selected ? selected.step : null + }) + }).then(function (response) { + return response.ok ? response.json() : null; + }).then(function (data) { + return data && data.id ? data.id : null; + }).catch(function () { + return null; + }); + + window.open('https://wa.me/' + number + '?text=' + encodeURIComponent(message), '_blank', 'noopener'); + + confirmMessageEl.value = message; + composeEl.hidden = true; + confirmEl.hidden = false; + }); + + function settle(outcome) { + var text = confirmMessageEl.value; + pendingRecord.then(function (id) { + if (id === null) { + overlay.classList.remove('open'); + return null; + } + return fetch(confirmUrl.replace('__ID__', id), { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken }, - body: JSON.stringify({ - user_id: currentUserId, - message: message, - template_id: selected ? selected.id : null, - journey: selected ? selected.journey : null, - step: selected ? selected.step : null - }), - keepalive: true + body: JSON.stringify({outcome: outcome, message: text}) + }).then(function () { + window.location.reload(); }); - } catch (error) { /* recording is best-effort; never block the admin */ } + }).catch(function () { + overlay.classList.remove('open'); + }); + } - window.open('https://wa.me/' + number + '?text=' + encodeURIComponent(message), '_blank', 'noopener'); - }); + document.getElementById('rehla-confirm-yes').addEventListener('click', function () { settle('sent'); }); + document.getElementById('rehla-confirm-no').addEventListener('click', function () { settle('not_sent'); }); var historyOverlay = document.getElementById('rehla-history-modal'); var historyTitle = document.getElementById('rehla-history-title'); @@ -264,7 +317,7 @@ function renderHistory(items) { var meta = document.createElement('div'); meta.className = 'followup-meta'; meta.dir = 'auto'; - var bits = [item.ago]; + var bits = [item.ago, labels.status[item.status] || item.status]; if (item.sender_name) { bits.push(labels.by + ' ' + item.sender_name); } diff --git a/routes/web.php b/routes/web.php index 4d9cd09..362c69d 100644 --- a/routes/web.php +++ b/routes/web.php @@ -9,6 +9,7 @@ Route::get('/', DashboardController::class)->name('dashboard'); Route::post('/follow-ups', [FollowUpController::class, 'store'])->name('follow-ups.store'); +Route::post('/follow-ups/{id}/confirm', [FollowUpController::class, 'confirm'])->whereNumber('id')->name('follow-ups.confirm'); Route::get('/follow-ups', [FollowUpController::class, 'index'])->name('follow-ups.index'); Route::get('/templates', [TemplateController::class, 'index'])->name('templates.index'); Route::get('/templates/create', [TemplateController::class, 'create'])->name('templates.create'); diff --git a/src/Http/Controllers/DashboardController.php b/src/Http/Controllers/DashboardController.php index c7fd4db..23ddf9e 100644 --- a/src/Http/Controllers/DashboardController.php +++ b/src/Http/Controllers/DashboardController.php @@ -100,7 +100,8 @@ public function __invoke( $lastFollowUps = RehlaFollowUp::query() ->where('trackable_type', $userInstance->getMorphClass()) ->whereIn('trackable_id', $ids) - ->selectRaw('trackable_id, MAX(created_at) as last_at') + ->where('status', RehlaFollowUp::STATUS_SENT) + ->selectRaw('trackable_id, MAX(sent_at) as last_at') ->groupBy('trackable_id') ->get() ->mapWithKeys(static fn (RehlaFollowUp $row): array => [ diff --git a/src/Http/Controllers/FollowUpController.php b/src/Http/Controllers/FollowUpController.php index 658812d..2ce3a07 100644 --- a/src/Http/Controllers/FollowUpController.php +++ b/src/Http/Controllers/FollowUpController.php @@ -76,11 +76,55 @@ public function store(Request $request, JourneyRegistry $journeys): JsonResponse 'step' => $step, 'message' => $data['message'], 'channel' => 'whatsapp', + 'status' => RehlaFollowUp::STATUS_OPENED, ]); return response()->json(['ok' => true, 'id' => $followUp->getKey()]); } + /** + * The admin says what happened after WhatsApp opened: sent (optionally + * with the text actually sent) or not sent. Only the admin who opened the + * draft can settle it, and only once. + */ + public function confirm(Request $request, int $id): JsonResponse + { + /** @var array{outcome: string, message?: string|null} $data */ + $data = $request->validate([ + 'outcome' => ['required', 'in:sent,not_sent'], + 'message' => ['nullable', 'string', 'max:5000'], + ]); + + $followUp = RehlaFollowUp::query()->find($id); + + abort_if($followUp === null, 404); + + $sender = $request->user(); + + abort_unless( + $sender instanceof Model + && $followUp->sender_id !== null + && $followUp->sender_type === $sender->getMorphClass() + && (string) $followUp->sender_id === (string) $sender->getKey(), + 403, + ); + + abort_unless($followUp->status === RehlaFollowUp::STATUS_OPENED, 409); + + if ($data['outcome'] === 'sent') { + $message = isset($data['message']) && trim($data['message']) !== '' ? $data['message'] : $followUp->message; + $followUp->forceFill([ + 'status' => RehlaFollowUp::STATUS_SENT, + 'sent_at' => now(), + 'message' => $message, + ])->save(); + } else { + $followUp->forceFill(['status' => RehlaFollowUp::STATUS_NOT_SENT])->save(); + } + + return response()->json(['ok' => true, 'status' => $followUp->status]); + } + /** * The follow-up history of one user, newest first, for the (i) popup. */ @@ -111,6 +155,7 @@ public function index(Request $request): JsonResponse 'step' => $followUp->step, 'sender_name' => $followUp->sender_name, 'channel' => $followUp->channel, + 'status' => $followUp->status, 'at' => $followUp->created_at->toIso8601String(), 'ago' => $followUp->created_at->diffForHumans(), ])->values()->all(), diff --git a/src/Models/RehlaFollowUp.php b/src/Models/RehlaFollowUp.php index 31670f2..8ef1afe 100644 --- a/src/Models/RehlaFollowUp.php +++ b/src/Models/RehlaFollowUp.php @@ -23,6 +23,8 @@ * @property string|null $step * @property string $message * @property string $channel + * @property string $status + * @property Carbon|null $sent_at * @property Carbon $created_at */ final class RehlaFollowUp extends Model @@ -42,8 +44,22 @@ final class RehlaFollowUp extends Model 'step', 'message', 'channel', + 'status', + 'sent_at', ]; + public const STATUS_OPENED = 'opened'; + + public const STATUS_SENT = 'sent'; + + public const STATUS_NOT_SENT = 'not_sent'; + + /** @return array */ + protected function casts(): array + { + return ['sent_at' => 'datetime']; + } + /** @return MorphTo */ public function trackable(): MorphTo { diff --git a/tests/Feature/FollowUpTest.php b/tests/Feature/FollowUpTest.php index e3e7573..233c528 100644 --- a/tests/Feature/FollowUpTest.php +++ b/tests/Feature/FollowUpTest.php @@ -122,7 +122,7 @@ RehlaFollowUp::query()->create([ 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, - 'sender_name' => 'Admin', 'message' => 'أهلاً', + 'sender_name' => 'Admin', 'message' => 'أهلاً', 'status' => 'sent', 'sent_at' => now(), ]); $this->travel(3)->hours(); @@ -155,7 +155,7 @@ $this->allowPanel(); $user = $this->makeUser(['phone' => '01070645696']); RehlaFollowUp::query()->create([ - 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'x', + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'x', 'status' => 'sent', 'sent_at' => now(), ]); $this->get('/rehla')->assertOk()->assertSee('data-recent-followup="', false); @@ -165,7 +165,7 @@ $this->allowPanel(); $user = $this->makeUser(['phone' => '01070645696']); RehlaFollowUp::query()->create([ - 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'x', + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'x', 'status' => 'sent', 'sent_at' => now(), ]); config()->set('rehla.follow_up.warn_within_hours', 0); @@ -175,3 +175,107 @@ $this->travel(2)->days(); $this->get('/rehla')->assertOk()->assertDontSee('data-recent-followup="', false); }); + +it('records new follow-ups as opened, not sent', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi'])->assertOk(); + + $followUp = RehlaFollowUp::query()->sole(); + expect($followUp->status)->toBe('opened')->and($followUp->sent_at)->toBeNull(); +}); + +it('does not count an opened-then-abandoned follow-up as last follow-up or warning', function () { + $this->actingAs($this->makeUser(['phone' => '01000000000'])); + $user = $this->makeUser(['phone' => '01070645696']); + + $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'hi'])->assertOk(); + + $this->get('/rehla')->assertOk() + ->assertDontSee('data-recent-followup="', false) + ->assertSee('Never'); +}); + +it('confirms a follow-up as sent with the text actually sent', function () { + $admin = $this->makeUser(); + $this->actingAs($admin); + $user = $this->makeUser(); + $id = $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'draft'])->json('id'); + + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'sent', 'message' => 'edited text']) + ->assertOk()->assertJson(['status' => 'sent']); + + $followUp = RehlaFollowUp::query()->findOrFail($id); + expect($followUp->status)->toBe('sent') + ->and($followUp->message)->toBe('edited text') + ->and($followUp->sent_at)->not->toBeNull(); + + $this->get('/rehla')->assertOk()->assertSee('ago'); +}); + +it('keeps the draft text when confirming without an edit', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + $id = $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'draft'])->json('id'); + + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'sent'])->assertOk(); + + expect(RehlaFollowUp::query()->findOrFail($id)->message)->toBe('draft'); +}); + +it('marks an abandoned follow-up as not sent', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + $id = $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'draft'])->json('id'); + + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'not_sent'])->assertOk(); + + $followUp = RehlaFollowUp::query()->findOrFail($id); + expect($followUp->status)->toBe('not_sent')->and($followUp->sent_at)->toBeNull(); +}); + +it('settles a follow-up only once', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + $id = $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'draft'])->json('id'); + + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'not_sent'])->assertOk(); + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'sent'])->assertStatus(409); +}); + +it('only lets the admin who opened the draft confirm it', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + $id = $this->postJson('/rehla/follow-ups', ['user_id' => $user->id, 'message' => 'draft'])->json('id'); + + $this->actingAs($this->makeUser()); + $this->postJson("/rehla/follow-ups/{$id}/confirm", ['outcome' => 'sent'])->assertForbidden(); + + expect(RehlaFollowUp::query()->findOrFail($id)->status)->toBe('opened'); +}); + +it('validates the confirm outcome and 404s unknown records', function () { + $this->actingAs($this->makeUser()); + + $this->postJson('/rehla/follow-ups/999/confirm', ['outcome' => 'sent'])->assertNotFound(); + $this->postJson('/rehla/follow-ups/999/confirm', ['outcome' => 'maybe'])->assertUnprocessable(); +}); + +it('exposes the status in the history and treats legacy rows as unconfirmed', function () { + $this->actingAs($this->makeUser()); + $user = $this->makeUser(); + RehlaFollowUp::query()->create([ + 'trackable_type' => $user->getMorphClass(), 'trackable_id' => $user->id, 'message' => 'legacy', + ]); + + $items = $this->getJson('/rehla/follow-ups?user_id='.$user->id)->assertOk()->json('items'); + + expect($items[0]['status'])->toBe('opened'); +}); + +it('requires the panel gate to confirm', function () { + config()->set('rehla.panel.gate', 'undefined-ability'); + + $this->postJson('/rehla/follow-ups/1/confirm', ['outcome' => 'sent'])->assertForbidden(); +});