mivita/app/Http/Controllers/CronController.php
2025-04-01 10:36:47 +02:00

420 lines
No EOL
14 KiB
PHP

<?php
namespace App\Http\Controllers;
use Carbon;
use App\User;
use App\Services\Util;
use App\Models\UserHistory;
use App\Models\UserMessage;
use App\Mail\MailCustomMessage;
use App\Mail\MailVerifyAccount;
use App\Services\PaymentHelper;
use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
class CronController extends Controller
{
protected $userRepo;
// Konstanten für bessere Lesbarkeit
private const CRON_KEY = 'CqZHL79FwUCcy9pjvi';
private const RUN_CRON_KEY = 'G8ZvEbnP8fEPfnWX4L';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
Log::channel('cron')->info('CronController initialisiert');
}
/**
* Hauptindex-Methode für Cron-Jobs
*
* @return string
*/
public function index()
{
Log::channel('cron')->info('Cron-Index aufgerufen');
//$this->checkConfirmation();
//TODO
//SEPA Booking
//Mail reminder
return "Cron-Index ausgeführt";
}
/**
* Führt eine bestimmte Cron-Aktion aus
*
* @param string|bool $action Die auszuführende Aktion
* @param string|bool $key Sicherheitsschlüssel
* @return mixed
*/
public function action($action = false, $key = false)
{
Log::channel('cron')->info('Cron-Aktion aufgerufen: ' . $action);
if($key !== self::CRON_KEY){
Log::channel('cron')->warning('Ungültiger Cron-Key verwendet: ' . $key);
abort(404);
}
if($action === 'check_payments_account'){
Log::channel('cron')->info('Starte Überprüfung der Zahlungskonten');
return $this->checkPaymentsAccounts();
}
Log::channel('cron')->warning('Unbekannte Aktion angefordert: ' . $action);
return response('Keine gültige Aktion angegeben', 400);
}
/**
* Überprüft Benutzerbestätigungen und sendet Erinnerungen
*
* @return string
*/
public function checkConfirmation()
{
Log::channel('cron')->info('Starte Überprüfung der Benutzerbestätigungen');
$now = date('Y-m-d H:i:s');
$next = date('Y-m-d H:i:s', strtotime('+3 week'));
$users = User::where('confirmed', '=', 0)->where('confirmation_code_to', '<', $now)->get();
Log::channel('cron')->info('Gefundene unbestätigte Benutzer: ' . $users->count());
foreach ($users as $user) {
//delete user
if ($user->confirmation_code_remider == 1) {
Log::channel('cron')->warning('Lösche unbestätigten Benutzer: ' . $user->email);
$this->userRepo->deleteUser($user);
}
//send new remider
if ($user->confirmation_code_remider == 0) {
if(!Util::isTestSystem()){
Log::channel('cron')->info('Sende Bestätigungserinnerung an: ' . $user->email);
Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyAccount($user->confirmation_code, $user));
$user->confirmation_code_to = $next;
$user->confirmation_code_remider = 1;
$user->save();
} else {
Log::channel('cron')->info('Testsystem: Bestätigungserinnerung an: ' . $user->email);
}
}
}
return "TOSK";
}
/**
* Überprüft Zahlungskonten und sendet Erinnerungen
*
* @return string
*/
public function checkPaymentsAccounts()
{
Log::channel('cron')->info('Starte Überprüfung der Zahlungskonten');
/*RULES
reminders
> 21 remind_first_days = 31 reminder_first
> 21 remind_first_days + sepa = 32 reminder_first_sepa
> 14 remind_sec_days = 33 reminder_sec
> 2 remind_last_days = 34 reminder_last
> 0 deaktiv = 35 reminder_deaktiv
> 0 deaktiv + sepa = 36 reminder_deaktiv_sepa
== 7 abo_booking_days + sepa + cron = 37 reminder_collect_sepa
*/
//max Date for reminder
$renewalDate = Carbon::now()->modify('+'.(config('mivita.remind_first_days')+1).' days');
Log::channel('cron')->info('Erneuerungsdatum für Zahlungen: ' . $renewalDate->format('Y-m-d H:i:s'));
$users = User::where('payment_account', '!=', NULL)
->where('active', '=', 1)
->where('blocked', '!=', 1)
->where('payment_account', '<', $renewalDate)
->get();
Log::channel('cron')->info('Gefundene Benutzer für Zahlungserinnerungen: ' . $users->count());
foreach ($users as $user){
Log::channel('cron')->info('Prüfe Zahlungserinnerungen für Benutzer: ' . $user->email);
$this->checkReminderPayments($user);
}
return "TOSK";
}
/**
* Initiiert Abo-Zahlungen für einen Benutzer
* hier geht es um die Mitglieschaft Abos - die sind derzeit deaktiviert
*
* @param User $user Benutzer
* @return bool
*/
private function userInitAboPayment(User $user)
{
if(!$user->isAcountAboPayDate()){
Log::channel('cron')->info('Kein Abo-Zahlungsdatum für Benutzer: ' . $user->email);
return false;
}
//user has a open Abo Payment
if($this->checkIsAboPaymentOpen($user)){
Log::channel('cron')->info('Offene Abo-Zahlung für Benutzer: ' . $user->email);
return false;
}
if($user->payment_order_product){
Log::channel('cron')->info('Starte Abo-Zahlung für Benutzer: ' . $user->email);
$this->buyProductAboPayment($user, $user->payment_order_product);
}
return true;
}
/**
* Prüft, ob eine offene Abo-Zahlung existiert
*
* @param User $user Benutzer
* @return bool
*/
private function checkIsAboPaymentOpen(User $user)
{
$isOpen = UserHistory::whereUserId($user->id)
->whereAction('abo_open_payment')
->whereIdentifier($user->payment_account)
->where('status', '>=', 1) //open //error // payment
->get()->last();
if($isOpen){
Log::channel('cron')->info('Offene Abo-Zahlung gefunden für: ' . $user->email);
return true;
}
return false;
}
/**
* Prüft und sendet Zahlungserinnerungen basierend auf Benutzerkontostand
*
* @param User $user Benutzer
* @return bool
*/
private function checkReminderPayments(User $user)
{
//35 reminder_deaktiv, 36 reminder_deaktiv_sepa
if(!$user->isActiveAccount()){
Log::channel('cron')->info('Inaktives Konto für Benutzer: ' . $user->email);
$isSend = $this->checkIsReminderSend($user, 35);
return $isSend;
}
//34 reminder_last
if($user->daysActiveAccount() <= config('mivita.remind_last_days')){
Log::channel('cron')->info('Letzte Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
$isSend = $this->checkIsReminderSend($user, 34);
return $isSend;
}
//33 reminder_sec
if($user->daysActiveAccount() <= config('mivita.remind_sec_days')){
Log::channel('cron')->info('Zweite Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
$isSend = $this->checkIsReminderSend($user, 33);
return $isSend;
}
//31 reminder_first
if($user->daysActiveAccount() > config('mivita.remind_sec_days')){
Log::channel('cron')->info('Erste Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
$isSend = $this->checkIsReminderSend($user, 31);
return $isSend;
}
return false;
}
/**
* Überprüft, ob eine Erinnerung bereits gesendet wurde
*
* @param User $user Benutzer
* @param int $status Status-Code der Erinnerung
* @return bool
*/
private function checkIsReminderSend(User $user, $status)
{
$isSend = UserHistory::whereUserId($user->id)
->whereAction('reminder_payments')
->whereIdentifier($user->payment_account)
->whereStatus($status)
->latest()
->first();
if($isSend){
Log::channel('cron')->info('Erinnerung bereits gesendet für Benutzer: ' . $user->email . ' (Status: ' . $status . ')');
return true;
}
Log::channel('cron')->info('Sende neue Erinnerung für Benutzer: ' . $user->email . ' (Status: ' . $status . ')');
$referenz = $this->sendReminderMail($user, $status);
//is not sent create
UserHistory::create([
'user_id' => $user->id,
'action' => 'reminder_payments',
'referenz' => $referenz,
'identifier' => $user->payment_account,
'status' => $status
]);
return false;
}
/**
* Sendet eine Erinnerungs-E-Mail an den Benutzer
*
* @param User $user Benutzer
* @param int $status Status-Code der Erinnerung
* @return int
*/
private function sendReminderMail(User $user, $status)
{
$days = abs($user->daysActiveAccount());
$pay_date = Carbon::parse($user->payment_account)
->modify('- ' . config('mivita.abo_booking_days') . ' days')
->format('d.m.Y');
$datetime = $user->getPaymentAccountDateFormat();
$price = "";
if($user->payment_order_id && isset($user->payment_order_product->price)){
$price = 'von ' . $user->payment_order_product->getFormattedPrice() . ' EUR';
}
$message = __('reminder.copy_first_' . $status, [
'days' => $days,
'datetime' => $datetime,
'price' => $price,
'pay_date' => $pay_date
]);
$message_last = __('reminder.copy_last_' . $status, [
'days' => $days,
'datetime' => $datetime,
'price' => $price,
'pay_date' => $pay_date
]);
$button = __('reminder.button_' . $status);
$message = preg_replace("/[\n\r]/", "", $message);
$message_last = preg_replace("/[\n\r]/", "", $message_last);
$data = [
'subject' => __('reminder.subject') . " | ID: " . $status,
'message' => $message,
'message_last' => $message_last,
'url' => route('user_membership'),
'button' => $button,
];
$sender = User::find(1);
$customer_mail = UserMessage::create([
'user_id' => $user->id,
'send_user_id' => $sender->id,
'email' => $user->email,
'subject' => $data['subject'],
'message' => $data['message'] . " " . $data['message_last'],
]);
try {
if(!Util::isTestSystem()){
if($status >= 34){
Log::channel('cron')->info('Sende kritische Erinnerung mit BCC an: ' . $user->email);
Mail::to($user->email)
->locale($user->getLocale())
->bcc(config('app.default_mail'))
->send(new MailCustomMessage($user, $data, $sender, false));
} else {
Log::channel('cron')->info('Sende normale Erinnerung an: ' . $user->email);
Mail::to($user->email)
->locale($user->getLocale())
->send(new MailCustomMessage($user, $data, $sender, false));
}
} else {
Log::channel('cron')->info('Testsystem: E-Mail-Versand simuliert für: ' . $user->email);
}
} catch(\Exception $e) {
Log::channel('cron')->error('Mail-Fehler für Benutzer ' . $user->email . ': ' . $e->getMessage());
$customer_mail->fail = true;
$customer_mail->error = $e->getMessage();
$customer_mail->save();
return 0;
}
$customer_mail->send = true;
$customer_mail->sent_at = now();
$customer_mail->save();
Log::channel('cron')->info('Erinnerungsmail erfolgreich gesendet an: ' . $user->email);
return 1;
}
/**
* Kauft ein Produkt mit Abo-Zahlung
*
* @param User $user Benutzer
* @param object $product Produkt
* @return void
*/
private function buyProductAboPayment($user, $product)
{
Log::channel('cron')->info('Starte Abo-Produktkauf für Benutzer: ' . $user->email);
$paymentHelper = new PaymentHelper();
$paymentHelper->setProduct($product);
$paymentHelper->initELVPayment($user);
Log::channel('cron')->info('Abo-Produktkauf abgeschlossen für: ' . $user->email);
}
/**
* Führt das Cron-Script aus
*
* @param string $key Sicherheitsschlüssel
* @return \Illuminate\Http\Response
*/
public function runCron($key)
{
Log::channel('cron')->info('Cron-Script-Ausführung angefordert');
if($key !== self::RUN_CRON_KEY){
Log::channel('cron')->warning('Ungültiger Cron-Script-Key verwendet: ' . $key);
abort(404);
}
$scriptPath = Util::isTestSystem() ? '../cron_script_local.sh' : '../cron_script_server.sh';
Log::channel('cron')->info('Führe Script aus: ' . $scriptPath);
exec("/bin/bash {$scriptPath} 2>&1", $out, $result);
Log::channel('cron')->info('Cron-Script-Ausführung abgeschlossen mit Code: ' . $result);
echo "Returncode: " . $result . "<br>";
echo "Ausgabe des Scripts: " . "<br>";
echo "<pre>"; print_r($out);
exit;
/*return response()->view('cron.result', [
'result' => $result,
'output' => $out
]);*/
}
}