Pint: Formatierung des bisherigen Stands, ohne inhaltliche Aenderung

Die Dateien lagen im Arbeitsbaum formatiert und inhaltlich geaendert
zusammen. Dieser Commit enthaelt nur die Pint-Formatierung des alten
Stands, damit die folgenden Commits nur noch Inhalt zeigen.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Kevin 2026-09-23 15:39:17 +00:00
parent bdef77462d
commit 316a9b76d6
33 changed files with 880 additions and 841 deletions

View file

@ -2,8 +2,8 @@
namespace App\Console\Commands;
use App\Models\UserBusinessStructure;
use App\Models\UserBusiness;
use App\Models\UserBusinessStructure;
use Illuminate\Console\Command;
class BusinessClearData extends Command
@ -37,12 +37,14 @@ class BusinessClearData extends Command
// Validierung
if ($month < 1 || $month > 12) {
$this->error('Invalid month. Must be between 1 and 12.');
return 1;
}
$currentYear = (int) date('Y');
if ($year < 2020 || $year > $currentYear + 1) {
$this->error('Invalid year. Must be between 2020 and ' . ($currentYear + 1));
$this->error('Invalid year. Must be between 2020 and '.($currentYear + 1));
return 1;
}
@ -53,8 +55,9 @@ class BusinessClearData extends Command
->where('month', $month)
->first();
if (!$existingStructure) {
if (! $existingStructure) {
$this->info('No stored business structure found for the specified month/year');
return 0;
}
@ -65,12 +68,13 @@ class BusinessClearData extends Command
$this->info("Found structure ID: {$structureId}");
$this->info("- UserBusiness records: {$userBusinessCount}");
$this->info("- Users in structure: {$userCount}");
$this->info("- Completed: " . ($existingStructure->completed ? 'Yes' : 'No'));
$this->info('- Completed: '.($existingStructure->completed ? 'Yes' : 'No'));
// Bestätigung (außer bei --force)
if (!$this->option('force')) {
if (!$this->confirm('Are you sure you want to delete this business structure data?')) {
if (! $this->option('force')) {
if (! $this->confirm('Are you sure you want to delete this business structure data?')) {
$this->info('Operation cancelled by user');
return 0;
}
}
@ -100,8 +104,9 @@ class BusinessClearData extends Command
return 0;
} catch (\Exception $e) {
$this->error('Error clearing business data: ' . $e->getMessage());
$this->error('Stack trace: ' . $e->getTraceAsString());
$this->error('Error clearing business data: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
return 1;
}
}
@ -125,12 +130,12 @@ class BusinessClearData extends Command
*/
private function formatBytes(int $bytes, int $precision = 2): string
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
}
return round($bytes, $precision) . ' ' . $units[$i];
return round($bytes, $precision).' '.$units[$i];
}
}

View file

@ -44,7 +44,7 @@ class BusinessLevelReports extends Command
'month' => $this->option('month'),
'year' => $this->option('year'),
'user_id' => $this->option('user-id'),
'only_not_updated' => $this->option('not-updated')
'only_not_updated' => $this->option('not-updated'),
];
$exportCsv = $this->option('csv');
@ -54,22 +54,25 @@ class BusinessLevelReports extends Command
if ($levelPromotions->isEmpty()) {
$this->info('Keine Level-Aufstiege gefunden.');
return 0;
}
if ($exportCsv) {
$filepath = $this->levelReportService->exportToCsv($levelPromotions);
$this->info('');
$this->info('CSV-Export erstellt: ' . $filepath);
$this->info('Anzahl Datensätze: ' . $levelPromotions->count());
$this->info('CSV-Export erstellt: '.$filepath);
$this->info('Anzahl Datensätze: '.$levelPromotions->count());
} else {
$this->displayReport($levelPromotions);
}
$this->info('Report erfolgreich generiert.');
return 0;
} catch (\Exception $e) {
$this->error('Fehler beim Generieren des Reports: ' . $e->getMessage());
$this->error('Fehler beim Generieren des Reports: '.$e->getMessage());
return 1;
}
}
@ -77,13 +80,14 @@ class BusinessLevelReports extends Command
private function displayReport($promotions)
{
$statistics = $this->levelReportService->getStatistics($promotions);
$this->info('');
$this->info('=== LEVEL-AUFSTIEG REPORT ===');
$this->info('');
if ($promotions->isEmpty()) {
$this->info('Keine Level-Aufstiege gefunden.');
return;
}
@ -102,7 +106,7 @@ class BusinessLevelReports extends Command
'User PP',
'User KP',
'Level Update',
'Aktiv'
'Aktiv',
];
$rows = [];
@ -110,15 +114,15 @@ class BusinessLevelReports extends Command
$rows[] = [
$promotion['date'],
$promotion['user_id'],
$promotion['first_name'] . ' ' . $promotion['last_name'],
$promotion['first_name'].' '.$promotion['last_name'],
$promotion['email'],
$promotion['from_level_name'] . ' (ID:' . $promotion['from_level_id'] . ')',
$promotion['to_level_name'] . ' (ID:' . $promotion['to_level_id'] . ')',
$promotion['current_user_level_name'] . ' (ID:' . ($promotion['current_user_level_id'] ?? 'N/A') . ')',
$promotion['to_level_margin'] . '%',
$promotion['from_level_name'].' (ID:'.$promotion['from_level_id'].')',
$promotion['to_level_name'].' (ID:'.$promotion['to_level_id'].')',
$promotion['current_user_level_name'].' (ID:'.($promotion['current_user_level_id'] ?? 'N/A').')',
$promotion['to_level_margin'].'%',
number_format($promotion['to_level_qual_kp'], 0, ',', '.'),
number_format($promotion['to_level_qual_pp'], 0, ',', '.'),
$promotion['to_level_growth_bonus'] . '%',
$promotion['to_level_growth_bonus'].'%',
number_format($promotion['total_pp'], 0, ',', '.'),
number_format($promotion['sales_volume_points_sum'], 0, ',', '.'),
$promotion['level_updated'],
@ -131,7 +135,7 @@ class BusinessLevelReports extends Command
// Zusammenfassung
$this->info('');
$this->info('=== ZUSAMMENFASSUNG ===');
$this->info('Anzahl Level-Aufstiege: ' . $statistics['total_count']);
$this->info('Anzahl Level-Aufstiege: '.$statistics['total_count']);
$this->info('');
$this->info('Aufstiege nach Ziel-Level:');
@ -145,5 +149,4 @@ class BusinessLevelReports extends Command
$this->info(" - {$period}: {$count}");
}
}
}

View file

@ -4,6 +4,7 @@ namespace App\Console\Commands;
use App\Cron\UserPaymentCredits;
use App\Models\UserBusiness;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\BusinessUserItemOptimized;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\User;
@ -45,37 +46,38 @@ class BusinessTestAccount extends Command
// Lade User mit Account
$user = User::with('account', 'user_level')->find($userId);
if (!$user) {
if (! $user) {
$this->error("User {$userId} not found");
return 1;
}
$this->info("User found: {$user->email}");
$this->info("Account ID: " . ($user->account_id ?? 'NULL'));
$this->info('Account ID: '.($user->account_id ?? 'NULL'));
if ($user->account) {
$this->info("Account loaded: YES");
$this->info("Account m_account: " . ($user->account->m_account ?? 'NULL'));
$this->info("Account first_name: " . ($user->account->first_name ?? 'NULL'));
$this->info("Account last_name: " . ($user->account->last_name ?? 'NULL'));
$this->info("Account birthday: " . ($user->account->birthday ?? 'NULL'));
$this->info("Account phone: " . ($user->account->getPhoneNumber() ?? 'NULL'));
$this->info('Account loaded: YES');
$this->info('Account m_account: '.($user->account->m_account ?? 'NULL'));
$this->info('Account first_name: '.($user->account->first_name ?? 'NULL'));
$this->info('Account last_name: '.($user->account->last_name ?? 'NULL'));
$this->info('Account birthday: '.($user->account->birthday ?? 'NULL'));
$this->info('Account phone: '.($user->account->getPhoneNumber() ?? 'NULL'));
} else {
$this->warn("Account loaded: NO");
$this->warn('Account loaded: NO');
}
$this->line('');
$this->info('Testing BusinessUserItemOptimized...');
// Erstelle Date Object
$date = new stdClass();
$date = new stdClass;
$date->month = $month;
$date->year = $year;
$date->start_date = "{$year}-{$month}-01 00:00:00";
$date->end_date = date('Y-m-t 23:59:59', strtotime("{$year}-{$month}-01"));
// Teste BusinessUserItemOptimized
$TreeCalcBot = new TreeCalcBotOptimized($date->month, $date->year, 'admin');
$TreeCalcBot = new TreeCalcBotOptimized($date->month, $date->year, 'admin');
$TreeCalcBot->initBusinesslUserDetail($user, true);
$businessUserItem = $TreeCalcBot->getItem();
@ -84,30 +86,30 @@ class BusinessTestAccount extends Command
$this->line('');
$this->info('Results from BusinessUserItemOptimized:');
$this->info("m_account: " . ($bUser->m_account ?? 'NULL'));
$this->info("first_name: " . ($bUser->first_name ?? 'NULL'));
$this->info("last_name: " . ($bUser->last_name ?? 'NULL'));
$this->info("user_birthday: " . ($bUser->user_birthday ?? 'NULL'));
$this->info("user_phone: " . ($bUser->user_phone ?? 'NULL'));
$this->info("email: " . ($bUser->email ?? 'NULL'));
$this->info('m_account: '.($bUser->m_account ?? 'NULL'));
$this->info('first_name: '.($bUser->first_name ?? 'NULL'));
$this->info('last_name: '.($bUser->last_name ?? 'NULL'));
$this->info('user_birthday: '.($bUser->user_birthday ?? 'NULL'));
$this->info('user_phone: '.($bUser->user_phone ?? 'NULL'));
$this->info('email: '.($bUser->email ?? 'NULL'));
$this->line('');
$this->info('Sales Volume Fields:');
$this->info("sales_volume_KP_points: " . ($bUser->sales_volume_KP_points ?? 'NULL'));
$this->info("sales_volume_TP_points: " . ($bUser->sales_volume_TP_points ?? 'NULL'));
$this->info("sales_volume_points_shop: " . ($bUser->sales_volume_points_shop ?? 'NULL'));
$this->info("sales_volume_points_KP_sum: " . ($bUser->sales_volume_points_KP_sum ?? 'NULL'));
$this->info("sales_volume_points_TP_sum: " . ($bUser->sales_volume_points_TP_sum ?? 'NULL'));
$this->info("sales_volume_total: " . ($bUser->sales_volume_total ?? 'NULL'));
$this->info("sales_volume_total_shop: " . ($bUser->sales_volume_total_shop ?? 'NULL'));
$this->info("sales_volume_total_sum: " . ($bUser->sales_volume_total_sum ?? 'NULL'));
$this->info('sales_volume_KP_points: '.($bUser->sales_volume_KP_points ?? 'NULL'));
$this->info('sales_volume_TP_points: '.($bUser->sales_volume_TP_points ?? 'NULL'));
$this->info('sales_volume_points_shop: '.($bUser->sales_volume_points_shop ?? 'NULL'));
$this->info('sales_volume_points_KP_sum: '.($bUser->sales_volume_points_KP_sum ?? 'NULL'));
$this->info('sales_volume_points_TP_sum: '.($bUser->sales_volume_points_TP_sum ?? 'NULL'));
$this->info('sales_volume_total: '.($bUser->sales_volume_total ?? 'NULL'));
$this->info('sales_volume_total_shop: '.($bUser->sales_volume_total_shop ?? 'NULL'));
$this->info('sales_volume_total_sum: '.($bUser->sales_volume_total_sum ?? 'NULL'));
$this->line('');
$this->info('Commission Fields:');
$this->info("payline_points: " . ($bUser->payline_points ?? 'NULL'));
$this->info("commission_pp_total: " . ($bUser->commission_pp_total ?? 'NULL'));
$this->info("commission_shop_sales: " . ($bUser->commission_shop_sales ?? 'NULL'));
$this->info("commission_growth_total: " . ($bUser->commission_growth_total ?? 'NULL'));
$this->info('payline_points: '.($bUser->payline_points ?? 'NULL'));
$this->info('commission_pp_total: '.($bUser->commission_pp_total ?? 'NULL'));
$this->info('commission_shop_sales: '.($bUser->commission_shop_sales ?? 'NULL'));
$this->info('commission_growth_total: '.($bUser->commission_growth_total ?? 'NULL'));
// Test UserSalesVolume directly
$this->line('');
@ -115,20 +117,20 @@ class BusinessTestAccount extends Command
$userSalesVolume = $user->getUserSalesVolume($month, $year, 'first');
if ($userSalesVolume) {
$this->info("UserSalesVolume found: ID {$userSalesVolume->id}");
$this->info("month_KP_points: " . ($userSalesVolume->month_KP_points ?? 'NULL'));
$this->info("month_TP_points: " . ($userSalesVolume->month_TP_points ?? 'NULL'));
$this->info("month_shop_points: " . ($userSalesVolume->month_shop_points ?? 'NULL'));
$this->info("month_total_net: " . ($userSalesVolume->month_total_net ?? 'NULL'));
$this->info("month_shop_total_net: " . ($userSalesVolume->month_shop_total_net ?? 'NULL'));
$this->info('month_KP_points: '.($userSalesVolume->month_KP_points ?? 'NULL'));
$this->info('month_TP_points: '.($userSalesVolume->month_TP_points ?? 'NULL'));
$this->info('month_shop_points: '.($userSalesVolume->month_shop_points ?? 'NULL'));
$this->info('month_total_net: '.($userSalesVolume->month_total_net ?? 'NULL'));
$this->info('month_shop_total_net: '.($userSalesVolume->month_shop_total_net ?? 'NULL'));
} else {
$this->warn("No UserSalesVolume found for month {$month}/{$year}");
// Check if any UserSalesVolume exists for this user
$anyVolume = \App\Models\UserSalesVolume::where('user_id', $userId)->orderBy('year', 'desc')->orderBy('month', 'desc')->first();
$anyVolume = UserSalesVolume::where('user_id', $userId)->orderBy('year', 'desc')->orderBy('month', 'desc')->first();
if ($anyVolume) {
$this->info("Latest UserSalesVolume found: {$anyVolume->month}/{$anyVolume->year}");
} else {
$this->warn("No UserSalesVolume records found for this user at all");
$this->warn('No UserSalesVolume records found for this user at all');
}
}
@ -142,12 +144,12 @@ class BusinessTestAccount extends Command
if ($existingUserBusiness) {
$this->info('Existing UserBusiness found:');
$this->info("m_account: " . ($existingUserBusiness->m_account ?? 'NULL'));
$this->info("first_name: " . ($existingUserBusiness->first_name ?? 'NULL'));
$this->info("last_name: " . ($existingUserBusiness->last_name ?? 'NULL'));
$this->info("user_birthday: " . ($existingUserBusiness->user_birthday ?? 'NULL'));
$this->info("user_phone: " . ($existingUserBusiness->user_phone ?? 'NULL'));
$this->info("email: " . ($existingUserBusiness->email ?? 'NULL'));
$this->info('m_account: '.($existingUserBusiness->m_account ?? 'NULL'));
$this->info('first_name: '.($existingUserBusiness->first_name ?? 'NULL'));
$this->info('last_name: '.($existingUserBusiness->last_name ?? 'NULL'));
$this->info('user_birthday: '.($existingUserBusiness->user_birthday ?? 'NULL'));
$this->info('user_phone: '.($existingUserBusiness->user_phone ?? 'NULL'));
$this->info('email: '.($existingUserBusiness->email ?? 'NULL'));
} else {
$this->info('No existing UserBusiness found for this period');
}
@ -161,11 +163,11 @@ class BusinessTestAccount extends Command
$userPaymentCredits = new UserPaymentCredits($month, $year);
$ret = $userPaymentCredits->addUserCreditItem($existingUserBusiness);
$this->info('UserBusinessCredit calculated:');
$this->info('User ID: ' . $ret->user_id);
$this->info('Team Commission: ' . $ret->commission_pp_total);
$this->info('Shop Commission: ' . $ret->commission_shop_sales);
$this->info('User ID: '.$ret->user_id);
$this->info('Team Commission: '.$ret->commission_pp_total);
$this->info('Shop Commission: '.$ret->commission_shop_sales);
} catch (\Exception $e) {
$this->error('Error calculating commissions: ' . $e->getMessage());
$this->error('Error calculating commissions: '.$e->getMessage());
}
} else {
$this->warn('No UserBusiness record found, cannot calculate commissions.');
@ -177,8 +179,9 @@ class BusinessTestAccount extends Command
return 0;
} catch (\Exception $e) {
$this->error('Test failed with error: ' . $e->getMessage());
$this->error('Stack trace: ' . $e->getTraceAsString());
$this->error('Test failed with error: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
return 1;
}
}

View file

@ -2,17 +2,14 @@
namespace App\Console\Commands;
use Carbon\Carbon;
use App\Models\UserBusiness;
use App\Models\UserLevel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class BusinessUpdateCalculatedFields extends Command
{
/**
* php artisan business:update-calculated-fields {year} {month?}
*
*
* Aktualisiert bereits gespeicherte UserBusiness-Einträge mit den neuen berechneten Feldern:
* - calc_qual_kp
* - _calculated_qual_kp in Level-Arrays
@ -32,9 +29,13 @@ class BusinessUpdateCalculatedFields extends Command
protected $description = 'Aktualisiert gespeicherte UserBusiness-Einträge mit neuen berechneten Feldern für Level-Qualifikationen';
private $timeStart;
private $month;
private $year;
private $isDryRun = false;
private $processAllMonths = false;
/**
@ -69,9 +70,10 @@ class BusinessUpdateCalculatedFields extends Command
return $this->processSingleMonth();
}
} catch (\Exception $e) {
$this->error('Command failed with error: ' . $e->getMessage());
$this->error('Stack trace: ' . $e->getTraceAsString());
$this->error('Command failed with error: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
$this->logExecutionTime('COMMAND FAILED');
return 1;
}
}
@ -91,15 +93,16 @@ class BusinessUpdateCalculatedFields extends Command
$this->month = $month;
$this->newLine();
$this->info("┌─────────────────────────────────────────────────────────────────────┐");
$this->info("│ Verarbeite Monat: " . str_pad($month, 2, '0', STR_PAD_LEFT) . "/" . $this->year . str_repeat(' ', 51) . "│");
$this->info("└─────────────────────────────────────────────────────────────────────┘");
$this->info('┌─────────────────────────────────────────────────────────────────────┐');
$this->info('│ Verarbeite Monat: '.str_pad($month, 2, '0', STR_PAD_LEFT).'/'.$this->year.str_repeat(' ', 51).'│');
$this->info('└─────────────────────────────────────────────────────────────────────┘');
try {
$userBusinesses = $this->getUserBusinesses();
if ($userBusinesses->isEmpty()) {
$this->warn(" Keine UserBusiness-Einträge für Monat {$month}/{$this->year} gefunden - überspringe");
continue;
}
@ -117,8 +120,9 @@ class BusinessUpdateCalculatedFields extends Command
$this->logMemoryUsage("Nach Monat {$month}");
} catch (\Exception $e) {
$monthsFailed++;
$this->error(" ✗ Fehler in Monat {$month}: " . $e->getMessage());
\Log::error("BusinessUpdateCalculatedFields: Error in month {$month}/{$this->year}: " . $e->getMessage());
$this->error(" ✗ Fehler in Monat {$month}: ".$e->getMessage());
\Log::error("BusinessUpdateCalculatedFields: Error in month {$month}/{$this->year}: ".$e->getMessage());
// Weiter mit nächstem Monat
continue;
}
@ -152,6 +156,7 @@ class BusinessUpdateCalculatedFields extends Command
if ($userBusinesses->isEmpty()) {
$this->error("Keine UserBusiness-Einträge für Monat {$this->month}/{$this->year} gefunden");
return 1;
}
@ -184,7 +189,7 @@ class BusinessUpdateCalculatedFields extends Command
{
$stats = $this->updateCalculatedFieldsWithStats($userBusinesses);
$this->info("Update abgeschlossen:");
$this->info('Update abgeschlossen:');
$this->info(" - Aktualisiert: {$stats['updated']}");
$this->info(" - Übersprungen: {$stats['skipped']}");
$this->info(" - Fehler: {$stats['errors']}");
@ -215,14 +220,15 @@ class BusinessUpdateCalculatedFields extends Command
$bar->advance();
// Memory-Check alle 100 Einträge (nur wenn nicht ganzes Jahr)
if (!$this->processAllMonths && ($updatedCount + $skippedCount) % 100 === 0) {
$this->logMemoryUsage("Nach " . ($updatedCount + $skippedCount) . " Einträgen");
if (! $this->processAllMonths && ($updatedCount + $skippedCount) % 100 === 0) {
$this->logMemoryUsage('Nach '.($updatedCount + $skippedCount).' Einträgen');
}
} catch (\Exception $e) {
$errorCount++;
$this->newLine();
$this->warn("Fehler bei UserBusiness ID {$userBusiness->id}: " . $e->getMessage());
\Log::error("BusinessUpdateCalculatedFields: Error for UserBusiness {$userBusiness->id}: " . $e->getMessage());
$this->warn("Fehler bei UserBusiness ID {$userBusiness->id}: ".$e->getMessage());
\Log::error("BusinessUpdateCalculatedFields: Error for UserBusiness {$userBusiness->id}: ".$e->getMessage());
continue;
}
}
@ -245,7 +251,7 @@ class BusinessUpdateCalculatedFields extends Command
$hasChanges = false;
// 1. Aktualisiere calc_qual_kp für qual_user_level
if (!$userBusiness->calc_qual_kp) {
if (! $userBusiness->calc_qual_kp) {
$qualKp = $userBusiness->qual_user_level['qual_kp'] ?? null;
if ($qualKp !== null) {
@ -263,7 +269,7 @@ class BusinessUpdateCalculatedFields extends Command
}
// 2. Aktualisiere qual_user_level_next
if (!empty($userBusiness->qual_user_level_next) && is_array($userBusiness->qual_user_level_next)) {
if (! empty($userBusiness->qual_user_level_next) && is_array($userBusiness->qual_user_level_next)) {
$levelData = $userBusiness->qual_user_level_next;
$updated = $this->addCalculatedFieldsToLevel($levelData, $userBusiness);
@ -274,7 +280,7 @@ class BusinessUpdateCalculatedFields extends Command
}
// 3. Aktualisiere next_qual_user_level
if (!empty($userBusiness->next_qual_user_level) && is_array($userBusiness->next_qual_user_level)) {
if (! empty($userBusiness->next_qual_user_level) && is_array($userBusiness->next_qual_user_level)) {
$levelData = $userBusiness->next_qual_user_level;
$updated = $this->addCalculatedFieldsToLevel($levelData, $userBusiness);
@ -285,7 +291,7 @@ class BusinessUpdateCalculatedFields extends Command
}
// 4. Aktualisiere next_can_user_level
if (!empty($userBusiness->next_can_user_level) && is_array($userBusiness->next_can_user_level)) {
if (! empty($userBusiness->next_can_user_level) && is_array($userBusiness->next_can_user_level)) {
$levelData = $userBusiness->next_can_user_level;
$updated = $this->addCalculatedFieldsToLevel($levelData, $userBusiness);
@ -296,7 +302,7 @@ class BusinessUpdateCalculatedFields extends Command
}
// Speichere nur wenn Änderungen vorhanden sind und nicht im Dry-Run Mode
if ($hasChanges && !$this->isDryRun) {
if ($hasChanges && ! $this->isDryRun) {
$userBusiness->save();
}
@ -305,7 +311,7 @@ class BusinessUpdateCalculatedFields extends Command
/**
* Füge berechnete Felder zu einem Level-Array hinzu
*
*
* @return array|false Array mit neuen Feldern oder false wenn keine Änderungen
*/
private function addCalculatedFieldsToLevel(array $levelData, UserBusiness $userBusiness)
@ -369,7 +375,7 @@ class BusinessUpdateCalculatedFields extends Command
$sec = intval($diff);
$micro = $diff - $sec;
$this->info($message . ' | Zeit: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info($message.' | Zeit: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
/**
@ -419,12 +425,12 @@ class BusinessUpdateCalculatedFields extends Command
*/
private function formatBytes(int $bytes, int $precision = 2): string
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
}
return round($bytes, $precision) . ' ' . $units[$i];
return round($bytes, $precision).' '.$units[$i];
}
}

View file

@ -30,7 +30,7 @@ class DhlBackfillEmails extends Command
$dryRun = $this->option('dry-run');
$this->info('DHL E-Mail Backfill gestartet');
$this->info('Modus: ' . ($dryRun ? 'DRY-RUN (keine Änderungen)' : 'LIVE'));
$this->info('Modus: '.($dryRun ? 'DRY-RUN (keine Änderungen)' : 'LIVE'));
$this->newLine();
// Hole alle Sendungen ohne E-Mail
@ -59,6 +59,7 @@ class DhlBackfillEmails extends Command
if (empty($email)) {
$skipped++;
continue;
}

View file

@ -2,10 +2,10 @@
namespace App\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class LogCleanup extends Command
{
@ -33,8 +33,9 @@ class LogCleanup extends Command
$days = $this->option('days');
$logPath = storage_path('logs');
if (!File::isDirectory($logPath)) {
if (! File::isDirectory($logPath)) {
$this->error("Log directory not found: {$logPath}");
return 1;
}
@ -64,24 +65,24 @@ class LogCleanup extends Command
$deletedFiles++;
$deletedSize += $fileSize;
$this->line("Deleted: {$filename} (" . $this->formatBytes($fileSize) . ", modified: {$lastModified->toDateString()})");
$this->line("Deleted: {$filename} (".$this->formatBytes($fileSize).", modified: {$lastModified->toDateString()})");
} catch (\Exception $e) {
$this->error("Failed to delete {$filename}: " . $e->getMessage());
$this->error("Failed to delete {$filename}: ".$e->getMessage());
}
}
}
if ($deletedFiles > 0) {
$this->info("\nCleanup complete!");
$this->info("Deleted {$deletedFiles} file(s), freed " . $this->formatBytes($deletedSize));
$this->info("Deleted {$deletedFiles} file(s), freed ".$this->formatBytes($deletedSize));
Log::channel('cleanup')->info("Log cleanup completed", [
Log::channel('cleanup')->info('Log cleanup completed', [
'deleted_files' => $deletedFiles,
'freed_space' => $this->formatBytes($deletedSize),
'days' => $days
'days' => $days,
]);
} else {
$this->info("No old log files found to delete.");
$this->info('No old log files found to delete.');
}
return 0;
@ -90,7 +91,7 @@ class LogCleanup extends Command
/**
* Format bytes to human readable format
*
* @param int $bytes
* @param int $bytes
* @return string
*/
private function formatBytes($bytes)
@ -101,6 +102,6 @@ class LogCleanup extends Command
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2) . ' ' . $units[$pow];
return round($bytes, 2).' '.$units[$pow];
}
}

View file

@ -3,6 +3,7 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class PayoneFailedPaypalReport extends Command
@ -45,14 +46,14 @@ class PayoneFailedPaypalReport extends Command
$this->newLine();
$this->info("CSV-Bericht: {$fullPath}");
$this->info('TXT-Bericht: ' . str_replace('.csv', '.txt', $fullPath));
$this->info('TXT-Bericht: '.str_replace('.csv', '.txt', $fullPath));
$this->info("E-Mail Berater: {$dir}/emails-berater.csv");
$this->info("E-Mail Shop-Kunden: {$dir}/emails-shop-kunden.csv");
return self::SUCCESS;
}
private function getAffectedOrders(string $from, string $to): \Illuminate\Support\Collection
private function getAffectedOrders(string $from, string $to): Collection
{
return DB::table('shopping_orders')
->join('shopping_payments', function ($join) {
@ -91,7 +92,7 @@ class PayoneFailedPaypalReport extends Command
->get();
}
private function displaySummary(\Illuminate\Support\Collection $rows, string $from, string $to): void
private function displaySummary(Collection $rows, string $from, string $to): void
{
$uniqueOrders = $rows->unique('order_id');
$paidOrders = $uniqueOrders->where('paid', 1);
@ -105,17 +106,17 @@ class PayoneFailedPaypalReport extends Command
['Betroffene Bestellungen (eindeutig)', $uniqueOrders->count()],
['Davon nachträglich bezahlt (andere Zahlungsart)', $paidOrders->count()],
['Nicht bezahlt (offen/verloren)', $unpaidOrders->count()],
['Summe nicht bezahlter Bestellungen', number_format($unpaidOrders->sum('total_shipping'), 2, ',', '.') . ' EUR'],
['Summe aller betroffenen Bestellungen', number_format($uniqueOrders->sum('total_shipping'), 2, ',', '.') . ' EUR'],
['Summe nicht bezahlter Bestellungen', number_format($unpaidOrders->sum('total_shipping'), 2, ',', '.').' EUR'],
['Summe aller betroffenen Bestellungen', number_format($uniqueOrders->sum('total_shipping'), 2, ',', '.').' EUR'],
]
);
}
private function writeCsvReport(string $path, \Illuminate\Support\Collection $rows, string $from, string $to): void
private function writeCsvReport(string $path, Collection $rows, string $from, string $to): void
{
$fp = fopen($path, 'w');
fprintf($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($fp, [
'Fehler-Datum',
@ -156,13 +157,13 @@ class PayoneFailedPaypalReport extends Command
fputcsv($fp, ['Fehlgeschlagene Transaktionen', $rows->count()], ';');
fputcsv($fp, ['Betroffene Bestellungen', $uniqueOrders->count()], ';');
fputcsv($fp, ['Nicht bezahlt (offen/verloren)', $unpaidOrders->count()], ';');
fputcsv($fp, ['Summe nicht bezahlter Bestellungen', number_format($unpaidOrders->sum('total_shipping'), 2, ',', '') . ' EUR'], ';');
fputcsv($fp, ['Summe aller betroffenen Bestellungen', number_format($uniqueOrders->sum('total_shipping'), 2, ',', '') . ' EUR'], ';');
fputcsv($fp, ['Summe nicht bezahlter Bestellungen', number_format($unpaidOrders->sum('total_shipping'), 2, ',', '').' EUR'], ';');
fputcsv($fp, ['Summe aller betroffenen Bestellungen', number_format($uniqueOrders->sum('total_shipping'), 2, ',', '').' EUR'], ';');
fclose($fp);
}
private function writeTxtReport(string $path, \Illuminate\Support\Collection $rows, string $from, string $to): void
private function writeTxtReport(string $path, Collection $rows, string $from, string $to): void
{
$uniqueOrders = $rows->unique('order_id');
$paidOrders = $uniqueOrders->where('paid', 1);
@ -174,7 +175,7 @@ class PayoneFailedPaypalReport extends Command
$lines[] = '================================================================================';
$lines[] = '';
$lines[] = "Zeitraum: {$from} bis {$to}";
$lines[] = 'Erstellt am: ' . now()->format('d.m.Y H:i:s');
$lines[] = 'Erstellt am: '.now()->format('d.m.Y H:i:s');
$lines[] = 'Ursache: PayPal-Kontoverknüpfung bei PAYONE nicht migriert (Vertragsübernahme GmbH)';
$lines[] = 'Portal-ID: 2030693';
$lines[] = 'Merchant-ID: 42504';
@ -199,7 +200,7 @@ class PayoneFailedPaypalReport extends Command
$lines[] = '--------------------------------------------------------------------------------';
$lines[] = '';
$byDate = $rows->groupBy(fn($r) => substr($r->error_date, 0, 10));
$byDate = $rows->groupBy(fn ($r) => substr($r->error_date, 0, 10));
foreach ($byDate as $date => $dayRows) {
$dayOrders = $dayRows->unique('order_id');
$dayUnpaid = $dayOrders->where('paid', 0);
@ -226,7 +227,7 @@ class PayoneFailedPaypalReport extends Command
'Betrag (EUR)',
'Status'
);
$lines[] = ' ' . str_repeat('-', 80);
$lines[] = ' '.str_repeat('-', 80);
foreach ($unpaidOrders->sortBy('order_date') as $order) {
$lines[] = sprintf(
@ -239,12 +240,12 @@ class PayoneFailedPaypalReport extends Command
);
}
$lines[] = ' ' . str_repeat('-', 80);
$lines[] = ' '.str_repeat('-', 80);
$lines[] = sprintf(
' %-12s %-20s %-18s %14s',
'GESAMT',
'',
$unpaidOrders->count() . ' Bestellungen',
$unpaidOrders->count().' Bestellungen',
number_format($unpaidOrders->sum('total_shipping'), 2, ',', '.')
);
@ -265,7 +266,7 @@ class PayoneFailedPaypalReport extends Command
'Betrag (EUR)',
'Status'
);
$lines[] = ' ' . str_repeat('-', 80);
$lines[] = ' '.str_repeat('-', 80);
foreach ($paidOrders->sortBy('order_date') as $order) {
$lines[] = sprintf(
@ -278,12 +279,12 @@ class PayoneFailedPaypalReport extends Command
);
}
$lines[] = ' ' . str_repeat('-', 80);
$lines[] = ' '.str_repeat('-', 80);
$lines[] = sprintf(
' %-12s %-20s %-18s %14s',
'GESAMT',
'',
$paidOrders->count() . ' Bestellungen',
$paidOrders->count().' Bestellungen',
number_format($paidOrders->sum('total_shipping'), 2, ',', '.')
);
}
@ -299,21 +300,21 @@ class PayoneFailedPaypalReport extends Command
file_put_contents($path, implode("\n", $lines));
}
private function appendEmailSectionToTxt(array &$lines, \Illuminate\Support\Collection $unpaidOrders): void
private function appendEmailSectionToTxt(array &$lines, Collection $unpaidOrders): void
{
$berater = $unpaidOrders->filter(fn($o) => ! empty($o->auth_user_id))->sortBy('billing_email');
$shopKunden = $unpaidOrders->filter(fn($o) => empty($o->auth_user_id))->sortBy('billing_email');
$berater = $unpaidOrders->filter(fn ($o) => ! empty($o->auth_user_id))->sortBy('billing_email');
$shopKunden = $unpaidOrders->filter(fn ($o) => empty($o->auth_user_id))->sortBy('billing_email');
$lines[] = '--------------------------------------------------------------------------------';
$lines[] = ' BETROFFENE BERATER (mit Auth-User-ID) - nicht bezahlt';
$lines[] = '--------------------------------------------------------------------------------';
$lines[] = '';
$lines[] = sprintf(' %-12s %-8s %-30s %-30s %14s', 'Bestell-Nr', 'User-ID', 'Name', 'E-Mail', 'Betrag (EUR)');
$lines[] = ' ' . str_repeat('-', 100);
$lines[] = ' '.str_repeat('-', 100);
$beraterSum = 0;
foreach ($berater as $order) {
$name = trim(($order->billing_firstname ?? '') . ' ' . ($order->billing_lastname ?? ''));
$name = trim(($order->billing_firstname ?? '').' '.($order->billing_lastname ?? ''));
$lines[] = sprintf(
' %-12s %-8s %-30s %-30s %14s',
$order->order_id,
@ -325,8 +326,8 @@ class PayoneFailedPaypalReport extends Command
$beraterSum += $order->total_shipping;
}
$lines[] = ' ' . str_repeat('-', 100);
$lines[] = sprintf(' %-12s %-8s %-30s %-30s %14s', 'GESAMT', '', $berater->count() . ' Bestellungen', '', number_format($beraterSum, 2, ',', '.'));
$lines[] = ' '.str_repeat('-', 100);
$lines[] = sprintf(' %-12s %-8s %-30s %-30s %14s', 'GESAMT', '', $berater->count().' Bestellungen', '', number_format($beraterSum, 2, ',', '.'));
$lines[] = '';
$lines[] = '--------------------------------------------------------------------------------';
@ -334,11 +335,11 @@ class PayoneFailedPaypalReport extends Command
$lines[] = '--------------------------------------------------------------------------------';
$lines[] = '';
$lines[] = sprintf(' %-12s %-30s %-30s %14s', 'Bestell-Nr', 'Name', 'E-Mail', 'Betrag (EUR)');
$lines[] = ' ' . str_repeat('-', 90);
$lines[] = ' '.str_repeat('-', 90);
$shopSum = 0;
foreach ($shopKunden as $order) {
$name = trim(($order->billing_firstname ?? '') . ' ' . ($order->billing_lastname ?? ''));
$name = trim(($order->billing_firstname ?? '').' '.($order->billing_lastname ?? ''));
$lines[] = sprintf(
' %-12s %-30s %-30s %14s',
$order->order_id,
@ -349,16 +350,16 @@ class PayoneFailedPaypalReport extends Command
$shopSum += $order->total_shipping;
}
$lines[] = ' ' . str_repeat('-', 90);
$lines[] = sprintf(' %-12s %-30s %-30s %14s', 'GESAMT', $shopKunden->count() . ' Bestellungen', '', number_format($shopSum, 2, ',', '.'));
$lines[] = ' '.str_repeat('-', 90);
$lines[] = sprintf(' %-12s %-30s %-30s %14s', 'GESAMT', $shopKunden->count().' Bestellungen', '', number_format($shopSum, 2, ',', '.'));
}
private function writeEmailLists(string $dir, \Illuminate\Support\Collection $rows): void
private function writeEmailLists(string $dir, Collection $rows): void
{
$unpaidOrders = $rows->unique('order_id')->where('paid', 0);
$berater = $unpaidOrders->filter(fn($o) => ! empty($o->auth_user_id))->sortBy('order_date');
$shopKunden = $unpaidOrders->filter(fn($o) => empty($o->auth_user_id))->sortBy('order_date');
$berater = $unpaidOrders->filter(fn ($o) => ! empty($o->auth_user_id))->sortBy('order_date');
$shopKunden = $unpaidOrders->filter(fn ($o) => empty($o->auth_user_id))->sortBy('order_date');
$this->writeEmailCsv("{$dir}/emails-berater.csv", $berater, true);
$this->writeEmailCsv("{$dir}/emails-shop-kunden.csv", $shopKunden, false);
@ -371,22 +372,22 @@ class PayoneFailedPaypalReport extends Command
'Berater (mit Auth-User-ID)',
$berater->count(),
$berater->pluck('billing_email')->filter()->unique()->count(),
number_format($berater->sum('total_shipping'), 2, ',', '.') . ' EUR',
number_format($berater->sum('total_shipping'), 2, ',', '.').' EUR',
],
[
'Shop-Kunden (ohne Auth-User-ID)',
$shopKunden->count(),
$shopKunden->pluck('billing_email')->filter()->unique()->count(),
number_format($shopKunden->sum('total_shipping'), 2, ',', '.') . ' EUR',
number_format($shopKunden->sum('total_shipping'), 2, ',', '.').' EUR',
],
]
);
}
private function writeEmailCsv(string $path, \Illuminate\Support\Collection $orders, bool $includeUserId): void
private function writeEmailCsv(string $path, Collection $orders, bool $includeUserId): void
{
$fp = fopen($path, 'w');
fprintf($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
$headers = ['Bestell-Nr', 'Bestell-Datum', 'Vorname', 'Nachname', 'E-Mail', 'Betrag (EUR)', 'Status'];
if ($includeUserId) {
@ -411,7 +412,7 @@ class PayoneFailedPaypalReport extends Command
}
fputcsv($fp, [], ';');
fputcsv($fp, ['GESAMT', '', '', '', $orders->count() . ' Bestellungen', number_format($orders->sum('total_shipping'), 2, ',', '') . ' EUR'], ';');
fputcsv($fp, ['GESAMT', '', '', '', $orders->count().' Bestellungen', number_format($orders->sum('total_shipping'), 2, ',', '').' EUR'], ';');
fputcsv($fp, ['Eindeutige E-Mail-Adressen', $orders->pluck('billing_email')->filter()->unique()->count()], ';');
fclose($fp);

View file

@ -7,6 +7,7 @@ use App\Models\ShoppingPayment;
use App\Services\AboHelper;
use App\Services\Incentive\IncentiveTracker;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class RepairMissingAboFromOrders extends Command
@ -96,9 +97,9 @@ class RepairMissingAboFromOrders extends Command
}
/**
* @return \Illuminate\Database\Eloquent\Builder<ShoppingOrder>
* @return Builder<ShoppingOrder>
*/
private function queryMissingOrders(): \Illuminate\Database\Eloquent\Builder
private function queryMissingOrders(): Builder
{
$q = ShoppingOrder::query()
->where('is_abo', true)

View file

@ -11,6 +11,7 @@ use App\Services\MyLog;
use App\Services\Payment;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
class RetryFailedPaypalAbos extends Command
@ -100,9 +101,9 @@ class RetryFailedPaypalAbos extends Command
}
/**
* @return \Illuminate\Database\Eloquent\Collection<int, UserAbo>
* @return Collection<int, UserAbo>
*/
private function getAffectedAbos(?string $singleAboId): \Illuminate\Database\Eloquent\Collection
private function getAffectedAbos(?string $singleAboId): Collection
{
$query = UserAbo::query()
->where('status', 3)
@ -119,7 +120,7 @@ class RetryFailedPaypalAbos extends Command
return $query->orderBy('id')->get();
}
private function displayAboList(\Illuminate\Database\Eloquent\Collection $abos): void
private function displayAboList(Collection $abos): void
{
$rows = $abos->map(fn (UserAbo $abo) => [
$abo->id,

View file

@ -2,17 +2,18 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
use App\Services\ShoppingUserService;
use App\User;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SyncShoppingUserData extends Command
{
//aufruf: php artisan shopping:sync-user-data --force --start=4
// aufruf: php artisan shopping:sync-user-data --force --start=4
protected $signature = 'shopping:sync-user-data {user_id?} {--force} {--start=1}';
protected $description = 'Synchronisiere Shopping User Daten für einen oder alle User';
public function handle()
@ -28,11 +29,12 @@ class SyncShoppingUserData extends Command
$this->syncAllUsers($force, $startId);
}
} catch (Exception $e) {
$this->error("Ein Fehler ist aufgetreten: " . $e->getMessage());
Log::error("Shopping User Sync Fehler: ", [
$this->error('Ein Fehler ist aufgetreten: '.$e->getMessage());
Log::error('Shopping User Sync Fehler: ', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
'trace' => $e->getTraceAsString(),
]);
return 1;
}
@ -50,27 +52,27 @@ class SyncShoppingUserData extends Command
User::where('id', '>=', $startId)
->orderBy('id')
->chunk(10, function($users) use (&$count, &$errors, $force) {
foreach($users as $user) {
->chunk(10, function ($users) use (&$count, &$errors, $force) {
foreach ($users as $user) {
try {
$this->info("\nVerarbeite User ID: {$user->id} ({$user->email})");
$this->syncUser($user);
$count++;
$this->info("✓ User ID {$user->id} erfolgreich synchronisiert");
} catch (Exception $e) {
$errorMessage = "Fehler bei User ID {$user->id} ({$user->email}): " . $e->getMessage();
$errorMessage = "Fehler bei User ID {$user->id} ({$user->email}): ".$e->getMessage();
$errors[] = $errorMessage;
$this->error($errorMessage);
// Log die letzten SQL Queries
Log::error("Letzte SQL Queries:", [
'queries' => DB::getQueryLog()
Log::error('Letzte SQL Queries:', [
'queries' => DB::getQueryLog(),
]);
if (!$force) {
if (! $force) {
throw $e;
}
}
@ -78,13 +80,13 @@ class SyncShoppingUserData extends Command
});
$this->newLine();
$this->info("Synchronisierung abgeschlossen!");
$this->info('Synchronisierung abgeschlossen!');
$this->info("Gesamt synchronisierte User: {$count}");
if (count($errors) > 0) {
$this->warn("Es gab " . count($errors) . " Fehler während der Synchronisierung:");
foreach($errors as $error) {
$this->warn("- " . $error);
$this->warn('Es gab '.count($errors).' Fehler während der Synchronisierung:');
foreach ($errors as $error) {
$this->warn('- '.$error);
}
}
}
@ -92,38 +94,37 @@ class SyncShoppingUserData extends Command
private function syncUser(User $user)
{
try {
$this->output->write(" Setze Faker Mail... ");
$this->output->write(' Setze Faker Mail... ');
ShoppingUserService::setFakerMail($user);
$this->info("✓");
$this->info('✓');
$this->output->write(" Synchronisiere Numbers... ");
$this->output->write(' Synchronisiere Numbers... ');
ShoppingUserService::syncNumbersByEmail($user);
$this->info("✓");
$this->info('✓');
$this->output->write(" Synchronisiere Orders... ");
$this->output->write(' Synchronisiere Orders... ');
ShoppingUserService::syncOrdersByEmail($user);
$this->info("✓");
$this->info('✓');
} catch (Exception $e) {
throw new Exception($e->getMessage() . "\n" . $e->getTraceAsString());
throw new Exception($e->getMessage()."\n".$e->getTraceAsString());
}
}
private function syncSingleUser($userId)
{
$user = User::find($userId);
if (!$user) {
if (! $user) {
throw new Exception("User ID {$userId} nicht gefunden");
}
$this->info("Starte Synchronisierung für User ID {$userId}...");
try {
$this->syncUser($user);
$this->info("✓ Synchronisierung erfolgreich abgeschlossen");
$this->info('✓ Synchronisierung erfolgreich abgeschlossen');
} catch (Exception $e) {
throw new Exception("Fehler bei User ID {$userId}: " . $e->getMessage());
throw new Exception("Fehler bei User ID {$userId}: ".$e->getMessage());
}
}
}
}

View file

@ -2,13 +2,13 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\Models\UserBusiness;
use App\Services\BusinessPlan\BusinessUserItemOptimized;
use App\Services\BusinessPlan\GrowthBonusCalculator;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\User;
use App\Models\UserBusiness;
use Carbon\Carbon;
use Illuminate\Console\Command;
class TestGrowthBonusCalculation extends Command
{
@ -29,14 +29,15 @@ class TestGrowthBonusCalculation extends Command
$debug = $this->option('debug');
$fromDb = $this->option('from-db');
$this->info("=== Growth Bonus Test ===");
$this->info('=== Growth Bonus Test ===');
$this->info("User: {$userId}, Monat: {$month}/{$year}");
$this->newLine();
// User laden
$user = User::find($userId);
if (!$user) {
if (! $user) {
$this->error("User {$userId} nicht gefunden!");
return 1;
}
@ -49,7 +50,7 @@ class TestGrowthBonusCalculation extends Command
->first();
if ($userBusiness) {
$this->info("=== GESPEICHERTE DATEN (UserBusiness) ===");
$this->info('=== GESPEICHERTE DATEN (UserBusiness) ===');
$qualLevel = $userBusiness->qual_user_level;
$this->table(
['Feld', 'Wert'],
@ -63,10 +64,11 @@ class TestGrowthBonusCalculation extends Command
);
} else {
$this->warn("Keine gespeicherten UserBusiness-Daten für {$month}/{$year}");
if (!$fromDb) {
$this->info("Versuche Live-Berechnung...");
if (! $fromDb) {
$this->info('Versuche Live-Berechnung...');
} else {
$this->error("--from-db erfordert gespeicherte Daten!");
$this->error('--from-db erfordert gespeicherte Daten!');
return 1;
}
}
@ -78,7 +80,7 @@ class TestGrowthBonusCalculation extends Command
}
$this->newLine();
$this->info("=== TEST ABGESCHLOSSEN ===");
$this->info('=== TEST ABGESCHLOSSEN ===');
return 0;
}
@ -86,7 +88,7 @@ class TestGrowthBonusCalculation extends Command
private function testFromDatabase(int $userId, int $month, int $year, bool $debug): void
{
$this->newLine();
$this->info("=== ANALYSE AUS DATENBANK ===");
$this->info('=== ANALYSE AUS DATENBANK ===');
// Lade User und seine Firstlines
$userBusiness = UserBusiness::where('user_id', $userId)
@ -100,16 +102,17 @@ class TestGrowthBonusCalculation extends Command
$this->info("Mein Growth Bonus Anspruch: {$myGrowthBonus}%");
if ($myGrowthBonus <= 0) {
$this->warn("Kein Growth Bonus Anspruch!");
$this->warn('Kein Growth Bonus Anspruch!');
return;
}
// Lade Firstlines
$firstlineIds = User::where('m_sponsor', $userId)->pluck('id')->toArray();
$this->info("Anzahl Firstlines: " . count($firstlineIds));
$this->info('Anzahl Firstlines: '.count($firstlineIds));
$this->newLine();
$this->info("=== FIRSTLINE ANALYSE ===");
$this->info('=== FIRSTLINE ANALYSE ===');
$totalExpectedGrowth = 0;
$problemsFound = false;
@ -120,7 +123,7 @@ class TestGrowthBonusCalculation extends Command
->where('year', $year)
->first();
if (!$flBusiness) {
if (! $flBusiness) {
continue;
}
@ -137,7 +140,7 @@ class TestGrowthBonusCalculation extends Command
$expectedDiff = max(0, $myGrowthBonus - $flGrowthBonus);
$expectedCommission = round($flTPSum / 100 * $expectedDiff, 2);
// Problem-Erkennung: Wenn FL einen Growth Bonus hat aber wir
// Problem-Erkennung: Wenn FL einen Growth Bonus hat aber wir
// trotzdem den vollen Betrag bekommen
$isPotentialProblem = $flGrowthBonus > 0 && $expectedDiff < $myGrowthBonus;
@ -146,11 +149,11 @@ class TestGrowthBonusCalculation extends Command
['Feld', 'Wert'],
[
['Level erreicht', $flLevelName],
['Growth Bonus (FL)', $flGrowthBonus . '%'],
['Growth Bonus (FL)', $flGrowthBonus.'%'],
['Team-Punkte (TP_sum)', number_format($flTPSum, 0, ',', '.')],
['Mein Anspruch', $myGrowthBonus . '%'],
['Differenz (erwartet)', $expectedDiff . '%'],
['Erwartete Provision', number_format($expectedCommission, 2, ',', '.') . ' €'],
['Mein Anspruch', $myGrowthBonus.'%'],
['Differenz (erwartet)', $expectedDiff.'%'],
['Erwartete Provision', number_format($expectedCommission, 2, ',', '.').' €'],
['ACHTUNG: Blockade?', $isPotentialProblem ? 'JA - FL sollte blockieren!' : 'Nein'],
]
);
@ -165,19 +168,19 @@ class TestGrowthBonusCalculation extends Command
}
$this->newLine();
$this->info("=== ZUSAMMENFASSUNG ===");
$this->info("Erwartete Growth Bonus Summe (mit korrekter Differenz): " . number_format($totalExpectedGrowth, 2, ',', '.') . ' €');
$this->info("Gespeicherte Growth Bonus Summe: " . number_format($userBusiness->commission_growth_total ?? 0, 2, ',', '.') . ' €');
$this->info('=== ZUSAMMENFASSUNG ===');
$this->info('Erwartete Growth Bonus Summe (mit korrekter Differenz): '.number_format($totalExpectedGrowth, 2, ',', '.').' €');
$this->info('Gespeicherte Growth Bonus Summe: '.number_format($userBusiness->commission_growth_total ?? 0, 2, ',', '.').' €');
if ($problemsFound) {
$this->newLine();
$this->error("⚠️ PROBLEME GEFUNDEN! Die Blockade durch qualifizierte Firstlines funktioniert möglicherweise nicht korrekt.");
$this->error('⚠️ PROBLEME GEFUNDEN! Die Blockade durch qualifizierte Firstlines funktioniert möglicherweise nicht korrekt.');
}
// Detailanalyse: Wie wurde die Berechnung durchgeführt?
if ($debug) {
$this->newLine();
$this->info("=== DEBUG: Rekursive Volumen-Analyse ===");
$this->info('=== DEBUG: Rekursive Volumen-Analyse ===');
$this->analyzeVolumeDistribution($userId, $month, $year, $myGrowthBonus, 1);
}
}
@ -193,14 +196,14 @@ class TestGrowthBonusCalculation extends Command
->where('year', $year)
->first();
if (!$userBusiness) {
if (! $userBusiness) {
return ['0.0' => 0];
}
$qualLevel = $userBusiness->qual_user_level;
$myProtection = (float) ($qualLevel['growth_bonus'] ?? 0);
$indent = str_repeat(" ", $depth);
$indent = str_repeat(' ', $depth);
// Eigenes Volumen (TP_sum - aber nur direkte Punkte, nicht Team)
// Bei gespeicherten Daten ist das schwer zu unterscheiden
@ -219,7 +222,7 @@ class TestGrowthBonusCalculation extends Command
->where('year', $year)
->first();
if (!$childBusiness) {
if (! $childBusiness) {
continue;
}
@ -251,7 +254,7 @@ class TestGrowthBonusCalculation extends Command
private function testLiveCalculation(User $user, Carbon $date, int $month, int $year, bool $debug): void
{
$this->newLine();
$this->info("=== LIVE-BERECHNUNG ===");
$this->info('=== LIVE-BERECHNUNG ===');
// TreeCalcBot erstellen
$treeCalcBot = new TreeCalcBotOptimized($month, $year, 'member', true);
@ -283,15 +286,15 @@ class TestGrowthBonusCalculation extends Command
);
$this->newLine();
$this->info("=== FIRSTLINES (Kinder) ===");
$this->info('=== FIRSTLINES (Kinder) ===');
if (empty($businessUserItem->businessUserItems)) {
$this->warn("Keine Firstlines geladen!");
$this->warn('Keine Firstlines geladen!');
} else {
foreach ($businessUserItem->businessUserItems as $index => $childItem) {
$childQual = $childItem->getQualUserLevel();
$this->info("--- Firstline " . ($index + 1) . " ---");
$this->info('--- Firstline '.($index + 1).' ---');
$this->table(
['Feld', 'Wert'],
[
@ -308,7 +311,7 @@ class TestGrowthBonusCalculation extends Command
}
if ($qualUserLevel && ($qualUserLevel['growth_bonus'] ?? 0) > 0) {
$calculator = new GrowthBonusCalculator();
$calculator = new GrowthBonusCalculator;
$qualData = (object) $qualUserLevel;
$totalGrowthBonus = $calculator->calculate($businessUserItem, $qualData);

View file

@ -2,11 +2,10 @@
namespace App\Console\Commands;
use App\User;
use App\Cron\UserLevelUpdate;
use App\Models\UserBusiness;
use App\Models\UserLevel;
use App\Cron\UserLevelUpdate;
use App\Console\Commands\BusinessStoreOptimized;
use App\User;
use Illuminate\Console\Command;
use ReflectionClass;
@ -41,17 +40,17 @@ class TestUserLevelUpdate extends Command
$sendMail = $this->option('send-mail');
$dryRun = $this->option('dry-run');
$this->info("===========================================");
$this->info("UserLevelUpdate Test");
$this->info("===========================================");
$this->info('===========================================');
$this->info('UserLevelUpdate Test');
$this->info('===========================================');
$this->line("Monat: {$month}");
$this->line("Jahr: {$year}");
if ($userId) {
$this->line("User ID: {$userId}");
}
$this->line("E-Mail senden: " . ($sendMail ? 'Ja' : 'Nein'));
$this->line("Dry-Run (nur zeigen): " . ($dryRun ? 'Ja' : 'Nein'));
$this->line("");
$this->line('E-Mail senden: '.($sendMail ? 'Ja' : 'Nein'));
$this->line('Dry-Run (nur zeigen): '.($dryRun ? 'Ja' : 'Nein'));
$this->line('');
if ($dryRun) {
// Im Dry-Run Modus zeigen wir nur die Analyse
@ -61,15 +60,16 @@ class TestUserLevelUpdate extends Command
$this->runOriginalFunction($month, $year, $sendMail);
}
$this->info("");
$this->info("===========================================");
$this->info("Test abgeschlossen!");
$this->info("===========================================");
$this->info('');
$this->info('===========================================');
$this->info('Test abgeschlossen!');
$this->info('===========================================');
return 0;
} catch (\Exception $e) {
$this->error('Test fehlgeschlagen: ' . $e->getMessage());
$this->error('Stack trace: ' . $e->getTraceAsString());
$this->error('Test fehlgeschlagen: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
return 1;
}
}
@ -79,10 +79,10 @@ class TestUserLevelUpdate extends Command
*/
private function runOriginalFunction(int $month, int $year, bool $sendMail)
{
$this->info("Erstelle BusinessStoreOptimized Instanz...");
$this->info('Erstelle BusinessStoreOptimized Instanz...');
// Erstelle BusinessStoreOptimized Command-Instanz
$businessStoreCommand = new BusinessStoreOptimized();
$businessStoreCommand = new BusinessStoreOptimized;
// Setze Output auf aktuellen Command (damit Ausgaben weitergeleitet werden)
$businessStoreCommand->setOutput($this->output);
@ -105,8 +105,8 @@ class TestUserLevelUpdate extends Command
// Setze sendUpdateMail
$businessStoreCommand->setSendUpdateMail($sendMail);
$this->info("Führe originale userLevelUpdate() Funktion aus...");
$this->line("");
$this->info('Führe originale userLevelUpdate() Funktion aus...');
$this->line('');
// Rufe die originale Funktion auf
$businessStoreCommand->userLevelUpdate();
@ -138,10 +138,10 @@ class TestUserLevelUpdate extends Command
->where('year', $this->argument('year'))
->where('user_id', $userId)
->whereNotNull('next_qual_user_level')
->whereRaw("JSON_LENGTH(next_qual_user_level) > 0")
->whereRaw('JSON_LENGTH(next_qual_user_level) > 0')
->first();
if (!$userBusiness) {
if (! $userBusiness) {
$this->warn("Keine UserBusiness mit next_qual_user_level gefunden für User ID: {$userId}");
// Zeige vorhandene UserBusiness-Daten
@ -151,18 +151,19 @@ class TestUserLevelUpdate extends Command
->first();
if ($anyUserBusiness) {
$this->info("UserBusiness existiert, aber hat kein next_qual_user_level");
$this->line("Current Level ID: " . ($anyUserBusiness->m_level_id ?? 'NULL'));
$this->line("next_qual_user_level: " . (is_null($anyUserBusiness->next_qual_user_level) ? 'NULL' : json_encode($anyUserBusiness->next_qual_user_level)));
$this->info('UserBusiness existiert, aber hat kein next_qual_user_level');
$this->line('Current Level ID: '.($anyUserBusiness->m_level_id ?? 'NULL'));
$this->line('next_qual_user_level: '.(is_null($anyUserBusiness->next_qual_user_level) ? 'NULL' : json_encode($anyUserBusiness->next_qual_user_level)));
} else {
$this->warn("Keine UserBusiness gefunden für diesen Monat/Jahr");
$this->warn('Keine UserBusiness gefunden für diesen Monat/Jahr');
}
return;
}
$this->displayUserBusinessInfo($userBusiness);
$this->info("");
$this->info("DRY-RUN MODUS: Änderungen werden nicht gespeichert");
$this->info('');
$this->info('DRY-RUN MODUS: Änderungen werden nicht gespeichert');
$this->analyzeLevelUpdate($userBusiness);
}
@ -173,22 +174,23 @@ class TestUserLevelUpdate extends Command
{
$levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
$this->info("Gefunden: " . $levelUpdateUsers->count() . " UserBusiness-Einträge mit next_qual_user_level");
$this->line("");
$this->info('Gefunden: '.$levelUpdateUsers->count().' UserBusiness-Einträge mit next_qual_user_level');
$this->line('');
if ($levelUpdateUsers->count() === 0) {
$this->warn("Keine UserBusiness-Einträge mit Level-Updates gefunden.");
$this->warn('Keine UserBusiness-Einträge mit Level-Updates gefunden.');
return;
}
$this->info("DRY-RUN MODUS: Änderungen werden nicht gespeichert");
$this->line("");
$this->info('DRY-RUN MODUS: Änderungen werden nicht gespeichert');
$this->line('');
foreach ($levelUpdateUsers as $userBusiness) {
$this->line("---------------------------------------------------");
$this->line('---------------------------------------------------');
$this->displayUserBusinessInfo($userBusiness);
$this->analyzeLevelUpdate($userBusiness);
$this->line("");
$this->line('');
}
}
@ -199,33 +201,33 @@ class TestUserLevelUpdate extends Command
{
$user = $userBusiness->user;
$this->line("User ID: " . ($user ? $user->id : 'NULL'));
$this->line("E-Mail: " . ($user ? $user->email : 'N/A'));
$this->line("Aktuelles Level: " . ($user && $user->m_level ? $user->m_level . ' (' . $this->getLevelName($user->m_level) . ')' : 'Kein Level'));
$this->line("UserBusiness Level ID: " . ($userBusiness->m_level_id ?? 'NULL'));
$this->line("UserBusiness Level Name: " . ($userBusiness->user_level_name ?? 'NULL'));
$this->line('User ID: '.($user ? $user->id : 'NULL'));
$this->line('E-Mail: '.($user ? $user->email : 'N/A'));
$this->line('Aktuelles Level: '.($user && $user->m_level ? $user->m_level.' ('.$this->getLevelName($user->m_level).')' : 'Kein Level'));
$this->line('UserBusiness Level ID: '.($userBusiness->m_level_id ?? 'NULL'));
$this->line('UserBusiness Level Name: '.($userBusiness->user_level_name ?? 'NULL'));
$nextQual = $userBusiness->next_qual_user_level;
if (is_array($nextQual)) {
if (isset($nextQual['id'])) {
// Einzelnes Level
$this->line("Nächstes qualifiziertes Level: ID " . $nextQual['id'] . ' - ' . ($nextQual['name'] ?? 'N/A') . ' (POS: ' . ($nextQual['pos'] ?? 'N/A') . ')');
$this->line(" Bereits aktualisiert: " . (isset($nextQual['hasUpdated']) && $nextQual['hasUpdated'] == 1 ? 'Ja' : 'Nein'));
$this->line('Nächstes qualifiziertes Level: ID '.$nextQual['id'].' - '.($nextQual['name'] ?? 'N/A').' (POS: '.($nextQual['pos'] ?? 'N/A').')');
$this->line(' Bereits aktualisiert: '.(isset($nextQual['hasUpdated']) && $nextQual['hasUpdated'] == 1 ? 'Ja' : 'Nein'));
} else {
// Array von Leveln
$this->line("Nächste qualifizierte Level: " . count($nextQual) . " Level gefunden");
$this->line('Nächste qualifizierte Level: '.count($nextQual).' Level gefunden');
foreach ($nextQual as $idx => $level) {
if (is_array($level) && isset($level['id'])) {
$updated = isset($level['hasUpdated']) && $level['hasUpdated'] == 1 ? ' (bereits aktualisiert)' : '';
$this->line(" [{$idx}] ID " . $level['id'] . ' - ' . ($level['name'] ?? 'N/A') . ' (POS: ' . ($level['pos'] ?? 'N/A') . ')' . $updated);
$this->line(" [{$idx}] ID ".$level['id'].' - '.($level['name'] ?? 'N/A').' (POS: '.($level['pos'] ?? 'N/A').')'.$updated);
}
}
}
} else {
$this->line("next_qual_user_level: " . (is_null($nextQual) ? 'NULL' : gettype($nextQual)));
$this->line('next_qual_user_level: '.(is_null($nextQual) ? 'NULL' : gettype($nextQual)));
}
$this->line("Total Qual PP: " . ($userBusiness->total_qual_pp ?? 0));
$this->line('Total Qual PP: '.($userBusiness->total_qual_pp ?? 0));
}
/**
@ -234,14 +236,16 @@ class TestUserLevelUpdate extends Command
private function analyzeLevelUpdate(UserBusiness $userBusiness)
{
$user = $userBusiness->user;
if (!$user) {
$this->warn("⚠ Kein User-Objekt vorhanden");
if (! $user) {
$this->warn('⚠ Kein User-Objekt vorhanden');
return;
}
$nextQual = $userBusiness->next_qual_user_level;
if (!is_array($nextQual) || empty($nextQual)) {
$this->warn("⚠ next_qual_user_level ist kein gültiges Array");
if (! is_array($nextQual) || empty($nextQual)) {
$this->warn('⚠ next_qual_user_level ist kein gültiges Array');
return;
}
@ -256,13 +260,13 @@ class TestUserLevelUpdate extends Command
$currentUserLevel = $userLevels->get($user->m_level);
}
$this->info("");
$this->info("📊 Analyse:");
$this->info('');
$this->info('📊 Analyse:');
if ($currentUserLevel) {
$this->line(" Aktuelles Level POS: {$currentUserLevel->pos}");
} else {
$this->line(" Aktuelles Level: Kein Level gesetzt");
$this->line(' Aktuelles Level: Kein Level gesetzt');
}
$wouldUpdate = false;
@ -270,12 +274,13 @@ class TestUserLevelUpdate extends Command
$highestPos = 0;
foreach ($levelArray as $levelData) {
if (!is_array($levelData) || !isset($levelData['id'])) {
if (! is_array($levelData) || ! isset($levelData['id'])) {
continue;
}
if (isset($levelData['hasUpdated']) && $levelData['hasUpdated'] == 1) {
$this->line(" ⏭ Level ID {$levelData['id']} wurde bereits aktualisiert");
continue;
}
@ -285,7 +290,7 @@ class TestUserLevelUpdate extends Command
$levelName = $levelData['name'] ?? 'N/A';
$this->line(" 📈 Level ID {$levelData['id']} ({$levelName}): POS {$newLevelPos}");
if (!$currentUserLevel || $newLevelPos > $currentUserLevel->pos) {
if (! $currentUserLevel || $newLevelPos > $currentUserLevel->pos) {
if ($newLevelPos > $highestPos) {
$highestPos = $newLevelPos;
$highestLevel = $levelData;
@ -297,15 +302,15 @@ class TestUserLevelUpdate extends Command
}
if ($wouldUpdate && $highestLevel) {
$this->info("");
$this->info('');
$highestLevelName = $highestLevel['name'] ?? 'N/A';
$this->info("✅ Würde Level aktualisieren zu: {$highestLevel['id']} ({$highestLevelName})");
$this->line(" Von: " . ($currentUserLevel ? "POS {$currentUserLevel->pos}" : "Kein Level") . " → Zu: POS {$highestPos}");
$this->line(' Von: '.($currentUserLevel ? "POS {$currentUserLevel->pos}" : 'Kein Level')." → Zu: POS {$highestPos}");
} else {
$this->info("");
$this->warn("⚠ Kein Level-Update würde durchgeführt:");
if (!$wouldUpdate) {
$this->line(" Kein höheres Level gefunden");
$this->info('');
$this->warn('⚠ Kein Level-Update würde durchgeführt:');
if (! $wouldUpdate) {
$this->line(' Kein höheres Level gefunden');
}
}
}
@ -316,6 +321,7 @@ class TestUserLevelUpdate extends Command
private function getLevelName($levelId)
{
$level = UserLevel::find($levelId);
return $level ? $level->name : 'Unbekannt';
}
}

View file

@ -1,25 +1,20 @@
<?php
namespace App\Http\Controllers\Admin;
use Auth;
use Request;
use App\User;
use Carbon\Carbon;
use App\Exports\UserTeamExport;
use App\Exports\xExport;
use App\Http\Controllers\Controller;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\UserInvoice;
use App\Services\HTMLHelper;
use App\Models\ShoppingOrder;
use App\Exports\UserTeamExport;
use App\Models\ShoppingOrderItem;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\BusinessPlan\ExportBot;
use Illuminate\Database\Eloquent\Collection;
use Request;
class PaymentSalesController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -32,132 +27,135 @@ class PaymentSalesController extends Controller
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2022),
];
return view('admin.payment.salesvolume', $data);
}
public function download(){
public function download()
{
/*
EXCEL EXPORT function */
/*
if(Request::get('action') === "exportfull_paid"){
return $this->exportFullList(1);
}
if(Request::get('action') === "exportfull_unpaid"){
return $this->exportFullList(0);
}
*/
if(Request::get('action') === "exportfull_paid_invoice"){
/*
if(Request::get('action') === "exportfull_paid"){
return $this->exportFullList(1);
}
if(Request::get('action') === "exportfull_unpaid"){
return $this->exportFullList(0);
}
*/
if (Request::get('action') === 'exportfull_paid_invoice') {
return $this->exportFullListInvoice();
}
if(Request::get('action') === "export"){
}
if (Request::get('action') === 'export') {
return $this->exportKompaktListInvoice();
}
}
private function setFilterVars(){
private function setFilterVars()
{
if(!session('payment_sales_vol_filter_month')){
if (! session('payment_sales_vol_filter_month')) {
session(['payment_sales_vol_filter_month' => intval(date('m'))]);
}
if(!session('payment_sales_vol_filter_year')){
if (! session('payment_sales_vol_filter_year')) {
session(['payment_sales_vol_filter_year' => intval(date('Y'))]);
}
if(Request::get('payment_sales_vol_filter_month')){
if (Request::get('payment_sales_vol_filter_month')) {
session(['payment_sales_vol_filter_month' => Request::get('payment_sales_vol_filter_month')]);
}
if(Request::get('payment_sales_vol_filter_year')){
if (Request::get('payment_sales_vol_filter_year')) {
session(['payment_sales_vol_filter_year' => Request::get('payment_sales_vol_filter_year')]);
}
}
private function exportKompaktListInvoice(){
private function exportKompaktListInvoice()
{
$objects = $this->initKompaktList();
$columns = [];
$filename = "mivita-absatzmengen-kompakt".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
$headers = array(
$filename = 'mivita-absatzmengen-kompakt'.session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year').'-export';
$headers = [
'#',
'Produkt',
'Artikelnummer',
'Menge',
);
if($objects){
foreach ($objects as $key => $obj){
$columns[] = array(
'id' => $key,
'name' => $obj['name'],
];
if ($objects) {
foreach ($objects as $key => $obj) {
$columns[] = [
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'value' => $obj['value'],
);
];
}
}
return Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
}
private function exportFullListInvoice(){
private function exportFullListInvoice()
{
$this->setFilterVars();
$UserInvoices = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
->get();
->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
->get();
$headers = array('Rechnungsnummer','Datum', 'EMail', 'Zahlung', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Summe', 'Kompensation');
$headers = ['Rechnungsnummer', 'Datum', 'EMail', 'Zahlung', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Summe', 'Kompensation'];
$columns = [];
$hasSOID = [];
$total_value = [];
foreach($UserInvoices as $UserInvoice){
if($UserInvoice->shopping_order){
foreach ($UserInvoices as $UserInvoice) {
if ($UserInvoice->shopping_order) {
$ShoppingOrder = $UserInvoice->shopping_order;
$object = [];
$object['Rechnungsnummer'] = $UserInvoice->full_number;
$object['Datum'] = $UserInvoice->date;
$object['EMail'] = $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->billing_email : 'n/a';
$object['Zahlung'] = $ShoppingOrder->getPaymentForType();
$object['Rechnungsnummer'] = $UserInvoice->full_number;
$object['Datum'] = $UserInvoice->date;
$object['EMail'] = $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->billing_email : 'n/a';
$object['Zahlung'] = $ShoppingOrder->getPaymentForType();
if($ShoppingOrder->payment_for === 5){ //homeparty
if($ShoppingOrder->homeparty){
foreach($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item){
if ($ShoppingOrder->payment_for === 5) { // homeparty
if ($ShoppingOrder->homeparty) {
foreach ($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item) {
$total_value[$homeparty_item->product_id] = isset($total_value[$homeparty_item->product_id]) ? $total_value[$homeparty_item->product_id] + $homeparty_item->qty : $homeparty_item->qty;
$object['ProduktNummer'] = $homeparty_item->product ? $homeparty_item->product->number : "n/a";
$object['ProduktName'] = $homeparty_item->product ? $homeparty_item->product->name : "n/a";
$object['Anzahl'] = $homeparty_item->qty;
$object['Summe'] = $total_value[$homeparty_item->product_id];
$object['Kompensation'] = '';
$object['ProduktNummer'] = $homeparty_item->product ? $homeparty_item->product->number : 'n/a';
$object['ProduktName'] = $homeparty_item->product ? $homeparty_item->product->name : 'n/a';
$object['Anzahl'] = $homeparty_item->qty;
$object['Summe'] = $total_value[$homeparty_item->product_id];
$object['Kompensation'] = '';
$columns[] = $object;
}
}
}elseif($ShoppingOrder->payment_for === 8){ //collective_invoice
if($ShoppingOrder->shopping_collect_order){
foreach($ShoppingOrder->shopping_collect_order->shop_items as $shop_item){
} elseif ($ShoppingOrder->payment_for === 8) { // collective_invoice
if ($ShoppingOrder->shopping_collect_order) {
foreach ($ShoppingOrder->shopping_collect_order->shop_items as $shop_item) {
$total_value[$shop_item['pid']] = isset($total_value[$shop_item['pid']]) ? $total_value[$shop_item['pid']] + $shop_item['qty'] : $shop_item['qty'];
$object['ProduktNummer'] = $shop_item['number'];
$object['ProduktName'] = $shop_item['name'];
$object['Anzahl'] = $shop_item['qty'];
$object['Summe'] = $total_value[$shop_item['pid']];
$object['Kompensation'] = '';
$object['ProduktNummer'] = $shop_item['number'];
$object['ProduktName'] = $shop_item['name'];
$object['Anzahl'] = $shop_item['qty'];
$object['Summe'] = $total_value[$shop_item['pid']];
$object['Kompensation'] = '';
$columns[] = $object;
}
}
}else{
if($ShoppingOrder->shopping_order_items){
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
} else {
if ($ShoppingOrder->shopping_order_items) {
foreach ($ShoppingOrder->shopping_order_items as $shopping_order_item) {
$total_value[$shopping_order_item->product_id] = isset($total_value[$shopping_order_item->product_id]) ? $total_value[$shopping_order_item->product_id] + $shopping_order_item->qty : $shopping_order_item->qty;
$object['ProduktNummer'] = $shopping_order_item->product ? $shopping_order_item->product->number : "n/a";
$object['ProduktName'] = $shopping_order_item->product ? $shopping_order_item->product->name : "n/a";
$object['Anzahl'] = $shopping_order_item->qty;
$object['Summe'] = $total_value[$shopping_order_item->product_id];
$object['Kompensation'] = ($shopping_order_item->comp ? $shopping_order_item->comp : '');
$object['ProduktNummer'] = $shopping_order_item->product ? $shopping_order_item->product->number : 'n/a';
$object['ProduktName'] = $shopping_order_item->product ? $shopping_order_item->product->name : 'n/a';
$object['Anzahl'] = $shopping_order_item->qty;
$object['Summe'] = $total_value[$shopping_order_item->product_id];
$object['Kompensation'] = ($shopping_order_item->comp ? $shopping_order_item->comp : '');
$columns[] = $object;
}
@ -167,74 +165,73 @@ class PaymentSalesController extends Controller
}
}
$filename = "mivita-absatzmengen-voll-".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
$filename = 'mivita-absatzmengen-voll-'.session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year').'-export';
return Excel::download(new xExport($columns, $headers), $filename.'.xls');
}
private function initKompaktList()
{
$this->setFilterVars();
$UserInvoices = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
->get();
->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
->get();
$objects = [];
foreach($UserInvoices as $UserInvoice){
if($UserInvoice->shopping_order){
foreach ($UserInvoices as $UserInvoice) {
if ($UserInvoice->shopping_order) {
$ShoppingOrder = $UserInvoice->shopping_order;
if($ShoppingOrder->payment_for === 5){ //homeparty
if($ShoppingOrder->homeparty){
foreach($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item){
if(isset($objects[$homeparty_item->product_id])){
if ($ShoppingOrder->payment_for === 5) { // homeparty
if ($ShoppingOrder->homeparty) {
foreach ($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item) {
if (isset($objects[$homeparty_item->product_id])) {
$value = intval($objects[$homeparty_item->product_id]['value'] + $homeparty_item->qty);
$objects[$homeparty_item->product_id]['value'] = $value;
}else{
} else {
$objects[$homeparty_item->product_id] = [
'name' => $homeparty_item->product ? $homeparty_item->product->name : "n/a ".$homeparty_item->product_id,
'number' => $homeparty_item->product ? $homeparty_item->product->number : "n/a ".$homeparty_item->product_id,
'value' => $homeparty_item->qty
'name' => $homeparty_item->product ? $homeparty_item->product->name : 'n/a '.$homeparty_item->product_id,
'number' => $homeparty_item->product ? $homeparty_item->product->number : 'n/a '.$homeparty_item->product_id,
'value' => $homeparty_item->qty,
];
}
}
}
}
}elseif($ShoppingOrder->payment_for === 8){ //collective_invoice
if($ShoppingOrder->shopping_collect_order){
foreach($ShoppingOrder->shopping_collect_order->shop_items as $shop_item){
} elseif ($ShoppingOrder->payment_for === 8) { // collective_invoice
if ($ShoppingOrder->shopping_collect_order) {
foreach ($ShoppingOrder->shopping_collect_order->shop_items as $shop_item) {
if(isset($objects[$shop_item['pid']])){
if (isset($objects[$shop_item['pid']])) {
$value = intval($objects[$shop_item['pid']]['value'] + $shop_item['qty']);
$objects[$shop_item['pid']]['value'] = $value;
}else{
} else {
$objects[$shop_item['pid']] = [
'name' => $shop_item['name'],
'number' => $shop_item['number'],
'value' => $shop_item['qty']
'value' => $shop_item['qty'],
];
}
}
}
}
}else{
if($ShoppingOrder->shopping_order_items){
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if(isset($objects[$shopping_order_item->product_id])){
} else {
if ($ShoppingOrder->shopping_order_items) {
foreach ($ShoppingOrder->shopping_order_items as $shopping_order_item) {
if (isset($objects[$shopping_order_item->product_id])) {
$value = intval($objects[$shopping_order_item->product_id]['value'] + $shopping_order_item->qty);
$objects[$shopping_order_item->product_id]['value'] = $value;
}else{
} else {
$objects[$shopping_order_item->product_id] = [
'name' => $shopping_order_item->product ? $shopping_order_item->product->name : "n/a ".$shopping_order_item->product_id,
'number' => $shopping_order_item->product ? $shopping_order_item->product->number : "n/a ".$shopping_order_item->product_id,
'value' => $shopping_order_item->qty
'name' => $shopping_order_item->product ? $shopping_order_item->product->name : 'n/a '.$shopping_order_item->product_id,
'number' => $shopping_order_item->product ? $shopping_order_item->product->number : 'n/a '.$shopping_order_item->product_id,
'value' => $shopping_order_item->qty,
];
}
}
}
}
}
@ -243,12 +240,12 @@ class PaymentSalesController extends Controller
}
}
return $objects;
return $objects;
}
public function datatable(){
public function datatable()
{
/*$collect = collect([
['id' => 1, 'name' => 'John', 'number'=>92012, 'value'=>123],
@ -257,29 +254,29 @@ class PaymentSalesController extends Controller
]);*/
$objects = $this->initKompaktList();
$collection = collect();
if($objects){
foreach($objects as $key => $obj){
if ($objects) {
foreach ($objects as $key => $obj) {
$collection->push([
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'value' => $obj['value'],
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'value' => $obj['value'],
]);
}
}
return \DataTables::of($collection)->toJson();
}
/*
//Auswertung nach ShoppingOrder
/*
//Auswertung nach ShoppingOrder
//nach Datum created_at wann die Bestellung erstellt wurde
//Ist nicht das Datum der Rechnung, da hier teilweise die Sammelrechnungen oder Zahlungen erst in nächsten Monat erfolgen
public function exportFullList($paid = 1){
$date_start = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->format('Y-m-d H:i:s');
$date_end = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d H:i:s');
$ShoppingOrders = ShoppingOrder::where('paid', $paid)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
@ -298,14 +295,14 @@ class PaymentSalesController extends Controller
$objects[$shopping_order_item->product->id]['value'] = $value;
}else{
$objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'value' => $shopping_order_item->qty
];
$value = $shopping_order_item->qty;
}
}
$object = [];
if(in_array($ShoppingOrder->id, $hasSOID)){
@ -329,7 +326,7 @@ class PaymentSalesController extends Controller
$hasSOID[] = $ShoppingOrder->id;
}
}
}
if($paid){
$filename = "mivita-absatzmengen-full-paid-".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
}else{
@ -338,7 +335,7 @@ class PaymentSalesController extends Controller
return Excel::download(new xExport($columns, $headers), $filename.'.xls');
//CSV EXPORT function
//CSV EXPORT function
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
@ -357,15 +354,15 @@ class PaymentSalesController extends Controller
foreach ($columns as $row) {
fputcsv($file, $row);
}
fclose($file);
};
return response()->stream($callback, 200, $headers);
}
*/
@ -387,7 +384,7 @@ class PaymentSalesController extends Controller
$counter = 0;
foreach($ShoppingOrders as $ShoppingOrder){
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if($shopping_order_item->product->id === 122){
//dump($shopping_order_item->qty);
@ -397,8 +394,8 @@ class PaymentSalesController extends Controller
$objects[$shopping_order_item->product->id]['value'] = $value;
}else{
$objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'value' => $shopping_order_item->qty
];
}
@ -438,11 +435,11 @@ class PaymentSalesController extends Controller
$objects[$shopping_order_item->product->id]['value'] = $value;
}else{
$objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'value' => $shopping_order_item->qty
];
}
}
}
}
}
@ -460,8 +457,8 @@ class PaymentSalesController extends Controller
}
return $collection;
}
return $objects;
return $objects;
}
*/
}
}

View file

@ -6,6 +6,8 @@ use App\Models\ShoppingUser;
use App\Models\ShoppingUserMemberLog;
use App\Models\UserCleanUpLog;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminUserCleanupController extends Controller
@ -86,7 +88,7 @@ class AdminUserCleanupController extends Controller
})
->addColumn('deleted_at', function (User $user) {
if ($user->pre_deleted_at) {
return \Carbon\Carbon::parse($user->pre_deleted_at)->format('d.m.Y H:i');
return Carbon::parse($user->pre_deleted_at)->format('d.m.Y H:i');
}
return '-';
@ -215,7 +217,7 @@ class AdminUserCleanupController extends Controller
return $html;
})
->addColumn('created_at', function (UserCleanUpLog $log) {
return \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i');
return Carbon::parse($log->created_at)->format('d.m.Y H:i');
})
->orderColumn('id', 'id $1')
->rawColumns(['inactive_sponsor', 'child_user', 'new_sponsor'])
@ -290,7 +292,7 @@ class AdminUserCleanupController extends Controller
return $html;
})
->addColumn('created_at', function (ShoppingUserMemberLog $log) {
return \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i');
return Carbon::parse($log->created_at)->format('d.m.Y H:i');
})
->orderColumn('id', 'id $1')
->rawColumns(['pre_member', 'shopping_user', 'new_member'])
@ -300,7 +302,7 @@ class AdminUserCleanupController extends Controller
/**
* User über Artisan Command wiederherstellen
*/
public function restore(\Illuminate\Http\Request $request)
public function restore(Request $request)
{
$userId = $request->input('user_id');
@ -348,7 +350,7 @@ class AdminUserCleanupController extends Controller
/**
* Suche nach aktiven Sponsoren für Select2
*/
public function searchSponsors(\Illuminate\Http\Request $request)
public function searchSponsors(Request $request)
{
$search = $request->input('q');
$userId = $request->input('exclude_user_id'); // User selbst ausschließen
@ -403,7 +405,7 @@ class AdminUserCleanupController extends Controller
/**
* Sponsor manuell neu zuweisen
*/
public function reassignSponsor(\Illuminate\Http\Request $request)
public function reassignSponsor(Request $request)
{
$userId = $request->input('user_id');
$newSponsorId = $request->input('new_sponsor_id');
@ -594,7 +596,7 @@ class AdminUserCleanupController extends Controller
'name' => trim($customer->billing_firstname.' '.$customer->billing_lastname),
'email' => $customer->billing_email,
'city' => $customer->billing_city,
'created_at' => \Carbon\Carbon::parse($customer->created_at)->format('d.m.Y'),
'created_at' => Carbon::parse($customer->created_at)->format('d.m.Y'),
];
});
@ -626,7 +628,7 @@ class AdminUserCleanupController extends Controller
'name' => $log->new_sponsor->account ? trim($log->new_sponsor->account->first_name.' '.$log->new_sponsor->account->last_name) : 'N/A',
'email' => $log->new_sponsor->email,
] : null,
'created_at' => \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i'),
'created_at' => Carbon::parse($log->created_at)->format('d.m.Y H:i'),
];
// Prüfe aktuellen Sponsor des child_user (falls geändert)
@ -658,7 +660,7 @@ class AdminUserCleanupController extends Controller
'name' => $log->new_member->account ? trim($log->new_member->account->first_name.' '.$log->new_member->account->last_name) : 'N/A',
'email' => $log->new_member->email,
] : null,
'created_at' => \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i'),
'created_at' => Carbon::parse($log->created_at)->format('d.m.Y H:i'),
];
// Prüfe aktuellen Berater des Kunden (falls geändert)
@ -685,7 +687,7 @@ class AdminUserCleanupController extends Controller
'm_account' => $user->account ? $user->account->m_account : 'N/A',
'active' => $user->active,
'deleted' => $user->pre_deleted_at ? true : false,
'deleted_at' => $user->pre_deleted_at ? \Carbon\Carbon::parse($user->pre_deleted_at)->format('d.m.Y H:i') : null,
'deleted_at' => $user->pre_deleted_at ? Carbon::parse($user->pre_deleted_at)->format('d.m.Y H:i') : null,
],
'sponsor' => $sponsor ? [
'id' => $sponsor->id,

View file

@ -2,81 +2,77 @@
namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
//protected static API_MAIL = 'api.thomas.krummel@gmail.com';
//protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
//protected static API_URL = 'https://mein.sterntours.test/api/';
// protected static API_MAIL = 'api.thomas.krummel@gmail.com';
// protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
// protected static API_URL = 'https://mein.sterntours.test/api/';
public $successStatus = 200;
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
'remember_me' => 'boolean',
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials))
if (! Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'
'message' => 'Unauthorized',
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me){
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(1);
}else{
} else {
$token->expires_at = Carbon::now()->addDays(1);
}
\DB::table('oauth_access_tokens')
->whereDate('expires_at', '<', now()->addWeeks(1))
->delete();
->whereDate('expires_at', '<', now()->addWeeks(1))
->delete();
\DB::table('oauth_refresh_tokens')
->whereDate('expires_at', '<', now()->addWeeks(1))
->delete();
->whereDate('expires_at', '<', now()->addWeeks(1))
->delete();
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
)->toDateTimeString(),
]);
}
public function checked(Request $request)
{
return response()->json([
'message' => 'login'
'message' => 'login',
]);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
'message' => 'Successfully logged out',
]);
}
@ -85,11 +81,11 @@ class AuthController extends Controller
*
* @return [json] user object
*/
/* public function user(Request $request)
{
return response()->json($request->user());
}
*/
/* public function user(Request $request)
{
return response()->json($request->user());
}
*/
/*public function signup(Request $request)
{
@ -109,4 +105,4 @@ class AuthController extends Controller
], 201);
}*/
}
}

View file

@ -2,12 +2,12 @@
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
@ -43,7 +43,7 @@ class RegisterController extends Controller
public function showRegistrationForm()
{
//register off! - to login
// register off! - to login
return redirect('login');
}
@ -51,7 +51,6 @@ class RegisterController extends Controller
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
@ -66,8 +65,7 @@ class RegisterController extends Controller
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
* @return User
*/
protected function create(array $data)
{

View file

@ -3,8 +3,10 @@
namespace App\Http\Controllers;
use Acme\Dhl\Models\DhlShipment;
use App\Jobs\CancelShipmentJob;
use Acme\Dhl\Services\ReturnsService;
// Old DHL model replaced with new package model
use Acme\Dhl\Support\DhlClient;
use App\Jobs\CancelShipmentJob;
use App\Jobs\CreateReturnLabelJob;
use App\Mail\MailDhlTracking;
use App\Models\Country;
@ -16,14 +18,15 @@ use App\Services\DhlShipmentService;
use App\Services\DhlTrackingService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
// Import new DHL package and SettingController
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
// Import new DHL package and SettingController
use Yajra\DataTables\Facades\DataTables;
use ZipArchive;
@ -47,16 +50,16 @@ class DhlShipmentController extends Controller
/**
* Test the DHL API login credentials and return a JSON response.
*
* @return \Illuminate\Http\JsonResponse
* @return JsonResponse
*/
public function testLogin()
{
try {
// Get DHL configuration with admin settings
$settingController = new \App\Http\Controllers\SettingController;
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Create DhlClient with merged configuration
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlClient = new DhlClient(
$dhlConfig['base_url'],
$dhlConfig['api_key'],
$dhlConfig['username'],
@ -249,7 +252,7 @@ class DhlShipmentController extends Controller
*
* @return View
*/
public function create(ShoppingOrder $order): View|\Illuminate\Http\RedirectResponse
public function create(ShoppingOrder $order): View|RedirectResponse
{
// Check if order already has a shipment
$existingShipment = DhlShipment::where('shopping_order_id', $order->id)
@ -627,7 +630,7 @@ class DhlShipmentController extends Controller
$dhlConfig = $settingController->getDhlConfig();
// Initialize DHL client
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlClient = new DhlClient(
$dhlConfig['base_url'],
$dhlConfig['api_key'],
$dhlConfig['username'],
@ -635,7 +638,7 @@ class DhlShipmentController extends Controller
);
// Use ReturnsService instead of ShippingService
$returnsService = new \Acme\Dhl\Services\ReturnsService($dhlClient);
$returnsService = new ReturnsService($dhlClient);
// Prepare return label data
$order = $shipment->shoppingOrder;

View file

@ -16,7 +16,12 @@ use App\Services\SysLog;
use App\Services\UserService;
use App\User;
use Auth;
use Carbon\Carbon;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;
use Request;
use Validator;
@ -31,7 +36,7 @@ class LeadController extends Controller
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return Factory|View
*/
public function index()
{
@ -69,7 +74,7 @@ class LeadController extends Controller
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return Factory|View
*/
public function edit($id)
{
@ -98,7 +103,7 @@ class LeadController extends Controller
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return Factory|View
*/
public function editPost($id)
{
@ -142,7 +147,7 @@ class LeadController extends Controller
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
* @return Factory|RedirectResponse|Redirector|View
*/
public function store(Request $request)
{
@ -263,7 +268,7 @@ class LeadController extends Controller
$to_user = isset($t_user->email) ? $t_user->email : 'empty';
SysLog::action('save-m_sponsor', 'lead_edit_sponsor', 3)
->setUserId(\Auth::user()->id)
->setUserId(Auth::user()->id)
->setModel($user->id, User::class)
->setMessage('Set user new sponsor from: '.$from_user.' | to: '.$to_user)
->save();
@ -364,7 +369,7 @@ class LeadController extends Controller
'confirmation_code' => $confirmation_code,
];
try {
Mail::to($user->email)->locale($user->getLocale())->send(new MailCustomMessage($user, $data, \Auth::user(), true));
Mail::to($user->email)->locale($user->getLocale())->send(new MailCustomMessage($user, $data, Auth::user(), true));
} catch (\Exception $e) {
dump($e->getMessage());
dd('error');
@ -541,7 +546,7 @@ class LeadController extends Controller
}
// Datum ermitteln
$contractDate = $useCurrentDate ? now() : ($user->active_date ? \Carbon\Carbon::parse($user->active_date) : now());
$contractDate = $useCurrentDate ? now() : ($user->active_date ? Carbon::parse($user->active_date) : now());
// Alten Vertrag löschen
File::where('user_id', $user->id)

View file

@ -8,14 +8,13 @@ use App\Repositories\CustomerRepository;
use App\Services\AboHelper;
use App\Services\CustomerPriority;
use App\Services\HTMLHelper;
use App\Services\Shop;
use App\Services\ShoppingUserService;
use App\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Request;
use Validator;
class CustomerController extends Controller
{
protected $customerRepository;
@ -29,22 +28,22 @@ class CustomerController extends Controller
public function index()
{
if(Request::get('reset') === 'filter'){
// set_user_attr('filter_member_id', null);
// set_user_attr('filter_customer_member', null);
if (Request::get('reset') === 'filter') {
// set_user_attr('filter_member_id', null);
// set_user_attr('filter_customer_member', null);
return redirect(route('admin_customers'));
}
$data = [
];
return view('user.customer.index', $data);
}
public function detail($id)
{
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->member_id != \Auth::user()->id){
if ($shopping_user->member_id != \Auth::user()->id) {
abort(404);
}
$data = [
@ -52,13 +51,14 @@ class CustomerController extends Controller
'isAdmin' => false,
'isView' => 'customer',
];
return view('user.customer.detail', $data);
}
public function edit($id)
{
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->member_id != \Auth::user()->id){
if ($shopping_user->member_id != \Auth::user()->id) {
abort(404);
}
$data = [
@ -67,33 +67,34 @@ class CustomerController extends Controller
'isView' => 'customer',
];
return view('user.customer.edit', $data);
}
public function add($id, $step=0)
public function add($id, $step = 0)
{
if($id === "new"){
$shopping_user = new ShoppingUser();
$shopping_user->id = "new";
}else{
if ($id === 'new') {
$shopping_user = new ShoppingUser;
$shopping_user->id = 'new';
} else {
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->member_id != \Auth::user()->id){
if ($shopping_user->member_id != \Auth::user()->id) {
abort(404);
}
}
$billing_email = null;
if(!session('errors')){
if(old('email') || old('billing_email')){
if (! session('errors')) {
if (old('email') || old('billing_email')) {
$step = 1;
$shopping_user->same_as_billing = true;
$billing_email = old('email');
}
if(old('switcher-without-email') === 'true'){
if (old('switcher-without-email') === 'true') {
$step = 1;
$shopping_user->same_as_billing = true;
$shopping_user->faker_mail = true;
$billing_email = time()."-faker@mivita.care";
$billing_email = time().'-faker@mivita.care';
}
}
$data = [
@ -104,42 +105,47 @@ class CustomerController extends Controller
'billing_email' => $billing_email,
];
return view('user.customer.add', $data);
}
private function checkShoppingUsersEmail($email = 'email', $action = 'return', $id=null){
private function checkShoppingUsersEmail($email = 'email', $action = 'return', $id = null)
{
$rules = array(
$rules = [
$email => 'required|string|email|max:255|unique:shopping_users,billing_email',
);
];
$messages = [
'unique' => __('validation.custom.unique_email_client'),
'unique' => __('validation.custom.unique_email_client'),
];
$validator = Validator::make(Request::all(), $rules, $messages);
if ($validator->fails()) {
\Session()->flash('alert-error', __('validation.custom.unique_email_client'));
return back()->withErrors($validator)->withInput(Request::all());
}
$rules = array(
$rules = [
$email => 'required|string|email|max:255|unique:users,email',
);
];
$messages = [
'unique' => __('validation.custom.unique_email_member'),
'unique' => __('validation.custom.unique_email_member'),
];
$validator = Validator::make(Request::all(), $rules, $messages);
if ($validator->fails()) {
\Session()->flash('alert-error', __('validation.custom.unique_email_member'));
return back()->withErrors($validator)->withInput(Request::all());
}
if($action === 'return'){
if ($action === 'return') {
return back()->withInput(Request::all());
}
if($action === 'save'){
if ($action === 'save') {
$shopping_user = ShoppingUser::findOrFail($id);
$shopping_user->faker_mail = false;
$shopping_user->billing_email = Request::get($email);
$shopping_user->save();
return redirect(route('user_customer_detail', [$shopping_user->id]));
}
}
@ -148,42 +154,42 @@ class CustomerController extends Controller
{
$data = Request::all();
if($id === 'new' && $data['action'] === 'add_customer_with_email'){
if ($id === 'new' && $data['action'] === 'add_customer_with_email') {
return $this->checkShoppingUsersEmail('email', 'return');
}
if($id === 'new' && $data['action'] === 'add_customer_without_email'){
if ($id === 'new' && $data['action'] === 'add_customer_without_email') {
return back()->withInput(Request::all());
}
if($id === 'new' && $data['action'] === ''){
if ($id === 'new' && $data['action'] === '') {
return back()->withInput(Request::all());
}
if($id !== 'new' && $data['action'] === 'add-mail-shopping-user-store'){
if ($id !== 'new' && $data['action'] === 'add-mail-shopping-user-store') {
return $this->checkShoppingUsersEmail('new_email_address', 'save', $id);
}
if($data['action'] === 'shopping-user-store-new' || $data['action']==='shopping-user-store'){
$rules = array(
if ($data['action'] === 'shopping-user-store-new' || $data['action'] === 'shopping-user-store') {
$rules = [
'billing_salutation' => 'required',
'billing_firstname'=>'required',
'billing_lastname'=>'required',
'billing_email'=>'required|email',
'billing_address'=>'required',
'billing_zipcode'=>'required',
'billing_firstname' => 'required',
'billing_lastname' => 'required',
'billing_email' => 'required|email',
'billing_address' => 'required',
'billing_zipcode' => 'required',
'billing_city' => 'required',
'billing_country_id' => 'required',
);
];
if(!Request::get('same_as_billing')){
if (! Request::get('same_as_billing')) {
$rules = array_merge($rules, [
'shipping_firstname'=>'required',
'shipping_lastname'=>'required',
'shipping_address'=>'required',
'shipping_zipcode'=>'required',
'shipping_firstname' => 'required',
'shipping_lastname' => 'required',
'shipping_address' => 'required',
'shipping_zipcode' => 'required',
'shipping_city' => 'required',
'shipping_salutation' => 'required',
'shipping_country_id' => 'required'
'shipping_country_id' => 'required',
]);
}
$validator = Validator::make(Request::all(), $rules);
@ -196,15 +202,15 @@ class CustomerController extends Controller
$data['faker_mail'] = isset($data['faker_mail']) ? true : false;
$data['has_buyed'] = isset($data['has_buyed']) ? true : false;
$data['subscribed'] = isset($data['subscribed']) ? true : false;
//subscribed can only true when has_buyed ist active
// subscribed can only true when has_buyed ist active
$data['subscribed'] = $data['has_buyed'] ? $data['subscribed'] : false;
$data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
$data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];
if($id > 0 && $data['action'] === 'shopping-user-store'){
if ($id > 0 && $data['action'] === 'shopping-user-store') {
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->member_id != \Auth::user()->id){
if ($shopping_user->member_id != \Auth::user()->id) {
abort(404);
}
CustomerPriority::checkChangeOne($shopping_user, $data, true);
@ -213,74 +219,76 @@ class CustomerController extends Controller
}
if($id === 'new' && $data['action'] === 'shopping-user-store-new') {
if ($id === 'new' && $data['action'] === 'shopping-user-store-new') {
$shopping_user = ShoppingUser::create($data);
$shopping_user->member_id = \Auth::user()->id;
$shopping_user->save();
CustomerPriority::checkNewOne($shopping_user, true);
}
\App\Services\Shop::newUserOrder($shopping_user->number);
Shop::newUserOrder($shopping_user->number);
if($shopping_user->is_like){
if ($shopping_user->is_like) {
\Session()->flash('custom-error', __('validation.custom.match_found'));
}
\Session()->flash('alert-save', true);
return redirect(route('user_customer_detail', [$shopping_user->id]));
}
private function checkShoppingUsersByEmail()
{
private function checkShoppingUsersByEmail(){
//ist an dieser stelle nicht machbar, zu viele Datenbankzugriffe
//siehe App\Console\Commands\SyncShoppingUserData
/* $user = User::find(\Auth::user()->id);
ShoppingUserService::setFakerMail($user);
ShoppingUserService::syncNumbersByEmail($user);
ShoppingUserService::syncOrdersByEmail($user); */
// ist an dieser stelle nicht machbar, zu viele Datenbankzugriffe
// siehe App\Console\Commands\SyncShoppingUserData
/* $user = User::find(\Auth::user()->id);
ShoppingUserService::setFakerMail($user);
ShoppingUserService::syncNumbersByEmail($user);
ShoppingUserService::syncOrdersByEmail($user); */
}
public function getCustomers()
{
//$this->checkShoppingUsersByEmail();
// $this->checkShoppingUsersByEmail();
$user = User::find(\Auth::user()->id);
//\Log::info('Current user ID: ' . $user->id);
// \Log::info('Current user ID: ' . $user->id);
$query = ShoppingUser::select(['id', 'billing_company', 'billing_salutation', 'billing_firstname', 'billing_lastname', 'billing_email', 'faker_mail', 'billing_zipcode', 'billing_city', 'billing_country_id', 'orders', 'subscribed', 'created_at', 'number', 'mode', 'is_like', 'wp_order_number'])
->with('billing_country')
->whereIn('id', function($query) {
$query->select(DB::raw('MAX(id)'))
->from('shopping_users')
->groupBy('billing_email');
})->where('shopping_users.member_id', '=', $user->id)->where('shopping_users.auth_user_id', '=', NULL);
->with('billing_country')
->whereIn('id', function ($query) {
$query->select(DB::raw('MAX(id)'))
->from('shopping_users')
->groupBy('billing_email');
})->where('shopping_users.member_id', '=', $user->id)->where('shopping_users.auth_user_id', '=', null);
if(Request::get('isfor') === 'ot-member'){ //Bestellung für Kunden
if (Request::get('isfor') === 'ot-member') { // Bestellung für Kunden
}
if(Request::get('isfor') === 'ot-customer' || Request::get('isfor') === 'abo-ot-customer'){ //Bestellung für Kunden Zahlungslink
$query->where(function($q) {
if (Request::get('isfor') === 'ot-customer' || Request::get('isfor') === 'abo-ot-customer') { // Bestellung für Kunden Zahlungslink
$query->where(function ($q) {
$q->where('shopping_users.faker_mail', '!=', 1)
->orWhereNull('shopping_users.faker_mail');
->orWhereNull('shopping_users.faker_mail');
});
}
//\Log::info('SQL Query: ' . $query->toSql());
//\Log::info('Query Bindings: ' . print_r($query->getBindings(), true));
// \Log::info('SQL Query: ' . $query->toSql());
// \Log::info('Query Bindings: ' . print_r($query->getBindings(), true));
return \DataTables::eloquent($query)
->addColumn('send_to', function (ShoppingUser $ShoppingUser) {
$ot = Request::get('isfor') ? Request::get('isfor') : 'ot-member';
if(Request::get('isfor') === 'abo-ot-customer' && AboHelper::memberHasAbo($ShoppingUser)){
if (Request::get('isfor') === 'abo-ot-customer' && AboHelper::memberHasAbo($ShoppingUser)) {
return '<span class="badge badge-pill badge-success"><i class="fa fa-check-circle"></i> '.__('abo.abo_assigned').'</span>';
}
return $ShoppingUser->is_like ? '<span class="badge badge-pill badge-warning"><i class="fa fa-clock"></i> '.__('customer.under_review').'</span>' : '<a href="' . route('user_order_my_delivery', [$ot, $ShoppingUser->id]) . '" class="btn btn-sm btn-secondary"><span class="fa fa-shopping-cart"></span> '.__('customer.select').'</a>';
return $ShoppingUser->is_like ? '<span class="badge badge-pill badge-warning"><i class="fa fa-clock"></i> '.__('customer.under_review').'</span>' : '<a href="'.route('user_order_my_delivery', [$ot, $ShoppingUser->id]).'" class="btn btn-sm btn-secondary"><span class="fa fa-shopping-cart"></span> '.__('customer.select').'</a>';
})
->addColumn('billing_email', function (ShoppingUser $ShoppingUser) {
return $ShoppingUser->faker_mail ? "-" : $ShoppingUser->billing_email;
return $ShoppingUser->faker_mail ? '-' : $ShoppingUser->billing_email;
})
->addColumn('id', function (ShoppingUser $ShoppingUser) {
return '<a href="' . route('user_customer_detail', [$ShoppingUser->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('user_customer_detail', [$ShoppingUser->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('billing_salutation', function (ShoppingUser $ShoppingUser) {
return HTMLHelper::getSalutationLang($ShoppingUser->billing_salutation);
@ -301,10 +309,10 @@ class CustomerController extends Controller
return $ShoppingUser->is_like ? '<span class="badge badge-pill badge-warning"><i class="fa fa-clock"></i> '.__('customer.under_review').'</span> ' : '<span class="badge badge-pill badge-success"><i class="fa fa-check-circle"></i> '.__('customer.assigned').'</span>';
})
->addColumn('extras', function (ShoppingUser $ShoppingUser) {
return $ShoppingUser->wp_order_number.($ShoppingUser->mode==='dev' ? ' <span class="badge badge-warning">dev</span>' : '');
return $ShoppingUser->wp_order_number.($ShoppingUser->mode === 'dev' ? ' <span class="badge badge-warning">dev</span>' : '');
})
->filterColumn('billing_email', function($query, $keyword) {
if($keyword != ""){
->filterColumn('billing_email', function ($query, $keyword) {
if ($keyword != '') {
$query->where('billing_email', 'LIKE', '%'.$keyword.'%');
}
})
@ -319,4 +327,4 @@ class CustomerController extends Controller
->rawColumns(['send_to', 'id', 'subscribed', 'extras', 'status'])
->make(true);
}
}
}

View file

@ -1,27 +1,24 @@
<?php
namespace App\Http\Controllers;
use App\Mail\MailActivateUser;
use App\User;
use Auth;
use Validator;
use Request;
use Carbon\Carbon;
use Illuminate\Database\Connection;
use App\Mail\MailActivateUser;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Request;
use Validator;
class UserUpdateEmailController extends Controller
{
protected $db;
protected $table = 'user_update_emails';
protected $resendAfter = 60; //1min
protected $resendAfter = 60; // 1min
public function __construct(Connection $db)
{
@ -38,15 +35,16 @@ class UserUpdateEmailController extends Controller
{
$user = Auth::user();
$rules = array(
'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . Auth::user()->id,
//'email-confirm' => 'required|same:email',
);
$rules = [
'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:'.Auth::user()->id,
// 'email-confirm' => 'required|same:email',
];
Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
if ($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()) {
return false;
}
return true;
});
@ -57,30 +55,31 @@ class UserUpdateEmailController extends Controller
return view('user.update_email')->withErrors($validator);
}else{
} else {
$this->sendActivationMail($user, Request::all());
\Session()->flash('alert-success', __('We sent you an activation code. Check your email!'));
return redirect(route('user_update_email'));
}
}
public function adminChangeMail($user_id)
public function adminChangeMail($user_id)
{
if(!Auth::user()->isAdmin()){
if (! Auth::user()->isAdmin()) {
abort(404);
}
$data = [
'user' => User::findOrFail($user_id),
];
return view('admin.change_email', $data);
}
public function adminUpdateMail(Request $request, $user_id)
public function adminUpdateMail(Request $request, $user_id)
{
if(!Auth::user()->isAdmin()){
if (! Auth::user()->isAdmin()) {
abort(404);
}
$user = User::findOrFail($user_id);
@ -88,16 +87,16 @@ class UserUpdateEmailController extends Controller
'user' => $user,
];
$rules = array(
'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . $user->id,
//'email-confirm' => 'required|same:email',
);
$rules = [
'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:'.$user->id,
// 'email-confirm' => 'required|same:email',
];
Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
if ($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()) {
return false;
}
return true;
});
@ -108,48 +107,45 @@ class UserUpdateEmailController extends Controller
return view('admin.change_email', $data)->withErrors($validator);
}else{
} else {
$this->sendActivationMail($user, Request::all());
\Session()->flash('alert-success', __('An activation code was sent to the account by e-mail!'));
return redirect(route('admin_lead_edit', [$user->id]));
}
}
public function activateMail($token)
{
if ($updateEmail = $this->getUpdateEmailByToken($token)) {
$user = User::findOrFail($updateEmail->user_id);
if($user->id == $updateEmail->user_id){
if ($user->id == $updateEmail->user_id) {
$user->fill([
'email' => $updateEmail->email
'email' => $updateEmail->email,
])->save();
$this->deleteUpdateEmail($token);
//Login!
// Login!
Auth::login($user);
\Session()->flash('alert-success', __('Your e-mail has been changed.'));
return redirect('/home');
}
}
return redirect('/home');
abort(404);
}
public function sendActivationMail($user, array $data)
{
$token = $this->createActivation($user, $data);
Mail::to($data['email'])->locale($user->getLocale())->send(new MailActivateUser($token, $user));
}
protected function getToken()
{
return hash_hmac('sha256', Str::random(40), config('app.key'));
@ -160,9 +156,10 @@ class UserUpdateEmailController extends Controller
$updateEmail = $this->getUpdateEmail($user);
if (!$updateEmail) {
if (! $updateEmail) {
return $this->createToken($user, $data);
}
return $this->regenerateToken($user, $data);
}
@ -174,8 +171,9 @@ class UserUpdateEmailController extends Controller
$this->db->table($this->table)->where('user_id', $user->id)->update([
'email' => $data['email'],
'token' => $token,
'created_at' => new Carbon()
'created_at' => new Carbon,
]);
return $token;
}
@ -186,8 +184,9 @@ class UserUpdateEmailController extends Controller
'user_id' => $user->id,
'email' => $data['email'],
'token' => $token,
'created_at' => new Carbon()
'created_at' => new Carbon,
]);
return $token;
}
@ -196,7 +195,6 @@ class UserUpdateEmailController extends Controller
return $this->db->table($this->table)->where('user_id', $user->id)->first();
}
public function getUpdateEmailByToken($token)
{
return $this->db->table($this->table)->where('token', $token)->first();
@ -206,4 +204,4 @@ class UserUpdateEmailController extends Controller
{
$this->db->table($this->table)->where('token', $token)->delete();
}
}
}

View file

@ -2,36 +2,31 @@
namespace App\Http\Controllers\Web;
use Request;
use App\User;
use Validator;
use App\Services\Util;
use GuzzleHttp\Client;
use App\Mail\MailContact;
use App\Models\UserLevel;
use App\Services\UserService;
use App\Mail\MailVerifyAccount;
use App\Http\Controllers\Controller;
use App\Mail\MailVerifyAccount;
use App\Models\UserLevel;
use App\Repositories\UserRepository;
use App\Services\UserService;
use App\Services\Util;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Mail;
use Request;
use Validator;
class RegisterController extends Controller
{
private $GOOGLE_ReCAPTCHA_KEY = '6LeeZosUAAAAAG907fMMqO4BFgsiR4ANDodd8FlU';
private $GOOGLE_ReCAPTCHA_KEY = "6LeeZosUAAAAAG907fMMqO4BFgsiR4ANDodd8FlU";
private $GOOGLE_ReCAPTCHA_SECRET = "6LeeZosUAAAAADIy2fyR4RG3EuM-Zdz7Pa2Qmb1J";
private $GOOGLE_ReCAPTCHA_SECRET = '6LeeZosUAAAAADIy2fyR4RG3EuM-Zdz7Pa2Qmb1J';
protected $userRepo;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
@ -47,7 +42,7 @@ class RegisterController extends Controller
'session_id' => \Session::getId(),
'session_domain' => config('session.domain'),
'request_host' => request()->getHost(),
'all_session_keys' => array_keys(\Session::all())
'all_session_keys' => array_keys(\Session::all()),
]);
}
@ -56,17 +51,18 @@ class RegisterController extends Controller
'user_shop' => Util::getUserShop(),
'yard_instance' => 'webshop',
];
return view('web.templates.registrierung', $data);
}
public function member($member_id = false)
{
if (!$member_id) {
if (! $member_id) {
return redirect('/registrierung');
}
$user_id = (int) str_replace('m', '', $member_id) - config('mivita.add_number_id');
$user = User::find($user_id);
if (!$user || !$user->isActive() || !$user->isActiveAccount()) {
if (! $user || ! $user->isActive() || ! $user->isActiveAccount()) {
return redirect('/registrierung');
}
$data = [
@ -75,13 +71,14 @@ class RegisterController extends Controller
'from_member_id' => $member_id,
'yard_instance' => 'webshop',
];
return view('web.templates.registrierung', $data);
}
public function register()
{
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -91,7 +88,7 @@ class RegisterController extends Controller
'password_confirmation' => 'required|string|min:6',
'g-recaptcha-response' => 'required|recaptcha',
'accepted_data_protection' => 'required',
);
];
Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {
return $this->reCaptcha_validate($attribute, $value, $parameters, $validator);
@ -114,7 +111,7 @@ class RegisterController extends Controller
if (isset($data['from_member_id'])) {
$m_sponsor_id = (int) str_replace('m', '', $data['from_member_id']) - config('mivita.add_number_id');
}
$user->lang = !empty(\App::getLocale()) ? \App::getLocale() : "de";
$user->lang = ! empty(\App::getLocale()) ? \App::getLocale() : 'de';
$user->confirmation_code = $confirmation_code;
$user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
$user->confirmation_code_remider = 0;
@ -133,6 +130,7 @@ class RegisterController extends Controller
$user->account->save();
Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyAccount($confirmation_code, User::find($user->id)));
return redirect('/registrierung/finish');
}
@ -142,26 +140,27 @@ class RegisterController extends Controller
'user_shop' => Util::getUserShop(),
'yard_instance' => 'webshop',
];
return view('web.templates.registrierung_finish', $data);
}
private function reCaptcha_validate($attribute, $value, $parameters, $validator)
{
$client = new Client();
$client = new Client;
$response = $client->post(
'https://www.google.com/recaptcha/api/siteverify',
[
'form_params' =>
[
'form_params' => [
'secret' => $this->GOOGLE_ReCAPTCHA_SECRET,
'response' => $value
]
'response' => $value,
],
]
);
$body = json_decode((string)$response->getBody());
$body = json_decode((string) $response->getBody());
return $body->success;
}
}

View file

@ -5,6 +5,7 @@ namespace App\Jobs;
use Acme\Dhl\Models\DhlShipment;
use Acme\Dhl\Services\ShippingService;
use Acme\Dhl\Support\DhlClient;
use App\Http\Controllers\SettingController;
use Exception;
use Illuminate\Bus\Queueable as BusQueueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@ -15,7 +16,7 @@ use Illuminate\Support\Facades\Log;
/**
* Job to cancel DHL shipments asynchronously
*
*
* This job handles the cancellation of DHL shipments in the background,
* preventing API timeouts and improving user experience.
*/
@ -49,9 +50,6 @@ class CancelShipmentJob implements ShouldQueue
/**
* Create a new job instance.
*
* @param DhlShipment $dhlShipment
* @param array $options
*/
public function __construct(DhlShipment $dhlShipment, array $options = [])
{
@ -79,7 +77,7 @@ class CancelShipmentJob implements ShouldQueue
]);
// Get DHL configuration
$settingController = new \App\Http\Controllers\SettingController;
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Create DHL client
@ -132,8 +130,6 @@ class CancelShipmentJob implements ShouldQueue
/**
* Handle a job failure.
*
* @param Exception $exception
*/
public function failed(Exception $exception): void
{

View file

@ -2,6 +2,9 @@
namespace App\Jobs;
use Acme\Dhl\Services\ShippingService;
use Acme\Dhl\Support\DhlClient;
use App\Http\Controllers\SettingController;
use App\Models\ShoppingOrder;
use App\Services\DhlDataHelper;
use Exception;
@ -92,16 +95,16 @@ class CreateShipmentJob implements ShouldQueue
]);
// Load DHL configuration here, never from the serialized job payload.
$dhlConfig = (new \App\Http\Controllers\SettingController)->getDhlConfig();
$dhlConfig = (new SettingController)->getDhlConfig();
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlClient = new DhlClient(
$dhlConfig['base_url'],
$dhlConfig['api_key'],
$dhlConfig['username'],
$dhlConfig['password']
);
$shippingService = new \Acme\Dhl\Services\ShippingService($dhlClient);
$shippingService = new ShippingService($dhlClient);
// Prepare order data using helper
$orderData = DhlDataHelper::prepareOrderData($this->shoppingOrder, $this->weight, $this->options, $dhlConfig);

View file

@ -1,19 +1,21 @@
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MailLog extends Mailable
{
use Queueable, SerializesModels;
protected $channel;
protected $context;
protected $message;
protected $data;
public $subject;
@ -25,39 +27,36 @@ class MailLog extends Mailable
$this->message = $message;
$this->data = $data;
$this->subject = 'mivita Log';
}
}
public function build()
{
$title = 'Log: '.$this->channel.' '.$this->context;
//make Data readable
// make Data readable
$this->data = json_encode($this->data, JSON_PRETTY_PRINT);
$content = "";
$content = '';
$content .= "\n";
$content .= "Channel: ".$this->channel."\n";
$content .= "Context: ".$this->context."\n";
if(\Auth::check()){
$content .= "From User: ".\Auth::user()->id." | ".\Auth::user()->email."\n";
}
$content .= "\n";
$content .= "Message: ".$this->message."\n";
$content .= "\n";
$content .= "Data: ".$this->data."\n";
$content .= "\n";
$content .= "\n";
$content .= "Time: ".now()->format("d.m.Y H:i");
$content .= "\n";
$content .= request()->header('User-Agent');
$content .= "\n";
$content .= 'Channel: '.$this->channel."\n";
$content .= 'Context: '.$this->context."\n";
if (\Auth::check()) {
$content .= 'From User: '.\Auth::user()->id.' | '.\Auth::user()->email."\n";
}
$content .= "\n";
$content .= 'Message: '.$this->message."\n";
$content .= "\n";
$content .= 'Data: '.$this->data."\n";
$content .= "\n";
$content .= "\n";
$content .= 'Time: '.now()->format('d.m.Y H:i');
$content .= "\n";
$content .= request()->header('User-Agent');
return $this->view('emails.sys')->with([
'title' => $title,
'content' => $content,
]);
}
}
}

View file

@ -63,161 +63,161 @@ use Illuminate\Database\Eloquent\Model;
*/
class ShoppingCollectOrder extends Model
{
protected $table = 'shopping_collect_orders';
protected $table = 'shopping_collect_orders';
protected $casts = [
'user_id' => 'int',
'shopping_order_id' => 'int',
'shipping' => 'float',
'shipping_net' => 'float',
'shipping_tax' => 'float',
'price_total_net' => 'float',
'price_total' => 'float',
'tax_total' => 'float',
'qty_total' => 'int',
'points' => 'float',
'status' => 'int',
'tax_split' => 'array',
'net_split' => 'array',
'orders' => AsArrayObject::class,
'shop_items' => AsArrayObject::class,
];
protected $casts = [
'user_id' => 'int',
'shopping_order_id' => 'int',
'shipping' => 'float',
'shipping_net' => 'float',
'shipping_tax' => 'float',
'price_total_net' => 'float',
'price_total' => 'float',
'tax_total' => 'float',
'qty_total' => 'int',
'points' => 'float',
'status' => 'int',
'tax_split' => 'array',
'net_split' => 'array',
'orders' => AsArrayObject::class,
'shop_items' => AsArrayObject::class,
];
protected $fillable = [
'user_id',
'shopping_order_id',
// 'identifier',
'shipping',
'shipping_net',
'shipping_tax',
'price_total_net',
'price_total',
'tax_total',
'qty_total',
'points',
'tax_split',
'net_split',
'orders',
'shop_items',
'status',
];
protected $fillable = [
'user_id',
'shopping_order_id',
// 'identifier',
'shipping',
'shipping_net',
'shipping_tax',
'price_total_net',
'price_total',
'tax_total',
'qty_total',
'points',
'tax_split',
'net_split',
'orders',
'shop_items',
'status',
];
public static $statusTypes = [
0 => '',
1 => 'store / pre',
2 => 'order',
];
public static $statusTypes = [
0 => '',
1 => 'store / pre',
2 => 'order',
];
public function shopping_order()
{
return $this->belongsTo(ShoppingOrder::class);
}
public function shopping_order()
{
return $this->belongsTo(ShoppingOrder::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function setPointsAttribute($value)
{
$this->attributes['points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function setPointsAttribute($value)
{
$this->attributes['points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? formatNumber($this->attributes['points']) : '';
}
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? formatNumber($this->attributes['points']) : '';
}
public function addTaxToSplit($tax_rate, $add_tax)
{
$tax_split = $this->tax_split;
$add_tax = round($add_tax, 2);
$existing_value = isset($tax_split[$tax_rate]) ? $this->parseNumericValue($tax_split[$tax_rate]) : 0;
$tax_split[$tax_rate] = round($existing_value + $add_tax, 2);
public function addTaxToSplit($tax_rate, $add_tax)
{
$tax_split = $this->tax_split;
$add_tax = round($add_tax, 2);
$existing_value = isset($tax_split[$tax_rate]) ? $this->parseNumericValue($tax_split[$tax_rate]) : 0;
$tax_split[$tax_rate] = round($existing_value + $add_tax, 2);
$this->tax_split = $tax_split;
}
$this->tax_split = $tax_split;
}
public function addNetToSplit($tax_rate, $add_net)
{
$net_split = $this->net_split;
$add_net = round($add_net, 2);
$existing_value = isset($net_split[$tax_rate]) ? $this->parseNumericValue($net_split[$tax_rate]) : 0;
$net_split[$tax_rate] = round($existing_value + $add_net, 2);
public function addNetToSplit($tax_rate, $add_net)
{
$net_split = $this->net_split;
$add_net = round($add_net, 2);
$existing_value = isset($net_split[$tax_rate]) ? $this->parseNumericValue($net_split[$tax_rate]) : 0;
$net_split[$tax_rate] = round($existing_value + $add_net, 2);
$this->net_split = $net_split;
}
$this->net_split = $net_split;
}
/**
* Parst verschiedene Zahlenformate zu einem float-Wert
* Unterstützt: 19.50, 1234.56, 1.234,56, 1,234.56
*/
private function parseNumericValue($value)
{
// Bereits eine Zahl? Direkt zurückgeben
if (is_numeric($value)) {
return (float) $value;
}
/**
* Parst verschiedene Zahlenformate zu einem float-Wert
* Unterstützt: 19.50, 1234.56, 1.234,56, 1,234.56
*/
private function parseNumericValue($value)
{
// Bereits eine Zahl? Direkt zurückgeben
if (is_numeric($value)) {
return (float) $value;
}
// String zu String konvertieren für weitere Verarbeitung
$value = (string) $value;
// String zu String konvertieren für weitere Verarbeitung
$value = (string) $value;
// Entferne Leerzeichen
$value = trim($value);
// Entferne Leerzeichen
$value = trim($value);
// Prüfe verschiedene Formate
if (preg_match('/^-?\d{1,3}(\.\d{3})*,\d{2}$/', $value)) {
// Deutsches Format: 1.234,56 oder 1.234.567,89
return (float) str_replace(',', '.', str_replace('.', '', $value));
} elseif (preg_match('/^-?\d{1,3}(,\d{3})*\.\d{2}$/', $value)) {
// Amerikanisches Format: 1,234.56 oder 1,234,567.89
return (float) str_replace(',', '', $value);
} else {
// Einfaches Format: 19.50, 123.45, etc.
// Nur Kommas durch Punkte ersetzen
return (float) str_replace(',', '.', $value);
}
}
// Prüfe verschiedene Formate
if (preg_match('/^-?\d{1,3}(\.\d{3})*,\d{2}$/', $value)) {
// Deutsches Format: 1.234,56 oder 1.234.567,89
return (float) str_replace(',', '.', str_replace('.', '', $value));
} elseif (preg_match('/^-?\d{1,3}(,\d{3})*\.\d{2}$/', $value)) {
// Amerikanisches Format: 1,234.56 oder 1,234,567.89
return (float) str_replace(',', '', $value);
} else {
// Einfaches Format: 19.50, 123.45, etc.
// Nur Kommas durch Punkte ersetzen
return (float) str_replace(',', '.', $value);
}
}
public function addShopItem($shop_item_id, $shop_item)
{
$numberFields = [
'user_price_net',
'user_price_total_net',
'user_tax',
'user_tax_total',
];
public function addShopItem($shop_item_id, $shop_item)
{
$numberFields = [
'user_price_net',
'user_price_total_net',
'user_tax',
'user_tax_total',
];
// Points werden jetzt auch als Dezimalzahlen behandelt
$decimalFields = [
'points_total',
'points',
];
// Points werden jetzt auch als Dezimalzahlen behandelt
$decimalFields = [
'points_total',
'points',
];
foreach ($numberFields as $field) {
if (isset($shop_item->$field)) {
$shop_item->$field = number_format($shop_item->$field, 2, '.', '');
}
}
foreach ($numberFields as $field) {
if (isset($shop_item->$field)) {
$shop_item->$field = number_format($shop_item->$field, 2, '.', '');
}
}
foreach ($decimalFields as $field) {
if (isset($shop_item->$field)) {
$shop_item->$field = round((float) $shop_item->$field, 2);
}
}
foreach ($decimalFields as $field) {
if (isset($shop_item->$field)) {
$shop_item->$field = round((float) $shop_item->$field, 2);
}
}
$this->shop_items[$shop_item_id] = $shop_item;
}
$this->shop_items[$shop_item_id] = $shop_item;
}
public function addOrder($order)
{
$this->orders[] = $order;
}
public function addOrder($order)
{
$this->orders[] = $order;
}
public function initShoppingOrder($order)
{
$order['shopping_order'] = ShoppingOrder::findOrFail($order['order_id']);
public function initShoppingOrder($order)
{
$order['shopping_order'] = ShoppingOrder::findOrFail($order['order_id']);
return $order;
}
return $order;
}
}

View file

@ -4,6 +4,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
/**
* App\Models\ShoppingOrderItem
@ -15,10 +16,10 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property int|null $qty
* @property float|null $price
* @property string|null $slug
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\Models\Product $product
* @property-read \App\Models\ShoppingOrder $shopping_order
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Product $product
* @property-read ShoppingOrder $shopping_order
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrderItem newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrderItem newQuery()
@ -34,7 +35,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrderItem whereUpdatedAt($value)
*
* @property float|null $tax_rate
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property Carbon|null $deleted_at
* @property string|null $user_deleted_at
*
* @method static \Illuminate\Database\Query\Builder|\App\Models\ShoppingOrderItem onlyTrashed()
@ -51,7 +52,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrderItem wherePriceNet($value)
*
* @property int|null $homeparty_id
* @property-read \App\Models\Homeparty|null $homeparty
* @property-read Homeparty|null $homeparty
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrderItem whereHomepartyId($value)
*

View file

@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
/**
* Class UserAboOneTimeItem
@ -21,7 +22,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property int|null $comp
* @property int $qty
* @property int|null $confirmed_qty
* @property \Illuminate\Support\Carbon|null $confirmed_at
* @property Carbon|null $confirmed_at
* @property float|null $price
* @property float|null $price_net
* @property float|null $tax_rate

View file

@ -6,11 +6,9 @@ use App\Models\ShoppingUser;
class CustomerRepository extends BaseRepository
{
public function __construct()
{
//$this->model = $model;
// $this->model = $model;
}
public function deleteCustomer(ShoppingUser $shopping_user)
@ -29,7 +27,7 @@ class CustomerRepository extends BaseRepository
$shopping_user->billing_zipcode = '00000';
$shopping_user->billing_city = 'Deleted';
$shopping_user->billing_phone = null;
$shopping_user->billing_email = 'deleted_' . $shopping_user->id . '@deleted.com';
$shopping_user->billing_email = 'deleted_'.$shopping_user->id.'@deleted.com';
$shopping_user->shipping_salutation = null;
$shopping_user->shipping_company = null;
@ -40,13 +38,14 @@ class CustomerRepository extends BaseRepository
$shopping_user->shipping_zipcode = '00000';
$shopping_user->shipping_city = 'Deleted';
$shopping_user->shipping_phone = null;
$shopping_user->shipping_email = 'deleted_' . $shopping_user->id . '@deleted.com';
$shopping_user->shipping_email = 'deleted_'.$shopping_user->id.'@deleted.com';
$shopping_user->remarks = null;
$shopping_user->notice = null;
$shopping_user->faker_mail = true;
$shopping_user->save();
return true;
}

View file

@ -2,9 +2,12 @@
namespace App\Services;
use Acme\Dhl\Models\DhlShipment;
use App\Http\Controllers\SettingController;
use App\Models\Country;
use App\Models\ShoppingOrder;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;
/**
@ -158,7 +161,7 @@ class DhlModalService
'label_path' => $shipment->label_path,
'created_at' => $shipment->created_at->toDateTimeString(),
'tracking_status' => $shipment->tracking_status,
'tracking_status_translated' => $shipment->tracking_status ? \Acme\Dhl\Models\DhlShipment::getStatusTranslationFor($shipment->tracking_status) : null,
'tracking_status_translated' => $shipment->tracking_status ? DhlShipment::getStatusTranslationFor($shipment->tracking_status) : null,
'last_tracked_at' => $shipment->last_tracked_at,
'can_cancel' => $shipment->canCancel(),
'is_delivered' => $shipment->isDelivered(),
@ -291,7 +294,7 @@ class DhlModalService
/**
* Get available countries for shipping
*
* @return \Illuminate\Database\Eloquent\Collection
* @return Collection
*/
private function getAvailableCountries()
{
@ -304,7 +307,7 @@ class DhlModalService
private function getAvailableProductCodes(): array
{
// Get DHL configuration with merged settings
$settingController = new \App\Http\Controllers\SettingController;
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
$productCodes = [];

View file

@ -8,6 +8,7 @@ use App\Http\Controllers\SettingController;
use App\Jobs\TrackShipmentJob;
use Carbon\CarbonInterface;
use Exception;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
@ -171,7 +172,7 @@ class DhlTrackingService
* structure, distinguishing the three outcomes the caller actually cares
* about: success, "not found", and "auth/transport error".
*
* @param \Illuminate\Http\Client\Response $response
* @param Response $response
* @return array<string, mixed>
*/
private function processSingleShipmentResponse(string $trackingNumber, $response): array
@ -332,7 +333,7 @@ class DhlTrackingService
/**
* Extract a `Retry-After` header value (in seconds) if DHL sent one.
*
* @param \Illuminate\Http\Client\Response $response
* @param Response $response
*/
private static function extractRetryAfter($response): ?int
{

View file

@ -5,27 +5,23 @@ namespace App\Services;
use App\Mail\MailLog;
use Illuminate\Support\Facades\Mail;
class MyLog
{
public static function writeLog($channel = 'payment', $context = 'error', $message = '', $data = [], $mail = true)
{
switch ($context) {
case 'notice':
\Log::channel($channel)->notice($message . ' : ' . json_encode($data));
\Log::channel($channel)->notice($message.' : '.json_encode($data));
break;
case 'warning':
\Log::channel($channel)->warning($message . ' : ' . json_encode($data));
\Log::channel($channel)->warning($message.' : '.json_encode($data));
break;
case 'info':
\Log::channel($channel)->info($message . ' : ' . json_encode($data));
\Log::channel($channel)->info($message.' : '.json_encode($data));
break;
default:
\Log::channel($channel)->error($message . ' : ' . json_encode($data));
\Log::channel($channel)->error($message.' : '.json_encode($data));
break;
}
if ($mail) {