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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Existing rows get "opened" (unverified): we cannot know whether the
* admin really sent them, so nothing is backfilled as "sent".
*/
public function up(): void
{
Schema::table('rehla_follow_ups', function (Blueprint $table): void {
$table->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']);
});
}
};
2 changes: 2 additions & 0 deletions docs/ar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ Gate::define('viewRehla', fn (User $user) => $user->isAdmin());

عمود **آخر متابعة** جنب **آخر زيارة** في الجدول، وزرار **(i)** في كل صف بيفتح نافذة سجل كامل: كل رسالة اتبعتت للمستخدم ده، الأحدث الأول. التسجيل بيحصل على أساس best-effort ولا يمنع فتح واتساب أبداً.

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

## تنضيف البيانات

لما التطبيق يمسح مستخدم، امسح بيانات رحلته كمان:
Expand Down
11 changes: 11 additions & 0 deletions resources/lang/ar/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' => 'الموضوع',
Expand Down
11 changes: 11 additions & 0 deletions resources/lang/en/rehla.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
83 changes: 68 additions & 15 deletions resources/views/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
<div class="modal-overlay" id="rehla-modal">
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="rehla-modal-title">
<h2 id="rehla-modal-title">{{ __('rehla::rehla.modal.title') }}</h2>
<div id="rehla-confirm" hidden>
<p>{{ __('rehla::rehla.confirm.question') }}</p>
<div class="field">
<label for="rehla-confirm-message">{{ __('rehla::rehla.confirm.actual_text') }}</label>
<textarea id="rehla-confirm-message"></textarea>
</div>
<div class="actions">
<button type="button" class="btn btn-plain" id="rehla-confirm-no">{{ __('rehla::rehla.confirm.not_sent') }}</button>
<button type="button" class="btn btn-wa" id="rehla-confirm-yes">{{ __('rehla::rehla.confirm.sent') }}</button>
</div>
</div>
<div id="rehla-compose">
<dl>
<dt>{{ __('rehla::rehla.modal.name') }}</dt>
<dd id="rehla-modal-name"></dd>
Expand All @@ -120,6 +132,7 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
<button type="button" class="btn btn-plain" id="rehla-modal-cancel">{{ __('rehla::rehla.modal.cancel') }}</button>
<button type="button" class="btn btn-wa" id="rehla-modal-send">{{ __('rehla::rehla.modal.send') }}</button>
</div>
</div>
</div>
</div>

Expand Down Expand Up @@ -148,10 +161,15 @@ class="{{ $key === $journey ? 'active' : '' }}">{{ $journeys->label($key) }}</a>
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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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');
Expand All @@ -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);
}
Expand Down
1 change: 1 addition & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
3 changes: 2 additions & 1 deletion src/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 => [
Expand Down
45 changes: 45 additions & 0 deletions src/Http/Controllers/FollowUpController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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(),
Expand Down
16 changes: 16 additions & 0 deletions src/Models/RehlaFollowUp.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<string, string> */
protected function casts(): array
{
return ['sent_at' => 'datetime'];
}

/** @return MorphTo<Model, $this> */
public function trackable(): MorphTo
{
Expand Down
Loading
Loading