Feuerwehr-eppingen/app/Jobs/MailDepartmentStatistics.php

113 lines
3.0 KiB
PHP

<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Mail\Mailer;
use App\Models\User;
use \Carbon\Carbon;
class MailDepartmentStatistics implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $email;
protected $template;
protected $posts;
protected $title;
protected $department;
protected $count;
protected $debug;
protected $debugText;
protected $isTestRun;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($template, $posts, $title, $department, $count, $debug = false, $debugText = '', $isTestRun = false)
{
$this->template = $template;
$this->posts = $posts;
$this->title = $title;
$this->department = $department;
$this->count = $count;
$this->debug = $debug;
$this->debugText = $debugText;
$this->isTestRun = $isTestRun;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Mailer $mailer)
{
$template = $this->template;
$posts = $this->posts;
$title = $this->title;
$department = $this->department;
$count = $this->count;
$debugText = $this->debugText;
// Wer soll per Email benachrichtigt werden
$users = User::select('email')
->join('user_tag as user_tag1', function ($join)
{
$join->on('users.id', 'user_tag1.user_id');
})
->join('tags as tags1', function ($join) use($department)
{
$join->on('tags1.id', 'user_tag1.tag_id')
->where('tags1.type', 'abteilung')
->where('tags1.name', $department);
})
->join('user_tag as user_tag2', function ($join)
{
$join->on('users.id', 'user_tag2.user_id');
})
->join('tags as tags2', function ($join) use($department)
{
$join->on('tags2.id', 'user_tag2.tag_id')
->where('tags2.type', 'benachrichtigung')
->where('tags2.name', 'Veröffentlichungen');
})->get();
$admin = User::select('email')
->where('name', 'Admin')
->get();
// $emailFrom = $admin[0]->email;
$emailFrom = config('mail.from.address');
foreach($users as $user)
{
if($this->isTestRun)
{
$email = $admin[0]->email;
}
else
{
$email = $user->email;
}
echo "Sende Bericht an: $email\n";
$mailer->send($template, ['publications' => $posts, 'debugText' => $debugText], function ($message) use ($email, $emailFrom, $department, $count, $title)
{
$message->to($email)
->from($emailFrom, "Feuerwehr Eppingen - Abteilung $department")
->subject("$title vom " . Carbon::now()->format('d.m.Y') . " ($count)");
// ->subject("Feuerwehr Eppingen: Abteilung $department - $title vom " . Carbon::now()->format('d.m.Y') . " ($count)");
});
if($this->isTestRun)
{
break;
}
}
}
}