openstamanager/modules/emails/src/EmailHook.php

104 lines
2.8 KiB
PHP
Raw Normal View History

2019-08-27 15:42:13 +02:00
<?php
namespace Modules\Emails;
use Carbon\Carbon;
2019-08-27 15:42:13 +02:00
use Hooks\Manager;
use Notifications\EmailNotification;
class EmailHook extends Manager
{
2019-08-29 11:25:13 +02:00
public function isSingleton()
{
return true;
}
public function needsExecution()
{
$diff = date('Y-m-d', strtotime('-4 hours'));
$failed = function ($query) use ($diff) {
$query->whereDate('failed_at', '<', $diff)
->orWhereNull('failed_at');
};
$remaining = Mail::whereNull('sent_at')
->where($failed)
->count();
return !empty($remaining);
}
2019-08-27 15:42:13 +02:00
public function execute()
{
$diff = date('Y-m-d', strtotime('-4 hours'));
$failed = function ($query) use ($diff) {
$query->whereDate('failed_at', '<', $diff)
->orWhereNull('failed_at');
};
2019-08-27 15:42:13 +02:00
$accounts = Account::all();
2019-08-27 15:42:13 +02:00
$list = [];
foreach ($accounts as $account) {
$last_mail = $account->emails()->whereNotNull('sent_at')->orderBy('sent_at')->first();
// Controllo sul timeout dell'account
$date = new Carbon($last_mail->sent_at);
$now = new Carbon();
$diff = $date->diffInMilliseconds($now);
if (empty($last_mail) || $diff > $account->timeout) {
$mail = Mail::whereNull('sent_at')
->where('id_account', $account->id)
->where($failed)
->orderBy('created_at')
->first();
if (!empty($mail)) {
$list[] = $mail;
}
2019-08-27 15:42:13 +02:00
}
}
foreach ($list as $mail) {
$email = EmailNotification::build($mail);
try {
// Invio mail
$email->send();
} catch (PHPMailer\PHPMailer\Exception $e) {
}
}
2019-08-29 11:25:13 +02:00
return $list;
2019-08-27 15:42:13 +02:00
}
2019-08-29 11:25:13 +02:00
public function response()
2019-08-27 15:42:13 +02:00
{
$yesterday = date('Y-m-d', strtotime('-1 days'));
$user = auth()->getUser();
2019-08-27 17:25:52 +02:00
$current = Mail::whereDate('sent_at', '>', $yesterday)
2019-08-27 15:42:13 +02:00
->where('created_by', $user->id)
->count();
2019-08-29 16:01:49 +02:00
$total = Mail::where(function ($query) use ($yesterday) {
$query->whereDate('sent_at', '>', $yesterday)
->orWhereNull('sent_at');
})
2019-08-27 15:42:13 +02:00
->where('created_by', $user->id)
->count();
2019-08-29 11:25:13 +02:00
$message = $total != $current ? tr('Invio email in corso...') : tr('Invio email completato!');
2019-08-28 11:52:04 +02:00
$message = empty($total) ? tr('Nessuna email presente...') : $message;
2019-08-27 15:42:13 +02:00
return [
'icon' => 'fa fa-envelope text-info',
'message' => $message,
2019-08-29 16:01:49 +02:00
'show' => ($total != $current),
2019-08-27 15:42:13 +02:00
'progress' => [
'current' => $current,
'total' => $total,
],
];
}
}