ultimatepos/Modules/Crm/Console/SendPhoneListReminder.php

92 lines
2.9 KiB
PHP

<?php
namespace Modules\Crm\Console;
use App\Business;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Modules\Crm\Entities\CrmPhoneFollowUp;
use Modules\Crm\Notifications\PhoneListReminderNotification;
use Modules\Crm\Utils\PhoneListUtil;
use Notification;
class SendPhoneListReminder extends Command
{
protected $signature = 'pos:sendPhoneListReminder';
protected $description = 'Send reminders for pending phone list numbers that need follow-up.';
protected $phoneListUtil;
public function __construct(PhoneListUtil $phoneListUtil)
{
parent::__construct();
$this->phoneListUtil = $phoneListUtil;
}
public function handle()
{
$businesses = Business::select('id', 'crm_settings')->get();
foreach ($businesses as $business) {
$settings = $this->phoneListUtil->getReminderSettings($business->id);
if (! $settings['enabled']) {
continue;
}
$cutoff = Carbon::now()->subDays($settings['days']);
$today = Carbon::today();
$phones = CrmPhoneFollowUp::where('business_id', $business->id)
->where('status', 'pending')
->where(function ($q) use ($cutoff) {
$q->whereNull('last_follow_up_at')
->where('created_at', '<=', $cutoff)
->orWhere(function ($q2) use ($cutoff) {
$q2->whereNotNull('last_follow_up_at')
->where('last_follow_up_at', '<=', $cutoff);
});
})
->where(function ($q) use ($today) {
$q->whereNull('last_reminder_at')
->orWhereDate('last_reminder_at', '<', $today);
})
->get();
foreach ($phones as $phone) {
$users = collect();
if (! empty($phone->assigned_to)) {
$assigned = User::find($phone->assigned_to);
if (! empty($assigned)) {
$users->push($assigned);
}
}
$creator = User::find($phone->created_by);
if (! empty($creator)) {
$users->push($creator);
}
$users = $users->unique('id');
if ($users->isEmpty()) {
continue;
}
$name = $phone->contact_name ?: $phone->mobile_number;
$body = __('crm::lang.phone_list_reminder_body', [
'name' => $name,
'number' => $phone->mobile_number,
'days' => $settings['days'],
]);
Notification::send($users, new PhoneListReminderNotification($phone, $body));
$phone->update(['last_reminder_at' => now()]);
}
}
}
}