Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down Expand Up @@ -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".

Expand Down
7 changes: 6 additions & 1 deletion config/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
],

/*
Expand Down
9 changes: 6 additions & 3 deletions docs/ar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down Expand Up @@ -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` لو عاوز تتخطى خطوة التأكيد: فتح واتساب وقتها بيسجّل المتابعة «اتبعتت» على طول.

فتح واتساب مش معناه إن الرسالة اتبعتت. السجل بيبدأ "غير مؤكد"، ولما الأدمن يرجع النافذة بتسأله "بعتّها فعلاً؟" (وممكن يصحح النص). المتابعات المؤكدة بس هي اللي بتتحسب "آخر متابعة" وبتطلّع تحذير "اتابع قريب". المسودات اللي اتساب بتفضل في السجل بعلامة "ماتبعتتش".

Expand Down
1 change: 1 addition & 0 deletions resources/lang/ar/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
'last_visit' => 'آخر زيارة',
'last_followup' => 'آخر متابعة',
'never_followup' => 'لسه',
'missing_tables' => 'جداول Rehla مش موجودة. شغّل: php artisan rehla:install',
'confirm' => [
'question' => 'بعتّها فعلاً على واتساب؟',
'actual_text' => 'النص اللي بعتّه فعلاً',
Expand Down
1 change: 1 addition & 0 deletions resources/lang/en/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
8 changes: 8 additions & 0 deletions resources/views/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
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')]])
Expand Down Expand Up @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions src/Console/InstallCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Rehla\Console;

use Illuminate\Console\Command;

final class InstallCommand extends Command
{
/** @var string */
protected $signature = 'rehla:install {--force : Run the migrations in production without asking}';

/** @var string */
protected $description = 'Publish the Rehla config (if missing) and create its tables. Safe to run again.';

public function handle(): int
{
if (! file_exists($this->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'),
]);
}
}
4 changes: 4 additions & 0 deletions src/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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'],
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 5 additions & 2 deletions src/Http/Controllers/FollowUpController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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]);
}

/**
Expand Down
9 changes: 8 additions & 1 deletion src/Http/Middleware/RecordActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
3 changes: 2 additions & 1 deletion src/RehlaServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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'),
Expand Down
30 changes: 30 additions & 0 deletions tests/Feature/FollowUpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
51 changes: 51 additions & 0 deletions tests/Feature/InstallTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Rehla\Http\Middleware\RecordActivity;

function dropRehlaTables(): void
{
foreach (['rehla_follow_ups', 'rehla_templates', 'rehla_activity', 'rehla_step_progress'] as $table) {
Schema::dropIfExists($table);
}

DB::table('migrations')->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);
});
Loading