20-02-2026

This commit is contained in:
Kevin Adametz 2026-02-20 17:55:06 +01:00
parent a8b395e20d
commit a00c42e770
252 changed files with 28785 additions and 8907 deletions

View file

@ -2,11 +2,11 @@
namespace App\Console\Commands;
use App\Models\Setting;
use Illuminate\Console\Command;
use App\Cron\BusinessUsersStore;
use App\Cron\UserLevelUpdate;
use App\Cron\UserPaymentCredits;
use App\Models\Setting;
use Illuminate\Console\Command;
class BusinessStore extends Command
{
@ -27,14 +27,15 @@ class BusinessStore extends Command
protected $description = 'Create Business Structure and UserDetails with optimized performance';
private $timeStart;
private $month;
private $year;
private $sendCreditMail = false;
private $sendUpdateMail = false;
/**
* Create a new command instance.
*
@ -45,6 +46,58 @@ class BusinessStore extends Command
parent::__construct();
}
/**
* Prüft ob der Command heute ausgeführt werden soll
*
* WICHTIG: Diese Methode verhindert, dass der Command täglich läuft!
* Der Command sollte nur am konfigurierten Tag des Monats laufen.
*
* @return bool True wenn Command ausgeführt werden soll, False sonst
*/
private function shouldExecuteToday(): bool
{
// Hole konfigurierten Ausführungstag (Standard: 1 = Monatserster)
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
// Fallback: Wenn Setting leer oder 0, verwende Tag 1
if ($executeDay === 0) {
$executeDay = 1;
$this->warn('Setting "day-exectute-business-structur" ist leer oder 0. Verwende Standard: Tag 1');
\Log::channel('cron')->warning('BusinessStore: Setting day-exectute-business-structur is empty, using default: 1');
}
$presentDay = (int) date('d');
// Logging für Debugging
$this->info("BusinessStore: Configured Day: {$executeDay}, Present Day: {$presentDay}");
\Log::channel('cron')->info("BusinessStore: Configured Day: {$executeDay}, Present Day: {$presentDay}");
// Prüfe ob heute der konfigurierte Tag ist
if ($executeDay !== $presentDay) {
// Erlaubnis zum Überschreiben für Entwicklung/Testing
// ENV-Variable BUSINESS_FORCE_EXECUTE=true überschreibt den Check
if (env('BUSINESS_FORCE_EXECUTE', false) === true) {
$this->warn('⚠️ BUSINESS_FORCE_EXECUTE ist aktiv - Command wird trotz falschem Tag ausgeführt!');
$this->warn('⚠️ Dies sollte NUR auf Test-Servern verwendet werden!');
\Log::channel('cron')->warning('BusinessStore: FORCED execution via BUSINESS_FORCE_EXECUTE');
return true;
}
// Command sollte heute NICHT laufen
$this->info("❌ Command wird NICHT ausgeführt - falscher Tag (erwartet: {$executeDay}, heute: {$presentDay})");
\Log::channel('cron')->info("BusinessStore: NOT EXECUTED - wrong day (expected: {$executeDay}, today: {$presentDay})");
return false;
}
// Command wird ausgeführt
$this->info("✅ Command wird ausgeführt - korrekter Tag ({$presentDay})");
\Log::channel('cron')->info("BusinessStore: EXECUTING - correct day ({$presentDay})");
return true;
}
/**
* Execute the console command.
*
@ -53,29 +106,21 @@ class BusinessStore extends Command
public function handle()
{
try {
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
$presentDay = (int) date('d');
$this->info('RUN Command BusinessStore on Day: ' . $executeDay);
$this->info('RUN Command BusinessStore present Day: ' . $presentDay);
\Log::channel('cron')->info('RUN Command BusinessStore on Day: ' . $executeDay);
\Log::channel('cron')->info('RUN Command BusinessStore present Day: ' . $presentDay);
$this->logMemoryUsage('Command Start');
if ($executeDay !== $presentDay) {
$this->info('NOT RUN Command BusinessStore is not present Day: ' . $presentDay);
\Log::channel('cron')->info('NOT RUN Command BusinessStore is not present Day: ' . $presentDay);
// Prüfe ob Command am richtigen Tag ausgeführt werden soll
if (! $this->shouldExecuteToday()) {
return 0;
}
$this->logMemoryUsage('Command Start');
$this->timeStart = microtime(true);
// Argumente mit Standardwerten für den Vormonat
$this->month = $this->argument('month') ?: (int) date("m", strtotime("-1 month"));
$this->year = $this->argument('year') ?: (int) date("Y", strtotime("-1 month"));
$this->month = $this->argument('month') ?: (int) date('m', strtotime('-1 month'));
$this->year = $this->argument('year') ?: (int) date('Y', strtotime('-1 month'));
$this->info('RUN Command BusinessStore on month: ' . $this->month . ' | year: ' . $this->year);
\Log::channel('cron')->info('RUN Command BusinessStore on month: ' . $this->month . ' | year: ' . $this->year);
$this->info('RUN Command BusinessStore on month: '.$this->month.' | year: '.$this->year);
\Log::channel('cron')->info('RUN Command BusinessStore on month: '.$this->month.' | year: '.$this->year);
$this->logMemoryUsage('Parameters initialized');
// Prozesse ausführen mit Fehlerbehandlung
@ -98,9 +143,10 @@ class BusinessStore extends Command
return 0;
} 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;
}
}
@ -108,25 +154,25 @@ class BusinessStore extends Command
private function storeBusinessStructureUsersDetailMonth()
{
$this->info('storeBusinessStructureUsersDetailMonth month: ' . $this->month . ' year:' . $this->year);
$this->info('storeBusinessStructureUsersDetailMonth month: '.$this->month.' year:'.$this->year);
$businessUsersStore = new BusinessUsersStore($this->month, $this->year);
$businessUsersStore->storeUserBusinessStructure();
$businessUsersStore->storeBusinessUsersDetail();
$bool = $businessUsersStore->storeBusinessCompleted();
$this->logExecutionTime('END Command storeBusinessStructureUsersDetailMonth: ' . $bool);
$this->logExecutionTime('END Command storeBusinessStructureUsersDetailMonth: '.$bool);
}
private function userBusinessCommissionsToCredit()
{
$this->info('userBusinessCommissionsToCredit month: ' . $this->month . ' year:' . $this->year);
$this->info('userBusinessCommissionsToCredit month: '.$this->month.' year:'.$this->year);
$userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
$userBusinesses = $userPaymentCredits->getUserBusinessByMonthYear();
foreach ($userBusinesses as $userBusiness) {
$ret = $userPaymentCredits->addUserCreditItem($userBusiness);
$this->info('userBusinessCredit: ' . $ret->user_id . ' : Team: ' . $ret->commission_pp_total . ' | Shop: ' . $ret->commission_shop_sales);
$this->info('userBusinessCredit: '.$ret->user_id.' : Team: '.$ret->commission_pp_total.' | Shop: '.$ret->commission_shop_sales);
}
$this->logExecutionTime('END Command userBusinessCommissionsToCredit:');
}
@ -134,13 +180,13 @@ class BusinessStore extends Command
private function userCreatePaymentCreditsPDF()
{
$this->info('userCreatePaymentCreditsPDF month: ' . $this->month . ' year:' . $this->year);
$this->info('userCreatePaymentCreditsPDF month: '.$this->month.' year:'.$this->year);
$userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
$creditItemUsers = $userPaymentCredits->getUserCreditItemUsersByMonthYear();
foreach ($creditItemUsers as $creditItemUser) {
$bool = $userPaymentCredits->makeCreditPaymentPDF($creditItemUser->user_id, $this->sendCreditMail);
$this->info('creditsPDF: ' . $bool . ' user_id: ' . $creditItemUser->user_id);
$this->info('creditsPDF: '.$bool.' user_id: '.$creditItemUser->user_id);
}
$this->logExecutionTime('END Command userCreatePaymentCreditsPDF:');
@ -149,7 +195,7 @@ class BusinessStore extends Command
private function userLevelUpdate()
{
$this->info('userLevelUpdate month: ' . $this->month . ' year:' . $this->year);
$this->info('userLevelUpdate month: '.$this->month.' year:'.$this->year);
$userLevelUpdate = new UserLevelUpdate($this->month, $this->year);
$levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
@ -157,26 +203,24 @@ class BusinessStore extends Command
foreach ($levelUpdateUsers as $userBusiness) {
$ret = $userLevelUpdate->makeUserLevelUpdate($userBusiness, $this->sendUpdateMail);
if ($ret) {
$this->info('updateLevel: ' . $userBusiness->user->id . ' | ' . $userBusiness->user->email . ' | ' .
'from: ' . $userBusiness->m_level_id . ' ' . $userBusiness->user_level_name . ' | ' .
'to: ' . $ret);
$this->info('updateLevel: '.$userBusiness->user->id.' | '.$userBusiness->user->email.' | '.
'from: '.$userBusiness->m_level_id.' '.$userBusiness->user_level_name.' | '.
'to: '.$ret);
}
}
$this->logExecutionTime('END Command userLevelUpdate:');
}
private function storeBusinessStructureUsersDetailPeriod($from, $to)
{
for ($i = $from; $i <= $to; $i++) {
$this->info('Store Business Structure Users Detail month: ' . $i . ' year:' . $this->year);
$this->info('Store Business Structure Users Detail month: '.$i.' year:'.$this->year);
$businessUsersStore = new BusinessUsersStore($i, $this->year);
$businessUsersStore->storeUserBusinessStructure();
$businessUsersStore->storeBusinessUsersDetail();
$bool = $businessUsersStore->storeBusinessCompleted();
$this->logExecutionTime('Period BusinessStore: ' . $bool);
$this->logExecutionTime('Period BusinessStore: '.$bool);
}
}
@ -186,6 +230,6 @@ class BusinessStore extends Command
$sec = intval($diff);
$micro = $diff - $sec;
$this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info($message.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
}

View file

@ -2,13 +2,13 @@
namespace App\Console\Commands;
use App\Models\Setting;
use App\Models\UserBusinessStructure;
use App\Models\UserBusiness;
use Illuminate\Console\Command;
use App\Cron\BusinessUsersStoreOptimized;
use App\Cron\UserLevelUpdate;
use App\Cron\UserPaymentCredits;
use App\Models\Setting;
use App\Models\UserBusiness;
use App\Models\UserBusinessStructure;
use Illuminate\Console\Command;
class BusinessStoreOptimized extends Command
{
@ -29,10 +29,13 @@ class BusinessStoreOptimized extends Command
protected $description = 'Create Business Structure and UserDetails with optimized performance and monitoring';
private $timeStart;
private $month;
private $year;
private $sendCreditMail = false;
private $sendUpdateMail = false;
/**
@ -51,6 +54,58 @@ class BusinessStoreOptimized extends Command
$this->sendUpdateMail = $sendUpdateMail;
}
/**
* Prüft ob der Command heute ausgeführt werden soll
*
* WICHTIG: Diese Methode verhindert, dass der Command täglich läuft!
* Der Command sollte nur am konfigurierten Tag des Monats laufen.
*
* @return bool True wenn Command ausgeführt werden soll, False sonst
*/
private function shouldExecuteToday(): bool
{
// Hole konfigurierten Ausführungstag (Standard: 1 = Monatserster)
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
// Fallback: Wenn Setting leer oder 0, verwende Tag 1
if ($executeDay === 0) {
$executeDay = 1;
$this->warn('Setting "day-exectute-business-structur" ist leer oder 0. Verwende Standard: Tag 1');
\Log::channel('cron')->warning('BusinessStoreOptimized: Setting day-exectute-business-structur is empty, using default: 1');
}
$presentDay = (int) date('d');
// Logging für Debugging
$this->info("BusinessStoreOptimized: Configured Day: {$executeDay}, Present Day: {$presentDay}");
\Log::channel('cron')->info("BusinessStoreOptimized: Configured Day: {$executeDay}, Present Day: {$presentDay}");
// Prüfe ob heute der konfigurierte Tag ist
if ($executeDay !== $presentDay) {
// Erlaubnis zum Überschreiben für Entwicklung/Testing
// ENV-Variable BUSINESS_FORCE_EXECUTE=true überschreibt den Check
if (env('BUSINESS_FORCE_EXECUTE', false) === true) {
$this->warn('⚠️ BUSINESS_FORCE_EXECUTE ist aktiv - Command wird trotz falschem Tag ausgeführt!');
$this->warn('⚠️ Dies sollte NUR auf Test-Servern verwendet werden!');
\Log::channel('cron')->warning('BusinessStoreOptimized: FORCED execution via BUSINESS_FORCE_EXECUTE');
return true;
}
// Command sollte heute NICHT laufen
$this->info("❌ Command wird NICHT ausgeführt - falscher Tag (erwartet: {$executeDay}, heute: {$presentDay})");
\Log::channel('cron')->info("BusinessStoreOptimized: NOT EXECUTED - wrong day (expected: {$executeDay}, today: {$presentDay})");
return false;
}
// Command wird ausgeführt
$this->info("✅ Command wird ausgeführt - korrekter Tag ({$presentDay})");
\Log::channel('cron')->info("BusinessStoreOptimized: EXECUTING - correct day ({$presentDay})");
return true;
}
/**
* Create a new command instance.
*
@ -69,28 +124,20 @@ class BusinessStoreOptimized extends Command
public function handle()
{
try {
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
$presentDay = (int) date('d');
$this->info('RUN Command BusinessStoreOptimized on Day: ' . $executeDay);
$this->info('RUN Command BusinessStoreOptimized present Day: ' . $presentDay);
\Log::channel('cron')->info('RUN Command BusinessStoreOptimized on Day: ' . $executeDay);
\Log::channel('cron')->info('RUN Command BusinessStoreOptimized present Day: ' . $presentDay);
$this->logMemoryUsage('Command Start');
if ($executeDay !== $presentDay) {
$this->info('NOT RUN Command BusinessStoreOptimized is not present Day: ' . $presentDay);
\Log::channel('cron')->info('NOT RUN Command BusinessStoreOptimized is not present Day: ' . $presentDay);
// return 0;
// Prüfe ob Command am richtigen Tag ausgeführt werden soll
if (! $this->shouldExecuteToday()) {
return 0;
}
$this->logMemoryUsage('Command Start');
$this->timeStart = microtime(true);
// Argumente mit Standardwerten für den Vormonat
$this->month = $this->argument('month') ?: (int) date("m", strtotime("-1 month"));
$this->year = $this->argument('year') ?: (int) date("Y", strtotime("-1 month"));
$this->month = $this->argument('month') ?: (int) date('m', strtotime('-1 month'));
$this->year = $this->argument('year') ?: (int) date('Y', strtotime('-1 month'));
$this->info('RUN Command BusinessStoreOptimized on month: ' . $this->month . ' | year: ' . $this->year);
$this->info('RUN Command BusinessStoreOptimized on month: '.$this->month.' | year: '.$this->year);
$this->logMemoryUsage('Parameters initialized');
// Prüfe --clear Option und lösche gespeicherte Daten falls gewünscht
@ -126,17 +173,18 @@ class BusinessStoreOptimized extends Command
return 0;
} 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');
\Log::channel('cron')->info('COMMAND FAILED');
return 1;
}
}
private function storeBusinessStructureUsersDetailMonth()
{
$this->info('storeBusinessStructureUsersDetailMonth month: ' . $this->month . ' year:' . $this->year);
$this->info('storeBusinessStructureUsersDetailMonth month: '.$this->month.' year:'.$this->year);
try {
$businessUsersStore = new BusinessUsersStoreOptimized($this->month, $this->year);
@ -144,16 +192,16 @@ class BusinessStoreOptimized extends Command
$businessUsersStore->storeBusinessUsersDetail();
$bool = $businessUsersStore->storeBusinessCompleted();
$this->logExecutionTime('END Command storeBusinessStructureUsersDetailMonth: ' . $bool);
$this->logExecutionTime('END Command storeBusinessStructureUsersDetailMonth: '.$bool);
} catch (\Exception $e) {
$this->error('Error in storeBusinessStructureUsersDetailMonth: ' . $e->getMessage());
$this->error('Error in storeBusinessStructureUsersDetailMonth: '.$e->getMessage());
throw $e;
}
}
private function userBusinessCommissionsToCredit()
{
$this->info('userBusinessCommissionsToCredit month: ' . $this->month . ' year:' . $this->year);
$this->info('userBusinessCommissionsToCredit month: '.$this->month.' year:'.$this->year);
try {
$userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
@ -162,7 +210,7 @@ class BusinessStoreOptimized extends Command
$processedCount = 0;
foreach ($userBusinesses as $userBusiness) {
$ret = $userPaymentCredits->addUserCreditItem($userBusiness);
$this->info('userBusinessCredit: ' . $ret->user_id . ' : Team: ' . $ret->commission_pp_total . ' | Shop: ' . $ret->commission_shop_sales);
$this->info('userBusinessCredit: '.$ret->user_id.' : Team: '.$ret->commission_pp_total.' | Shop: '.$ret->commission_shop_sales);
$processedCount++;
// Memory-Check alle 100 User
@ -174,14 +222,14 @@ class BusinessStoreOptimized extends Command
$this->info("Processed {$processedCount} user businesses total");
$this->logExecutionTime('END Command userBusinessCommissionsToCredit:');
} catch (\Exception $e) {
$this->error('Error in userBusinessCommissionsToCredit: ' . $e->getMessage());
$this->error('Error in userBusinessCommissionsToCredit: '.$e->getMessage());
throw $e;
}
}
private function userCreatePaymentCreditsPDF()
{
$this->info('userCreatePaymentCreditsPDF month: ' . $this->month . ' year:' . $this->year);
$this->info('userCreatePaymentCreditsPDF month: '.$this->month.' year:'.$this->year);
try {
$userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
@ -190,7 +238,7 @@ class BusinessStoreOptimized extends Command
$processedCount = 0;
foreach ($creditItemUsers as $creditItemUser) {
$bool = $userPaymentCredits->makeCreditPaymentPDF($creditItemUser->user_id, $this->sendCreditMail);
$this->info('creditsPDF: ' . $bool . ' user_id: ' . $creditItemUser->user_id);
$this->info('creditsPDF: '.$bool.' user_id: '.$creditItemUser->user_id);
$processedCount++;
// Memory-Check alle 50 PDFs
@ -202,7 +250,7 @@ class BusinessStoreOptimized extends Command
$this->info("Created {$processedCount} PDF files total");
$this->logExecutionTime('END Command userCreatePaymentCreditsPDF:');
} catch (\Exception $e) {
$this->error('Error in userCreatePaymentCreditsPDF: ' . $e->getMessage());
$this->error('Error in userCreatePaymentCreditsPDF: '.$e->getMessage());
throw $e;
}
}
@ -213,13 +261,13 @@ class BusinessStoreOptimized extends Command
*/
public function userLevelUpdate()
{
$this->info('userLevelUpdate month: ' . $this->month . ' year:' . $this->year);
$this->info('userLevelUpdate month: '.$this->month.' year:'.$this->year);
try {
$userLevelUpdate = new UserLevelUpdate($this->month, $this->year);
$levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
$this->info("Found " . $levelUpdateUsers->count() . " user businesses with level promotions to process");
$this->info('Found '.$levelUpdateUsers->count().' user businesses with level promotions to process');
$updatedCount = 0;
$skippedCount = 0;
@ -229,11 +277,11 @@ class BusinessStoreOptimized extends Command
try {
$ret = $userLevelUpdate->makeUserLevelUpdate($userBusiness, $this->sendUpdateMail);
if ($ret) {
$oldLevel = $userBusiness->m_level_id . ' ' . ($userBusiness->user_level_name ?? 'N/A');
$this->info('updateLevel: User ' . $userBusiness->user->id .
' | ' . $userBusiness->user->email .
' | from: ' . $oldLevel .
' | to: ' . $ret);
$oldLevel = $userBusiness->m_level_id.' '.($userBusiness->user_level_name ?? 'N/A');
$this->info('updateLevel: User '.$userBusiness->user->id.
' | '.$userBusiness->user->email.
' | from: '.$oldLevel.
' | to: '.$ret);
$updatedCount++;
} else {
$skippedCount++;
@ -241,12 +289,13 @@ class BusinessStoreOptimized extends Command
// Memory-Check alle 50 User
if (($updatedCount + $skippedCount) % 50 === 0) {
$this->logMemoryUsage("After processing " . ($updatedCount + $skippedCount) . " users");
$this->logMemoryUsage('After processing '.($updatedCount + $skippedCount).' users');
}
} catch (\Exception $e) {
$errorCount++;
$this->warn('Error updating level for UserBusiness ' . $userBusiness->id . ': ' . $e->getMessage());
\Log::channel('cron')->warning('UserLevelUpdate error for UserBusiness ' . $userBusiness->id . ': ' . $e->getMessage());
$this->warn('Error updating level for UserBusiness '.$userBusiness->id.': '.$e->getMessage());
\Log::channel('cron')->warning('UserLevelUpdate error for UserBusiness '.$userBusiness->id.': '.$e->getMessage());
// Weiter mit nächstem User statt abzubrechen
continue;
}
@ -256,9 +305,9 @@ class BusinessStoreOptimized extends Command
$this->logExecutionTime('END Command userLevelUpdate:');
$this->logMemoryUsage('After userLevelUpdate');
} catch (\Exception $e) {
$this->error('Error in userLevelUpdate: ' . $e->getMessage());
$this->error('Stack trace: ' . $e->getTraceAsString());
\Log::channel('cron')->error('UserLevelUpdate command failed: ' . $e->getMessage());
$this->error('Error in userLevelUpdate: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
\Log::channel('cron')->error('UserLevelUpdate command failed: '.$e->getMessage());
throw $e;
}
}
@ -267,7 +316,7 @@ class BusinessStoreOptimized extends Command
{
try {
for ($i = $from; $i <= $to; $i++) {
$this->info('Store Business Structure Users Detail month: ' . $i . ' year:' . $this->year);
$this->info('Store Business Structure Users Detail month: '.$i.' year:'.$this->year);
$this->logMemoryUsage("Before month {$i}");
$businessUsersStore = new BusinessUsersStoreOptimized($i, $this->year);
@ -275,11 +324,11 @@ class BusinessStoreOptimized extends Command
$businessUsersStore->storeBusinessUsersDetail();
$bool = $businessUsersStore->storeBusinessCompleted();
$this->logExecutionTime('Period BusinessStore: ' . $bool);
$this->logExecutionTime('Period BusinessStore: '.$bool);
$this->logMemoryUsage("After month {$i}");
}
} catch (\Exception $e) {
$this->error('Error in storeBusinessStructureUsersDetailPeriod: ' . $e->getMessage());
$this->error('Error in storeBusinessStructureUsersDetailPeriod: '.$e->getMessage());
throw $e;
}
}
@ -297,8 +346,9 @@ class BusinessStoreOptimized extends Command
->where('month', $this->month)
->first();
if (!$existingStructure) {
if (! $existingStructure) {
$this->info('No stored business structure found to clear');
return;
}
@ -322,7 +372,7 @@ class BusinessStoreOptimized extends Command
$this->info('Successfully cleared all stored business data');
$this->logMemoryUsage('After clearing data');
} catch (\Exception $e) {
$this->error('Error clearing stored data: ' . $e->getMessage());
$this->error('Error clearing stored data: '.$e->getMessage());
throw $e;
}
}
@ -333,7 +383,7 @@ class BusinessStoreOptimized extends Command
$sec = intval($diff);
$micro = $diff - $sec;
$this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info($message.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
/**
@ -353,8 +403,8 @@ class BusinessStoreOptimized extends Command
$this->info("Completed: {$processName} in {$duration}ms");
$this->logMemoryUsage("After {$processName}");
} catch (\Exception $e) {
$this->error("Error in {$processName}: " . $e->getMessage());
$this->error("Stack trace: " . $e->getTraceAsString());
$this->error("Error in {$processName}: ".$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
throw $e;
}
}
@ -406,12 +456,12 @@ class BusinessStoreOptimized 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

@ -17,18 +17,20 @@ class DhlUpdateTracking extends Command
* @var string
*/
protected $signature = 'dhl:update-tracking
{--days=14 : Sendungen der letzten X Tage aktualisieren}
{--days=30 : Sendungen der letzten X Tage aktualisieren}
{--send-emails : Automatisch E-Mails bei Transit-Status senden}
{--dry-run : Nur simulieren, keine Änderungen}
{--test-email= : Test-E-Mail an angegebene Adresse senden}
{--order= : Nur für bestimmte Bestellung (Order-ID)}';
{--order= : Nur für bestimmte Bestellung (Order-ID)}
{--force : Intervall-Filter überspringen, alle aktiven Sendungen aktualisieren}
{--stale-days=30 : Sendungen ohne Statusänderung nach X Tagen als abgeschlossen markieren}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Aktualisiert Tracking-Status für alle aktiven DHL Sendungen und sendet automatisch E-Mails bei Transit-Status';
protected $description = 'Aktualisiert Tracking-Status für DHL Sendungen (status-basierte Intervalle, Batch-API)';
/**
* Execute the console command.
@ -40,9 +42,14 @@ class DhlUpdateTracking extends Command
$dryRun = $this->option('dry-run');
$testEmail = $this->option('test-email');
$orderId = $this->option('order');
$force = $this->option('force');
$staleDays = (int) $this->option('stale-days');
$this->info('DHL Tracking Update gestartet');
$this->info("Optionen: --days={$days}, --send-emails=" . ($sendEmails ? 'ja' : 'nein') . ', --dry-run=' . ($dryRun ? 'ja' : 'nein'));
$this->info("Optionen: --days={$days}, --send-emails=".($sendEmails ? 'ja' : 'nein')
.', --dry-run='.($dryRun ? 'ja' : 'nein')
.', --force='.($force ? 'ja' : 'nein')
.", --stale-days={$staleDays}");
if ($testEmail) {
$this->info("Test-Modus: E-Mails werden an {$testEmail} gesendet");
}
@ -51,95 +58,185 @@ class DhlUpdateTracking extends Command
}
$this->newLine();
// Hole alle aktiven Sendungen der letzten X Tage
$query = DhlShipment::active()
// Step 1: Mark stale shipments as completed (before main query)
$staleCompleted = $this->markStaleShipmentsCompleted($staleDays, $dryRun);
// Step 2: Build query for shipments that need tracking update
$query = $this->buildShipmentQuery($days, $orderId, $force);
$shipments = $query->orderBy('created_at', 'desc')->get();
// Count total active shipments for statistics (before interval filter)
$totalActive = DhlShipment::active()
->whereNull('tracking_completed_at')
->where('created_at', '>=', now()->subDays($days))
->whereNotNull('dhl_shipment_no');
->whereNotNull('dhl_shipment_no')
->count();
$total = $shipments->count();
$skippedByInterval = $totalActive - $total;
$this->info("Aktive Sendungen gesamt: {$totalActive}");
$this->info('Übersprungen (Intervall): '.max(0, $skippedByInterval));
$this->info("Zu aktualisieren: {$total}");
if ($total === 0) {
$this->info('Keine Sendungen zum Aktualisieren gefunden.');
$this->printSummary(0, ['updated' => 0, 'failed' => 0, 'completed' => 0, 'emails_sent' => 0, 'skipped' => 0], $staleCompleted, max(0, $skippedByInterval));
return self::SUCCESS;
}
$trackingService = new DhlTrackingService;
$stats = [
'updated' => 0,
'failed' => 0,
'completed' => 0,
'emails_sent' => 0,
'skipped' => 0,
];
if ($dryRun) {
$stats['skipped'] = $total;
$this->info("Dry-Run: {$total} Sendungen würden aktualisiert.");
} else {
// Collect old statuses for email decision
$oldStatuses = $shipments->pluck('status', 'id')->toArray();
// Use batch API for efficient processing
$this->info('Starte Batch-Tracking-Update...');
$bar = $this->output->createProgressBar($total);
$bar->start();
$batchResult = $trackingService->updateTrackingBatch($shipments);
$stats['updated'] = $batchResult['updated'];
$stats['failed'] = $batchResult['failed'];
$stats['completed'] = $batchResult['completed'];
$bar->advance($total);
$bar->finish();
$this->newLine(2);
// Send tracking emails if enabled
if ($sendEmails) {
$this->info('Prüfe E-Mail-Versand...');
foreach ($shipments as $shipment) {
$shipment->refresh();
$oldStatus = $oldStatuses[$shipment->id] ?? '';
if ($this->shouldSendEmail($shipment, $oldStatus)) {
try {
$this->sendTrackingEmail($shipment, $testEmail);
$stats['emails_sent']++;
} catch (\Exception $e) {
Log::error('[DHL Cron] Failed to send tracking email', [
'shipment_id' => $shipment->id,
'error' => $e->getMessage(),
]);
}
}
}
}
}
$this->printSummary($total, $stats, $staleCompleted, max(0, $skippedByInterval));
Log::info('[DHL Cron] Tracking update completed', array_merge($stats, [
'total' => $total,
'stale_completed' => $staleCompleted,
'skipped_interval' => max(0, $skippedByInterval),
]));
return self::SUCCESS;
}
/**
* Build the shipment query with or without interval filtering.
*/
private function buildShipmentQuery(int $days, ?string $orderId, bool $force)
{
if ($force) {
// --force: Alle aktiven Sendungen ohne Intervall-Filter
$query = DhlShipment::active()
->whereNull('tracking_completed_at')
->where('created_at', '>=', now()->subDays($days))
->whereNotNull('dhl_shipment_no');
} else {
// Normal: Status-basierte Intervalle beachten
$query = DhlShipment::needsTrackingUpdate()
->where('created_at', '>=', now()->subDays($days));
}
// Filter nach Order-ID wenn angegeben
if ($orderId) {
$query->where('order_id', $orderId);
}
$shipments = $query->orderBy('created_at', 'desc')->get();
return $query;
}
$total = $shipments->count();
$this->info("Gefundene aktive Sendungen: {$total}");
/**
* Mark shipments as tracking-completed if they haven't changed status
* for a given number of days (stale shipments).
*/
private function markStaleShipmentsCompleted(int $staleDays, bool $dryRun): int
{
$staleShipments = DhlShipment::active()
->whereNull('tracking_completed_at')
->whereNotNull('last_tracked_at')
->where('last_tracked_at', '<', now()->subDays($staleDays))
->where('created_at', '<', now()->subDays($staleDays))
->get();
if ($total === 0) {
$this->info('Keine Sendungen zum Aktualisieren gefunden.');
$count = $staleShipments->count();
return self::SUCCESS;
}
if ($count > 0) {
$this->warn("Veraltete Sendungen gefunden: {$count} (>{$staleDays} Tage ohne Änderung)");
$bar = $this->output->createProgressBar($total);
$bar->start();
if (! $dryRun) {
foreach ($staleShipments as $shipment) {
$shipment->markTrackingCompleted();
$trackingService = new DhlTrackingService;
$stats = [
'updated' => 0,
'failed' => 0,
'emails_sent' => 0,
'skipped' => 0,
];
foreach ($shipments as $shipment) {
try {
$oldStatus = $shipment->status;
if (! $dryRun) {
// Tracking aktualisieren
$result = $trackingService->updateTracking($shipment, ['auto_retrack' => false]);
if ($result['success']) {
$shipment->refresh();
$stats['updated']++;
// Prüfen ob E-Mail gesendet werden soll
if ($sendEmails && $this->shouldSendEmail($shipment, $oldStatus)) {
$this->sendTrackingEmail($shipment, $testEmail);
$stats['emails_sent']++;
}
} else {
$stats['failed']++;
Log::warning('[DHL Cron] Tracking update failed', [
'shipment_id' => $shipment->id,
'message' => $result['message'] ?? 'Unknown error',
]);
}
} else {
$stats['skipped']++;
Log::info('[DHL Cron] Stale shipment tracking completed', [
'shipment_id' => $shipment->id,
'dhl_shipment_no' => $shipment->dhl_shipment_no,
'status' => $shipment->status,
'last_tracked_at' => $shipment->last_tracked_at?->toDateTimeString(),
]);
}
} catch (\Exception $e) {
$stats['failed']++;
Log::error('[DHL Cron] Exception during tracking update', [
'shipment_id' => $shipment->id,
'error' => $e->getMessage(),
]);
}
$bar->advance();
$this->info("{$count} Sendungen als Tracking-abgeschlossen markiert.");
} else {
$this->info(" → Dry-Run: {$count} Sendungen würden als abgeschlossen markiert.");
}
}
$bar->finish();
$this->newLine(2);
$this->newLine();
// Zusammenfassung
return $count;
}
/**
* Print the final summary table.
*/
private function printSummary(int $total, array $stats, int $staleCompleted, int $skippedByInterval): void
{
$this->info('Zusammenfassung:');
$this->table(
['Metrik', 'Anzahl'],
[
['Gesamt', $total],
['Zu aktualisieren', $total],
['Aktualisiert', $stats['updated']],
['Fehlgeschlagen', $stats['failed']],
['Tracking abgeschlossen', $stats['completed']],
['E-Mails gesendet', $stats['emails_sent']],
['Übersprungen (Dry-Run)', $stats['skipped']],
['Übersprungen (Intervall)', $skippedByInterval],
['Veraltet → abgeschlossen', $staleCompleted],
]
);
Log::info('[DHL Cron] Tracking update completed', $stats);
return self::SUCCESS;
}
/**
@ -212,9 +309,9 @@ class DhlUpdateTracking extends Command
]);
if ($allShipments->count() > 1) {
$this->line(" -> E-Mail mit {$allShipments->count()} Sendungen gesendet an: {$recipientEmail}");
$this->line(" E-Mail mit {$allShipments->count()} Sendungen gesendet an: {$recipientEmail}");
} else {
$this->line(" -> E-Mail gesendet an: {$recipientEmail}");
$this->line(" E-Mail gesendet an: {$recipientEmail}");
}
} catch (\Exception $e) {
Log::error('[DHL Cron] Failed to send tracking email', [

View file

@ -0,0 +1,119 @@
<?php
namespace App\Console\Commands;
use App\Models\ShoppingInstance;
use App\Models\ShoppingPayment;
use Illuminate\Console\Command;
class FixPaymentLinkStatus extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'payment:fix-link-status {--dry-run : Run without making changes}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Fix payment link status for paid orders that have incorrect status in shopping_instances';
/**
* Execute the console command.
*/
public function handle()
{
$isDryRun = $this->option('dry-run');
if ($isDryRun) {
$this->info(' DRY RUN MODE - No changes will be made');
$this->newLine();
}
$this->info('🔎 Searching for payment links with incorrect status...');
$this->newLine();
// Find all ShoppingPayments with identifier that are paid
$paidPayments = ShoppingPayment::whereNotNull('identifier')
->whereHas('shopping_order', function ($query) {
$query->where('paid', 1)
->where('txaction', 'paid');
})
->with(['shopping_order'])
->get();
$this->info("Found {$paidPayments->count()} paid payments with identifiers");
$this->newLine();
$fixed = 0;
$skipped = 0;
$errors = 0;
foreach ($paidPayments as $payment) {
$identifier = $payment->identifier;
// Find the corresponding ShoppingInstance
$instance = ShoppingInstance::where('identifier', $identifier)->first();
if (! $instance) {
$this->warn("⚠️ ShoppingInstance not found for identifier: {$identifier}");
$errors++;
continue;
}
// Check if status needs to be updated
if ($instance->status < 10) {
$oldStatus = $instance->status;
$oldStatusName = $instance->getStatus();
if (! $isDryRun) {
$instance->status = 10; // link_paid
$instance->save();
}
$this->line(sprintf(
'%s Payment #%d: %s → %s (Order #%d, Amount: %s)',
$isDryRun ? '📋' : '✅',
$payment->id,
$oldStatusName." ($oldStatus)",
'link_paid (10)',
$payment->shopping_order_id,
$payment->getPaymentAmount()
));
$fixed++;
} else {
$skipped++;
}
}
$this->newLine();
$this->info('📊 Summary:');
$this->table(
['Status', 'Count'],
[
['Fixed/Would fix', $fixed],
['Already correct', $skipped],
['Errors', $errors],
['Total processed', $paidPayments->count()],
]
);
if ($isDryRun && $fixed > 0) {
$this->newLine();
$this->warn('⚠️ This was a DRY RUN. Run without --dry-run to apply changes.');
}
if (! $isDryRun && $fixed > 0) {
$this->newLine();
$this->info("✨ Successfully updated {$fixed} payment link(s)!");
}
return 0;
}
}

View file

@ -2,17 +2,14 @@
namespace App\Console\Commands;
use App\Services\UserUtil;
use App\User;
use Carbon\Carbon;
use App\Services\UserUtil;
use Illuminate\Console\Command;
class UserCleanUp extends Command
{
/**
* ln -sfv /usr/bin/php73 /usr/bin/php
* php74 artisan user:cleanup
* The name and signature of the console command.
*
* @var string
@ -24,7 +21,8 @@ class UserCleanUp extends Command
*
* @var string
*/
protected $description = 'User Clean Up inactive for Business Structur and UserDetails';
protected $description = 'User Clean Up inactive for Business Structure and UserDetails';
private $timeStart;
/**
@ -44,118 +42,162 @@ class UserCleanUp extends Command
*/
public function handle()
{
$this->info('RUN Command user:cleanup');
\Log::channel('cleanup')->info('COMMAND [user:cleanup] started.');
$this->timeStart = microtime(true);
$this->deleteInavtiveUsers();
//alle inaktive User werden deaktivert, die childs werden dem nächsten aktiven Berater (parent) zugewiesen.
// Schritt 1: User löschen, die länger als 2 Monate inaktiv sind
$this->deleteInactiveUsers();
// Schritt 2: Alle inaktiven User deaktivieren (länger als 2 Wochen inaktiv)
// Ihre Downline wird dem nächsten aktiven Berater (Sponsor) zugewiesen
$this->cleanUpInActiveUser();
return 0;
\Log::channel('cleanup')->info('COMMAND [user:cleanup] finished.');
//return 0;
return 0;
}
//gibt es gelöschte Berater mit Kunden und childs???
private function deleteInavtiveUsers()
/**
* Löscht User, die länger als 2 Monate inaktiv sind (payment_account < -2 month)
* - Weist deren Vertriebspartner-Kinder dem nächsten aktiven Sponsor zu
* - Überträgt deren Shopping-Kunden zum neuen Sponsor
* - Konvertiert den User zu einem Shopping-Kunden
* - Löscht den User (soft delete)
*/
private function deleteInactiveUsers()
{
$this->info('START Command deleteInavtiveUsers');
$methodStartTime = microtime(true);
$this->info('START Command deleteInactiveUsers');
$count = 0;
$date = Carbon::now()->modify('-2 month');
$delete_users = User::where('admin', 0)->where('payment_account', '<', $date)->get();
foreach ($delete_users as $delete_user) {
/*
dump('delete_users ---------- ');
dump($delete_user->id);
dump($delete_user->email);
*/
//finde nächsten aktiven Sponsor $delete_user->id kann sponsor oder pre sponsor sein
$active_sponsor = UserUtil::findNextActiveSponsor($delete_user->id);
if ($active_sponsor) {
//setze alle Berater vom Sponsor für alle childs
\DB::beginTransaction();
try {
// Finde nächsten aktiven Sponsor
$active_sponsor = UserUtil::findNextActiveSponsor($delete_user->id);
if (! $active_sponsor) {
\Log::channel('cleanup')->error('deleteInactiveUsers find no active_sponsor by delete_user_id: '.$delete_user->id);
\DB::rollBack();
continue;
}
// Prüfe ob User Account-Daten hat
if (! $delete_user->account) {
\Log::channel('cleanup')->error('deleteInactiveUsers: User has no account data, skipping user_id: '.$delete_user->id);
\DB::rollBack();
continue;
}
// Setze alle Vertriebspartner-Kinder zum neuen Sponsor
UserUtil::setNewSponsorToChilds($delete_user->id, $active_sponsor->id);
// Übertrage Shopping-User zum neuen Sponsor
UserUtil::setShoppingUserToNewMember($delete_user->id, $active_sponsor->id);
} else {
\Log::channel('cleanup')->error('deleteInavtiveUsers find no active_sponsor by delete_user_id:' . $delete_user->id);
// Konvertiere User zu Client beim neuen Sponsor
UserUtil::setUserToClient($delete_user->id, $active_sponsor->id);
$data = [
'user_id' => $delete_user->id,
'email' => $delete_user->email,
'm_account' => $delete_user->account->m_account,
'm_first_name' => $delete_user->account->m_first_name,
'm_last_name' => $delete_user->account->m_last_name,
];
// Lösche User (soft delete)
UserUtil::deleteUser($delete_user);
\DB::commit();
$count++;
\Log::channel('cleanup')->info('deleteUser: '.json_encode($data));
} catch (\Exception $e) {
\DB::rollBack();
\Log::channel('cleanup')->error('deleteInactiveUsers failed for user_id: '.$delete_user->id.' | Error: '.$e->getMessage());
continue;
}
/*
dump('findNextActiveSponsor');
dump($active_sponsor->email);
*/
//make User to an Client from sponsor and delete User
UserUtil::setUserToClient($delete_user->id, $active_sponsor->id);
$data = [
'user_id' => $delete_user->id,
'email' => $delete_user->email,
'm_account' => $delete_user->account ? $delete_user->account->m_account : '',
'm_first_name' => $delete_user->account ? $delete_user->account->m_first_name : '',
'm_last_name' => $delete_user->account ? $delete_user->account->m_last_name : '',
];
$count++;
\Log::channel('cleanup')->info('deleteUser: ' . json_encode($data));
UserUtil::deleteUser($delete_user);
}
$diff = microtime(true) - $this->timeStart;
$diff = microtime(true) - $methodStartTime;
$sec = intval($diff);
$micro = $diff - $sec;
$this->info('END Command deleteInavtiveUsers: ' . $count . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info('END Command deleteInactiveUsers: '.$count.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
/**
* Deaktiviert User, die länger als 2 Wochen inaktiv sind
* - Weist deren Vertriebspartner-Kinder dem nächsten aktiven Sponsor zu
* - Deaktiviert den User (behält Account, speichert Sponsor in pre_sponsor)
* - Shopping-Kunden werden NICHT übertragen (bleiben beim deaktivierten User)
*/
private function cleanUpInActiveUser()
{
$methodStartTime = microtime(true);
$this->info('START Command cleanUpInActiveUser');
$count = 0;
//clean up user where inactive since 2 weeks
// Finde User die länger als 2 Wochen inaktiv sind
$date = Carbon::now()->modify('-2 weeks');
$inactive_users = User::where('active', true)->where('m_sponsor', '!=', null)->where('payment_account', '<', $date)->get();
foreach ($inactive_users as $inactive_user) {
/*
dump('inactive_user ---------- ');
dump($inactive_user->id);
dump($inactive_user->email);
*/
$active_sponsor = UserUtil::findNextActiveSponsor($inactive_user->m_sponsor);
if ($active_sponsor) {
UserUtil::setNewSponsorToChilds($inactive_user->id, $active_sponsor->id);
} else {
\Log::channel('cleanup')->error('cleanUpInActiveUser find no active_sponsor by inactive_user:' . $inactive_user->id);
}
/*
dump('findNextActiveSponsor');
dump($active_sponsor->email);
*/
$data = [
'user_id' => $inactive_user->id,
'email' => $inactive_user->email,
'm_account' => $inactive_user->account ? $inactive_user->account->m_account : '',
'm_first_name' => $inactive_user->account ? $inactive_user->account->m_first_name : '',
'm_last_name' => $inactive_user->account ? $inactive_user->account->m_last_name : '',
];
$count++;
$inactive_users = User::where('active', true)
->where('m_sponsor', '!=', null)
->where('payment_account', '<', $date)
->get();
\Log::channel('cleanup')->info('inactive_user: ' . json_encode($data));
UserUtil::deactiveUser($inactive_user);
foreach ($inactive_users as $inactive_user) {
\DB::beginTransaction();
try {
// Finde nächsten aktiven Sponsor
$active_sponsor = UserUtil::findNextActiveSponsor($inactive_user->m_sponsor);
if (! $active_sponsor) {
\Log::channel('cleanup')->error('cleanUpInActiveUser find no active_sponsor by inactive_user: '.$inactive_user->id);
\DB::rollBack();
continue;
}
// Setze alle Vertriebspartner-Kinder zum neuen Sponsor
UserUtil::setNewSponsorToChilds($inactive_user->id, $active_sponsor->id);
$data = [
'user_id' => $inactive_user->id,
'email' => $inactive_user->email,
'm_account' => $inactive_user->account ? $inactive_user->account->m_account : '',
'm_first_name' => $inactive_user->account ? $inactive_user->account->m_first_name : '',
'm_last_name' => $inactive_user->account ? $inactive_user->account->m_last_name : '',
];
// Deaktiviere User (setzt pre_sponsor, entfernt m_sponsor, setzt active=false)
UserUtil::deactiveUser($inactive_user);
\DB::commit();
$count++;
\Log::channel('cleanup')->info('inactive_user: '.json_encode($data));
} catch (\Exception $e) {
\DB::rollBack();
\Log::channel('cleanup')->error('cleanUpInActiveUser failed for user_id: '.$inactive_user->id.' | Error: '.$e->getMessage());
continue;
}
}
$diff = microtime(true) - $this->timeStart;
$diff = microtime(true) - $methodStartTime;
$sec = intval($diff);
$micro = $diff - $sec;
$this->info('END Command cleanUpInActiveUser: ' . $count . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info('END Command cleanUpInActiveUser: '.$count.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
}

View file

@ -2,17 +2,13 @@
namespace App\Console\Commands;
use App\User;
use Carbon\Carbon;
use App\Services\UserUtil;
use App\User;
use Illuminate\Console\Command;
class UserRestore extends Command
{
/**
* ln -sfv /usr/bin/php73 /usr/bin/php
* php artisan user:restore {user_id}
* The name and signature of the console command.
*
* @var string
@ -24,9 +20,9 @@ class UserRestore extends Command
*
* @var string
*/
protected $description = 'User Restore active User where inactive for Business Structur and UserDetails';
protected $description = 'User Restore: Reactivates an inactive user and restores their downline structure';
private $timeStart;
private $user_id;
/**
* Create a new command instance.
@ -45,68 +41,95 @@ class UserRestore extends Command
*/
public function handle()
{
$this->info('RUN Command user:restore');
\Log::channel('cleanup')->info('COMMAND [user:restore] started.');
$this->timeStart = microtime(true);
$this->restoreInavtiveUsers();
return 0;
//\Log::info('Cron is running');
//return 0;
$result = $this->restoreInactiveUsers();
\Log::channel('cleanup')->info('COMMAND [user:restore] finished.');
return $result;
}
//gibt es gelöschte Berater mit Kunden und childs???
private function restoreInavtiveUsers(){
/**
* Stellt einen deaktivierten User wieder her
* - Reaktiviert den User (setzt active=true, stellt m_sponsor wieder her)
* - Stellt die Vertriebspartner-Kinder (Downline) wieder her
* - Nutzt UserCleanUpLog um die ursprüngliche Struktur wiederherzustellen
*
* @return int
*/
private function restoreInactiveUsers()
{
$methodStartTime = microtime(true);
$this->info('START Command restoreInactiveUsers');
$this->info('START Command restoreInavtiveUsers');
$count = 0;
$user_id = $this->argument('user_id');
$this->user_id = $this->argument('user_id');
if (! $user_id) {
$this->error('ERROR: No user_id provided as argument');
\Log::channel('cleanup')->error('restoreInactiveUsers: No user_id provided');
if(!$this->user_id){
$this->info('NO user_id as argument');
return;
return 1;
}
$this->info('RUN Command restoreInavtiveUsers on user_id: '.$this->user_id);
$this->info('Restoring user with ID: '.$user_id);
$user = User::find($this->user_id);
$user = User::find($user_id);
if (! $user) {
$this->error('ERROR: User not found with ID: '.$user_id);
\Log::channel('cleanup')->error('restoreInactiveUsers: User not found, user_id: '.$user_id);
return 1;
}
// Prüfe ob User bereits aktiv ist
if ($user->active) {
$this->warn('WARNING: User is already active, user_id: '.$user_id);
\Log::channel('cleanup')->warning('restoreInactiveUsers: User is already active, user_id: '.$user_id);
if(!$user){
$this->info('restoreInavtiveUsers find no user by user_id:'.$this->user_id);
\Log::channel('cleanup')->error('restoreInavtiveUsers find no user by user_id:'.$this->user_id);
return 0;
}
$data = [
'user_id' => $user->id,
'email' => $user->email,
'm_account' => $user->account ? $user->account->m_account : '',
'm_first_name' => $user->account ? $user->account->m_first_name : '',
'm_last_name' => $user->account ? $user->account->m_last_name : '',
];
\Log::channel('cleanup')->info('reactiveUser: '.json_encode($data));
\DB::beginTransaction();
UserUtil::reactiveUser($user);
//childs wieder herstellen
UserUtil::resetChildsToSponsor($user->id);
try {
$data = [
'user_id' => $user->id,
'email' => $user->email,
'm_account' => $user->account ? $user->account->m_account : '',
'm_first_name' => $user->account ? $user->account->m_first_name : '',
'm_last_name' => $user->account ? $user->account->m_last_name : '',
];
// Reaktiviere User (setzt active=true, stellt m_sponsor aus pre_sponsor wieder her)
UserUtil::reactiveUser($user);
$diff = microtime(true) - $this->timeStart;
$sec = intval($diff);
$micro = $diff - $sec;
// Stelle alle Vertriebspartner-Kinder wieder her
UserUtil::resetChildsToSponsor($user->id);
$this->info('END Command deleteInavtiveUsers: '.$count. ' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");
\DB::commit();
$diff = microtime(true) - $methodStartTime;
$sec = intval($diff);
$micro = $diff - $sec;
$this->info('SUCCESS: User restored successfully');
$this->info('END Command restoreInactiveUsers | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
\Log::channel('cleanup')->info('restoreInactiveUsers SUCCESS: '.json_encode($data));
return 0;
} catch (\Exception $e) {
\DB::rollBack();
$this->error('ERROR: Failed to restore user: '.$e->getMessage());
\Log::channel('cleanup')->error('restoreInactiveUsers FAILED for user_id: '.$user_id.' | Error: '.$e->getMessage());
return 1;
}
}
}
//497
//489 -> de
//478 new

View file

@ -47,9 +47,9 @@ class Kernel extends ConsoleKernel
// Cleanup old log files weekly (keeps logs for 30 days)
$schedule->command('logs:cleanup --days=30')->weekly()->sundays()->at('05:00');
// DHL Tracking Update: Täglich um 06:00 Uhr, automatische E-Mails bei Transit-Status
$schedule->command('dhl:update-tracking --days=14 --send-emails')
->dailyAt('06:00')
// DHL Tracking Update: Stündlich mit status-basierten Intervallen und Batch-API
$schedule->command('dhl:update-tracking --days=30 --send-emails')
->hourly()
->withoutOverlapping()
->runInBackground();
}

View file

@ -2,13 +2,13 @@
namespace App\Http\Controllers\Admin;
use Request;
use App\Services\Shop;
use App\Models\UserAbo;
use App\Services\AboOrderCart;
use App\Repositories\AboRepository;
use App\Http\Controllers\Controller;
use App\Models\UserAbo;
use App\Repositories\AboRepository;
use App\Services\AboItemHistoryService;
use App\Services\AboOrderCart;
use App\Services\Shop;
use Request;
class AboController extends Controller
{
@ -26,26 +26,27 @@ class AboController extends Controller
set_user_attr('filter_user_shop_id', null);
set_user_attr('filter_status', null);
set_user_attr('filter_member_id', null);
return redirect(route('admin_sales_customers'));
}
//$filter_user_shops = UserAbo::join('user_shops', 'user_shop_id', '=', 'user_shops.id')->orderBy('slug')->get()->pluck('slug', 'id')->unique()->toArray();
// $filter_user_shops = UserAbo::join('user_shops', 'user_shop_id', '=', 'user_shops.id')->orderBy('slug')->get()->pluck('slug', 'id')->unique()->toArray();
$filter_members = UserAbo::join('users', 'user_id', '=', 'users.id')->groupBy('user_id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->get();
$data = [
//'filter_user_shops' => $filter_user_shops,
// 'filter_user_shops' => $filter_user_shops,
'filter_members' => $filter_members,
];
return view('admin.abo.index', $data);
}
public function detail($id)
{
$data = Request::all();
$user_abo = UserAbo::findOrFail($id);
//init Yard
// init Yard
AboOrderCart::initYard($user_abo);
$customer_detail = AboOrderCart::getCustomerDetail();
AboOrderCart::makeOrderYard($user_abo);
@ -62,10 +63,10 @@ class AboController extends Controller
'view' => $user_abo->is_for,
'comp_products' => $comp_products,
];
return view('admin.abo.detail', $data);
}
public function update($id)
{
$data = Request::all();
@ -74,29 +75,51 @@ class AboController extends Controller
$user_abo = UserAbo::findOrFail($data['id']);
$this->aboRepository->setModel($user_abo);
$this->aboRepository->update($data);
return redirect(route('admin_abos_detail', [$id]));
}
}
}
public function rollback($id)
{
$user_abo = UserAbo::findOrFail($id);
AboOrderCart::initYard($user_abo);
$success = AboItemHistoryService::rollbackToInitial($user_abo);
if ($success) {
$user_abo->refresh();
AboOrderCart::makeOrderYard($user_abo);
AboOrderCart::checkNumOfCompProducts($user_abo);
\Session()->flash('alert-success', __('abo_history.rollback_success'));
} else {
\Session()->flash('alert-error', __('abo_history.rollback_no_data'));
}
return redirect(route('admin_abos_detail', [$id]));
}
public function datatable()
{
$query = UserAbo::with('user_abo_orders')->with('shopping_user')->select('user_abos.*');
set_user_attr('filter_member_id', Request::get('filter_member_id'));
if (Request::get('filter_member_id') != "") {
if (Request::get('filter_member_id') != '') {
$query->where('user_id', '=', Request::get('filter_member_id'));
}
set_user_attr('filter_status', Request::get('filter_status'));
if (Request::get('filter_status') != "") {
if (Request::get('filter_status') != '') {
$query->where('status', '=', Request::get('filter_status'));
}
return \DataTables::eloquent($query)
->addColumn('id', function (UserAbo $user_abo) {
return '<a href="' . route('admin_abos_detail', [$user_abo->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('admin_abos_detail', [$user_abo->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('start_date', function (UserAbo $user_abo) {
return $user_abo->start_date;
@ -121,14 +144,14 @@ class AboController extends Controller
return $user_abo->getCountOrders();
})
->addColumn('amount', function (UserAbo $user_abo) {
return $user_abo->getFormattedAmount() . ' €';
return $user_abo->getFormattedAmount().' €';
})
->addColumn('payment', function (UserAbo $user_abo) {
return $user_abo->getPaymentType();
})
->addColumn('member', function (UserAbo $user_abo) {
if (isset($user_abo->shopping_user) && $user_abo->shopping_user->member_id > 0) {
return '<a href="' . route('admin_lead_edit', [$user_abo->shopping_user->member_id]) . '">' . $user_abo->shopping_user->member->getFullName() . '</a>';
return '<a href="'.route('admin_lead_edit', [$user_abo->shopping_user->member_id]).'">'.$user_abo->shopping_user->member->getFullName().'</a>';
}
})
->addColumn('payone_userid', function (UserAbo $user_abo) {

View file

@ -2,21 +2,20 @@
namespace App\Http\Controllers\Admin;
use Util;
use Response;
use Request;
use App\Models\DcTag;
use App\Models\DcFile;
use App\Models\DcCategory;
use App\Http\Controllers\Controller;
use App\Repositories\DC\TagRepository;
use App\Models\DcCategory;
use App\Models\DcFile;
use App\Models\DcTag;
use App\Repositories\DC\FileRepository;
use App\Repositories\DC\TagRepository;
use Request;
use Response;
use Util;
class DownloadController extends Controller
{
protected $tagRepository;
protected $fileRepository;
public function __construct(TagRepository $tagRepository, FileRepository $fileRepository)
@ -26,139 +25,160 @@ class DownloadController extends Controller
$this->fileRepository = $fileRepository;
}
public function files(){
$q = DcFile::orderBy('id', 'desc')->get(); //File::all();
public function files()
{
$q = DcFile::orderBy('id', 'desc')->get(); // File::all();
$data = [
'files' => $q,
];
return view('admin.downloadcenter.files', $data);
}
public function fileEdit($id = null){
public function fileEdit($id = null)
{
$file = $id ? DcFile::find($id) : new DcFile;
$data = [
'file' => $file,
'categories' => DcCategory::where('active', true)->orderBy('pos')->get(),
'tags' => DcTag::orderBy('pos')->get(),
];
return view('admin.downloadcenter.file_edit', $data);
}
public function fileUpdate($do, $id){
if($do === 'make_thumb'){
public function fileUpdate($do, $id)
{
if ($do === 'make_thumb') {
$this->fileRepository->makeThumb($id);
\Session()->flash('alert-success', 'Vorschaubild erstellt!');
return back();
}
if($do === 'delete'){
if ($do === 'delete') {
$this->fileRepository->deleteFile($id);
\Session()->flash('alert-success', 'Datei gelöscht!');
return redirect(route('admin_downloadcenter_files'));
}
if($do === 'delete_thumb'){
if ($do === 'delete_thumb') {
$this->fileRepository->deleteThumb($id);
\Session()->flash('alert-success', 'Vorschaubild gelöscht!');
return back();
}
if($do === 'deactivate'){
if ($do === 'deactivate') {
$file = DcFile::findOrFail($id);
$file->active = false;
$file->save();
\Session()->flash('alert-success', 'Datei nicht anzeigen!');
return back();
}
if($do === 'activate'){
if ($do === 'activate') {
$file = DcFile::findOrFail($id);
$file->active = true;
$file->save();
\Session()->flash('alert-success', 'Datei wird angezeigt!');
return back();
}
if($do === 'file_tags_update'){
if ($do === 'file_tags_update') {
$file = DcFile::findOrFail($id);
$this->fileRepository->tagsUpdate($id, Request::get('nestable_check'));
$tags = Request::get('nestable_check', []);
$this->fileRepository->tagsUpdate($id, is_array($tags) ? $tags : []);
\Session()->flash('alert-success', 'Tags aktualisiert!');
return back();
}
}
public function upload(){
public function upload()
{
return view('admin.downloadcenter.file_upload');
}
public function uploadFile(){
public function uploadFile()
{
$data = Request::all();
$file = $this->fileRepository->uploadFile($data);
return Response::json([
'error' => false,
'filename' => $file->filename,
'filedata' => '',
'code' => 200
'code' => 200,
], 200);
//return response()->json(['success'=>basename($file)]);
// return response()->json(['success'=>basename($file)]);
}
public function tags($flash = false){
public function tags($flash = false)
{
$active = DcCategory::orderBy('pos')->get();
$inactive = DcTag::where('category_id', null)->get();
$data = [
'category_active' => $active,
'tags_inactive' => $inactive,
];
if($flash){
if ($flash) {
\Session()->flash('alert-success', 'gespeichert!');
}
return view('admin.downloadcenter.tags', $data);
}
public function storeItem($obj = false){
public function storeItem($obj = false)
{
$data = Request::all();
return $this->tagRepository->storeItem($obj, $data);
return redirect(route('admin_downloadcenter_tags'));
}
public function deleteItem($obj, $id){
public function deleteItem($obj, $id)
{
$this->tagRepository->deleteItem($obj, $id);
return redirect(route('admin_downloadcenter_tags'));
}
public function datatable(){
public function datatable()
{
$query = DcFile::with('tags')->select('dc_files.*');
$query = DcFile::with('tags')->select('dc_files.*');
return \DataTables::eloquent($query)
->addColumn('id', function (DcFile $file) {
return '<a href="'.route('admin_downloadcenter_file_edit', [$file->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('image', function (DcFile $file) {
return ($file->hasThumb() && $file->hasBig()) ?
'<img src="' .route('storage_file', [$file->id, 'dc_thumb', 'image']) . '" class="img-fluid img-responsive" style="max-width: 100px;">' :
return ($file->hasThumb() && $file->hasBig()) ?
'<img src="'.route('storage_file', [$file->id, 'dc_thumb', 'image']).'" class="img-fluid img-responsive" style="max-width: 100px;">' :
'<a href="'.route('admin_downloadcenter_file', ['make_thumb', $file->id]).'" class="btn btn-sm btn-warning"> Vorschaubild<br>erstellen <i class="ion ion-md-refresh-circle"></i></a>';
})
->addColumn('name', function (DcFile $file) {
//Storage::disk('local')->url($file->filename) }}
// Storage::disk('local')->url($file->filename) }}
return '<a target="_blank" href="'.route('storage_file', [$file->id, 'dc_file', 'stream']).'">'.$file->original_name.'</a>';
// return '<a target="_blank" href="">'.$file->original_name.'</a>';
// return '<a target="_blank" href="">'.$file->original_name.'</a>';
})
->addColumn('category', function (DcFile $file) {
//return $file->category ? $file->category->name : '';
// return $file->category ? $file->category->name : '';
})
->addColumn('tags', function (DcFile $file) {
//return $file->hasTags() ? '<span class="badge badge-pill badge-success">('.$file->fileTag()->count().')</span>' : '<span class="badge badge-pill badge-dange">X</span>';
// return $file->hasTags() ? '<span class="badge badge-pill badge-success">('.$file->fileTag()->count().')</span>' : '<span class="badge badge-pill badge-dange">X</span>';
return $file->tags->implode('name', '<br>');
})
->addColumn('size', function (DcFile $file) {
return Util::formatBytes($file->size);
})
})
->addColumn('active', function (DcFile $file) {
return get_active_badge($file->active);
//return $file->active ? '<span class="badge badge-pill badge-success"><i class="fa fa-check-circle"></i> aktiv</span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times-circle"></i> inaktiv</span>';
// return $file->active ? '<span class="badge badge-pill badge-success"><i class="fa fa-check-circle"></i> aktiv</span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times-circle"></i> inaktiv</span>';
})
->addColumn('created_at', function (DcFile $file) {
return $file->created_at->format('d.m.Y H:i');
@ -169,8 +189,8 @@ class DownloadController extends Controller
->addColumn('action', function (DcFile $file) {
return '<a onclick="return confirm(\'Diese Datei wirklich löschen?\');" class="btn btn-sm btn-danger" href="'.route('admin_downloadcenter_file', ['delete', $file->id]).'"><i class="fa fa-trash"></i></a>';
})
->filterColumn('name', function($query, $keyword) {
if($keyword != ""){
->filterColumn('name', function ($query, $keyword) {
if ($keyword != '') {
$query->where('original_name', 'LIKE', '%'.$keyword.'%');
}
})
@ -184,5 +204,4 @@ class DownloadController extends Controller
->rawColumns(['id', 'image', 'name', 'active', 'tags', 'action'])
->make(true);
}
}

View file

@ -0,0 +1,708 @@
<?php
namespace App\Http\Controllers;
use App\Models\ShoppingUser;
use App\Models\ShoppingUserMemberLog;
use App\Models\UserCleanUpLog;
use App\User;
use Illuminate\Support\Facades\Auth;
class AdminUserCleanupController extends Controller
{
public function __construct()
{
$this->middleware('superadmin');
}
/**
* Übersicht deaktivierter und gelöschter User
*/
public function index()
{
return view('admin.user.cleanup.index');
}
/**
* Protokoll der User-Cleanup-Logs (Downline-Übertragungen)
*/
public function logs()
{
return view('admin.user.cleanup.logs');
}
/**
* Protokoll der Shopping-User-Member-Logs (Kunden-Übertragungen)
*/
public function shoppingLogs()
{
return view('admin.user.cleanup.shopping_logs');
}
/**
* DataTable für deaktivierte/gelöschte User
*/
public function getInactiveUsers()
{
// Deaktivierte User (active=false) ODER gelöschte User (mit pre_deleted_at)
$query = User::withTrashed()
->where(function ($q) {
$q->where('active', false)
->orWhere('pre_deleted_at', '!=', null);
})
->with('account')
->select('users.*')
->where('users.admin', '<', 5);
return \DataTables::eloquent($query)
->addColumn('user_id', function (User $user) {
return $user->id;
})
->addColumn('first_name', function (User $user) {
return $user->account ? $user->account->first_name : '';
})
->addColumn('last_name', function (User $user) {
return $user->account ? $user->account->last_name : '';
})
->addColumn('email', function (User $user) {
if ($user->pre_deleted_at) {
return '<span class="badge badge-pill badge-danger">'.$user->email.'</span>';
}
return $user->email;
})
->addColumn('m_account', function (User $user) {
return $user->account ? $user->account->m_account : '';
})
->addColumn('status', function (User $user) {
if ($user->pre_deleted_at) {
return '<span class="badge badge-danger">Gelöscht</span>';
}
if (! $user->active) {
return '<span class="badge badge-warning">Deaktiviert</span>';
}
return '<span class="badge badge-success">Aktiv</span>';
})
->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 '-';
})
->addColumn('payment_account', function (User $user) {
return $user->getPaymentAccountDateFormat();
})
->addColumn('m_sponsor', function (User $user) {
if ($user->m_sponsor) {
$sponsor = User::find($user->m_sponsor);
return $sponsor ? $sponsor->email : 'ID: '.$user->m_sponsor;
}
return '-';
})
->addColumn('pre_sponsor', function (User $user) {
if ($user->pre_sponsor) {
$sponsor = User::withTrashed()->find($user->pre_sponsor);
return $sponsor ? $sponsor->email : 'ID: '.$user->pre_sponsor;
}
return '-';
})
->addColumn('childs_count', function (User $user) {
$count = User::where('m_sponsor', $user->id)->count();
return $count > 0 ? '<span class="badge badge-info">'.$count.'</span>' : '0';
})
->addColumn('shopping_users_count', function (User $user) {
$count = ShoppingUser::where('member_id', $user->id)->count();
return $count > 0 ? '<span class="badge badge-info">'.$count.'</span>' : '0';
})
->addColumn('action', function (User $user) {
$html = '';
if ($user->pre_deleted_at) {
$html .= '<a href="'.route('admin_lead_edit', [$user->id]).'" class="btn btn-sm btn-info" title="Details"><i class="fa fa-eye"></i></a> ';
} else {
$html .= '<a href="'.route('admin_lead_edit', [$user->id]).'" class="btn btn-sm btn-primary" title="Bearbeiten"><i class="fa fa-edit"></i></a> ';
}
// Historie-Button
$html .= ' <button class="btn btn-sm btn-secondary btn-user-history" data-id="'.$user->id.'" data-email="'.$user->email.'" title="Historie & Details"><i class="fa fa-history"></i></button>';
// Restore-Button für gelöschte User
if ($user->pre_deleted_at) {
$html .= ' <button class="btn btn-sm btn-success" data-toggle="modal" data-target="#modal-restore-user" data-id="'.$user->id.'" data-email="'.str_replace('delete-', '', $user->email).'" title="Wiederherstellen"><i class="fa fa-undo"></i></button>';
}
return $html;
})
->orderColumn('user_id', 'id $1')
->orderColumn('email', 'email $1')
->orderColumn('status', 'active $1')
->rawColumns(['email', 'status', 'childs_count', 'shopping_users_count', 'action'])
->make(true);
}
/**
* DataTable für UserCleanUpLogs (Downline-Übertragungen)
*/
public function getCleanupLogs()
{
$query = UserCleanUpLog::with(['inactive_sponsor.account', 'child_user.account', 'new_sponsor.account'])
->select('user_clean_up_logs.*');
return \DataTables::eloquent($query)
->addColumn('id', function (UserCleanUpLog $log) {
return $log->id;
})
->addColumn('inactive_sponsor', function (UserCleanUpLog $log) {
if ($log->inactive_sponsor && $log->inactive_sponsor->account) {
$name = trim($log->inactive_sponsor->account->first_name.' '.$log->inactive_sponsor->account->last_name);
return ($name ?: 'N/A').'<br><small>'.$log->inactive_sponsor->email.'</small>';
}
return 'ID: '.$log->inactive_sponsor_id;
})
->addColumn('child_user', function (UserCleanUpLog $log) {
if ($log->child_user && $log->child_user->account) {
$name = trim($log->child_user->account->first_name.' '.$log->child_user->account->last_name);
return ($name ?: 'N/A').'<br><small>'.$log->child_user->email.'</small>';
}
return 'ID: '.$log->child_user_id;
})
->addColumn('new_sponsor', function (UserCleanUpLog $log) {
$html = '';
// Original-Sponsor aus dem Log
if ($log->new_sponsor && $log->new_sponsor->account) {
$name = trim($log->new_sponsor->account->first_name.' '.$log->new_sponsor->account->last_name);
$html .= '<span class="text-muted"><small>Damals:</small></span><br>';
$html .= ($name ?: 'N/A').'<br><small>'.$log->new_sponsor->email.'</small>';
} else {
$html .= 'ID: '.$log->new_sponsor_id;
}
// Prüfe aktuellen Sponsor des child_user
if ($log->child_user) {
$currentSponsorId = $log->child_user->m_sponsor;
// Wenn aktueller Sponsor ANDERS ist als im Log
if ($currentSponsorId && $currentSponsorId != $log->new_sponsor_id) {
$currentSponsor = User::with('account')->find($currentSponsorId);
if ($currentSponsor) {
$html .= '<hr class="my-1">';
$html .= '<span class="badge badge-warning">Geändert!</span><br>';
$html .= '<span class="text-success"><small>Aktuell:</small></span><br>';
if ($currentSponsor->account) {
$currentName = trim($currentSponsor->account->first_name.' '.$currentSponsor->account->last_name);
$html .= '<strong>'.($currentName ?: 'N/A').'</strong><br>';
}
$html .= '<small>'.$currentSponsor->email.'</small>';
}
}
}
return $html;
})
->addColumn('created_at', function (UserCleanUpLog $log) {
return \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i');
})
->orderColumn('id', 'id $1')
->rawColumns(['inactive_sponsor', 'child_user', 'new_sponsor'])
->make(true);
}
/**
* DataTable für ShoppingUserMemberLogs (Kunden-Übertragungen)
*/
public function getShoppingLogs()
{
$query = ShoppingUserMemberLog::with(['pre_member.account', 'shopping_user', 'new_member.account'])
->select('shopping_user_member_logs.*');
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingUserMemberLog $log) {
return $log->id;
})
->addColumn('pre_member', function (ShoppingUserMemberLog $log) {
if ($log->pre_member && $log->pre_member->account) {
$name = trim($log->pre_member->account->first_name.' '.$log->pre_member->account->last_name);
return ($name ?: 'N/A').'<br><small>'.$log->pre_member->email.'</small>';
}
return 'ID: '.$log->pre_member_id;
})
->addColumn('shopping_user', function (ShoppingUserMemberLog $log) {
if ($log->shopping_user) {
$name = trim($log->shopping_user->billing_firstname.' '.$log->shopping_user->billing_lastname);
return ($name ?: 'N/A').'<br><small>'.$log->shopping_user->billing_email.'</small>';
}
return 'ID: '.$log->shopping_user_id;
})
->addColumn('new_member', function (ShoppingUserMemberLog $log) {
$html = '';
// Original-Berater aus dem Log
if ($log->new_member && $log->new_member->account) {
$name = trim($log->new_member->account->first_name.' '.$log->new_member->account->last_name);
$html .= '<span class="text-muted"><small>Damals:</small></span><br>';
$html .= ($name ?: 'N/A').'<br><small>'.$log->new_member->email.'</small>';
} else {
$html .= 'ID: '.$log->new_member_id;
}
// Prüfe aktuellen Berater des Kunden
if ($log->shopping_user) {
$currentMemberId = $log->shopping_user->member_id;
// Wenn aktueller Berater ANDERS ist als im Log
if ($currentMemberId && $currentMemberId != $log->new_member_id) {
$currentMember = User::with('account')->find($currentMemberId);
if ($currentMember) {
$html .= '<hr class="my-1">';
$html .= '<span class="badge badge-warning">Geändert!</span><br>';
$html .= '<span class="text-success"><small>Aktuell:</small></span><br>';
if ($currentMember->account) {
$currentName = trim($currentMember->account->first_name.' '.$currentMember->account->last_name);
$html .= '<strong>'.($currentName ?: 'N/A').'</strong><br>';
}
$html .= '<small>'.$currentMember->email.'</small>';
}
}
}
return $html;
})
->addColumn('created_at', function (ShoppingUserMemberLog $log) {
return \Carbon\Carbon::parse($log->created_at)->format('d.m.Y H:i');
})
->orderColumn('id', 'id $1')
->rawColumns(['pre_member', 'shopping_user', 'new_member'])
->make(true);
}
/**
* User über Artisan Command wiederherstellen
*/
public function restore(\Illuminate\Http\Request $request)
{
$userId = $request->input('user_id');
if (! $userId) {
return response()->json([
'success' => false,
'message' => 'Keine User-ID angegeben',
], 400);
}
try {
// Führe Artisan Command aus
\Artisan::call('user:restore', ['user_id' => $userId]);
$output = \Artisan::output();
// Prüfe ob Command erfolgreich war (Exit Code 0)
$exitCode = \Artisan::call('user:restore', ['user_id' => $userId]);
\Log::channel('cleanup')->info('AdminUserCleanupController restore via web: user_id='.$userId.' | exitCode='.$exitCode);
if ($exitCode === 0) {
return response()->json([
'success' => true,
'message' => 'User wurde erfolgreich wiederhergestellt',
'output' => $output,
]);
} else {
return response()->json([
'success' => false,
'message' => 'Fehler beim Wiederherstellen (Exit Code: '.$exitCode.')',
'output' => $output,
], 500);
}
} catch (\Exception $e) {
\Log::channel('cleanup')->error('AdminUserCleanupController restore failed: '.$e->getMessage());
return response()->json([
'success' => false,
'message' => 'Exception: '.$e->getMessage(),
], 500);
}
}
/**
* Suche nach aktiven Sponsoren für Select2
*/
public function searchSponsors(\Illuminate\Http\Request $request)
{
$search = $request->input('q');
$userId = $request->input('exclude_user_id'); // User selbst ausschließen
$loadAll = $request->input('load_all', false); // Alle Sponsoren laden
$query = User::where('active', true)
->where('admin', '<', 5)
->where('blocked', false)
->where('payment_account', '>=', now())
->with('account')
->orderBy('email', 'asc');
if ($userId) {
$query->where('id', '!=', $userId);
}
// Nur filtern wenn Suche vorhanden und nicht load_all
if ($search && ! $loadAll) {
$query->where(function ($q) use ($search) {
$q->where('email', 'like', '%'.$search.'%')
->orWhereHas('account', function ($q2) use ($search) {
$q2->where('first_name', 'like', '%'.$search.'%')
->orWhere('last_name', 'like', '%'.$search.'%')
->orWhere('m_account', 'like', '%'.$search.'%');
});
});
}
// Limit nur wenn nicht alle geladen werden sollen
if (! $loadAll) {
$query->limit(20);
}
$users = $query->get()->map(function ($user) {
$name = '';
if ($user->account) {
$name = trim($user->account->first_name.' '.$user->account->last_name);
if ($name) {
$name .= ' | ';
}
}
return [
'id' => $user->id,
'text' => $name.$user->email.($user->account && $user->account->m_account ? ' #'.$user->account->m_account : ''),
];
});
return response()->json(['results' => $users]);
}
/**
* Sponsor manuell neu zuweisen
*/
public function reassignSponsor(\Illuminate\Http\Request $request)
{
$userId = $request->input('user_id');
$newSponsorId = $request->input('new_sponsor_id');
// Boolean-Werte korrekt konvertieren (auch wenn sie als String ankommen)
$transferDownline = filter_var($request->input('transfer_downline', false), FILTER_VALIDATE_BOOLEAN);
$transferCustomers = filter_var($request->input('transfer_customers', false), FILTER_VALIDATE_BOOLEAN);
if (! $userId || ! $newSponsorId) {
return response()->json([
'success' => false,
'message' => 'User-ID und neuer Sponsor sind erforderlich',
], 400);
}
$user = User::withTrashed()->find($userId);
$newSponsor = User::find($newSponsorId);
if (! $user) {
return response()->json([
'success' => false,
'message' => 'User nicht gefunden',
], 404);
}
if (! $newSponsor || ! $newSponsor->active) {
return response()->json([
'success' => false,
'message' => 'Neuer Sponsor nicht gefunden oder nicht aktiv',
], 404);
}
\DB::beginTransaction();
try {
$oldSponsorId = $user->m_sponsor;
$logs = [];
// 1. Downline neu zuweisen (aus Logs - bereits übertragene)
$childrenTransferred = 0;
if ($transferDownline) {
// Hole die Kinder aus den vorherigen Cleanup-Logs (die bereits VON diesem User weg übertragen wurden)
$cleanupLogs = UserCleanUpLog::where('inactive_sponsor_id', $userId)->get();
\Log::channel('cleanup')->info('Reassigning downline from logs: found '.$cleanupLogs->count().' log entries for user_id='.$userId);
foreach ($cleanupLogs as $oldLog) {
$child = User::find($oldLog->child_user_id);
if (! $child) {
\Log::channel('cleanup')->warning('Child user not found: '.$oldLog->child_user_id);
continue;
}
// Neuen Log erstellen für die Neu-Zuweisung
UserCleanUpLog::create([
'inactive_sponsor_id' => $child->m_sponsor, // Aktueller Sponsor (wohin es vorher übertragen wurde)
'child_user_id' => $child->id,
'new_sponsor_id' => $newSponsorId, // Neuer Sponsor
]);
// Sponsor ändern
$child->m_sponsor = $newSponsorId;
$child->save();
$childrenTransferred++;
$logs[] = 'Downline: '.$child->email.' → Neuer Sponsor: '.$newSponsor->email;
}
\Log::channel('cleanup')->info('Children reassigned: '.$childrenTransferred);
}
// 2. Shopping-Kunden neu zuweisen (aus Logs - bereits übertragene)
$customersTransferred = 0;
if ($transferCustomers) {
// Hole die Kunden aus den vorherigen Shopping-Logs (die bereits VON diesem User weg übertragen wurden)
$shoppingLogs = ShoppingUserMemberLog::where('pre_member_id', $userId)->get();
\Log::channel('cleanup')->info('Reassigning customers from logs: found '.$shoppingLogs->count().' log entries for user_id='.$userId);
foreach ($shoppingLogs as $oldLog) {
$customer = ShoppingUser::find($oldLog->shopping_user_id);
if (! $customer) {
\Log::channel('cleanup')->warning('Shopping user not found: '.$oldLog->shopping_user_id);
continue;
}
// Neuen Log erstellen für die Neu-Zuweisung
ShoppingUserMemberLog::create([
'pre_member_id' => $customer->member_id, // Aktueller Berater (wohin es vorher übertragen wurde)
'shopping_user_id' => $customer->id,
'new_member_id' => $newSponsorId, // Neuer Berater
]);
// Member ändern
$customer->member_id = $newSponsorId;
$customer->save();
$customersTransferred++;
$logs[] = 'Kunde: '.$customer->billing_email.' → Neuer Berater: '.$newSponsor->email;
}
\Log::channel('cleanup')->info('Customers reassigned: '.$customersTransferred);
}
// 3. User selbst dem neuen Sponsor zuweisen
$user->m_sponsor = $newSponsorId;
$user->save();
\DB::commit();
// Cleanup-Log
\Log::channel('cleanup')->info('Manual reassign sponsor: user_id='.$userId.' | old_sponsor='.$oldSponsorId.' | new_sponsor='.$newSponsorId.' | transfer_downline='.(int) $transferDownline.' | transfer_customers='.(int) $transferCustomers.' | by_admin='.Auth::id());
return response()->json([
'success' => true,
'message' => 'Sponsor erfolgreich neu zugewiesen',
'logs' => $logs,
'transferred' => [
'downline' => $childrenTransferred,
'customers' => $customersTransferred,
],
]);
} catch (\Exception $e) {
\DB::rollBack();
\Log::channel('cleanup')->error('Manual reassign sponsor failed: user_id='.$userId.' | error='.$e->getMessage());
return response()->json([
'success' => false,
'message' => 'Fehler beim Neu-Zuweisen: '.$e->getMessage(),
], 500);
}
}
/**
* Lade User-Historie: Downline-Position und Shopping-Kunden
*/
public function getUserHistory($userId)
{
$user = User::withTrashed()->with('account')->find($userId);
if (! $user) {
return response()->json([
'success' => false,
'message' => 'User nicht gefunden',
], 404);
}
// Aktueller/Vorheriger Sponsor
$sponsor = null;
$preSponsor = null;
if ($user->m_sponsor) {
$sponsor = User::withTrashed()->with('account')->find($user->m_sponsor);
}
if ($user->pre_sponsor) {
$preSponsor = User::withTrashed()->with('account')->find($user->pre_sponsor);
}
// Direkte Downline (Kinder) - nur die, die aktuell m_sponsor haben
// pre_sponsor sind bereits deaktiviert und würden doppelt gezählt
$children = User::withTrashed()
->with('account')
->where('m_sponsor', $userId)
->get()
->map(function ($child) use ($userId) {
return [
'id' => $child->id,
'name' => $child->account ? trim($child->account->first_name.' '.$child->account->last_name) : 'N/A',
'email' => $child->email,
'active' => $child->active,
'deleted' => $child->pre_deleted_at ? true : false,
'is_pre_sponsor' => $child->pre_sponsor == $userId,
];
});
// Shopping-Kunden
$shoppingUsers = ShoppingUser::where('member_id', $userId)
->get()
->map(function ($customer) {
return [
'id' => $customer->id,
'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'),
];
});
// Downline-Übertragungen (wo dieser User betroffen war)
$cleanupLogs = UserCleanUpLog::with(['inactive_sponsor.account', 'child_user.account', 'new_sponsor.account'])
->where(function ($query) use ($userId) {
$query->where('inactive_sponsor_id', $userId)
->orWhere('child_user_id', $userId);
})
->orderBy('created_at', 'desc')
->get()
->map(function ($log) use ($userId) {
$data = [
'type' => $log->inactive_sponsor_id == $userId ? 'as_inactive' : 'as_child',
'child_user' => $log->child_user ? [
'id' => $log->child_user->id,
'name' => $log->child_user->account ? trim($log->child_user->account->first_name.' '.$log->child_user->account->last_name) : 'N/A',
'email' => $log->child_user->email,
'active' => $log->child_user->active,
'deleted' => $log->child_user->pre_deleted_at ? true : false,
] : null,
'inactive_sponsor' => $log->inactive_sponsor ? [
'id' => $log->inactive_sponsor->id,
'name' => $log->inactive_sponsor->account ? trim($log->inactive_sponsor->account->first_name.' '.$log->inactive_sponsor->account->last_name) : 'N/A',
'email' => $log->inactive_sponsor->email,
] : null,
'new_sponsor' => $log->new_sponsor ? [
'id' => $log->new_sponsor->id,
'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'),
];
// Prüfe aktuellen Sponsor des child_user (falls geändert)
if ($log->child_user && $log->child_user->m_sponsor && $log->child_user->m_sponsor != $log->new_sponsor_id) {
$currentSponsor = User::with('account')->find($log->child_user->m_sponsor);
if ($currentSponsor) {
$data['current_sponsor'] = [
'id' => $currentSponsor->id,
'name' => $currentSponsor->account ? trim($currentSponsor->account->first_name.' '.$currentSponsor->account->last_name) : 'N/A',
'email' => $currentSponsor->email,
];
}
}
return $data;
});
// Kunden-Übertragungen
$shoppingLogs = ShoppingUserMemberLog::with(['shopping_user', 'new_member.account'])
->where('pre_member_id', $userId)
->orderBy('created_at', 'desc')
->get()
->map(function ($log) {
$data = [
'customer_name' => $log->shopping_user ? trim($log->shopping_user->billing_firstname.' '.$log->shopping_user->billing_lastname) : 'N/A',
'customer_email' => $log->shopping_user ? $log->shopping_user->billing_email : 'N/A',
'new_member' => $log->new_member ? [
'id' => $log->new_member->id,
'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'),
];
// Prüfe aktuellen Berater des Kunden (falls geändert)
if ($log->shopping_user && $log->shopping_user->member_id && $log->shopping_user->member_id != $log->new_member_id) {
$currentMember = User::with('account')->find($log->shopping_user->member_id);
if ($currentMember) {
$data['current_member'] = [
'id' => $currentMember->id,
'name' => $currentMember->account ? trim($currentMember->account->first_name.' '.$currentMember->account->last_name) : 'N/A',
'email' => $currentMember->email,
];
}
}
return $data;
});
return response()->json([
'success' => true,
'user' => [
'id' => $user->id,
'name' => $user->account ? trim($user->account->first_name.' '.$user->account->last_name) : 'N/A',
'email' => $user->email,
'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,
],
'sponsor' => $sponsor ? [
'id' => $sponsor->id,
'name' => $sponsor->account ? trim($sponsor->account->first_name.' '.$sponsor->account->last_name) : 'N/A',
'email' => $sponsor->email,
'active' => $sponsor->active,
] : null,
'pre_sponsor' => $preSponsor ? [
'id' => $preSponsor->id,
'name' => $preSponsor->account ? trim($preSponsor->account->first_name.' '.$preSponsor->account->last_name) : 'N/A',
'email' => $preSponsor->email,
'active' => $preSponsor->active,
] : null,
'children' => $children,
'shopping_users' => $shoppingUsers,
'cleanup_logs' => $cleanupLogs,
'shopping_logs' => $shoppingLogs,
]);
}
}

View file

@ -2,27 +2,19 @@
namespace App\Http\Controllers\Api;
use App\Services\Shop;
use App\Services\Util;
use App\Models\UserAbo;
use App\Services\MyLog;
use App\Services\Payment;
use App\Services\AboHelper;
use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\PaymentTransaction;
use App\Http\Controllers\Controller;
use App\Services\MyLog;
use App\Services\Payment;
use App\Services\ShoppingUserService;
use App\Services\Util;
class PayoneController extends Controller
{
public function __construct() {}
public function paymentStatus()
{
@ -42,14 +34,14 @@ class PayoneController extends Controller
*/
if (!isset($data['key']) || !isset($data['param']) || !isset($data['userid']) || !isset($data['txid']) || !isset($data['reference']) || !isset($data['price'])) {
if (! isset($data['key']) || ! isset($data['param']) || ! isset($data['userid']) || ! isset($data['txid']) || ! isset($data['reference']) || ! isset($data['price'])) {
MyLog::writeLog(
'payone',
'error',
'Error:2001 App\Http\Controllers\Api\PayoneController::paymentStatus parameter incomplete',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
@ -60,31 +52,31 @@ class PayoneController extends Controller
'Error:2002 App\Http\Controllers\Api\PayoneController::paymentStatus Key error',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
$shopping_order = ShoppingOrder::find($data['param']);
if (!$shopping_order) {
if (! $shopping_order) {
MyLog::writeLog(
'payone',
'error',
'Error:2003 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingOrder not found:',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
$shopping_payment = ShoppingPayment::where('reference', $data['reference'])->first();
if (!$shopping_payment) {
if (! $shopping_payment) {
MyLog::writeLog(
'payone',
'error',
'Error:2004 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment not found',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
@ -95,11 +87,11 @@ class PayoneController extends Controller
'Error:2005 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment no realation ShoppingOrder',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
$price = number_format((round($data['price'], 2) * 100), 0, '.', '');
$price = number_format((round($data['price'], 2) * 100), 0, '.', '');
$price_amount = number_format($shopping_payment->amount, 0, '.', '');
if ($price_amount != $price) {
$data['shopping_payment-amount'] = $price_amount;
@ -110,7 +102,7 @@ class PayoneController extends Controller
'Error:2006 App\Http\Controllers\Api\PayoneController::paymentStatus Price error',
$data
);
print("TSOK");
echo 'TSOK';
exit;
}
@ -125,8 +117,8 @@ class PayoneController extends Controller
$data,
false
);
//was already paid
print("TSOK");
// was already paid
echo 'TSOK';
exit;
} else {
MyLog::writeLog(
@ -139,7 +131,7 @@ class PayoneController extends Controller
}
}
//create transaction
// create transaction
PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'transaction',
@ -152,10 +144,32 @@ class PayoneController extends Controller
'mode' => $data['mode'],
]);
$shopping_order->txaction = $data['txaction'];
$shopping_order->save();
$shopping_payment->txaction = $data['txaction'];
$shopping_payment->save();
// Define txaction priority (higher number = higher priority)
$txaction_priority = [
'appointed' => 1,
'pending' => 2,
'failed' => 3,
'paid' => 10, // highest priority - final state
];
$current_priority = isset($txaction_priority[$shopping_order->txaction]) ? $txaction_priority[$shopping_order->txaction] : 0;
$new_priority = isset($txaction_priority[$data['txaction']]) ? $txaction_priority[$data['txaction']] : 0;
// Only update txaction if new priority is higher than current
if ($new_priority > $current_priority) {
$shopping_order->txaction = $data['txaction'];
$shopping_order->save();
$shopping_payment->txaction = $data['txaction'];
$shopping_payment->save();
} else {
MyLog::writeLog(
'payone',
'info',
'App\Http\Controllers\Api\PayoneController::paymentStatus - txaction not updated (current: '.$shopping_order->txaction.' has higher/equal priority than new: '.$data['txaction'].')',
$data,
false
);
}
$send_link = false;
$send_mail = true;
@ -170,17 +184,38 @@ class PayoneController extends Controller
}
if ($data['txaction'] === 'paid') {
if (!$shopping_order->paid) {
$send_link = Payment::paymentStatusPaidAction($shopping_order, true, $shopping_payment);
} else {
$send_mail = false;
// Use DB transaction and row locking to prevent race conditions
\DB::beginTransaction();
try {
// Lock the shopping order row to prevent concurrent processing
$locked_order = ShoppingOrder::where('id', $shopping_order->id)
->lockForUpdate()
->first();
// Double-check if payment was already processed
if (! $locked_order->paid) {
$send_link = Payment::paymentStatusPaidAction($locked_order, true, $shopping_payment);
\DB::commit();
} else {
$send_mail = false;
\DB::commit();
}
} catch (\Exception $e) {
\DB::rollBack();
MyLog::writeLog(
'payone',
'error',
'Error:2008 App\Http\Controllers\Api\PayoneController::paymentStatus Transaction failed',
['error' => $e->getMessage(), 'data' => $data]
);
throw $e;
}
}
$data['send_link'] = $send_link;
if ($send_mail) {
Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
}
print("TSOK");
echo 'TSOK';
exit;
}
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Mail\MailCheckout;
use App\Models\Country;
use App\Models\Product;
@ -10,28 +11,23 @@ use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Services\CustomerPriority;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use PHPUnit\Framework\Constraint\Count;
use Yard;
class ShoppingUserController extends Controller
{
//protected static API_MAIL = 'api.thomas.krummel@gmail.com';
//protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
// protected static API_MAIL = 'api.thomas.krummel@gmail.com';
// protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
protected $successStatus = 200;
protected $member_id = 3; //service@aloe-vera.bio
protected $member_id = 3; // service@aloe-vera.bio
/**
* @param Request $request
* wp_order_numbers[1234, 1234]
* @param Request $request
* wp_order_numbers[1234, 1234]
* @return \Illuminate\Http\JsonResponse
*/
public function status(Request $request)
@ -41,23 +37,23 @@ class ShoppingUserController extends Controller
'wp_order_numbers' => 'required',
]);
if(!is_array($request->wp_order_numbers)){
if (! is_array($request->wp_order_numbers)) {
$wp_order_numbers = json_decode($request->wp_order_numbers);
}else{
$wp_order_numbers = $request->wp_order_numbers;
} else {
$wp_order_numbers = $request->wp_order_numbers;
}
if(!$wp_order_numbers || !is_array($wp_order_numbers)){
if (! $wp_order_numbers || ! is_array($wp_order_numbers)) {
return response()->json([
'success' => false,
'message' => 'wp_order_numbers need as json [1234, 1234] ',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$status = [];
foreach ($wp_order_numbers as $wp_order_number){
foreach ($wp_order_numbers as $wp_order_number) {
$shopping_user = ShoppingUser::where('wp_order_number', '=', $wp_order_number)->first();
$status[] = [
'wp_order_number' => $wp_order_number,
@ -70,14 +66,14 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => true,
'data' => $status,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* wp_order_number [1234]
* @param Request $request
* wp_order_number [1234]
* @return \Illuminate\Http\JsonResponse
*/
public function cancel(Request $request)
@ -86,31 +82,31 @@ class ShoppingUserController extends Controller
'wp_order_number' => 'required|int',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
if (!$shopping_user) {
if (! $shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'order' => false,
'status' => false,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if(!$shopping_user->shopping_order){
if (! $shopping_user->shopping_order) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' has no order',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' has no order',
'order' => false,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if($shopping_user->shopping_order->shipped > 0){
if ($shopping_user->shopping_order->shipped > 0) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' can not cancel',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' can not cancel',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -119,18 +115,17 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => true,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' is cancel',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' is cancel',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* wp_order_number [1234]
* @param Request $request
* wp_order_number [1234]
* @return \Illuminate\Http\JsonResponse
*/
public function open(Request $request)
@ -139,31 +134,31 @@ class ShoppingUserController extends Controller
'wp_order_number' => 'required|int',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
if (!$shopping_user) {
if (! $shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'order' => false,
'status' => false,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if(!$shopping_user->shopping_order){
if (! $shopping_user->shopping_order) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' has no order',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' has no order',
'order' => false,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if($shopping_user->shopping_order->shipped !== 10){
if ($shopping_user->shopping_order->shipped !== 10) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' can not open',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' can not open',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -172,45 +167,44 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => true,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' is open',
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' is open',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* wp_order_numbers [1234, 1234]
* @param Request $request
* wp_order_numbers [1234, 1234]
* @return \Illuminate\Http\JsonResponse
*/
public function show(Request $request)
{
//$this->member_id = auth()->user()->m_sponsor;
// $this->member_id = auth()->user()->m_sponsor;
$request->validate([
'wp_order_numbers' => 'required',
]);
if(!is_array($request->wp_order_numbers)){
if (! is_array($request->wp_order_numbers)) {
$wp_order_numbers = json_decode($request->wp_order_numbers);
}else{
$wp_order_numbers = $request->wp_order_numbers;
} else {
$wp_order_numbers = $request->wp_order_numbers;
}
if(!$wp_order_numbers || !is_array($wp_order_numbers)){
if (! $wp_order_numbers || ! is_array($wp_order_numbers)) {
return response()->json([
'success' => false,
'message' => 'wp_order_numbers need as json [1234, 1234] ',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$data = [];
foreach ($wp_order_numbers as $wp_order_number){
$shopping_user = ShoppingUser::where('wp_order_number', '=', $wp_order_number)->first();
foreach ($wp_order_numbers as $wp_order_number) {
$shopping_user = ShoppingUser::where('wp_order_number', '=', $wp_order_number)->first();
$user = false;
$order = false;
if ($shopping_user) {
@ -220,21 +214,21 @@ class ShoppingUserController extends Controller
$data[] = [
'wp_order_number' => $wp_order_number,
'user' => $user,
'order' => $order,
'order' => $order,
'customer_number' => $shopping_user ? $shopping_user->number : false,
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user ? $shopping_user->getAPIShippedType() : false, ];
}
return response()->json([
'success' => true,
'data' => $data,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
@ -254,7 +248,7 @@ class ShoppingUserController extends Controller
$this->member_id = auth()->user()->m_sponsor;
$data = $this->prepareForStore($request->all());
$data['member_id'] = $this->member_id ;
$data['member_id'] = $this->member_id;
$data['number'] = ShoppingUser::max('number') + 1;
$data['mode'] = $request->mode ? $request->mode : 'live';
$data['is_from'] = 'extern';
@ -262,11 +256,12 @@ class ShoppingUserController extends Controller
$shopping_user = ShoppingUser::create($data);
//Kundenhoheit prüfen
// Kundenhoheit prüfen
$priority = CustomerPriority::checkOne($shopping_user, true, false, true);
\App\Services\Shop::newUserOrder($shopping_user->number);
//exists //like //update
// exists //like //update
$user = $this->prepareForShow($shopping_user);
return response()->json([
'success' => true,
'data' => [
@ -276,13 +271,12 @@ class ShoppingUserController extends Controller
'customer_number' => $shopping_user->number,
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request)
@ -291,40 +285,42 @@ class ShoppingUserController extends Controller
'wp_order_number' => 'required|int',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
if (!$shopping_user) {
if (! $shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
'time' => Carbon::now()->toDateTimeString()
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$data = $this->prepareForUpdate($request->all());
//Kundenhoheit prüfen
// Kundenhoheit prüfen
$priority = CustomerPriority::checkChangeOne($shopping_user, $data, true);
$updated = $shopping_user->fill($data)->save();
\App\Services\Shop::newUserOrder($shopping_user->number);
if ($updated){
if ($updated) {
$user = $this->prepareForShow($shopping_user);
$order = $this->prepareForShowOrder($shopping_user->shopping_order);
return response()->json([
return response()->json([
'success' => true,
'data' => [
'wp_order_number' => $shopping_user->wp_order_number,
'user' => $user,
'order' => $order,
'order' => $order,
'customer_priority' => $priority,
'customer_number' => $shopping_user ? $shopping_user->number : false,
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user ? $shopping_user->getAPIShippedType() : false,
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
return response()->json([
'success' => false,
'message' => 'Entry could not be updated'
'message' => 'Entry could not be updated',
], 500);
}
@ -335,28 +331,27 @@ class ShoppingUserController extends Controller
'wp_order' => 'required',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
if (!$shopping_user) {
if (! $shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
'time' => Carbon::now()->toDateTimeString()
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if($shopping_user->shopping_order){
if ($shopping_user->shopping_order) {
return response()->json([
'success' => false,
'message' => 'Order with wp_order_number ' . $request->wp_order_number . ' exists',
'time' => Carbon::now()->toDateTimeString()
'message' => 'Order with wp_order_number '.$request->wp_order_number.' exists',
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if(!is_array($request->wp_order)){
if (! is_array($request->wp_order)) {
$wp_order = json_decode($request->wp_order);
}else{
$wp_order = $request->wp_order;
} else {
$wp_order = $request->wp_order;
}
$wp_invoice_path = isset($request->wp_invoice_path) ? $request->wp_invoice_path : null;
@ -370,9 +365,10 @@ class ShoppingUserController extends Controller
$wp_order = $this->prepareOrder($wp_order, $shopping_user, $wp_invoice_path, $api_notice);
if ($wp_order){
if ($wp_order) {
$user = $this->prepareForShow($shopping_user);
$order = $this->prepareForShowOrder($shopping_user->shopping_order);
return response()->json([
'success' => true,
'data' => [
@ -387,166 +383,175 @@ class ShoppingUserController extends Controller
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user->getAPIShippedType(),
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
return response()->json([
'success' => false,
'message' => 'Order could not be stored'
'message' => 'Order could not be stored',
], 500);
}
public function delete(Request $request)
{
$request->validate([
'wp_order_number' => 'required|int',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->where('mode', '=', 'dev')->first();
if (!$shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found or mode != dev',
'time' => Carbon::now()->toDateTimeString()
], 400);
}
$shopping_order = $shopping_user->shopping_order;
if($shopping_order){
foreach ($shopping_order->shopping_order_items as $shopping_order_item){
$shopping_order_item->delete();
}
$shopping_order->delete();
}
$shopping_user->wp_order_number = time();
$shopping_user->save();
if ($shopping_user->delete()) {
return response()->json([
'success' => true
]);
}
return response()->json([
'success' => false,
'message' => 'Entry could not be deleted'
], 500);
}
{
$request->validate([
'wp_order_number' => 'required|int',
]);
$shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->where('mode', '=', 'dev')->first();
if (! $shopping_user) {
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found or mode != dev',
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$shopping_order = $shopping_user->shopping_order;
if ($shopping_order) {
foreach ($shopping_order->shopping_order_items as $shopping_order_item) {
$shopping_order_item->delete();
}
$shopping_order->delete();
}
$shopping_user->wp_order_number = time();
$shopping_user->save();
if ($shopping_user->delete()) {
return response()->json([
'success' => true,
]);
}
private function prepareForShow($shopping_user){
return response()->json([
'success' => false,
'message' => 'Entry could not be deleted',
], 500);
}
if(!$shopping_user){
private function prepareForShow($shopping_user)
{
if (! $shopping_user) {
return false;
}
$shopping_user_data = $shopping_user->toArray();
$needs = ['wp_order_number', 'wp_order_date', 'billing_company', 'billing_firstname', 'billing_lastname', 'billing_address', 'billing_address_2', 'billing_zipcode', 'billing_city', 'billing_phone', 'billing_email',
'same_as_billing', 'shipping_company', 'shipping_firstname', 'shipping_lastname', 'shipping_address', 'shipping_address_2', 'shipping_zipcode', 'shipping_city', 'shipping_phone',
'created_at', 'updated_at', 'user_deleted_at']; //'has_buyed', 'subscribed',
'created_at', 'updated_at', 'user_deleted_at']; // 'has_buyed', 'subscribed',
//$salutation = array('mr' => 1, 'ms' => 2);
// $salutation = array('mr' => 1, 'ms' => 2);
$ret = [];
foreach ($shopping_user_data as $key=>$value){
foreach ($shopping_user_data as $key => $value) {
if($key === 'billing_country_id'){
if ($key === 'billing_country_id') {
$ret['billing_country_code'] = $shopping_user->billing_country_id ? $shopping_user->billing_country->code : null;
}
if($key === 'shipping_country_id'){
if ($key === 'shipping_country_id') {
$ret['shipping_country_code'] = $shopping_user->shipping_country_id ? $shopping_user->shipping_country->code : null;
}
if($key === 'billing_salutation'){
if ($key === 'billing_salutation') {
$ret['billing_salutation'] = $shopping_user->billing_salutation === 'ms' ? 2 : 1;
}
if($key === 'shipping_salutation'){
if ($key === 'shipping_salutation') {
$ret['shipping_salutation'] = $shopping_user->shipping_salutation === 'ms' ? 2 : 1;
}
if(in_array($key, $needs)){
if (in_array($key, $needs)) {
$ret[$key] = $value;
}
}
return $ret;
}
private function prepareForShowOrder($shopping_order){
private function prepareForShowOrder($shopping_order)
{
if(!$shopping_order){
if (! $shopping_order) {
return false;
}
$ret = [
'country' => isset($shopping_order->shipping_country->country->code) ? $shopping_order->shipping_country->country->code : '',
'wp_invoice_path' => $shopping_order->wp_invoice_path,
'total' => ($shopping_order->total*100),
'shipping' => ($shopping_order->shipping*100),
'total_net' => ($shopping_order->subtotal*100),
'tax_rate' => ($shopping_order->tax_rate*100),
'tax' => ($shopping_order->tax*100),
'total_with_shipping' => ($shopping_order->total_shipping*100),
'total' => ($shopping_order->total * 100),
'shipping' => ($shopping_order->shipping * 100),
'total_net' => ($shopping_order->subtotal * 100),
'tax_rate' => ($shopping_order->tax_rate * 100),
'tax' => ($shopping_order->tax * 100),
'total_with_shipping' => ($shopping_order->total_shipping * 100),
'weight' => $shopping_order->weight,
];
$ret['items'] = [];
foreach ($shopping_order->shopping_order_items as $item){
foreach ($shopping_order->shopping_order_items as $item) {
$ret['items'][] = [
'article' => $item->product->wp_number,
'name' => $item->product->getLang('name'),
'qty' => $item->qty,
'price' => ($item->price * 100),
'article' => $item->product->wp_number,
'name' => $item->product->getLang('name'),
'qty' => $item->qty,
'price' => ($item->price * 100),
];
}
return $ret;
}
private function prepareForUpdate($data){
private function prepareForUpdate($data)
{
//$salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
// $salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
if(isset($data['billing_salutation'])){
$data['billing_salutation'] = (int) $data['billing_salutation'];
if (isset($data['billing_salutation'])) {
$data['billing_salutation'] = (int) $data['billing_salutation'];
$data['billing_salutation'] = $data['billing_salutation'] == 2 ? 'ms' : 'mr';
}
if(isset($data['shipping_salutation'])){
$data['shipping_salutation'] = (int) $data['shipping_salutation'];
$data['shipping_salutation'] = $data['shipping_salutation'] == 2 ? 'ms' : 'mr';
if (isset($data['shipping_salutation'])) {
$data['shipping_salutation'] = (int) $data['shipping_salutation'];
$data['shipping_salutation'] = $data['shipping_salutation'] == 2 ? 'ms' : 'mr';
}
$ret = [];
$needs = [ 'billing_salutation', 'billing_company', 'billing_firstname', 'billing_lastname', 'billing_address', 'billing_address_2', 'billing_zipcode', 'billing_city', 'billing_phone', 'billing_email', 'same_as_billing',
$needs = ['billing_salutation', 'billing_company', 'billing_firstname', 'billing_lastname', 'billing_address', 'billing_address_2', 'billing_zipcode', 'billing_city', 'billing_phone', 'billing_email', 'same_as_billing',
'shipping_salutation', 'shipping_company', 'shipping_firstname', 'shipping_lastname', 'shipping_address', 'shipping_address_2', 'shipping_zipcode', 'shipping_city', 'shipping_phone'];
foreach ($data as $key=>$value){
if($key === 'billing_country_code' && isset($data['billing_country_code'])) {
$ret['billing_country_id'] = Country::getCountryIdByCodeOrOne($data['billing_country_code']);
foreach ($data as $key => $value) {
if ($key === 'billing_country_code' && isset($data['billing_country_code'])) {
$ret['billing_country_id'] = Country::getCountryIdByCodeOrOne($data['billing_country_code']);
}
if($key === 'shipping_country_code' && isset($data['shipping_country_code']) ) {
if ($key === 'shipping_country_code' && isset($data['shipping_country_code'])) {
$ret['shipping_country_id'] = Country::getCountryIdByCodeOrOne($data['shipping_country_code']);
}
if($key === 'billing_phone') {
if ($key === 'billing_phone') {
$ret['billing_phone'] = strlen($data['billing_phone']) <= 3 ? '' : $data['billing_phone'];
}
if($key === 'shipping_phone') {
if ($key === 'shipping_phone') {
$ret['shipping_phone'] = strlen($data['shipping_phone']) <= 3 ? '' : $data['shipping_phone'];
}
if(in_array($key, $needs)){
if (in_array($key, $needs)) {
$ret[$key] = $value;
}
}
return $ret;
}
private function prepareForStore($data){
private function prepareForStore($data)
{
//$salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
if(isset($data['billing_salutation'])){
$data['billing_salutation'] = (int) $data['billing_salutation'];
// $salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
if (isset($data['billing_salutation'])) {
$data['billing_salutation'] = (int) $data['billing_salutation'];
$data['billing_salutation'] = $data['billing_salutation'] == 2 ? 'ms' : 'mr';
}
if(isset($data['shipping_salutation'])){
$data['shipping_salutation'] = (int) $data['shipping_salutation'];
$data['shipping_salutation'] = $data['shipping_salutation'] == 2 ? 'ms' : 'mr';
if (isset($data['shipping_salutation'])) {
$data['shipping_salutation'] = (int) $data['shipping_salutation'];
$data['shipping_salutation'] = $data['shipping_salutation'] == 2 ? 'ms' : 'mr';
}
$ret = [];
$needs = [ 'billing_salutation', 'billing_company', 'billing_firstname', 'billing_lastname', 'billing_address', 'billing_address_2', 'billing_zipcode', 'billing_city', 'billing_country_id', 'billing_phone', 'billing_email',
$needs = ['billing_salutation', 'billing_company', 'billing_firstname', 'billing_lastname', 'billing_address', 'billing_address_2', 'billing_zipcode', 'billing_city', 'billing_country_id', 'billing_phone', 'billing_email',
'shipping_salutation', 'shipping_company', 'shipping_firstname', 'shipping_lastname', 'shipping_address', 'shipping_address_2', 'shipping_zipcode', 'shipping_city', 'shipping_country_id', 'shipping_phone',
'same_as_billing', //'has_buyed', 'subscribed',
'same_as_billing', // 'has_buyed', 'subscribed',
'wp_order_number', 'wp_order_date'];
foreach ($needs as $need){
foreach ($needs as $need) {
$ret[$need] = isset($data[$need]) ? $data[$need] : null;
if ($need === 'billing_country_id') {
@ -565,35 +570,37 @@ class ShoppingUserController extends Controller
$ret['wp_order_date'] = Carbon::parse($ret['wp_order_date'])->toDateTimeString();
}
if ($need === 'same_as_billing') {
$ret['same_as_billing'] = isset($data['same_as_billing']) ? $data['same_as_billing'] : true;
$ret['same_as_billing'] = isset($data['same_as_billing']) ? $data['same_as_billing'] : true;
}
}
$ret['has_buyed'] = true;
$ret['subscribed'] = false;
return $ret;
}
private function prepareOrder($wp_shopping_order, $shopping_user, $wp_invoice_path, $api_notice){
private function prepareOrder($wp_shopping_order, $shopping_user, $wp_invoice_path, $api_notice)
{
Yard::instance('shopping')->destroy();
$ret = [];
if(is_array($wp_shopping_order)){
if (is_array($wp_shopping_order)) {
foreach ($wp_shopping_order as $order) {
//$object = json_decode(json_encode($order), FALSE);
// $object = json_decode(json_encode($order), FALSE);
$order = (object) $order;
$error = [];
if (!isset($order->article) || !isset($order->qty) || !isset($order->price)) {
$error[] = "article parameter is missing";
if (! isset($order->article) || ! isset($order->qty) || ! isset($order->price)) {
$error[] = 'article parameter is missing';
} else {
$product = Product::whereWpNumber($order->article)->first();
if (!$product) {
$error[] = "article not found";
if (! $product) {
$error[] = 'article not found';
} else {
if ($order->price != ($product->price * 100)) {
$error[] = "different price: " . ($product->price * 100);
$error[] = 'different price: '.($product->price * 100);
}
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), (int) $order->qty, $product->price, false, false, ['image' => [], 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), (int) $order->qty, $product->price, false, false, ['image' => [], 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
Yard::setTax($cartItem->rowId, $product->getTaxWith());
}
}
@ -602,7 +609,7 @@ class ShoppingUserController extends Controller
}
$ShippingCountry = ShippingCountry::whereCountryId($shopping_user->shipping_country_id)->first();
if($ShippingCountry){
if ($ShippingCountry) {
Yard::instance('shopping')->setShippingCountryWithPrice($ShippingCountry->id);
}
$shopping_order = $this->makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice);
@ -611,11 +618,13 @@ class ShoppingUserController extends Controller
$shopping_user->shopping_order = $shopping_order;
Yard::instance('shopping')->destroy();
}
return $ret;
}
private function makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice){
private function makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice)
{
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
@ -641,23 +650,22 @@ class ShoppingUserController extends Controller
'mode' => $shopping_user->mode,
];
$shopping_order = $shopping_user->shopping_order;
if($shopping_order){
if ($shopping_order) {
$shopping_order->fill($data);
$shopping_order->save();
}else{
$shopping_order= ShoppingOrder::create($data);
} else {
$shopping_order = ShoppingOrder::create($data);
}
$items = Yard::instance('shopping')->content();
$shopping_order->shopping_order_items()->each(function($model) use ($items, $shopping_order) {
$shopping_order->shopping_order_items()->each(function ($model) use ($items, $shopping_order) {
foreach ($items as $item) {
$price_net = Yard::instance('shopping')->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
if ($model->row_id === $item->rowId) {
$model->fill([
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'qty' => $item->qty,
'price' => $item->price,
@ -669,20 +677,21 @@ class ShoppingUserController extends Controller
'points' => $item->options->points,
'slug' => $item->options->slug,
])->save();
return false;
}
}
return $model->delete();
});
foreach ($items as $item) {
if (!ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()){
if (! ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
$price_net = Yard::instance('shopping')->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
ShoppingOrderItem::create([
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'qty' => $item->qty,
'price' => $item->price,
@ -692,27 +701,27 @@ class ShoppingUserController extends Controller
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
'slug' => $item->options->slug,
]);
}
}
$shopping_order->makeTaxSplit();
return $shopping_order;
}
public function orderStatusSendMail(ShoppingOrder $shopping_order){
public function orderStatusSendMail(ShoppingOrder $shopping_order)
{
$bcc = [];
$user_mail = $shopping_order->shopping_user->member->email;
if($shopping_order->mode === 'dev'){
if ($shopping_order->mode === 'dev') {
$bcc[] = config('app.checkout_test_mail');
}else{
} else {
$bcc[] = config('app.checkout_mail');
}
Mail::to($user_mail)->bcc($bcc)->locale($shopping_order->getLocale())->send(new MailCheckout($shopping_order->txaction, $shopping_order, null, false, $shopping_order->mode));
}
}
}

View file

@ -1,19 +1,14 @@
<?php
namespace App\Http\Controllers;
use Carbon;
use Request;
use App\Services\Payment;
use App\Models\UserInvoice;
use App\Services\HTMLHelper;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\HTMLHelper;
use Request;
class BusinessPointsController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -26,7 +21,6 @@ class BusinessPointsController extends Controller
->groupBy('user_id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->get();
$this->setFilterVars();
$data = [
'filter_months' => HTMLHelper::getTransMonths(),
@ -34,37 +28,40 @@ class BusinessPointsController extends Controller
'filter_members' => $filter_members,
'filter_status_types' => UserSalesVolume::getTransStatusType(),
];
return view('admin.business.points', $data);
}
public function store()
{
$data = Request::all();
if (!isset($data['action'])) {
if (! isset($data['action'])) {
return back();
}
if (!isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
if (! isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
\Session()->flash('alert-error', 'Das Passwort ist falsch.');
return back();
}
if (!isset($data['is_checked_action'])) {
if (! isset($data['is_checked_action'])) {
\Session()->flash('alert-error', 'Änderung nicht bestätigt');
return back();
}
if ($data['action'] === 'add_user_sales_volume') {
SalesPointsVolume::addSalesPointsVolume($data);
return back();
}
if ($data['action'] === 'edit_user_sales_volume') {
SalesPointsVolume::editSalesPointsVolume($data);
return back();
}
return redirect(route('admin_business_points'));
}
@ -74,34 +71,35 @@ class BusinessPointsController extends Controller
$month = Request::get('points_filter_month');
$year = Request::get('points_filter_year');
if (!$user_id) {
if (! $user_id) {
\Session()->flash('alert-error', 'Kein Berater ausgewählt.');
return back();
}
if (!$month || !$year) {
if (! $month || ! $year) {
\Session()->flash('alert-error', 'Monat und Jahr müssen angegeben sein.');
return back();
}
try {
SalesPointsVolume::reCalculateSalesPointsVolume($user_id, $month, $year);
\Session()->flash('alert-success', 'Punkte für den ausgewählten Berater im Monat ' . str_pad($month, 2, "0", STR_PAD_LEFT) . '/' . $year . ' wurden erfolgreich neu berechnet.');
\Session()->flash('alert-success', 'Punkte für den ausgewählten Berater im Monat '.str_pad($month, 2, '0', STR_PAD_LEFT).'/'.$year.' wurden erfolgreich neu berechnet.');
} catch (\Exception $e) {
\Session()->flash('alert-error', 'Fehler bei der Neuberechnung: ' . $e->getMessage());
\Session()->flash('alert-error', 'Fehler bei der Neuberechnung: '.$e->getMessage());
}
return back();
}
private function setFilterVars()
{
if (!session('points_filter_month')) {
if (! session('points_filter_month')) {
session(['points_filter_month' => intval(date('m'))]);
}
if (!session('points_filter_year')) {
if (! session('points_filter_year')) {
session(['points_filter_year' => intval(date('Y'))]);
}
@ -120,7 +118,7 @@ class BusinessPointsController extends Controller
{
$this->setFilterVars();
//$query = UserSalesVolume::with('user', 'user.account')->with('shopping_order')->select('user_sales_volumes.*')
// $query = UserSalesVolume::with('user', 'user.account')->with('shopping_order')->select('user_sales_volumes.*')
$query = UserSalesVolume::join('users', 'user_id', '=', 'users.id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('user_sales_volumes.*', 'users.email', 'user_accounts.m_account', 'user_accounts.first_name', 'user_accounts.last_name')
->where('user_sales_volumes.month', '=', Request::get('points_filter_month'))
@ -132,6 +130,7 @@ class BusinessPointsController extends Controller
if (Request::get('points_filter_status_type_id')) {
$query->where('user_sales_volumes.status', '=', Request::get('points_filter_status_type_id'));
}
return $query;
}
@ -141,10 +140,10 @@ class BusinessPointsController extends Controller
$month = Request::get('points_filter_month');
$year = Request::get('points_filter_year');
if (!$user_id || !$month || !$year) {
if (! $user_id || ! $month || ! $year) {
return response()->json([
'success' => false,
'data' => null
'data' => null,
]);
}
@ -155,10 +154,10 @@ class BusinessPointsController extends Controller
->orderBy('id', 'DESC')
->first();
if (!$lastEntry) {
if (! $lastEntry) {
return response()->json([
'success' => false,
'data' => null
'data' => null,
]);
}
@ -173,7 +172,7 @@ class BusinessPointsController extends Controller
'total_KP_points' => ($lastEntry->month_KP_points ?? 0) + ($lastEntry->month_shop_points ?? 0),
'total_TP_points' => ($lastEntry->month_TP_points ?? 0) + ($lastEntry->month_shop_points ?? 0),
'total_net' => ($lastEntry->month_total_net ?? 0) + ($lastEntry->month_shop_total_net ?? 0),
]
],
]);
}
@ -181,67 +180,80 @@ class BusinessPointsController extends Controller
{
$query = $this->initSearch();
return \DataTables::eloquent($query)
->addColumn('id', function (UserSalesVolume $UserSalesVolume) {
return '<button type="button" class="btn btn-xs btn-secondary" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $UserSalesVolume->id . '"
data-id="'.$UserSalesVolume->id.'"
data-action="edit_user_sales_volume"
data-back=""
data-modal="modal-xl"
data-init_from="user"
data-route="' . route('modal_load') . '"><span class="fa fa-eye"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
})
->addColumn('order', function (UserSalesVolume $UserSalesVolume) {
if ($UserSalesVolume->shopping_order) {
// Status 1 = Beraterbestellung
if ($UserSalesVolume->status === 1) {
return '<a href="' . route('admin_sales_users_detail', [$UserSalesVolume->shopping_order->id]) . '" class="btn btn-xs btn-primary">' . $UserSalesVolume->shopping_order->id . '</a>';
return '<a href="'.route('admin_sales_users_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-primary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
// Status 2/3 = Shop-Bestellung
if ($UserSalesVolume->status === 2 || $UserSalesVolume->status === 3) {
return '<a href="' . route('admin_sales_customers_detail', [$UserSalesVolume->shopping_order->id]) . '" class="btn btn-xs btn-secondary">' . $UserSalesVolume->shopping_order->id . '</a>';
return '<a href="'.route('admin_sales_customers_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-secondary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
// Status 6 = Storno - Link zur ursprünglichen Bestellung mit Storno-Icon
if ($UserSalesVolume->status === 6) {
// Prüfen ob Berater- oder Shop-Bestellung anhand des payment_for Feldes
$route = ($UserSalesVolume->shopping_order->payment_for === 6 || $UserSalesVolume->shopping_order->payment_for === 7)
? route('admin_sales_customers_detail', [$UserSalesVolume->shopping_order->id])
: route('admin_sales_users_detail', [$UserSalesVolume->shopping_order->id]);
return '<a href="'.$route.'" class="btn btn-xs btn-danger" title="Storno-Eintrag"><i class="fa fa-undo"></i> '.$UserSalesVolume->shopping_order->id.'</a>';
}
}
return '';
})
->addColumn('points', function (UserSalesVolume $UserSalesVolume) {
return formatNumber($UserSalesVolume->points);
})
->addColumn('total_net', function (UserSalesVolume $UserSalesVolume) {
return formatNumber($UserSalesVolume->total_net) . ' &euro;';
return formatNumber($UserSalesVolume->total_net).' &euro;';
})
->addColumn('status_turnover', function (UserSalesVolume $UserSalesVolume) {
return '<span class="badge badge-pill badge-' . $UserSalesVolume->getStatusTurnoverColor() . '">' . $UserSalesVolume->getStatusTurnoverType() . '</span>';
return '<span class="badge badge-pill badge-'.$UserSalesVolume->getStatusTurnoverColor().'">'.$UserSalesVolume->getStatusTurnoverType().'</span>';
})
->addColumn('status', function (UserSalesVolume $UserSalesVolume) {
return '<span class="badge badge-pill badge-' . $UserSalesVolume->getStatusColor() . '">' . $UserSalesVolume->getStatusType() . '</span>';
return '<span class="badge badge-pill badge-'.$UserSalesVolume->getStatusColor().'">'.$UserSalesVolume->getStatusType().'</span>';
})
->addColumn('status_points', function (UserSalesVolume $UserSalesVolume) {
return '<span class="badge badge-pill badge-' . $UserSalesVolume->getStatusPointsColor() . '">' . $UserSalesVolume->getStatusPointsType() . '</span>';
return '<span class="badge badge-pill badge-'.$UserSalesVolume->getStatusPointsColor().'">'.$UserSalesVolume->getStatusPointsType().'</span>';
})
->addColumn('message', function (UserSalesVolume $UserSalesVolume) {
return '<span class="no-line-break">' . $UserSalesVolume->message . '</span>';
return '<span class="no-line-break">'.$UserSalesVolume->message.'</span>';
})
->addColumn('info', function (UserSalesVolume $UserSalesVolume) {
return '<span class="no-line-break">' . $UserSalesVolume->info . '</span>';
return '<span class="no-line-break">'.$UserSalesVolume->info.'</span>';
})
->filterColumn('m_account', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("m_account LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('m_account LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('first_name', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("first_name LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('first_name LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('last_name', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("last_name LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('last_name LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('email', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("email LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('email LIKE ?', '%'.$keyword.'%');
}
})

View file

@ -52,7 +52,6 @@ class DhlShipmentController extends Controller
// Get DHL configuration with admin settings
$settingController = new \App\Http\Controllers\SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Create DhlClient with merged configuration
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlConfig['base_url'],
@ -67,7 +66,7 @@ class DhlShipmentController extends Controller
if ($connectionTest) {
$result = [
'success' => true,
'message' => 'DHL API Verbindung erfolgreich getestet!',
'message' => 'DHL API Verbindung erfolgreich getestet! '.config('dhl.config_source').' '.$dhlConfig['base_url'],
'details' => [
'base_url' => $dhlConfig['base_url'],
'using_admin_config' => ! empty($dhlConfig['api_key']),
@ -88,7 +87,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'DHL API Test fehlgeschlagen: ' . $e->getMessage(),
'message' => 'DHL API Test fehlgeschlagen: '.$e->getMessage(),
], 500);
}
}
@ -148,12 +147,13 @@ class DhlShipmentController extends Controller
return DataTables::eloquent($query)
->addColumn('checkbox', function ($shipment) {
return '<label class="custom-control custom-checkbox mb-0"><input type="checkbox" class="custom-control-input shipment-checkbox" value="' . $shipment->id . '"><span class="custom-control-label"></span></label>';
return '<label class="custom-control custom-checkbox mb-0"><input type="checkbox" class="custom-control-input shipment-checkbox" value="'.$shipment->id.'"><span class="custom-control-label"></span></label>';
})
->editColumn('id', function ($shipment) {
$class = $shipment->type === 'return' ? 'text-warning font-weight-bold' : 'text-primary font-weight-semibold';
$icon = $shipment->type === 'return' ? '<i class="fas fa-undo mr-1"></i>' : '';
return '<a href="' . route('admin.dhl.show', $shipment) . '" class="' . $class . '">' . $icon . '#' . $shipment->id . '</a>';
return '<a href="'.route('admin.dhl.show', $shipment).'" class="'.$class.'">'.$icon.'#'.$shipment->id.'</a>';
})
->addColumn('type', function ($shipment) {
if ($shipment->type == 'outbound') {
@ -164,16 +164,16 @@ class DhlShipmentController extends Controller
})
->addColumn('order', function ($shipment) {
if ($shipment->order_id) {
return '<a href="' . route('admin_sales_customers_detail', $shipment->order_id) . '" class="text-primary">#' . $shipment->order_id . '</a>';
return '<a href="'.route('admin_sales_customers_detail', $shipment->order_id).'" class="text-primary">#'.$shipment->order_id.'</a>';
}
return '<span class="text-muted">N/A</span>';
})
->addColumn('customer', function ($shipment) {
return $shipment->firstname . ' ' . $shipment->lastname;
return $shipment->firstname.' '.$shipment->lastname;
})
->editColumn('dhl_shipment_no', function ($shipment) {
return $shipment->dhl_shipment_no ? '<code class="text-success">' . e($shipment->dhl_shipment_no) . '</code>' : '<span class="text-muted">-</span>';
return $shipment->dhl_shipment_no ? '<code class="text-success">'.e($shipment->dhl_shipment_no).'</code>' : '<span class="text-muted">-</span>';
})
->addColumn('status', function ($shipment) {
$statusMap = [
@ -186,43 +186,43 @@ class DhlShipmentController extends Controller
];
$statusInfo = $statusMap[$shipment->status] ?? ['class' => 'light', 'text' => e($shipment->status)];
return '<span class="badge badge-' . $statusInfo['class'] . '">' . $statusInfo['text'] . '</span>';
return '<span class="badge badge-'.$statusInfo['class'].'">'.$statusInfo['text'].'</span>';
})
->addColumn('tracking_status', function ($shipment) {
if ($shipment->tracking_status) {
return '<small class="text-muted">' . e($shipment->tracking_status) . '</small>' .
($shipment->last_tracked_at ? '<br><small class="text-muted">' . $shipment->last_tracked_at->format('d.m.Y H:i') . '</small>' : '');
return '<small class="text-muted">'.e($shipment->tracking_status).'</small>'.
($shipment->last_tracked_at ? '<br><small class="text-muted">'.$shipment->last_tracked_at->format('d.m.Y H:i').'</small>' : '');
}
return '<span class="text-muted">-</span>';
})
->editColumn('weight_kg', function ($shipment) {
return number_format($shipment->weight_kg, 2) . ' kg';
return number_format($shipment->weight_kg, 2).' kg';
})
->editColumn('created_at', function ($shipment) {
return $shipment->created_at->format('d.m.Y H:i');
})
->addColumn('actions', function ($shipment) {
$buttons = '<div class="btn-group" role="group">';
$buttons .= '<a href="' . route('admin.dhl.show', $shipment) . '" class="btn btn-sm btn-outline-primary" data-toggle="tooltip" title="Details anzeigen"><i class="fas fa-eye"></i></a>';
$buttons .= '<a href="'.route('admin.dhl.show', $shipment).'" class="btn btn-sm btn-outline-primary" data-toggle="tooltip" title="Details anzeigen"><i class="fas fa-eye"></i></a>';
if ($shipment->label_path) {
$buttons .= '<a href="' . route('admin.dhl.download-label', $shipment) . '" class="btn btn-sm btn-outline-success" data-toggle="tooltip" title="Label herunterladen"><i class="fas fa-download"></i></a>';
$buttons .= '<a href="'.route('admin.dhl.download-label', $shipment).'" class="btn btn-sm btn-outline-success" data-toggle="tooltip" title="Label herunterladen"><i class="fas fa-download"></i></a>';
}
// Email button
if ($shipment->dhl_shipment_no && $shipment->canSendTrackingEmail()) {
$emailTitle = $shipment->wasTrackingEmailSent()
? 'Tracking-E-Mail erneut senden (gesendet: ' . $shipment->tracking_email_sent_at->format('d.m.Y H:i') . ')'
? 'Tracking-E-Mail erneut senden (gesendet: '.$shipment->tracking_email_sent_at->format('d.m.Y H:i').')'
: 'Tracking-E-Mail senden';
$emailClass = $shipment->wasTrackingEmailSent() ? 'btn-success' : 'btn-outline-info';
$buttons .= '<button type="button" class="btn btn-sm ' . $emailClass . ' send-tracking-email-btn" data-shipment-id="' . $shipment->id . '" data-toggle="tooltip" title="' . $emailTitle . '"><i class="fas fa-envelope"></i></button>';
$buttons .= '<button type="button" class="btn btn-sm '.$emailClass.' send-tracking-email-btn" data-shipment-id="'.$shipment->id.'" data-toggle="tooltip" title="'.$emailTitle.'"><i class="fas fa-envelope"></i></button>';
}
// Cancel button
if ($shipment->canCancel()) {
$buttons .= '<button type="button" class="btn btn-sm btn-outline-danger cancel-shipment-btn" data-shipment-id="' . $shipment->id . '" data-toggle="tooltip" title="Sendung stornieren"><i class="fas fa-ban"></i></button>';
$buttons .= '<button type="button" class="btn btn-sm btn-outline-danger cancel-shipment-btn" data-shipment-id="'.$shipment->id.'" data-toggle="tooltip" title="Sendung stornieren"><i class="fas fa-ban"></i></button>';
}
// Return label button
// Return label button (for outbound shipments without existing return)
if ($shipment->type == 'outbound' && ! $shipment->returns()->count()) {
$buttons .= '<button type="button" class="btn btn-sm btn-outline-info create-return-btn" data-shipment-id="' . $shipment->id . '" data-toggle="tooltip" title="Retourenlabel erstellen"><i class="fas fa-undo"></i></button>';
$buttons .= '<button type="button" class="btn btn-sm btn-outline-info create-return-btn" data-shipment-id="'.$shipment->id.'" data-toggle="tooltip" title="Retourenlabel erstellen"><i class="fas fa-undo"></i></button>';
}
$buttons .= '</div>';
@ -268,7 +268,7 @@ class DhlShipmentController extends Controller
if (! $validationResult['valid']) {
return response()->json([
'success' => false,
'message' => 'Validierungsfehler: ' . implode(', ', $validationResult['errors']),
'message' => 'Validierungsfehler: '.implode(', ', $validationResult['errors']),
], 422);
}
@ -341,7 +341,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Erstellen der Sendung: ' . $e->getMessage(),
'message' => 'Fehler beim Erstellen der Sendung: '.$e->getMessage(),
], 500);
}
}
@ -351,7 +351,11 @@ class DhlShipmentController extends Controller
*/
public function show(DhlShipment $shipment): View
{
$shipment->load(['shoppingOrder.shopping_user', 'relatedShipment']);
$shipment->load([
'shoppingOrder.shopping_user',
'relatedShipment',
'trackingEvents' => fn ($q) => $q->orderBy('event_time', 'desc'),
]);
return view('admin.dhl.show', compact('shipment'));
}
@ -394,7 +398,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Stornieren der Sendung: ' . $e->getMessage(),
'message' => 'Fehler beim Stornieren der Sendung: '.$e->getMessage(),
], 500);
}
}
@ -426,7 +430,7 @@ class DhlShipmentController extends Controller
}
// Check DHL_USE_QUEUE configuration
$settingController = new SettingController();
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
$useQueue = $dhlConfig['use_queue'] ?? false;
@ -462,11 +466,59 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Erstellen des Retourenlabels: ' . $e->getMessage(),
'message' => 'Fehler beim Erstellen des Retourenlabels: '.$e->getMessage(),
], 500);
}
}
/**
* Get billing address for return label (used when original delivery was to Packstation)
*/
private function getBillingAddressForReturn($shippingUser, array $recipient): array
{
if (! $shippingUser) {
Log::warning('[DHL Controller] No shipping user found, using recipient data', [
'recipient' => $recipient,
]);
// Fallback: use recipient data but without Packstation fields
return [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => 'Adresse fehlt',
'houseNumber' => '',
'postalCode' => $recipient['postalCode'] ?? '',
'city' => $recipient['city'] ?? '',
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
];
}
// Parse billing address to extract street and house number
$billingAddress = trim($shippingUser->billing_address ?? '');
$street = $billingAddress;
$houseNumber = '';
// Try to extract house number from address
if (preg_match('/^(.+?)\s+(\d+[a-zA-Z]?[-\/\d]*)$/u', $billingAddress, $matches)) {
$street = trim($matches[1]);
$houseNumber = trim($matches[2]);
}
return [
'name' => trim(($shippingUser->billing_firstname ?? '').' '.($shippingUser->billing_lastname ?? '')),
'name2' => $shippingUser->billing_company ?? '',
'street' => $street,
'houseNumber' => $houseNumber,
'postalCode' => $shippingUser->billing_zipcode ?? '',
'city' => $shippingUser->billing_city ?? '',
'country' => $shippingUser->billing_country?->code ?? 'DEU',
'email' => $shippingUser->billing_email ?? '',
'phone' => $shippingUser->billing_phone ?? '',
];
}
/**
* Create return label synchronously
*/
@ -478,7 +530,7 @@ class DhlShipmentController extends Controller
]);
// Get DHL configuration
$settingController = new SettingController();
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Initialize DHL client
@ -496,15 +548,22 @@ class DhlShipmentController extends Controller
$order = $shipment->shoppingOrder;
$recipient = $shipment->recipient ?? [];
$returnData = [
'order_id' => $order->id,
'original_shipment_id' => $shipment->id,
'weight_kg' => $shipment->weight_kg,
'label_format' => $shipment->label_format ?? 'PDF',
// Check if this is a Packstation delivery - use billing address as return sender
$hasPostNumber = ! empty($recipient['postnumber'] ?? $recipient['postNumber'] ?? '');
// Shipper: Customer sends back to us (swap addresses)
'shipper' => [
'name' => trim(($recipient['firstname'] ?? '') . ' ' . ($recipient['lastname'] ?? '')),
if ($hasPostNumber) {
Log::info('[DHL Controller] Packstation detected - using billing address for return sender', [
'shipment_id' => $shipment->id,
'order_id' => $order->id,
]);
// Load billing address from order
$shippingUser = $order->shopping_user;
$shipperAddress = $this->getBillingAddressForReturn($shippingUser, $recipient);
} else {
// Use original recipient address (normal delivery)
$shipperAddress = [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => $recipient['street'] ?? '',
'houseNumber' => $recipient['houseNumber'] ?? '',
@ -513,7 +572,17 @@ class DhlShipmentController extends Controller
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
],
];
}
$returnData = [
'order_id' => $order->id,
'original_shipment_id' => $shipment->id,
'weight_kg' => $shipment->weight_kg,
'label_format' => $shipment->label_format ?? 'PDF',
// Shipper: Customer sends back to us (using billing address for Packstation)
'shipper' => $shipperAddress,
// Consignee: Our warehouse
'consignee' => [
@ -551,7 +620,7 @@ class DhlShipmentController extends Controller
return [
'success' => false,
'message' => 'Fehler beim Erstellen des Retourenlabels: ' . $e->getMessage(),
'message' => 'Fehler beim Erstellen des Retourenlabels: '.$e->getMessage(),
];
}
}
@ -589,7 +658,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Aktualisieren der Tracking-Informationen: ' . $e->getMessage(),
'message' => 'Fehler beim Aktualisieren der Tracking-Informationen: '.$e->getMessage(),
], 500);
}
}
@ -679,7 +748,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Senden der Tracking-E-Mail: ' . $e->getMessage(),
'message' => 'Fehler beim Senden der Tracking-E-Mail: '.$e->getMessage(),
], 500);
}
}
@ -721,7 +790,7 @@ class DhlShipmentController extends Controller
private function generateLabelFilename(DhlShipment $shipment): string
{
// Load order with customer data
$customerName = $shipment->firstname . '_' . $shipment->lastname;
$customerName = $shipment->firstname.'_'.$shipment->lastname;
if ($shipment->company) {
$customerName = $shipment->company;
}
@ -747,7 +816,7 @@ class DhlShipmentController extends Controller
// Ensure filename is not too long (max 255 characters)
if (strlen($filename) > 255) {
$maxCustomerLength = 255 - strlen('DHL--' . $shipmentNumber . '-' . $date . '.pdf');
$maxCustomerLength = 255 - strlen('DHL--'.$shipmentNumber.'-'.$date.'.pdf');
$customerName = substr($customerName, 0, max(10, $maxCustomerLength));
$filename = sprintf(
'DHL-%s-%s-%s.pdf',
@ -802,7 +871,7 @@ class DhlShipmentController extends Controller
if ($trackingResult['success']) {
$processed++;
} else {
$errors[] = "Sendung #{$shipment->id}: " . $trackingResult['message'];
$errors[] = "Sendung #{$shipment->id}: ".$trackingResult['message'];
}
} else {
$errors[] = "Sendung #{$shipment->id} hat keine DHL-Sendungsnummer.";
@ -823,7 +892,7 @@ class DhlShipmentController extends Controller
break;
}
} catch (Exception $e) {
$errors[] = "Fehler bei Sendung {$shipmentId}: " . $e->getMessage();
$errors[] = "Fehler bei Sendung {$shipmentId}: ".$e->getMessage();
}
}
@ -852,7 +921,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler bei der Stapelverarbeitung: ' . $e->getMessage(),
'message' => 'Fehler bei der Stapelverarbeitung: '.$e->getMessage(),
], 500);
}
}
@ -917,8 +986,8 @@ class DhlShipmentController extends Controller
{
try {
$zip = new ZipArchive;
$zipFilename = 'dhl_labels_' . date('Y-m-d_H-i-s') . '.zip';
$zipPath = storage_path('app/temp/' . $zipFilename);
$zipFilename = 'dhl_labels_'.date('Y-m-d_H-i-s').'.zip';
$zipPath = storage_path('app/temp/'.$zipFilename);
// Ensure temp directory exists
if (! file_exists(storage_path('app/temp'))) {
@ -963,7 +1032,7 @@ class DhlShipmentController extends Controller
return response()->json([
'success' => false,
'message' => 'Fehler beim Erstellen der ZIP-Datei: ' . $e->getMessage(),
'message' => 'Fehler beim Erstellen der ZIP-Datei: '.$e->getMessage(),
], 500);
}
}

View file

@ -2,11 +2,11 @@
namespace App\Http\Controllers;
use Auth;
use Storage;
use Response;
use App\Models\UserCredit;
use App\Repositories\CreditRepository;
use Auth;
use Response;
use Storage;
class FileController extends Controller
{
@ -19,16 +19,37 @@ class FileController extends Controller
private function isPermissionShoppingOrder($shopping_order)
{
$user_id = $shopping_order->auth_user_id ? $shopping_order->auth_user_id : $shopping_order->member_id;
if (Auth::user()->isAdmin() || $user_id == Auth::user()->id) {
return true;
// Portal-Kunden (auth:customers) Prüfung über shopping_user (billing_email + member_id)
if (Auth::guard('customers')->check()) {
$customer = Auth::guard('customers')->user();
if ($customer->shopping_user_id) {
$member = $customer->shoppingUser;
if ($member && $shopping_order->shopping_user) {
$orderUser = $shopping_order->shopping_user;
if (
$orderUser->billing_email === $member->billing_email
&& $orderUser->member_id === $member->member_id
) {
return true;
}
}
}
}
// Admin / Berater (auth:user)
if (Auth::check()) {
$user_id = $shopping_order->auth_user_id ?: $shopping_order->member_id;
if (Auth::user()->isAdmin() || $user_id == Auth::user()->id) {
return true;
}
}
abort(404);
}
private function isPermissionUserCredit($user_credit)
{
if (Auth::user()->isAdmin() || $user_credit->user_id == Auth::user()->id) {
if (Auth::user()->isAdmin() || $user_credit->user_id == Auth::user()->id) {
return true;
}
abort(404);
@ -39,16 +60,15 @@ class FileController extends Controller
if (Auth::check()) {
return true;
}
abort(403, "Nicht autorisiert");
abort(403, 'Nicht autorisiert');
}
public function show($id = null, $from = null, $do = 'file')
public function show($id = null, $from = null, $do = 'file', $locale = null)
{
$path = "";
$filename = "";
$disk = "public";
$path = '';
$filename = '';
$disk = 'public';
/*if($disk === 'user'){
$file = \App\Models\File::findOrFail($id);
$this->isPermission($file->user_id);
@ -62,9 +82,15 @@ class FileController extends Controller
if ($shopping_order->user_invoice) {
$this->isPermissionShoppingOrder($shopping_order);
$user_invoice = $shopping_order->user_invoice;
$filename = $user_invoice->filename;
$disk = $user_invoice->disk;
$path = $user_invoice->getDownloadPath();
// Lokalisierte Version wenn angegeben
if ($locale && $locale !== 'de') {
$filename = $user_invoice->getFilenameLocale($locale);
$path = $user_invoice->getDownloadPathLocale($locale);
} else {
$filename = $user_invoice->filename;
$path = $user_invoice->getDownloadPath();
}
}
}
@ -73,18 +99,65 @@ class FileController extends Controller
if ($shopping_order->user_invoice) {
$this->isPermissionShoppingOrder($shopping_order);
$user_invoice = $shopping_order->user_invoice;
$filename = $user_invoice->delivery_filename;
$disk = $user_invoice->disk;
$path = $user_invoice->getDownloadPathDelivery();
// Lokalisierte Version wenn angegeben
if ($locale && $locale !== 'de') {
$filename = $user_invoice->getFilenameLocale($locale);
// Für Lieferschein den lokalisierten Pfad ermitteln
$localizedDeliveryFilename = str_replace('.pdf', '-'.$locale.'.pdf', $user_invoice->delivery_filename);
$localizedPath = $user_invoice->delivery_dir.$localizedDeliveryFilename;
if (Storage::disk($disk)->exists($localizedPath)) {
$filename = $localizedDeliveryFilename;
$path = $localizedPath;
} else {
$filename = $user_invoice->delivery_filename;
$path = $user_invoice->getDownloadPathDelivery();
}
} else {
$filename = $user_invoice->delivery_filename;
$path = $user_invoice->getDownloadPathDelivery();
}
}
}
if ($from === 'cancellation') {
$shopping_order = \App\Models\ShoppingOrder::findOrFail($id);
$this->isPermissionShoppingOrder($shopping_order);
// Stornorechnung finden: cancellation=true UND cancellation_id=null
// (Die Original-Rechnung hat auch cancellation=true, aber MIT cancellation_id)
$cancellation_invoice = \App\Models\UserInvoice::where('shopping_order_id', $shopping_order->id)
->where('cancellation', true)
->whereNull('cancellation_id')
->first();
if ($cancellation_invoice) {
$disk = $cancellation_invoice->disk;
// Lokalisierte Version wenn angegeben
if ($locale && $locale !== 'de') {
$filename = $cancellation_invoice->getFilenameLocale($locale);
$path = $cancellation_invoice->getDownloadPathLocale($locale);
} else {
$filename = $cancellation_invoice->filename;
$path = $cancellation_invoice->getDownloadPath();
}
} else {
return Response::make('Stornorechnung nicht gefunden.', 404);
}
}
if ($from === 'credit') {
$user_credit = \App\Models\UserCredit::findOrFail($id);
$this->isPermissionUserCredit($user_credit);
$filename = $user_credit->filename;
$disk = $user_credit->disk;
$path = $user_credit->getDownloadPath();
// Lokalisierte Version wenn angegeben
if ($locale && $locale !== 'de') {
$filename = $user_credit->getFilenameLocale($locale);
$path = $user_credit->getDownloadPathLocale($locale);
} else {
$filename = $user_credit->filename;
$path = $user_credit->getDownloadPath();
}
}
if ($from === 'credit_detail') {
@ -93,15 +166,13 @@ class FileController extends Controller
return $this->create_credit_detail($user_credit, $do);
/*
$filename = $user_credit->filename;
$disk = $user_credit->disk;
$path = $user_credit->getDownloadPath();
/*
$filename = $user_credit->filename;
$disk = $user_credit->disk;
$path = $user_credit->getDownloadPath();
*/
}
if ($from === 'dc_file') {
// $this->isPermissionAuth();
$dc_file = \App\Models\DcFile::findOrFail($id);
@ -125,9 +196,14 @@ class FileController extends Controller
$path = $dc_file->getBig();
}
if ($from === 'user') {
$file = \App\Models\File::findOrFail($id);
$filename = $file->filename;
$disk = 'user';
$path = $file->dir.$file->filename;
}
if (!Storage::disk($disk)->exists($path)) {
if (! Storage::disk($disk)->exists($path)) {
return Response::make('Datei nicht gefunden.', 404);
}
@ -137,7 +213,6 @@ class FileController extends Controller
$file = Storage::disk($disk)->get($path);
$mime = Storage::disk($disk)->mimeType($path);
if (isset($file)) {
if ($do === 'stream') {
return Storage::disk($disk)->response($path, $filename);
@ -145,22 +220,22 @@ class FileController extends Controller
if ($do === 'file') {
return Response::make($file, 200)
->header("Content-Type", $mime)
->header("Content-Length", strlen($file))
->header('Content-disposition', 'filename="' . $filename . '"');
->header('Content-Type', $mime)
->header('Content-Length', strlen($file))
->header('Content-disposition', 'filename="'.$filename.'"');
}
if ($do === 'image') {
return Response::make($file, 200)
->header("Content-Type", $mime);
->header('Content-Type', $mime);
}
if ($do === 'pdf') {
$path = storage_path() . '/app/public/' . $path;
$path = storage_path().'/app/public/'.$path;
$headers = array(
'Content-Type:' . $mime,
$headers = [
'Content-Type:'.$mime,
// 'Content-Length: ' . $file->size
// 'Content-Disposition: ' . $stream . '; filename=' . $file->original_name
);
];
return Response::download($path, $filename, $headers);
}
@ -171,8 +246,9 @@ class FileController extends Controller
{
$credit_repo = new CreditRepository($user_credit->user);
return $credit_repo->create_report($user_credit, $do);
//\Session()->flash('alert-success', "Gutschrift erstellt");
// \Session()->flash('alert-success', "Gutschrift erstellt");
}
}

View file

@ -4,9 +4,8 @@ namespace App\Http\Controllers;
use App\Models\ShoppingPayment;
use App\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Config;
use Illuminate\Support\Facades\Auth;
use Request;
use Util;
@ -19,20 +18,28 @@ class HomeController extends Controller
*/
public function __construct() {}
public function index()
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
return redirect('home');
}
//login / Dashboard
public function newsArchive(): \Illuminate\View\View
{
return view('dashboard.news_archive', [
'currentNews' => \App\Models\DashboardNews::getActiveNews(),
'archiveNews' => \App\Models\DashboardNews::getArchiveNews(),
]);
}
// login / Dashboard
public function show()
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
@ -41,17 +48,17 @@ class HomeController extends Controller
'now' => Carbon::now(),
'dashboardNews' => \App\Models\DashboardNews::getActiveNews(),
];
return view('home', $data);
}
public function loadingModal()
{
$data = Request::get('data');
$target = Request::get('target');
$response = "";
if ($data === "data_protection") {
$response = '';
if ($data === 'data_protection') {
$data = [
'modal' => true,
'user_shop' => true,
@ -59,21 +66,21 @@ class HomeController extends Controller
];
$response = view('legal.data_protect_de', $data)->render();
}
if ($data === "imprint") {
if ($data === 'imprint') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
];
$response = view('legal.imprint_de', $data)->render();
}
if ($data === "shop_term_of_use") {
if ($data === 'shop_term_of_use') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
];
$response = view('legal.shop_term_of_use_de', $data)->render();
}
if ($data === "agb") {
if ($data === 'agb') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
@ -81,7 +88,7 @@ class HomeController extends Controller
$response = view('legal.agb_de', $data)->render();
}
if (Request::ajax()) {
return response()->json(['response' => $response, 'target' => $target]);
return response()->json(['response' => $response, 'target' => $target]);
}
abort(404);
}
@ -154,6 +161,7 @@ class HomeController extends Controller
'isMivitaShop' => Util::isMivitaShop(),
'yard_instance' => 'webshop',
];
return view('legal.data_protected', $data);
}
@ -166,6 +174,7 @@ class HomeController extends Controller
'yard_instance' => 'webshop',
];
return view('legal.agb', $data);
}
@ -177,6 +186,7 @@ class HomeController extends Controller
'user_shop' => Util::getUserShop(),
'yard_instance' => 'webshop',
];
return view('legal.imprint', $data);
}
@ -195,19 +205,20 @@ class HomeController extends Controller
$user->confirmed = 1;
$user->confirmation_date = now();
$user_auto_login = true;
//nur bei der ersten Verifizierung den user auto login
// nur bei der ersten Verifizierung den user auto login
}
//wird nun in WizardController::releaseAccount() auf null gesetzt
//$user->confirmation_code = null;
//$user->confirmation_code_to = null;
//$user->confirmation_code_remider = 0;
// wird nun in WizardController::releaseAccount() auf null gesetzt
// $user->confirmation_code = null;
// $user->confirmation_code_to = null;
// $user->confirmation_code_remider = 0;
$user->save();
//Login!
// Login!
if ($user_auto_login) {
Auth::login($user);
}
$url = Util::getMyMivitaUrl();
return redirect($url);
}
@ -215,20 +226,22 @@ class HomeController extends Controller
{
return view('status.status_register');
}
public function statusVerify()
{
return view('status.status_verify');
}
public function statusError()
{
return view('status.status_error');
}
public function notFound()
{
return view('status.not_found');
}
/**
* @return string
*/
@ -236,7 +249,7 @@ class HomeController extends Controller
{
$data = Request::all();
if ($data['user_id'] === "new") {
if ($data['user_id'] === 'new') {
if (User::where('email', $data['email'])->count()) {
return json_encode(false);
}
@ -245,6 +258,7 @@ class HomeController extends Controller
return json_encode(false);
}
}
return json_encode(true);
}
@ -253,21 +267,23 @@ class HomeController extends Controller
return view('status.user_blocked');
}
public function backToShop($reference = "")
public function backToShop($reference = '')
{
if ($reference) {
$ShoppingPayment = ShoppingPayment::where('reference', $reference)->first();
if ($ShoppingPayment && $ShoppingPayment->status === 'success') {
$user = Auth::user();
//is form wizard create payment
// is form wizard create payment
if ($user && ($user->wizard == 13 || $user->wizard == 20)) {
$user->wizard = 15; //realese Payments
$user->wizard = 15; // realese Payments
$user->save();
return redirect(route('wizard_create', [15]));
}
} else {
\Session()->flash('alert-error', __('msg.error_occurred_with_order'));
return redirect(url('/'));
}
}

View file

@ -2,21 +2,23 @@
namespace App\Http\Controllers;
use Request;
use App\User;
use Validator;
use App\Services\SysLog;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Services\HTMLHelper;
use App\Services\UserService;
use App\Mail\MailAccountActive;
use App\Mail\MailCustomMessage;
use App\Mail\MailVerifyAccount;
use App\Mail\MailVerifyContact;
use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Mail;
use App\Models\File;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Repositories\ContractPDFRepository;
use App\Repositories\UserRepository;
use App\Services\HTMLHelper;
use App\Services\SysLog;
use App\Services\UserService;
use App\User;
use Auth;
use Illuminate\Support\Facades\Mail;
use Request;
use Validator;
class LeadController extends Controller
{
@ -34,8 +36,7 @@ class LeadController extends Controller
public function index()
{
$filter_sponsor = User::join('user_accounts', 'account_id', '=', 'user_accounts.id')->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->where('users.deleted_at', '=', null)->where('users.admin', "<", 4)->get();
$filter_sponsor = User::join('user_accounts', 'account_id', '=', 'user_accounts.id')->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->where('users.deleted_at', '=', null)->where('users.admin', '<', 4)->get();
$this->setFilterVars();
$data = [
@ -47,7 +48,6 @@ class LeadController extends Controller
return view('admin.lead.index', $data);
}
private function setFilterVars()
{
@ -68,25 +68,22 @@ class LeadController extends Controller
}*/
}
/**
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
if ($id === "new") {
$user = new User();
$user->account = new UserAccount();
if ($id === 'new') {
$user = new User;
$user->account = new UserAccount;
$user->account->same_as_billing = 1;
$user->account->country_id = 1;
$user->account->shipping_country_id = 1;
$user->id = "new";
$user->id = 'new';
} else {
$user = User::withTrashed()->findOrFail($id);
if (!$user->account) {
$user->account = new UserAccount();
if (! $user->account) {
$user->account = new UserAccount;
}
}
$data = [
@ -96,11 +93,11 @@ class LeadController extends Controller
'm_data_load' => false,
'm_data_error' => false,
];
return view('admin.lead.edit', $data);
}
/**
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function editPost($id)
@ -108,23 +105,23 @@ class LeadController extends Controller
$m_data_load = false;
$m_data_error = false;
$data = Request::all();
if (!isset($data['edit_m_data_key']) || $data['edit_m_data_key'] !== config('mivita.edit_data_pass')) {
$m_data_error = "Das Passwort ist falsch.";
if (! isset($data['edit_m_data_key']) || $data['edit_m_data_key'] !== config('mivita.edit_data_pass')) {
$m_data_error = 'Das Passwort ist falsch.';
} else {
$m_data_load = true;
}
if ($id === "new") {
$user = new User();
$user->account = new UserAccount();
if ($id === 'new') {
$user = new User;
$user->account = new UserAccount;
$user->account->same_as_billing = 1;
$user->account->country_id = 1;
$user->account->shipping_country_id = 1;
$user->id = "new";
$user->id = 'new';
} else {
$user = User::withTrashed()->findOrFail($id);
if (!$user->account) {
$user->account = new UserAccount();
if (! $user->account) {
$user->account = new UserAccount;
}
}
$next_account_id = UserAccount::withTrashed()->max('m_account') + 1;
@ -138,13 +135,13 @@ class LeadController extends Controller
'm_data_load' => $m_data_load,
'm_data_error' => $m_data_error,
'can_change_mail' => true,
'next_account_id' => $next_account_id
'next_account_id' => $next_account_id,
];
return view('admin.lead.edit', $data);
}
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function store(Request $request)
@ -152,16 +149,27 @@ class LeadController extends Controller
$data = Request::all();
$show = Request::get('show');
if (isset($data['action']) && $data['action'] == "reverse_charge_validate" && isset($data['user_id'])) {
if (! isset($data['user_id'])) {
return redirect()->back()->with('error', 'User ID is required');
}
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate' && isset($data['user_id'])) {
$user = User::findOrFail($data['user_id']);
return $this->userRepo->reverse_charge_validate($data, $user, route('admin_lead_edit', [$user->id]));
}
if (isset($data['action']) && $data['action'] == "reverse_charge_delete" && isset($data['user_id'])) {
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete' && isset($data['user_id'])) {
$user = User::findOrFail($data['user_id']);
return $this->userRepo->reverse_charge_delete($data, $user, route('admin_lead_edit', [$user->id]));
}
if (isset($data['action']) && $data['action'] == 'recreate_contract' && isset($data['user_id'])) {
$user = User::findOrFail($data['user_id']);
$useCurrentDate = isset($data['use_current_date']) && $data['use_current_date'] == '1';
return $this->recreateContract($user, $useCurrentDate);
}
/*
if(isset($data['reverse_charge_validate']) && isset($data['user_id'])){
@ -171,7 +179,7 @@ class LeadController extends Controller
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_validate($data, $user);
}
if(isset($data['reverse_charge_delete']) && isset($data['user_id'])){
$user = User::findOrFail($data['user_id']);
$user->wizard = 1;
@ -180,16 +188,16 @@ class LeadController extends Controller
return $userRepo->reverse_charge_delete($data, $user);
}*/
if ($data['user_id'] === "new" || $data['user_id'] == 0) {
$rules = array(
if ($data['user_id'] === 'new' || $data['user_id'] == 0) {
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
'email-confirm' => 'required|same:email',
);
];
} else {
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -201,15 +209,15 @@ class LeadController extends Controller
'bank_owner' => 'required',
'bank_iban' => 'required',
'bank_bic' => '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_city' => 'required',
'shipping_salutation' => 'required'
'shipping_salutation' => 'required',
]);
}
@ -217,53 +225,54 @@ class LeadController extends Controller
if (isset($data['m_account']) && $data['m_account']) {
$user = User::findOrFail($data['user_id']);
$rules['m_account'] = 'unique:user_accounts,m_account,' . $user->account->id . ',id';
$rules['m_account'] = 'unique:user_accounts,m_account,'.$user->account->id.',id';
}
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
if ($data['user_id'] === "new" || $data['user_id'] == 0) {
$user_id = "new";
if ($data['user_id'] === 'new' || $data['user_id'] == 0) {
$user_id = 'new';
} else {
$user = User::findOrFail($data['user_id']);
$user_id = $user->id;
}
return redirect(route('admin_lead_edit', [$user_id]) . "?show=" . $show)->withErrors($validator)->withRequest(Request::all());
return redirect(route('admin_lead_edit', [$user_id]).'?show='.$show)->withErrors($validator)->withRequest(Request::all());
}
if ($data['user_id'] === "new" || $data['user_id'] == 0) {
$user = new User();
$user->id = "new";
$user->account = new UserAccount();
if ($data['user_id'] === 'new' || $data['user_id'] == 0) {
$user = new User;
$user->id = 'new';
$user->account = new UserAccount;
} else {
$user = User::findOrFail($data['user_id']);
if (!$user->account) {
$user->account = new UserAccount();
if (! $user->account) {
$user->account = new UserAccount;
}
}
$this->userRepo->update($data);
if (isset($data['m_data_edit']) && $data['m_data_edit'] === "TSOK") {
//syslog
if (isset($data['m_data_edit']) && $data['m_data_edit'] === 'TSOK') {
// syslog
if (isset($data['m_sponsor'])) {
if ($user->m_sponsor != $data['m_sponsor']) {
$from_user = isset($user->user_sponsor->email) ? $user->user_sponsor->email : "empty";
$from_user = isset($user->user_sponsor->email) ? $user->user_sponsor->email : 'empty';
$t_user = User::find($data['m_sponsor']);
$to_user = isset($t_user->email) ? $t_user->email : "empty";
$to_user = isset($t_user->email) ? $t_user->email : 'empty';
SysLog::action('save-m_sponsor', 'lead_edit_sponsor', 3)
->setUserId(\Auth::user()->id)
->setModel($user->id, User::class)
->setMessage('Set user new sponsor from: ' . $from_user . " | to: " . $to_user)
->setMessage('Set user new sponsor from: '.$from_user.' | to: '.$to_user)
->save();
}
}
$user = $this->userRepo->getModel();
$user->m_level = isset($data['m_level']) ? $data['m_level'] : NULL;
$user->m_sponsor = isset($data['m_sponsor']) ? $data['m_sponsor'] : NULL;
$user->m_level = isset($data['m_level']) ? $data['m_level'] : null;
$user->m_sponsor = isset($data['m_sponsor']) ? $data['m_sponsor'] : null;
$user->save();
}
@ -275,19 +284,22 @@ class LeadController extends Controller
$user->lang = $user->getLandByCountry();
$user->confirmation_code = $confirmation_code;
//10 == start wizard form create Lead
// 10 == start wizard form create Lead
$user->wizard = 10;
$user->save();
Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyContact($confirmation_code, $user));
\Session()->flash('alert-save', true);
return redirect(route('admin_leads'));
}
\Session()->flash('alert-save', true);
return redirect(route('admin_lead_edit', [$user->id]) . "?show=" . $show);
return redirect(route('admin_lead_edit', [$user->id]).'?show='.$show);
}
//user released when register is complete
// user released when register is complete
public function released($action, $id)
{
@ -295,31 +307,31 @@ class LeadController extends Controller
if ($action === 'completed') {
$validator = Validator::make(Request::all(), []);
if (!$user->m_sponsor) {
if (! $user->m_sponsor) {
$validator->errors()->add('m_sponsor', __('Berater hat keinen Sponsor.'));
}
if (!$user->account->m_first_name) {
if (! $user->account->m_first_name) {
$validator->errors()->add('m_first_name', __('Berater hat keinen Vornamen.'));
}
if (!$user->account->m_last_name) {
if (! $user->account->m_last_name) {
$validator->errors()->add('m_last_name', __('Berater hat keinen Nachnamen.'));
}
if (!$user->account->m_account) {
if (! $user->account->m_account) {
$validator->errors()->add('m_account', __('Berater hat keine Account ID'));
}
if ($validator->errors()->count()) {
return back()->withErrors($validator)->withRequest(Request::all());
}
//create PDF
// create PDF
$pdf = new ContractPDFRepository($user);
$pdf->_set('disk', 'user');
$pdf->_set('dir', '/' . $user->id . '/documents/');
$pdf->_set('dir', '/'.$user->id.'/documents/');
$pdf->_set('user_id', $user->id);
$pdf->_set('identifier', 'contract');
$pdf->createContractPDF();
//set wizard tp payments
// set wizard tp payments
$user->wizard = 20;
$user->active = 1;
$user->active_date = now();
@ -328,16 +340,15 @@ class LeadController extends Controller
$user->confirmation_code_remider = 0;
$user->save();
//mail with code to user?
// mail with code to user?
Mail::to($user->email)->locale($user->getLocale())->send(new MailAccountActive($user));
UserHistory::create(['user_id' => $user->id, 'action' => 'released_completed', 'status' => 0]);
\Session()->flash('alert-success', "Berater freigeschaltet!");
\Session()->flash('alert-success', 'Berater freigeschaltet!');
}
if ($action === 'incomplete') {
//reset release
// reset release
$confirmation_code = UserService::createConfirmationCode();
$user->confirmation_code = $confirmation_code;
$user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
@ -356,16 +367,16 @@ class LeadController extends Controller
Mail::to($user->email)->locale($user->getLocale())->send(new MailCustomMessage($user, $data, \Auth::user(), true));
} catch (\Exception $e) {
dump($e->getMessage());
dd("error");
dd('error');
}
UserHistory::create(['user_id' => $user->id, 'action' => 'released_incomplete', 'status' => 0]);
\Session()->flash('alert-success', "E-Mail an Berater gesendet.");
\Session()->flash('alert-success', 'E-Mail an Berater gesendet.');
}
return redirect(route('admin_lead_edit', [$user->id]));
}
//send new verfified mail to user
// send new verfified mail to user
public function newMailVerified($id)
{
@ -381,15 +392,15 @@ class LeadController extends Controller
Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyAccount($confirmation_code, $user));
} catch (\Exception $e) {
dump($e->getMessage());
dd("error");
dd('error');
}
UserHistory::create(['user_id' => $user->id, 'action' => 'new_mail_verified', 'status' => 0]);
\Session()->flash('alert-success', "E-Mail erneut gesendet");
\Session()->flash('alert-success', 'E-Mail erneut gesendet');
return redirect(route('admin_lead_edit', [$user->id]));
}
public function deleteFile($user_id, $file_id, $relation)
{
@ -399,11 +410,12 @@ class LeadController extends Controller
if ($file->identifier === 'business_license') {
$user->account->setNotice('business_license', '');
}
//remove file
\Storage::disk('user')->delete($file->dir . $file->filename);
// remove file
\Storage::disk('user')->delete($file->dir.$file->filename);
$file->delete();
\Session()->flash('alert-success', __('msg.file_deleted'));
}
return back();
}
@ -411,22 +423,21 @@ class LeadController extends Controller
{
$this->setFilterVars();
//$query = UserSalesVolume::with('user', 'user.account')->with('shopping_order')->select('user_sales_volumes.*')
// $query = UserSalesVolume::with('user', 'user.account')->with('shopping_order')->select('user_sales_volumes.*')
$query = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', "<", 5);
$query = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', '<', 5);
if (Request::get('leads_filter_sponsor_id')) {
$query->where('users.m_sponsor', '=', Request::get('leads_filter_sponsor_id'));
}
return $query;
}
public function getLeads()
{
$query = $this->initSearch();
return \DataTables::eloquent($query)
->addColumn('first_name', function (User $user) {
return $user->account ? $user->account->first_name : '';
@ -435,14 +446,14 @@ class LeadController extends Controller
return $user->account ? $user->account->last_name : '';
})
->addColumn('user_level', function (User $user) {
return $user->user_level ? '<span class="badge badge-outline-success">' . $user->user_level->name . '</span>' : '';
return $user->user_level ? '<span class="badge badge-outline-success">'.$user->user_level->name.'</span>' : '';
})
->addColumn('user_sponsor', function (User $user) {
return $user->user_sponsor ?
'<span class="badge badge-outline-warning-dark">' . $user->user_sponsor->account->first_name . " " . $user->user_sponsor->account->last_name . '</span>' : "-";
'<span class="badge badge-outline-warning-dark">'.$user->user_sponsor->account->first_name.' '.$user->user_sponsor->account->last_name.'</span>' : '-';
})
->addColumn('id', function (User $user) {
return '<a href="' . route('admin_lead_edit', [$user->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('admin_lead_edit', [$user->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('confirmed', function (User $user) {
return $user->confirmed ? '<span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
@ -456,54 +467,58 @@ class LeadController extends Controller
->addColumn('useractive', function (User $user) {
$date = $user->getActiveDateFormat();
$link = '<a href="#" data-toggle="modal" data-target="#modals-active" data-id="' . $user->id . '" data-email="' . $user->email . '" data-active="' . $user->active . '" data-active_date="' . $date . '">';
return $user->active ? $link . '<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> ' . $date . '</span></a>' : $link . '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
$link = '<a href="#" data-toggle="modal" data-target="#modals-active" data-id="'.$user->id.'" data-email="'.$user->email.'" data-active="'.$user->active.'" data-active_date="'.$date.'">';
return $user->active ? $link.'<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> '.$date.'</span></a>' : $link.'<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
})
->addColumn('payaccount', function (User $user) {
$date = $user->getPaymentAccountDateFormat();
$link = '<a href="#" data-toggle="modal" data-target="#modals-account" data-id="' . $user->id . '" data-email="' . $user->email . '" data-payment_account="' . $date . '">';
$link = '<a href="#" data-toggle="modal" data-target="#modals-account" data-id="'.$user->id.'" data-email="'.$user->email.'" data-payment_account="'.$date.'">';
if ($user->payment_account) {
if ($user->isActiveAccount()) {
return $link . '<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> ' . $date . '</span></a>';
return $link.'<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> '.$date.'</span></a>';
}
return $link . '<span class="badge badge-pill badge-warning"><i class="fa fa-ban"></i> ' . $date . '</span></a>';
return $link.'<span class="badge badge-pill badge-warning"><i class="fa fa-ban"></i> '.$date.'</span></a>';
}
return $link . '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
return $link.'<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
})
->addColumn('payshop', function (User $user) {
$date = $user->getPaymentShopDateFormat();
$link = '<a href="#" data-toggle="modal" data-target="#modals-shop" data-id="' . $user->id . '" data-email="' . $user->email . '" data-payment_shop="' . $date . '">';
$link = '<a href="#" data-toggle="modal" data-target="#modals-shop" data-id="'.$user->id.'" data-email="'.$user->email.'" data-payment_shop="'.$date.'">';
if ($user->payment_shop) {
if ($user->isActiveShop()) {
return $link . '<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> ' . $date . '</span></a>';
return $link.'<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> '.$date.'</span></a>';
}
return $link . '<span class="badge badge-pill badge-warning"><i class="fa fa-ban"></i> ' . $date . '</span></a>';
}
return $link . '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
})
return $link.'<span class="badge badge-pill badge-warning"><i class="fa fa-ban"></i> '.$date.'</span></a>';
}
return $link.'<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span></a>';
})
->addColumn('payment_account', function (User $user) {
return $user->payment_account ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
})
->addColumn('payment_account_date', function (User $user) {
return $user->payment_account ? $user->getPaymentAccountDateFormat(false) : "-";
return $user->payment_account ? $user->getPaymentAccountDateFormat(false) : '-';
})
->addColumn('payment_shop', function (User $user) {
return $user->payment_shop ? ' <span class="badge badge-pill badge-success"><i class="fa fa-check"></i></span>' : '<span class="badge badge-pill badge-danger"><i class="fa fa-times"></i></span>';
})
->addColumn('payment_shop_date', function (User $user) {
return $user->payment_shop ? $user->getPaymentShopDateFormat(false) : "-";
return $user->payment_shop ? $user->getPaymentShopDateFormat(false) : '-';
})
->addColumn('shop_domain', function (User $user) {
return $user->shop ? ' <span class="small"><a href="' . $user->shop->getSubdomain(false) . '" target="_blank">' . $user->shop->getSubdomain(false) . '</a></span>' : '';
return $user->shop ? ' <span class="small"><a href="'.$user->shop->getSubdomain(false).'" target="_blank">'.$user->shop->getSubdomain(false).'</a></span>' : '';
})
->addColumn('turnover', function (User $user) {
return "-";
return '-';
})
->addColumn('sales_total', function (User $user) {
return "-";
return '-';
})
->orderColumn('id', 'id $1')
->orderColumn('confirmed', 'confirmed $1')
@ -514,4 +529,37 @@ class LeadController extends Controller
->rawColumns(['id', 'user_level', 'user_sponsor', 'confirmed', 'useractive', 'payaccount', 'payshop', 'agreement', 'active', 'payment_account', 'payment_shop', 'shop_domain'])
->make(true);
}
/**
* Erstellt den Beratervertrag neu (überschreibt bestehende Verträge)
* Verwendet für mehrsprachige Verträge
*/
public function recreateContract($user, $useCurrentDate = true)
{
if (! Auth::user()->isAdmin()) {
abort(403, 'Nicht autorisiert');
}
// Datum ermitteln
$contractDate = $useCurrentDate ? now() : ($user->active_date ? \Carbon\Carbon::parse($user->active_date) : now());
// Alten Vertrag löschen
File::where('user_id', $user->id)
->where('identifier', 'contract')
->delete();
// Neue Verträge erstellen (DE + Benutzersprache)
$pdf = new ContractPDFRepository($user);
$pdf->_set('disk', 'user');
$pdf->_set('dir', '/'.$user->id.'/documents/');
$pdf->_set('user_id', $user->id);
$pdf->_set('identifier', 'contract');
$pdf->_set('contract_date', $contractDate);
$pdf->createContractPDF();
$dateInfo = $useCurrentDate ? 'mit aktuellem Datum' : 'mit bestehendem Datum ('.$contractDate->format('d.m.Y').')';
\Session()->flash('alert-success', 'Beratervertrag wurde neu erstellt (DE + '.strtoupper($user->account->language ?? 'de').') '.$dateInfo);
return back();
}
}

View file

@ -2,26 +2,23 @@
namespace App\Http\Controllers;
use Request;
use App\User;
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\Homeparty;
use App\Models\UserLevel;
use App\Models\UserCredit;
use App\Models\ShoppingUser;
use App\Services\HTMLHelper;
use App\Models\HomepartyUser;
use App\Models\Product;
use App\Models\ShoppingOrder;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserCredit;
use App\Models\UserLevel;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\Services\DhlModalService;
use App\User;
use Request;
class ModalController extends Controller
{
public function __construct()
{
$this->middleware('auth');
@ -30,21 +27,21 @@ class ModalController extends Controller
public function load()
{
$data = Request::all();
$ret = "";
$ret = '';
$status = false;
if (Request::ajax()) {
if ($data['action'] === 'shopping-order-change-member') {
$value = ShoppingOrder::find($data['id']);
$route = route('admin_sales_customers_detail', [$value->id]);
$ret = view("admin.modal.member", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.member', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'shopping-user-change-member') {
$value = ShoppingUser::find($data['id']);
$route = route('admin_customer_edit', [$value->id]);
$ret = view("admin.modal.member", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.member', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'shopping-user-is-like-member') {
$current = ShoppingUser::find($data['id']); //current user form order
$current = ShoppingUser::find($data['id']); // current user form order
$possibles = [];
if ($current->is_like) {
$likes = $current->getNotice('like');
@ -52,46 +49,46 @@ class ModalController extends Controller
$possibles[] = ShoppingUser::find($like_id);
}
}
$ret = view("admin.modal.is_like_member", compact('current', 'possibles', 'data'))->render();
$ret = view('admin.modal.is_like_member', compact('current', 'possibles', 'data'))->render();
}
if ($data['action'] === 'shopping-order-change-points') {
$value = ShoppingOrder::find($data['id']);
$route = route('admin_sales_customers_detail', [$value->id]);
$ret = view("admin.modal.change_points", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.change_points', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'user-order-show-product') {
$product = Product::find($data['id']); //current user form order
$ret = view("admin.modal.show_product", compact('product', 'data'))->render();
$product = Product::find($data['id']); // current user form order
$ret = view('admin.modal.show_product', compact('product', 'data'))->render();
}
if ($data['action'] === 'user-order-show-product') {
$product = Product::find($data['id']); //current user form order
$ret = view("admin.modal.show_product", compact('product', 'data'))->render();
$product = Product::find($data['id']); // current user form order
$ret = view('admin.modal.show_product', compact('product', 'data'))->render();
}
if ($data['action'] === 'shop-user-order-detail') {
$user = \Auth::user();
$shopping_order = ShoppingOrder::findOrFail($data['id']);
if (!$user->isAdmin() && $shopping_order->member_id !== $user->id) {
if (! $user->isAdmin() && $shopping_order->member_id !== $user->id) {
abort(404);
}
$isAdmin = false;
$ret = view("user.shop.sales.modal_api_order_detail", compact('shopping_order', 'isAdmin', 'data'))->render();
$ret = view('user.shop.sales.modal_api_order_detail', compact('shopping_order', 'isAdmin', 'data'))->render();
}
if ($data['action'] === 'shop-user-order-shipping-detail') {
$user = \Auth::user();
$shopping_order = ShoppingOrder::findOrFail($data['id']);
if (!$user->isAdmin() && $shopping_order->auth_user_id !== $user->id) {
if (! $user->isAdmin() && $shopping_order->auth_user_id !== $user->id) {
abort(404);
}
$isAdmin = false;
$ret = view("user.shop.sales.modal_api_order_shipping_detail", compact('shopping_order', 'isAdmin', 'data'))->render();
$ret = view('user.shop.sales.modal_api_order_shipping_detail', compact('shopping_order', 'isAdmin', 'data'))->render();
}
if ($data['action'] === 'user-order-my-delivery-show') {
$user = \Auth::user();
$ret = view("admin.modal.show_user_customers", compact('user', 'data'))->render();
$ret = view('admin.modal.show_user_customers', compact('user', 'data'))->render();
}
if ($data['action'] === 'user-order-my-delivery-add') {
@ -103,60 +100,62 @@ class ModalController extends Controller
$homeparty = Homeparty::find($data['id']);
$homeparty_user = HomepartyUser::find($data['user_id']);
$data['homeparty'] = $homeparty;
$ret = view("user.homeparty.modal_hp_show_products", compact('data', 'homeparty', 'homeparty_user'))->render();
$ret = view('user.homeparty.modal_hp_show_products', compact('data', 'homeparty', 'homeparty_user'))->render();
}
if ($data['action'] === 'user-level-edit') {
$value = UserLevel::find($data['id']);
$route = route('admin_level_store', [$value->id]);
$ret = view("admin.modal.user_level_edit", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.user_level_edit', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'user-level-add') {
$value = new UserLevel();
$value = new UserLevel;
$route = route('admin_level_store', ['new']);
$ret = view("admin.modal.user_level_edit", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.user_level_edit', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'business-user-detail') {
$user = User::findOrFail($data['id']);
if ($data['init_from'] === 'admin') {
$data['month'] = session('business_user_filter_month');
$data['year'] = session('business_user_filter_year');
$data['year'] = session('business_user_filter_year');
} else {
$data['month'] = session('team_user_filter_month');
$data['year'] = session('team_user_filter_year');
$data['month'] = session('team_user_filter_month');
$data['year'] = session('team_user_filter_year');
}
$data['live'] = $data['live'] ?? false;
$data['optimized'] = $data['optimized'] ?? false;
$TreeCalcBot = $this->getForBusinessUserDetail($user, $data);
$route = "";
$ret = view("admin.modal.business_user_detail", compact('TreeCalcBot', 'user', 'data'))->render();
$route = '';
$ret = view('admin.modal.business_user_detail', compact('TreeCalcBot', 'user', 'data'))->render();
}
if ($data['action'] === 'business-user-show') {
$user = User::find($data['id']);
if ($user && $user->account) {
$route = "";
$ret = view("admin.modal.business_user_show", compact('user', 'data'))->render();
$user = User::with(['account', 'account.country', 'account.shipping_country', 'user_level', 'user_sponsor.account'])->find($data['id']);
\Log::info('business-user-show', ['user' => $user]);
if ($user) {
$route = '';
$ret = view('admin.modal.business_user_show', compact('user', 'data'))->render();
} else {
$ret = view('admin.modal.business_user_notfound', compact('data'))->render();
}
$ret = view("admin.modal.business_user_notfound", compact('data'))->render();
}
if ($data['action'] === 'edit_user_sales_volume') {
$userSalesVolume = UserSalesVolume::findOrFail($data['id']);
$route = route('admin_business_points_store',);
$ret = view("admin.business.modal_edit_points", compact('userSalesVolume', 'data', 'route'))->render();
$route = route('admin_business_points_store');
$ret = view('admin.business.modal_edit_points', compact('userSalesVolume', 'data', 'route'))->render();
}
if ($data['action'] === 'add_user_sales_volume') {
$userSalesVolume = new UserSalesVolume();
$route = route('admin_business_points_store',);
$ret = view("admin.business.modal_add_points", compact('userSalesVolume', 'data', 'route'))->render();
$userSalesVolume = new UserSalesVolume;
$route = route('admin_business_points_store');
$ret = view('admin.business.modal_add_points', compact('userSalesVolume', 'data', 'route'))->render();
}
if ($data['action'] === 'add-user-credit') {
$value = [];
$ret = view("admin.payment.modal_add_credit", compact('value', 'data'))->render();
$ret = view('admin.payment.modal_add_credit', compact('value', 'data'))->render();
}
if ($data['action'] === 'user-credit-status') {
$UserCredit = UserCredit::find($data['id']); //current user form order
$ret = view("admin.payment.modal_credit_status", compact('UserCredit', 'data'))->render();
$UserCredit = UserCredit::find($data['id']); // current user form order
$ret = view('admin.payment.modal_credit_status', compact('UserCredit', 'data'))->render();
}
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::find($data['id']);
@ -165,11 +164,11 @@ class ModalController extends Controller
} else {
$route = route('user_abos_update', [$data['view'], $user_abo->id]);
}
$ret = view("admin.abo.modal_abo_update", compact('user_abo', 'data', 'route'))->render();
$ret = view('admin.abo.modal_abo_update', compact('user_abo', 'data', 'route'))->render();
}
if ($data['action'] === 'abo-add-product') {
$user_abo = UserAbo::find($data['id']);
$ret = view("user.abo.modal_abo_show_products", compact('data', 'user_abo'))->render();
$ret = view('user.abo.modal_abo_show_products', compact('data', 'user_abo'))->render();
}
if ($data['action'] === 'create-dhl-shipment') {
@ -177,54 +176,57 @@ class ModalController extends Controller
$ret = $this->handleDhlShipmentModal($id, $data);
}
}
return response()->json(['response' => $data, 'html' => $ret, 'status' => $status]);
}
private function getForBusinessUserDetail(User $user, $data)
{
//$auth_user = \Auth::user();
//if($auth_user->isAdmin() || $auth_user->id === $user->id){
// $auth_user = \Auth::user();
// if($auth_user->isAdmin() || $auth_user->id === $user->id){
if ($data['optimized']) {
$TreeCalcBot = new TreeCalcBotOptimized($data['month'], $data['year'], $data['init_from'], $data['live']);
} else {
$TreeCalcBot = new TreeCalcBot($data['month'], $data['year'], $data['init_from']);
}
$TreeCalcBot->initBusinesslUserDetail($user, $data['live']);
//TODO is not Admin, read is user in Parent tree ...
if (!$TreeCalcBot->business_user) {
// TODO is not Admin, read is user in Parent tree ...
if (! $TreeCalcBot->business_user) {
abort(403, 'no user found');
}
return $TreeCalcBot;
//}
// }
return null;
}
/**
* Handle DHL shipment modal preparation
*
* @param mixed $id Order ID or 'new'
* @param array $data Request data
*
* @param mixed $id Order ID or 'new'
* @param array $data Request data
* @return string Rendered view
*/
private function handleDhlShipmentModal($id, array $data): string
{
try {
$dhlModalService = new DhlModalService();
$dhlModalService = new DhlModalService;
$modalData = $dhlModalService->prepareModalData($id, $data);
// Merge the prepared data with the original request data
$viewData = array_merge($data, $modalData, [
'id' => $id,
'data' => $data
'data' => $data,
]);
return view("admin.dhl.modal_create_shipment", $viewData)->render();
return view('admin.dhl.modal_create_shipment', $viewData)->render();
} catch (\Exception $e) {
\Log::error('[ModalController] Error in DHL shipment modal', [
'order_id' => $id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
'trace' => $e->getTraceAsString(),
]);
// Return error view or fallback
@ -239,17 +241,15 @@ class ModalController extends Controller
'V01PAK' => 'DHL Paket (National)',
'V53WPAK' => 'DHL Paket International',
],
'errors' => ['Fehler beim Laden der Daten: ' . $e->getMessage()],
'warnings' => []
'errors' => ['Fehler beim Laden der Daten: '.$e->getMessage()],
'warnings' => [],
];
return view("admin.dhl.modal_create_shipment", $errorData)->render();
return view('admin.dhl.modal_create_shipment', $errorData)->render();
}
}
}
/* <button type="button" class="btn btn-sm btn-primary" data-toggle="modal"
data-target="#modals-load-content"
data-id="{{ $value->id }}"
@ -257,4 +257,4 @@ class ModalController extends Controller
data-action="modal-email-template"
data-url=""
data-redirect="back"
data-route="{{ route('modal_load') }}"><span class="fa fa-edit"></span></button>*/
data-route="{{ route('modal_load') }}"><span class="fa fa-edit"></span></button>*/

View file

@ -21,7 +21,6 @@ fnc Financing
'pref' => 'Vorauskasse',
];*/
namespace App\Http\Controllers\Pay;
use App\Http\Controllers\Controller;
@ -31,36 +30,39 @@ use App\Services\MyLog;
use App\Services\Payone;
use Util;
class PayoneController extends Controller
{
const PREAUTHORIZATION = 'preauthorization';
const AUTHORIZATION = 'authorization';
const CAPTURE = 'capture';
const REFUND = 'refund';
const DEBIT = 'debit';
private $default = [];
private $personalData = [];
private $aboInitPayment = [];
private $method = [];
private $prepayment = [];
/* private $onlineTransfer = [];
private $creditCard = []; */
private $deliveryData = [];
// private $payment_method;
private $urls = [];
private $shopping_user;
private $shopping_order;
private $shopping_payment;
private $reference;
@ -82,40 +84,40 @@ class PayoneController extends Controller
{
return $this->shopping_payment;
}
public function setAboPayment($user_abo, $amount, $currency)
{
$this->reference = substr(uniqid('m', false), 0, 16);
$amount = intval($amount);
$this->method = [
"clearingtype" => $user_abo->clearingtype,
"wallettype" => $user_abo->wallettype,
"pseudocardpan" => isset($user_abo->carddata['pseudocardpan']) ? $user_abo->carddata['pseudocardpan'] : '',
"cardexpiredate" => isset($user_abo->carddata['cardexpiredate']) ? $user_abo->carddata['cardexpiredate'] : '',
'clearingtype' => $user_abo->clearingtype,
'wallettype' => $user_abo->wallettype,
'pseudocardpan' => isset($user_abo->carddata['pseudocardpan']) ? $user_abo->carddata['pseudocardpan'] : '',
'cardexpiredate' => isset($user_abo->carddata['cardexpiredate']) ? $user_abo->carddata['cardexpiredate'] : '',
'userid' => $user_abo->payone_userid,
'onlinebanktransfertype' => '',
"request" => "authorization",
'request' => 'authorization',
];
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'no',
'request' => 'authorization',
'amount' => $amount
'amount' => $amount,
];
$this->prepayment = [
"reference" => $this->reference, // a unique reference, e.g. order number
"amount" => $amount, // amount in smallest currency unit, i.e. cents
"currency" => $currency,
"param" => $this->shopping_order->id,
'reference' => $this->reference, // a unique reference, e.g. order number
'amount' => $amount, // amount in smallest currency unit, i.e. cents
'currency' => $currency,
'param' => $this->shopping_order->id,
];
$this->shopping_payment = ShoppingPayment::create([
'shopping_order_id' => $this->shopping_order->id,
'clearingtype' => $this->method["clearingtype"],
'wallettype' => $this->method["wallettype"],
'onlinebanktransfertype' => $this->method["onlinebanktransfertype"],
'clearingtype' => $this->method['clearingtype'],
'wallettype' => $this->method['wallettype'],
'onlinebanktransfertype' => $this->method['onlinebanktransfertype'],
'carddata' => $user_abo->carddata,
'reference' => $this->reference,
'amount' => $amount,
@ -125,9 +127,11 @@ class PayoneController extends Controller
'mode' => $this->shopping_order->mode,
]);
}
//make Payone payment
// make Payone payment
public function setPrePayment($payment_method, $amount, $currency, $ret = [])
{
$amount = intval($amount);
$this->reference = substr(uniqid('m', false), 0, 16);
$this->setMethod($payment_method, $ret);
@ -139,30 +143,30 @@ class PayoneController extends Controller
];
$this->prepayment = [
"reference" => $this->reference, // a unique reference, e.g. order number
"amount" => $amount, // amount in smallest currency unit, i.e. cents
"currency" => $currency,
"param" => $this->shopping_order->id,
'reference' => $this->reference, // a unique reference, e.g. order number
'amount' => $amount, // amount in smallest currency unit, i.e. cents
'currency' => $currency,
'param' => $this->shopping_order->id,
];
//init Abo
// init Abo
if ($this->shopping_order->is_abo) {
if ($this->method["clearingtype"] === "cc") {
if ($this->method['clearingtype'] === 'cc') {
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'yes',
'request' => 'authorization',
'amount' => $amount,
'amount' => $amount,
];
$this->method['request'] = 'authorization';
}
if ($this->method["clearingtype"] === "wlt") {
//payment for Abo PayPal
if ($this->method['clearingtype'] === 'wlt') {
// payment for Abo PayPal
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'yes',
'request' => 'authorization',
'amount' => $amount,
'amount' => $amount,
'add_paydata[redirection_mode]' => 'DIRECT_TO_MERCHANT',
];
$this->setDeliverylData($this->shopping_user);
@ -172,9 +176,9 @@ class PayoneController extends Controller
$this->shopping_payment = ShoppingPayment::create([
'shopping_order_id' => $this->shopping_order->id,
'clearingtype' => $this->method["clearingtype"],
'wallettype' => $this->method["wallettype"],
'onlinebanktransfertype' => $this->method["onlinebanktransfertype"],
'clearingtype' => $this->method['clearingtype'],
'wallettype' => $this->method['wallettype'],
'onlinebanktransfertype' => $this->method['onlinebanktransfertype'],
'carddata' => isset($ret['cc']) ? $ret['cc'] : null,
'reference' => $this->reference,
'amount' => $amount,
@ -186,21 +190,22 @@ class PayoneController extends Controller
]);
$this->default['mode'] = $this->shopping_order->mode;
return $this->reference;
}
public function setPersonalData()
{
$this->personalData = [
"firstname" => $this->shopping_user->billing_firstname,
"lastname" => $this->shopping_user->billing_lastname, // mandatory
"street" => $this->shopping_user->billing_address,
"zip" => $this->shopping_user->billing_zipcode,
"city" => $this->shopping_user->billing_city,
"country" => ($this->shopping_user->billing_country) ? $this->shopping_user->billing_country->code : "DE", // mandatory
"email" => $this->shopping_user->billing_email,
'firstname' => $this->shopping_user->billing_firstname,
'lastname' => $this->shopping_user->billing_lastname, // mandatory
'street' => $this->shopping_user->billing_address,
'zip' => $this->shopping_user->billing_zipcode,
'city' => $this->shopping_user->billing_city,
'country' => ($this->shopping_user->billing_country) ? $this->shopping_user->billing_country->code : 'DE', // mandatory
'email' => $this->shopping_user->billing_email,
// "language" => ($this->shopping_user->billing_country) ? strtoupper($this->shopping_user->billing_country->code) : "DE", // mandatory
"language" => "DE",
'language' => 'DE',
];
/**
@ -222,38 +227,38 @@ class PayoneController extends Controller
if ($payment_method) {
if (strpos($payment_method, '#')) {
$payment_method = explode('#', $payment_method);
//wallet Paypal
// wallet Paypal
if ($payment_method[0] === 'wlt') {
$this->method = [
"clearingtype" => "wlt",
"wallettype" => $payment_method[1],
'onlinebanktransfertype' => "",
"request" => "authorization"
'clearingtype' => 'wlt',
'wallettype' => $payment_method[1],
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
}
//Online-Überweisung
// Online-Überweisung
if ($payment_method[0] === 'sb') {
$this->method = [
"clearingtype" => "sb",
"wallettype" => "",
"onlinebanktransfertype" => $payment_method[1], // this is the type for Sofort.com
"bankcountry" => "DE", // we need to know the country of the customer's bank, i.e. of the invoice address
"request" => "authorization",
'clearingtype' => 'sb',
'wallettype' => '',
'onlinebanktransfertype' => $payment_method[1], // this is the type for Sofort.com
'bankcountry' => 'DE', // we need to know the country of the customer's bank, i.e. of the invoice address
'request' => 'authorization',
];
}
//Rechnungskauf
// Rechnungskauf
if ($payment_method[0] === 'fnc') {
//MIVITA
// MIVITA
if (isset($payment_method[1]) && $payment_method[1] === 'MIV') {
$this->method = [
"clearingtype" => "fnc",
"wallettype" => "",
'onlinebanktransfertype' => "MIV",
"request" => "authorization",
'clearingtype' => 'fnc',
'wallettype' => '',
'onlinebanktransfertype' => 'MIV',
'request' => 'authorization',
];
}
//PAYONE
// PAYONE
/* $this->method = [
"clearingtype" => "fnc",
"wallettype" => "",
@ -265,41 +270,41 @@ class PayoneController extends Controller
];*/
}
}
//vorkasse
// vorkasse
if ($payment_method === 'elv') {
$this->method = [
"clearingtype" => "elv",
"wallettype" => "",
'onlinebanktransfertype' => "",
"request" => "authorization",
"mandate_identification" => $ret['elv']['mandate_identification'],
"iban" => $ret['elv']['iban'],
"bic" => $ret['elv']['bic'],
"bankaccountholder" => $ret['elv']['bankaccountholder'],
'clearingtype' => 'elv',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'mandate_identification' => $ret['elv']['mandate_identification'],
'iban' => $ret['elv']['iban'],
'bic' => $ret['elv']['bic'],
'bankaccountholder' => $ret['elv']['bankaccountholder'],
// "bankcountry" => "DE",
];
}
//vorkasse
// vorkasse
if ($payment_method === 'vor') {
$this->method = [
"clearingtype" => "vor",
"wallettype" => "",
'onlinebanktransfertype' => "",
"request" => "authorization",
'clearingtype' => 'vor',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
}
//CreditCard
// CreditCard
if ($payment_method === 'cc') {
//need the $cc_ret
// need the $cc_ret
$this->method = [
"clearingtype" => "cc",
"wallettype" => "",
'onlinebanktransfertype' => "",
"request" => "authorization",
"pseudocardpan" => $ret['cc']['pseudocardpan'],
//"xid" => "3-D Secure transaction ID"
'clearingtype' => 'cc',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'pseudocardpan' => $ret['cc']['pseudocardpan'],
// "xid" => "3-D Secure transaction ID"
];
}
}
@ -309,6 +314,7 @@ class PayoneController extends Controller
{
$request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
$response = Payone::sendRequest($request);
return $response;
}
@ -316,11 +322,10 @@ class PayoneController extends Controller
{
$request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
//RECHNUNG MIV
if ($this->shopping_payment->clearingtype === 'fnc' && $this->shopping_payment->onlinebanktransfertype === 'MIV') {
$payt = PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'request' => $this->method['request'],
'txid' => 0,
'userid' => 0,
'status' => 'FNCMIV',
@ -332,6 +337,7 @@ class PayoneController extends Controller
if ($is_abo) {
return $this->reference;
}
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
@ -343,7 +349,7 @@ class PayoneController extends Controller
MyLog::writeLog(
'payone',
'error',
'PayPal Preauthorization Fehler: ' . $response['errormessage'],
'PayPal Preauthorization Fehler: '.$response['errormessage'],
$response
);
PaymentTransaction::create([
@ -352,6 +358,7 @@ class PayoneController extends Controller
'errorcode' => $response['errorcode'],
'errormessage' => $response['errormessage'],
'customermessage' => $response['customermessage'],
'transmitted_data' => $request,
'status' => $response['status'],
'mode' => $this->shopping_payment->mode,
]);
@ -361,10 +368,10 @@ class PayoneController extends Controller
}
\Session::flash('errormessage', $response['errormessage']);
\Session::flash('customermessage', $response['customermessage']);
return redirect(route('checkout.checkout_card'));
}
if ($response['status'] === 'REDIRECT') {
PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
@ -379,7 +386,8 @@ class PayoneController extends Controller
if ($is_abo) {
return $response;
}
return redirect()->away($response["redirecturl"]);
return redirect()->away($response['redirecturl']);
exit;
}
@ -387,7 +395,7 @@ class PayoneController extends Controller
// header("Location: " . $response["redirecturl"]); // or other redirect method
$payt = PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'request' => $this->method['request'],
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
@ -400,33 +408,32 @@ class PayoneController extends Controller
return $response;
}
if ($payt->shopping_payment->clearingtype === "vor") {
//vorkasse
if ($payt->shopping_payment->clearingtype === 'vor') {
// vorkasse
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
if ($payt->shopping_payment->clearingtype === "cc") {
//creditcard
if ($payt->shopping_payment->clearingtype === 'cc') {
// creditcard
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
if ($payt->shopping_payment->clearingtype === "elv") {
//sepa
if ($payt->shopping_payment->clearingtype === 'elv') {
// sepa
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
var_dump($response);
die();
//txid
//Payment process ID (PAYONE)
//userid
//Debtor ID (PAYONE)
exit();
// txid
// Payment process ID (PAYONE)
// userid
// Debtor ID (PAYONE)
}
if ($response['status'] === 'PENDING') {
MyLog::writeLog(
'payone',
@ -434,11 +441,11 @@ class PayoneController extends Controller
'Error:1000 Status PENDING App\Http\Controllers\Pay\PayoneController::ResponseData response status PENDING',
$response
);
die();
//txid
//Payment process ID (PAYONE)
//userid
//Debtor ID (PAYONE)
exit();
// txid
// Payment process ID (PAYONE)
// userid
// Debtor ID (PAYONE)
}
MyLog::writeLog(
'payone',
@ -449,22 +456,20 @@ class PayoneController extends Controller
abort(403, 'Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1001');
}
public function checkCreditCard($data)
{
$this->prepayment = [
"request" => "creditcardcheck", // create account receivable and instantly book the amount
"cardholder" => $data['cc_cardholder_first'] . " " . $data['cc_cardholder_last'],
"cardpan" => $data['cc_cardpan'],
"cardexpiredate" => substr($data['cc_cardexpireyear'], -2) . $data['cc_cardexpiremonth'],
"cardtype" => $data['cc_cardtype'],
"cardcvc2" => $data['cc_cardcvc2'],
"storecarddata" => 'yes',
"language" => 'de',
'request' => 'creditcardcheck', // create account receivable and instantly book the amount
'cardholder' => $data['cc_cardholder_first'].' '.$data['cc_cardholder_last'],
'cardpan' => $data['cc_cardpan'],
'cardexpiredate' => substr($data['cc_cardexpireyear'], -2).$data['cc_cardexpiremonth'],
'cardtype' => $data['cc_cardtype'],
'cardcvc2' => $data['cc_cardcvc2'],
'storecarddata' => 'yes',
'language' => 'de',
];
$request = array_merge($this->default, $this->prepayment);
return Payone::sendRequest($request);
}
@ -474,18 +479,19 @@ class PayoneController extends Controller
$this->setPersonalData();
$this->prepayment = [
"clearingtype" => "elv",
"amount" => $amount, // amount in smallest currency unit, i.e. cents
"currency" => $currency,
"request" => "managemandate", // create account receivable and instantly book the amount
"bankaccountholder" => $data['elv_bankaccountholder'],
"iban" => $data['elv_iban'],
"bic" => $data['elv_bic'],
'clearingtype' => 'elv',
'amount' => $amount, // amount in smallest currency unit, i.e. cents
'currency' => $currency,
'request' => 'managemandate', // create account receivable and instantly book the amount
'bankaccountholder' => $data['elv_bankaccountholder'],
'iban' => $data['elv_iban'],
'bic' => $data['elv_bic'],
// "language" => 'de',
];
$request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->urls);
return Payone::sendRequest($request);
}
@ -524,9 +530,6 @@ class PayoneController extends Controller
}
*/
/* public function checkStatus(){
// again, the default values will be needed
$capture = array(
@ -541,9 +544,8 @@ class PayoneController extends Controller
} */
//set for clearingtype
//debit payment
// set for clearingtype
// debit payment
/*
*
*
@ -596,6 +598,6 @@ class PayoneController extends Controller
*/
}

View file

@ -1,29 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Repositories\CreditRepository;
use App\Services\Credit;
use App\Services\HTMLHelper;
use App\Services\Payment;
use App\Services\Util;
use App\User;
use Carbon;
use Request;
use App\User;
use App\Services\Util;
use App\Services\Credit;
use App\Services\Payment;
use App\Models\UserCredit;
use App\Services\HTMLHelper;
use App\Models\UserCreditItem;
use App\Models\UserCreditMargin;
use Illuminate\Support\Collection;
use App\Models\ShoppingOrderMargin;
use App\Repositories\CreditRepository;
use App\Models\Models\UserCreditMargin as ModelsUserCreditMargin;
use App\Models\UserAccount;
use stdClass;
class PaymentCreditController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -37,31 +28,34 @@ class PaymentCreditController extends Controller
'filter_years' => HTMLHelper::getYearRange(2022),
'user_credit_items' => $this->makeUserCreditItems(),
];
return view('admin.payment.credit', $data);
}
public function store()
{
$data = Request::all();
if (isset($data['action']) && $data['action'] === 'add-user-credit') {
if (!isset($data['member_id']) || !$user = User::find($data['member_id'])) {
if (! isset($data['member_id']) || ! $user = User::find($data['member_id'])) {
\Session()->flash('alert-error', 'Vertriebspartner nicht gefunden');
return back();
}
if (!isset($data['credit'])) {
if (! isset($data['credit'])) {
\Session()->flash('alert-error', 'Bitte Betrag eingeben');
return back();
}
if (!isset($data['message'])) {
if (! isset($data['message'])) {
\Session()->flash('alert-error', 'Bitte Betreff eingeben');
return back();
}
$credit = Util::reFormatNumber($data['credit']);
$credit = number_format($credit, 2, '.', '');
Payment::addUserCreditMargin($user, $credit, 3, $data['message']);
\Session()->flash('alert-success', "Guthaben hinzugefügt");
\Session()->flash('alert-success', 'Guthaben hinzugefügt');
}
return redirect(route('admin_payments_credit'));
@ -72,20 +66,22 @@ class PaymentCreditController extends Controller
$data = Request::all();
if (isset($data['action'])) {
if ($data['action'] === 'create_credit') {
if (!isset($data['userid'])) {
if (! isset($data['userid'])) {
abort(404);
}
$user = User::findOrFail($data['userid']);
$credit_repo = new CreditRepository($user);
$credit_repo->create($data);
\Session()->flash('alert-success', "Gutschrift erstellt");
\Session()->flash('alert-success', 'Gutschrift erstellt');
return redirect($data['back']);
}
if ($data['action'] === 'user-credit-status') {
$UserCredit = UserCredit::findOrFail($data['id']);
$UserCredit->status = $data['status'];
$UserCredit->save();
\Session()->flash('alert-success', "Status gespeichert");
\Session()->flash('alert-success', 'Status gespeichert');
return back();
}
}
@ -93,10 +89,10 @@ class PaymentCreditController extends Controller
private function setFilterVars()
{
if (!session('credit_filter_month')) {
if (! session('credit_filter_month')) {
session(['credit_filter_month' => intval(date('m'))]);
}
if (!session('credit_filter_year')) {
if (! session('credit_filter_year')) {
session(['credit_filter_year' => intval(date('Y'))]);
}
if (Request::get('credit_filter_name')) {
@ -121,7 +117,7 @@ class PaymentCreditController extends Controller
$ret[$userCreditItem->user_id]['sum'] += $userCreditItem->credit;
$ret[$userCreditItem->user_id]['entries'][$userCreditItem->id] = $userCreditItem;
} else {
if (!isset($userCreditItem->user)) {
if (! isset($userCreditItem->user)) {
/* gelöschte User nicht anzeigen
$user = User::withTrashed()->with(['account' => fn($q) => $q->withTrashed()])->where('id', $userCreditItem->user_id)->first();
$ret[$userCreditItem->user_id] = [
@ -147,6 +143,7 @@ class PaymentCreditController extends Controller
}
}
}
return $ret;
}
@ -157,11 +154,12 @@ class PaymentCreditController extends Controller
$UserCreditItem = UserCreditItem::findOrFail($id);
if ($deleteTime = $UserCreditItem->deleteTime()) {
$UserCreditItem->delete();
\Session()->flash('alert-success', "Guthaben ist gelöscht");
\Session()->flash('alert-success', 'Guthaben ist gelöscht');
} else {
\Session()->flash('alert-error', "Guthaben kann nicht gelöscht werden");
\Session()->flash('alert-error', 'Guthaben kann nicht gelöscht werden');
}
}
return redirect(route('admin_payments_credit'));
}
@ -170,17 +168,18 @@ class PaymentCreditController extends Controller
$this->setFilterVars();
$date_start = Carbon::parse('01.' . Request::get('credit_filter_month') . '.' . Request::get('credit_filter_year'))->format('Y-m-d');
$date_end = Carbon::parse('01.' . Request::get('credit_filter_month') . '.' . Request::get('credit_filter_year'))->endOfMonth()->format('Y-m-d');
$date_start = Carbon::parse('01.'.Request::get('credit_filter_month').'.'.Request::get('credit_filter_year'))->format('Y-m-d');
$date_end = Carbon::parse('01.'.Request::get('credit_filter_month').'.'.Request::get('credit_filter_year'))->endOfMonth()->format('Y-m-d');
$query = UserCredit::with('user', 'user.account')->select('user_credits.*')
->whereBetween('date', [$date_start, $date_end]);
if (Request::get('credit_filter_name')) {
$query->whereHas('user.account', function ($query) {
return $query->where('first_name', 'LIKE', '%' . Request::get('credit_filter_name') . '%')
->orWhere('last_name', 'LIKE', '%' . Request::get('credit_filter_name') . '%');
return $query->where('first_name', 'LIKE', '%'.Request::get('credit_filter_name').'%')
->orWhere('last_name', 'LIKE', '%'.Request::get('credit_filter_name').'%');
});
}
return $query;
}
@ -192,64 +191,75 @@ class PaymentCreditController extends Controller
return \DataTables::eloquent($query)
->addColumn('user.account.first_name', function (UserCredit $UserCredit) {
return isset($UserCredit->user->account) ? $UserCredit->user->account->first_name : "gelöscht";
return isset($UserCredit->user->account) ? $UserCredit->user->account->first_name : 'gelöscht';
})
->addColumn('user.account.last_name', function (UserCredit $UserCredit) {
return isset($UserCredit->user->account) ? $UserCredit->user->account->last_name : "gelöscht";
return isset($UserCredit->user->account) ? $UserCredit->user->account->last_name : 'gelöscht';
})
->addColumn('user.email', function (UserCredit $UserCredit) {
return isset($UserCredit->user) ? $UserCredit->user->email : "gelöscht";
return isset($UserCredit->user) ? $UserCredit->user->email : 'gelöscht';
})
->addColumn('view', function (UserCredit $UserCredit) {
$ret = "";
$ret = '';
if ($UserCredit->isCredit()) {
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit', 'download']) . '" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit', 'stream']) . '" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a><br>';
// Deutsches Original (ausgefüllter Button)
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download']).'" class="btn btn-primary btn-xs mb-2 mr-1" title="Gutschrift DE"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream']).'" target="_blank" class="btn btn-warning btn-xs mb-2 mr-1" title="Vorschau DE"><i class="fa fa-eye"></i></a>';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit_detail', 'html']) . '" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']) . '" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
// Lokalisierte Versionen (outline Buttons)
$availableLocales = $UserCredit->getAvailableLocales();
foreach ($availableLocales as $locale) {
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download', $locale]).'" class="btn btn-outline-primary btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-download"></i> '.strtoupper($locale).'</a>';
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream', $locale]).'" class="btn btn-outline-warning btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-eye"></i> '.strtoupper($locale).'</a>';
}
$ret .= '<br>';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'html']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1"><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
} else {
$ret = "-";
$ret = '-';
}
return $ret;
})
->addColumn('total', function (UserCredit $UserCredit) {
return '<span class="no-line-break">' . $UserCredit->getFormattedTotal() . " €</span>";
return '<span class="no-line-break">'.$UserCredit->getFormattedTotal().' €</span>';
})
->addColumn('credits', function (UserCredit $UserCredit) {
$ret = "";
$ret = '';
if ($UserCredit->user_credit_items) {
foreach ($UserCredit->user_credit_items as $user_credit_item) {
$ret .= nl2br($user_credit_item->getTransMessage()) . " / " . $user_credit_item->created_at->format('d.m.Y') . "<br>";
$ret .= nl2br($user_credit_item->getTransMessage()).' / '.$user_credit_item->created_at->format('d.m.Y').'<br>';
}
}
return $ret;
})
->addColumn('status', function (UserCredit $UserCredit) {
return '<a href="#" data-toggle="modal" data-target="#modals-load-content" data-modal="modal-lg"
data-id="' . $UserCredit->id . '" data-route="' . route('modal_load') . '" data-action="user-credit-status" data-view="">
<span class="badge badge-pill badge-' . $UserCredit->getStatusColor() . '">' . $UserCredit->getStatusType() . ' <span class="ion ion-md-cash"></span></span>
data-id="'.$UserCredit->id.'" data-route="'.route('modal_load').'" data-action="user-credit-status" data-view="">
<span class="badge badge-pill badge-'.$UserCredit->getStatusColor().'">'.$UserCredit->getStatusType().' <span class="ion ion-md-cash"></span></span>
</a>';
})
->filterColumn('user.account.first_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user.account', function ($query) use ($keyword) {
return $query->where('first_name', 'LIKE', '%' . $keyword . '%');
return $query->where('first_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('user.account.last_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user.account', function ($query) use ($keyword) {
return $query->where('last_name', 'LIKE', '%' . $keyword . '%');
return $query->where('last_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('user.email', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user', function ($query) use ($keyword) {
return $query->where('email', 'LIKE', '%' . $keyword . '%');
return $query->where('email', 'LIKE', '%'.$keyword.'%');
});
}
})

View file

@ -1,246 +1,277 @@
<?php
namespace App\Http\Controllers;
use Auth;
use Request;
use ZipArchive;
use App\Models\UserInvoice;
use App\Models\DatevExport;
use App\Models\DatevExportLine;
use App\Services\DatevExportService;
use App\Services\HTMLHelper;
use App\Exports\UserTeamExport;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class PaymentTaxAdvisorController extends Controller
{
private $BUKey = [
1 => 8120, //für Kunden aus der Schweiz
11 => 8125, //Steuerfreie EU-Lieferungen
2 => 8300, //Erlöse mit 7 % meistens für Käufe mit Aloe Vera
3 => 8400, //Regulär mit 19 %
];
private DatevExportService $datevService;
private $accountKey = [
'A'=>'10000',
'B'=>'10100',
'C'=>'10200',
'D'=>'10300',
'E'=>'10400',
'F'=>'10500',
'G'=>'10600',
'H'=>'10700',
'I'=>'10800',
'J'=>'10900',
'K'=>'11000',
'L'=>'11100',
'M'=>'11200',
'N'=>'11300',
'O'=>'11400',
'P'=>'11500',
'Q'=>'11600',
'R'=>'11700',
'S'=>'11800',
'SCH'=>'11900',
'T'=>'12000',
'U'=>'12100',
'V'=>'12200',
'W'=>'12300',
'X'=>'12400',
'Y'=>'12500',
'Z'=>'12600'
];
public function __construct()
public function __construct(DatevExportService $datevService)
{
$this->middleware('admin');
$this->datevService = $datevService;
}
public function index()
/**
* Hauptseite: Periodenauswahl + Export-Übersicht
*/
public function index(Request $request)
{
$this->setFilterVars();
$this->setFilterVars($request);
$month = intval(session('payment_taxadvisor_filter_month'));
$year = intval(session('payment_taxadvisor_filter_year'));
// Letzter Export für diese Periode
$currentExport = DatevExport::forPeriod($month, $year)
->generated()
->latest()
->first();
// Letzte 10 Exports für die Historie
$recentExports = DatevExport::generated()
->latest()
->limit(10)
->get();
$data = [
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2023),
'current_month' => $month,
'current_year' => $year,
'current_export' => $currentExport,
'recent_exports' => $recentExports,
];
return view('admin.payment.taxadvisor', $data);
}
public function createZip($filesToZip)
/**
* AJAX: Vorschau der Daten für die gewählte Periode.
*/
public function preview(Request $request)
{
$zip = new ZipArchive;
$zipFileName = 'mysample.zip';
$path = storage_path().'/app/public/zip/';
if ($zip->open($path.$zipFileName, ZipArchive::CREATE) === TRUE) {
foreach ($filesToZip as $file) {
$zip->addFile($file, basename($file));
}
$month = intval($request->get('month', session('payment_taxadvisor_filter_month')));
$year = intval($request->get('year', session('payment_taxadvisor_filter_year')));
$zip->close();
return response()->download($path.$zipFileName)->deleteFileAfterSend(true);
try {
$preview = $this->datevService->getPreview($month, $year);
return response()->json([
'success' => true,
'data' => $preview,
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Fehler bei der Vorschau: '.$e->getMessage(),
], 500);
}
}
/**
* Export generieren und speichern.
*/
public function generate(Request $request)
{
$month = intval($request->get('month', session('payment_taxadvisor_filter_month')));
$year = intval($request->get('year', session('payment_taxadvisor_filter_year')));
try {
$export = $this->datevService->generateExport($month, $year);
return redirect()
->route('admin_payments_taxadvisor')
->with('success', "DATEV-Export für {$month}/{$year} erfolgreich generiert. {$export->total_lines} Buchungszeilen erstellt.");
} catch (\RuntimeException $e) {
return redirect()
->route('admin_payments_taxadvisor')
->with('error', $e->getMessage());
} catch (\Exception $e) {
return redirect()
->route('admin_payments_taxadvisor')
->with('error', 'Fehler beim Generieren: '.$e->getMessage());
}
}
/**
* CSV-Datei herunterladen.
*/
public function download($id)
{
$export = DatevExport::findOrFail($id);
if (! $export->isGenerated()) {
return redirect()
->route('admin_payments_taxadvisor')
->with('error', 'Export wurde noch nicht generiert.');
}
$disk = config('datev.storage_disk', 'local');
$path = $export->file_path;
if (! Storage::disk($disk)->exists($path)) {
// CSV neu generieren falls Datei nicht mehr vorhanden
$csvContent = $this->datevService->buildCsv($export);
Storage::disk($disk)->makeDirectory($export->getStoragePath());
Storage::disk($disk)->put($path, $csvContent);
}
// Status auf "heruntergeladen" setzen
$export->markAsDownloaded();
return Storage::disk($disk)->download($path, $export->filename, [
'Content-Type' => 'text/csv; charset=utf-8',
]);
}
/**
* DataTable: Export-Lines eines bestimmten Exports.
*/
public function datatable(Request $request)
{
$exportId = $request->get('export_id');
$query = DatevExportLine::select('datev_export_lines.*');
if ($exportId) {
$query->where('datev_export_id', $exportId);
} else {
return "Failed to create the zip file.";
}
}
// Fallback: Lines des aktuellen Perioden-Exports
$month = intval(session('payment_taxadvisor_filter_month', date('m')));
$year = intval(session('payment_taxadvisor_filter_year', date('Y')));
public function download(){
$export = DatevExport::forPeriod($month, $year)
->generated()
->latest()
->first();
$query = $this->initSearch();
$files = [];
$user_invoices = $query->get();
foreach ($user_invoices as $user_invoice) {
$filename = $user_invoice->filename;
$disk = $user_invoice->disk;
$path = $user_invoice->getDownloadPath();
if (Storage::disk($disk)->exists($path)) {
$file = Storage::disk($disk)->get($path);
$pdf_path = storage_path().'/app/public/'.$path;
$files[] = $pdf_path;
if ($export) {
$query->where('datev_export_id', $export->id);
} else {
$query->where('datev_export_id', 0); // Leere Ergebnismenge
}
}
return $this->createZip($files);
dd("asd");
return \DataTables::eloquent($query)
->editColumn('line_number', function (DatevExportLine $line) {
return $line->line_number;
})
->addColumn('source_type_label', function (DatevExportLine $line) {
return $line->source_type_label;
})
->addColumn('amount_display', function (DatevExportLine $line) {
return '<span class="no-line-break">'.$line->formatted_amount.'</span>';
})
->editColumn('soll_haben', function (DatevExportLine $line) {
$badge = $line->soll_haben === 'H' ? 'success' : 'warning';
return '<span class="badge badge-'.$badge.'">'.$line->soll_haben.'</span>';
})
->editColumn('konto', function (DatevExportLine $line) {
return $line->konto;
})
->editColumn('gegenkonto', function (DatevExportLine $line) {
return $line->gegenkonto;
})
->editColumn('bu_schluessel', function (DatevExportLine $line) {
return $line->bu_schluessel;
})
->addColumn('belegdatum_display', function (DatevExportLine $line) {
return $line->formatted_belegdatum;
})
->editColumn('belegfeld1', function (DatevExportLine $line) {
return $line->belegfeld1;
})
->editColumn('buchungstext', function (DatevExportLine $line) {
return $line->buchungstext;
})
->editColumn('eu_ustid', function (DatevExportLine $line) {
return $line->eu_ustid ?: '-';
})
->filterColumn('source_type_label', function ($query, $keyword) {
$typeMap = ['rechnung' => 'invoice', 'gutschrift' => 'credit', 'storno' => 'cancellation'];
foreach ($typeMap as $label => $type) {
if (stripos($label, $keyword) !== false) {
$query->where('source_type', $type);
if(Request::get('action') === "export"){
$objects = $this->initSearch(false);
$columns = [];
$filename = "mivita-absatzmengen-".session('payment_taxadvisor_filter_month').'_'.session('payment_taxadvisor_filter_year')."-export";
$headers = array(
'#',
'Produkt',
'Artikelnummer',
'Menge',
);
if($objects){
foreach ($objects as $key => $obj){
$columns[] = array(
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'value' => $obj['value'],
);
return;
}
}
}
return Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
}
$query->where('source_type', 'like', "%{$keyword}%");
})
->orderColumn('line_number', 'line_number $1')
->rawColumns(['amount_display', 'soll_haben'])
->make(true);
}
private function setFilterVars(){
/**
* Export sperren (Lock).
*/
public function lock($id)
{
$export = DatevExport::findOrFail($id);
if(!session('payment_taxadvisor_filter_month')){
if ($export->isLocked()) {
return redirect()
->route('admin_payments_taxadvisor')
->with('info', 'Export ist bereits gesperrt.');
}
$export->lock();
return redirect()
->route('admin_payments_taxadvisor')
->with('success', "Export {$export->period_label} wurde gesperrt.");
}
/**
* Export löschen (soft delete).
*/
public function destroy($id)
{
$export = DatevExport::findOrFail($id);
if ($export->isLocked()) {
return redirect()
->route('admin_payments_taxadvisor')
->with('error', 'Gesperrte Exports können nicht gelöscht werden.');
}
$export->delete();
return redirect()
->route('admin_payments_taxadvisor')
->with('success', "Export {$export->period_label} wurde gelöscht.");
}
/*
|--------------------------------------------------------------------------
| Private Hilfsmethoden
|--------------------------------------------------------------------------
*/
private function setFilterVars(Request $request): void
{
if (! session('payment_taxadvisor_filter_month')) {
session(['payment_taxadvisor_filter_month' => intval(date('m'))]);
}
if(!session('payment_taxadvisor_filter_year')){
if (! session('payment_taxadvisor_filter_year')) {
session(['payment_taxadvisor_filter_year' => intval(date('Y'))]);
}
if(Request::get('payment_taxadvisor_filter_month')){
session(['payment_taxadvisor_filter_month' => Request::get('payment_taxadvisor_filter_month')]);
if ($request->get('payment_taxadvisor_filter_month')) {
session(['payment_taxadvisor_filter_month' => $request->get('payment_taxadvisor_filter_month')]);
}
if(Request::get('payment_taxadvisor_filter_year')){
session(['payment_taxadvisor_filter_year' => Request::get('payment_taxadvisor_filter_year')]);
if ($request->get('payment_taxadvisor_filter_year')) {
session(['payment_taxadvisor_filter_year' => $request->get('payment_taxadvisor_filter_year')]);
}
}
private function initSearch()
{
$this->setFilterVars();
$query = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
->where('user_invoices.month', '=', Request::get('payment_taxadvisor_filter_month'))
->where('user_invoices.year', '=', Request::get('payment_taxadvisor_filter_year'));
return $query;
}
public function datatable(){
$query = $this->initSearch();
return \DataTables::eloquent($query)
->addColumn('id', function (UserInvoice $UserInvoice) {
return $UserInvoice->id;
})
->addColumn('turnover', function (UserInvoice $UserInvoice) {
return '<span class="no-line-break">'.$UserInvoice->shopping_order->getFormattedTotalShipping()." €</span>";
})
->addColumn('debit_credit_indicator', function (UserInvoice $UserInvoice) {
return "H";
})
->addColumn('account', function (UserInvoice $UserInvoice) {
if($UserInvoice->shopping_order && $UserInvoice->shopping_order->shopping_user){
$key = strtoupper(substr($UserInvoice->shopping_order->shopping_user->billing_lastname, 0, 1));
if($key === "S"){
if(strtoupper(substr($UserInvoice->shopping_order->shopping_user->billing_lastname, 0, 3)) === "SCH"){
return $this->accountKey['SCH'];
}
}
return isset($this->accountKey[$key]) ? $this->accountKey[$key] : $key;
}
return "-";
})
->addColumn('contra_account', function (UserInvoice $UserInvoice) {
return "-";
})
->addColumn('bu_key', function (UserInvoice $UserInvoice) {
if($UserInvoice->shopping_order){
return $UserInvoice->shopping_order->country_id;
}
})
->addColumn('voucher_date', function (UserInvoice $UserInvoice) {
// 101 -> für 01 Januar
return $UserInvoice->month."01";
})
->addColumn('document_field_1', function (UserInvoice $UserInvoice) {
//Rechnungsnummer
return $UserInvoice->full_number;
})
->addColumn('posting_text', function (UserInvoice $UserInvoice) {
//Buchungstext hier wäre es toll wenn der Name des Kunden steht.
if($UserInvoice->shopping_order && $UserInvoice->shopping_order->shopping_user){
return $UserInvoice->shopping_order->shopping_user->billing_firstname." ".$UserInvoice->shopping_order->shopping_user->billing_lastname;
}
return "-";
})
->addColumn('invoice', function (UserInvoice $UserInvoice) {
$ret = "";
$ret .= '<a href="'.route('storage_file', [$UserInvoice->shopping_order->id, 'invoice', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserInvoice->shopping_order->id, 'invoice', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a>';
return $ret;
})
->orderColumn('id', 'id $1')
->orderColumn('invoice_number', 'invoice_number $1')
->orderColumn('turnover', 'turnover $1')
->orderColumn('shipped', 'shipped $1')
->orderColumn('total_shipping', 'total_shipping $1')
->rawColumns(['id', 'shipping_order', 'turnover', 'total_shipping', 'status', 'txaction', 'invoice'])
->make(true);
}
}
}

View file

@ -2,25 +2,27 @@
namespace App\Http\Controllers\Portal;
use Auth;
use Yard;
use Request;
use Validator;
use App\Services\Shop;
use App\Services\Util;
use App\Models\Product;
use App\Models\UserAbo;
use App\Services\AboHelper;
use App\Models\ShoppingUser;
use App\Models\ShoppingOrder;
use App\Services\UserService;
use App\Models\ShoppingInstance;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ShoppingInstance;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Repositories\AboRepository;
use App\Services\AboHelper;
use App\Services\AboItemHistoryService;
use App\Services\AboOrderCart;
use App\Services\Shop;
use App\Services\UserService;
use App\Services\Util;
use Auth;
use Request;
use Yard;
class AboController extends Controller
{
private $instance = 'subscription';
private $yard;
/**
@ -34,12 +36,11 @@ class AboController extends Controller
$this->yard = Yard::instance($this->instance);
}
public function myAbo()
{
$user = Auth::guard('customers')->user();
if (!$user->shopping_user_id) {
if (! $user->shopping_user_id) {
return view('portal.abo.my_abo_create', [
'user' => $user,
'no_shopping_user' => true,
@ -49,30 +50,304 @@ class AboController extends Controller
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$user_abo = UserAbo::where('email', $shopping_user->billing_email)
->where('status', '>', 1)
->first();
->where('status', '>', 1)
->first();
return $user_abo
? view('portal.abo.my_abo', ['user_abo' => $user_abo])
: view('portal.abo.my_abo_create', [
if (! $user_abo) {
return view('portal.abo.my_abo_create', [
'shopping_user' => $shopping_user,
'step' => 0,
]);
}
$this->checkPortalPermission($user_abo);
$view = 'portal';
// Init Yard und Customer-Detail
AboOrderCart::initYard($user_abo);
$customer_detail = AboOrderCart::getCustomerDetail();
AboOrderCart::makeOrderYard($user_abo);
return view('portal.abo.my_abo', [
'user_abo' => $user_abo,
'customer_detail' => $customer_detail,
'view' => $view,
'comp_products' => [],
'isAdmin' => false,
]);
}
public function update($view, $id)
{
$data = Request::all();
$user_abo = UserAbo::findOrFail($id);
$this->checkPortalPermission($user_abo);
$isAddOnlyMode = AboHelper::isAddOnlyMode($user_abo, $view);
if (isset($data['action'])) {
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::findOrFail($data['id']);
$this->checkPortalPermission($user_abo);
$aboRepository = new AboRepository;
$aboRepository->setModel($user_abo);
$aboRepository->update($data);
return redirect(route('portal.my_subscriptions'));
}
if (Request::ajax()) {
$message = false;
// addProduct
if ($data['action'] === 'addProduct') {
if ($product = Product::find($data['product_id'])) {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('product_id', $product->id)->where('comp', 0)->first()) {
$qtyBefore = $UserAboItem->qty;
$UserAboItem->qty = $UserAboItem->qty + 1;
$UserAboItem->save();
AboItemHistoryService::logProductAdded($user_abo, $UserAboItem, $qtyBefore, $view);
} else {
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $product->id,
'comp' => 0,
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
}
// updateCart
if ($data['action'] === 'updateCart') {
if (isset($data['product_id']) && $product = Product::find($data['product_id'])) {
if (isset($data['order_item_id']) && $UserAboItem = UserAboItem::find($data['order_item_id'])) {
if (isset($data['qty'])) {
$qtyBefore = $UserAboItem->qty;
$qty = (int) $data['qty'];
$qty = $qty < 1 ? 1 : $qty;
$qty = $qty > 100 ? 100 : $qty;
if ($isAddOnlyMode && $qty < $UserAboItem->qty) {
$qty = $UserAboItem->qty;
}
$UserAboItem->qty = $qty;
$UserAboItem->save();
AboItemHistoryService::logQtyChanged($user_abo, $UserAboItem, $qtyBefore, $qty, $view);
}
}
}
}
// removeFromCart
if ($data['action'] === 'removeFromCart') {
if ($isAddOnlyMode) {
return response()->json([
'response' => false,
'message' => __('abo.error_add_only_no_remove'),
], 403);
}
if (! isset($data['product_id']) || ! ($product = Product::find($data['product_id']))) {
$message = __('abo.product_not_found');
}
if (! isset($data['order_item_id']) || ! ($userAboItem = UserAboItem::find($data['order_item_id']))) {
$message = __('abo.abo_item_not_found');
}
$has_basis_product = $this->checkNeedBasisProduct($user_abo, $product, $data['order_item_id']);
if (! $has_basis_product) {
$message = __('abo.need_basis_product');
}
if (! $message) {
AboItemHistoryService::logProductRemoved($user_abo, $userAboItem, $view);
$userAboItem->delete();
$user_abo->refresh();
}
}
// updateCompProduct
if ($data['action'] === 'updateCompProduct') {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('comp', $data['comp_num'])->first()) {
$oldProduct = $UserAboItem->product;
$UserAboItem->product_id = $data['comp_product_id'];
$UserAboItem->save();
$UserAboItem->load('product');
AboItemHistoryService::logCompProductChanged($user_abo, $UserAboItem, $oldProduct, $UserAboItem->product, $view);
} else {
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $data['comp_product_id'],
'comp' => $data['comp_num'],
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
AboOrderCart::initYard($user_abo);
AboOrderCart::makeOrderYard($user_abo);
AboOrderCart::checkNumOfCompProducts($user_abo);
$error_message = $message ? $message : false;
$html_cart = view('admin.abo._order_abo_show', ['user_abo' => $user_abo, 'error_message' => $error_message, 'add_only_mode' => $isAddOnlyMode])->render();
$html_comp = view('user.order.comp_product', $data)->render();
$amount = $user_abo->getFormattedAmount();
return response()->json(['response' => true, 'data' => $data, 'html_cart' => $html_cart, 'html_comp' => $html_comp, 'amount' => $amount]);
}
}
}
public function datatable($user_abo_id)
{
$user_abo = UserAbo::findOrFail($user_abo_id);
$this->checkPortalPermission($user_abo);
$show_on_ids = ['12', '13'];
$query = Product::select('products.*')
->where('active', true)
->where(function ($q) use ($show_on_ids) {
foreach ($show_on_ids as $id) {
$q->orWhereJsonContains('show_on', $id);
}
})
->orderByRaw(
"CASE
WHEN JSON_CONTAINS(show_on, ?, '$') THEN 1
WHEN JSON_CONTAINS(show_on, ?, '$') THEN 2
ELSE 3 END",
[$show_on_ids[0], isset($show_on_ids[1]) ? $show_on_ids[1] : $show_on_ids[0]]
);
return \DataTables::eloquent($query)
->addColumn('add_card', function (Product $product) {
$tax_free = Yard::instance('shopping')->getUserTaxFree();
$price = $product->getFormattedPriceWith($tax_free, false, Yard::instance('shopping')->getUserCountry());
return '<button type="button" class="btn btn-sm btn-md-extra btn-secondary add-product-basket" data-product-id="'.$product->id.'" data-product-name="'.e($product->getLang('name')).'" data-product-price="'.$price.' &euro;">
<strong>&euro; '.$price.'</strong>&nbsp; +<span class="ion ion-md-cart"></span>
</button>';
})
->addColumn('picture', function (Product $product) {
if (count($product->images)) {
return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
}
return '';
})
->addColumn('name', function (Product $product) {
return '<strong>'.$product->getLang('name').'</strong><br>'.get_abo_type_badge_by_product($product);
})
->addColumn('points', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPoints().'</span>';
})
->addColumn('price_net', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_gross', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('action', function (Product $product) {
return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg"
data-toggle="modal" data-target="#modals-load-content" data-id="'.$product->id.'" data-route="'.route('portal.loading_modal').'"
data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
})
->filterColumn('product', function ($query, $keyword) {
if ($keyword != '') {
$query->where('name', 'LIKE', '%'.$keyword.'%');
}
})
->orderColumn('name', 'name $1')
->orderColumn('product', 'name $1')
->orderColumn('number', 'number $1')
->orderColumn('points', 'points $1')
->orderColumn('price_net', 'price_net $1')
->orderColumn('price_gross', 'price_gross $1')
->orderColumn('contents_total', 'contents_total $1')
->orderColumn('weight', 'weight $1')
->rawColumns(['add_card', 'points', 'product', 'name', 'quantity', 'picture', 'price_net', 'price_gross', 'action'])
->make(true);
}
public function modalLoad()
{
$data = Request::all();
$ret = '';
if (isset($data['action'])) {
if ($data['action'] === 'abo-add-product') {
$user_abo = UserAbo::find($data['id']);
$this->checkPortalPermission($user_abo);
$ret = view('user.abo.modal_abo_show_products', compact('data', 'user_abo'))->render();
}
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::find($data['id']);
$this->checkPortalPermission($user_abo);
$route = route('user_abos_update', [$data['view'], $user_abo->id]);
$ret = view('admin.abo.modal_abo_update', compact('user_abo', 'data', 'route'))->render();
}
if ($data['action'] === 'user-order-show-product') {
$product = Product::find($data['id']);
$ret = view('admin.modal.show_product', compact('product', 'data'))->render();
}
}
if (Request::ajax()) {
return response()->json(['response' => $data, 'html' => $ret, 'status' => true]);
}
abort(404);
}
public function checkNeedBasisProduct($user_abo, $product, $order_item_id)
{
if (AboHelper::getAboShowOn($product) !== 'base') {
return true;
}
foreach ($user_abo->user_abo_items as $user_abo_item) {
if ($user_abo_item->id == $order_item_id) {
continue;
}
if ($user_abo_item->comp) {
continue;
}
if (AboHelper::getAboShowOn($user_abo_item->product) === 'base') {
return true;
}
}
return false;
}
private function checkPortalPermission($user_abo)
{
$user = Auth::guard('customers')->user();
if (! $user || ! $user->shopping_user_id) {
abort(403, 'Unauthorized action.');
}
$shopping_user = ShoppingUser::find($user->shopping_user_id);
if (! $shopping_user || $user_abo->email !== $shopping_user->billing_email) {
abort(403, 'Unauthorized action.');
}
}
public function myAboCreate($step)
{
$user = Auth::guard('customers')->user();
if (!$user->shopping_user_id) {
if (! $user->shopping_user_id) {
abort(403, 'Unauthorized action.');
}
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$data = $this->prepareAboCreateData($shopping_user, $step);
if(isset($data['checkout_url'])){
if (isset($data['checkout_url'])) {
return redirect($data['checkout_url']);
}
return view('portal.abo.my_abo_create', $data);
}
@ -81,16 +356,16 @@ class AboController extends Controller
$data = [
'shopping_user' => $shopping_user,
'basis_products' => Product::where('active', true)
->whereJsonContains('show_on', ['12'])
->orderBy('pos', 'ASC')
->get(),
->whereJsonContains('show_on', ['12'])
->orderBy('pos', 'ASC')
->get(),
'upgrade_products' => Product::where('active', true)
->whereJsonContains('show_on', ['13'])
->orderBy('pos', 'ASC')
->get(),
->whereJsonContains('show_on', ['13'])
->orderBy('pos', 'ASC')
->get(),
'step' => 0,
];
if(Request::get('action') == 'back') {
if (Request::get('action') == 'back') {
$step = $step - 2;
}
@ -110,14 +385,14 @@ class AboController extends Controller
case 3:
UserService::setInstance($this->instance);
UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
if(Request::get('action') == 'next'){
if (!$this->checkBasisProduct()) {
if (Request::get('action') == 'next') {
if (! $this->checkBasisProduct()) {
$data['error'] = __('abo.abo_error_basis_product');
$data['step'] = 2;
} else {
$data['step'] = 3;
}
}else{
} else {
$data['step'] = 3;
}
break;
@ -128,12 +403,12 @@ class AboController extends Controller
$data['step'] = 4;
break;
case 5:
//chekout verarbeiten
// chekout verarbeiten
UserService::setInstance($this->instance);
UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
if(Request::get('action') == 'checkout'){
//checkout verarbeiten
if (!$this->preCheckCheckout()) {
if (Request::get('action') == 'checkout') {
// checkout verarbeiten
if (! $this->preCheckCheckout()) {
$data['error'] = __('abo.abo_error_basis_product');
$data['step'] = 4;
} else {
@ -152,8 +427,8 @@ class AboController extends Controller
private function initYard($shopping_user)
{
$delivery_country = $shopping_user->getDeliveryCountry(true);
if (!$delivery_country) {
if (! $delivery_country) {
abort(404, 'No delivery country found, please edit your personal data.');
}
@ -164,55 +439,55 @@ class AboController extends Controller
Shop::initUserShopLang($delivery_country, $this->instance);
}
private function preCheckCheckout(){
private function preCheckCheckout()
{
$result = false;
//alle inhlate des warenkorb
// alle inhlate des warenkorb
$cartItems = $this->yard->content();
foreach($cartItems as $item){
if(in_array(12, $item->options->show_on)){
foreach ($cartItems as $item) {
if (in_array(12, $item->options->show_on)) {
$result = true;
}
}
return $result;
}
private function checkBasisProduct()
{
$data = Request::all();
$result = false;
if (!isset($data['base_product_qty'])) {
if (! isset($data['base_product_qty'])) {
return false;
}
foreach ($data['base_product_qty'] as $product_id => $quantity) {
$product = Product::find($product_id);
if (!$product || intval($quantity) <= 0) {
if (! $product || intval($quantity) <= 0) {
continue;
}
$result = true;
$this->addProductToCart($product, $quantity);
}
return $result;
}
private function upgradeProductToCart(){
private function upgradeProductToCart()
{
$data = Request::all();
$result = false;
if (!isset($data['upgrade_product_qty'])) {
if (! isset($data['upgrade_product_qty'])) {
return false;
}
foreach ($data['upgrade_product_qty'] as $product_id => $quantity) {
$product = Product::find($product_id);
if (!$product) {
if (! $product) {
continue;
}
@ -226,7 +501,7 @@ class AboController extends Controller
private function addProductToCart($product, $quantity)
{
// Suche nach dem Produkt im Warenkorb
$cartItems = $this->yard->search(function($item) use ($product) {
$cartItems = $this->yard->search(function ($item) use ($product) {
return $item->id === $product->id;
});
@ -235,13 +510,14 @@ class AboController extends Controller
foreach ($cartItems as $item) {
$this->yard->remove($item->rowId);
}
return;
}
$image = $product->images->first()->slug ?? '';
$price = $product->getPriceWith(
$this->yard->getUserTaxFree(),
false,
$this->yard->getUserTaxFree(),
false,
$this->yard->getUserCountry()
);
@ -265,7 +541,7 @@ class AboController extends Controller
'points' => $product->points,
'no_commission' => $product->no_commission,
'no_free_shipping' => $product->no_free_shipping,
'show_on' => $product->show_on
'show_on' => $product->show_on,
]
);
}
@ -274,15 +550,15 @@ class AboController extends Controller
$this->yard->reCalculateShippingPrice();
}
private function processCheckout(){
private function processCheckout()
{
$user_shop = Util::getUserShop();
if(!$user_shop){
if (! $user_shop) {
$user_shop = Util::getDefaultUserShop();
}
do {
$identifier = Util::getToken();
} while( ShoppingInstance::where('identifier', $identifier)->count() );
} while (ShoppingInstance::where('identifier', $identifier)->count());
$data = [];
$data['is_from'] = 'shopping';
@ -291,7 +567,7 @@ class AboController extends Controller
ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => $user_shop->id,
'payment' => 1, //Customer Shop Payment
'payment' => 1, // Customer Shop Payment
'subdomain' => url('/'),
'country_id' => $this->yard->getShippingCountryId(),
'language' => \App::getLocale(),
@ -299,13 +575,14 @@ class AboController extends Controller
'back' => url()->previous(),
]);
$this->yard->store($identifier);
//add to DB
$path = route('checkout.checkout_card', ['identifier'=>$identifier]);
if(strpos($path, 'https') === false){
// add to DB
$path = route('checkout.checkout_card', ['identifier' => $identifier]);
if (strpos($path, 'https') === false) {
$path = str_replace('http', 'https', $path);
}
return $path;
}
}

View file

@ -2,13 +2,12 @@
namespace App\Http\Controllers\Portal;
use App\Http\Controllers\Controller;
use App\Models\ShoppingUser;
use App\Services\CustomerPriority;
use Auth;
use Request;
use Validator;
use App\Models\ShoppingUser;
use App\Services\CustomerPriority;
use App\Http\Controllers\Controller;
class CustomerController extends Controller
{
@ -22,49 +21,48 @@ class CustomerController extends Controller
$this->middleware('auth:customers');
}
public function myDataEdit()
{
$user = Auth::guard('customers')->user();
if($user->shopping_user_id){
if ($user->shopping_user_id) {
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
}else{
$shopping_user = new ShoppingUser();
} else {
$shopping_user = new ShoppingUser;
}
$data = [
'shopping_user' => $shopping_user,
'isAdmin' => false,
'isView' => 'customer',
];
return view('portal.customer.edit', $data);
return view('portal.customer.edit', $data);
}
public function myDataStore(){
public function myDataStore()
{
$user = Auth::guard('customers')->user();
$data = Request::all();
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_address'=>'required',
'billing_zipcode'=>'required',
'billing_firstname' => 'required',
'billing_lastname' => 'required',
'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);
@ -72,28 +70,31 @@ class CustomerController extends Controller
return back()->withErrors($validator)->withInput(Request::all());
}
}
$data['language'] = \App::getLocale();
$data['language'] = $data['language'] ?? \App::getLocale();
$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($user->shopping_user_id){
if ($user->shopping_user_id) {
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$shopping_user->fill($data);
$shopping_user->save();
}else{
// Sprachpräferenz auch im Customer-Modell für Portal-UI synchronisieren
if (isset($data['language'])) {
$user->update(['language' => $data['language']]);
}
} else {
$data['billing_email'] = $user->email;
$shopping_user = ShoppingUser::create($data);
$user->shopping_user_id = $shopping_user->id;
if (isset($data['language'])) {
$user->language = $data['language'];
}
$user->save();
//kundenhoheit
// kundenhoheit
CustomerPriority::checkOne(ShoppingUser::find($shopping_user->id), true);
}
\Session()->flash('alert-save', true);
return redirect(route('portal.my_data.edit'));
}
}

View file

@ -5,68 +5,202 @@ namespace App\Http\Controllers\Portal;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Services\Payment;
use App\Services\Shop;
use App\Services\Util;
use Auth;
use Request;
use Validator;
use Yard;
class OrderController extends Controller
{
private $instance = 'webshop';
/**
* Create a new controller instance.
*
* @return void
*/
private string $instance = 'webshop';
public function __construct()
{
$this->middleware('auth:customers');
}
/**
* Bestellübersicht anzeigen.
*/
public function myOrders()
{
$user = Auth::guard('customers')->user();
if($user->shopping_user_id){
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$shopping_orders = $shopping_user->getAllOrdersByMember();
}else{
$shopping_user = new ShoppingUser();
$shopping_orders = [];
}
$data = [
'shopping_user' => $shopping_user,
'shopping_orders' => $shopping_orders,
];
return view('portal.order.my_orders', $data);
return view('portal.order.my_orders');
}
public function myOrderShow($id)
/**
* DataTable-Daten für Bestellübersicht (server-side).
*/
public function ordersDatatable()
{
$user = Auth::guard('customers')->user();
if (! $user->shopping_user_id) {
return \DataTables::of(collect())->make(true);
}
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$shopping_order = ShoppingOrder::findOrFail($id);
if($shopping_order->shopping_user_id != $user->shopping_user_id){
$userIds = ShoppingUser::where('billing_email', $shopping_user->billing_email)
->where('member_id', $shopping_user->member_id)
->pluck('id');
$query = ShoppingOrder::with('shopping_user')
->select('shopping_orders.*')
->whereIn('shopping_user_id', $userIds)
->whereNotNull('txaction');
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $order) {
return '<a href="'.route('portal.my_orders.show', $order->id).'" '
.'class="btn icon-btn btn-sm btn-primary"><span class="fa fa-eye"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $order) {
return $order->created_at->format('d.m.Y');
})
->addColumn('total_shipping', function (ShoppingOrder $order) {
return '<span class="no-line-break">'.$order->getFormattedTotalShipping().' €</span>';
})
->addColumn('txaction', function (ShoppingOrder $order) {
return Payment::getShoppingOrderBadge($order);
})
->addColumn('shipped', function (ShoppingOrder $order) {
return '<span class="badge badge-pill badge-'.$order->getShippedColor().'">'
.$order->getShippedType().'</span>';
})
->addColumn('firstname', function (ShoppingOrder $order) {
return $order->shopping_user->billing_firstname ?? '-';
})
->addColumn('lastname', function (ShoppingOrder $order) {
return $order->shopping_user->billing_lastname ?? '-';
})
->addColumn('email', function (ShoppingOrder $order) {
return $order->shopping_user->billing_email ?? '-';
})
->addColumn('invoice', function (ShoppingOrder $order) {
if ($order->isInvoice()) {
return '<span class="no-line-break">'
.'<a href="'.route('storage_file', [$order->id, 'invoice', 'download']).'" '
.'class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> '
.'<a href="'.route('storage_file', [$order->id, 'invoice', 'stream']).'" '
.'target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a>'
.'</span>';
}
return '-';
})
->addColumn('payment_for', function (ShoppingOrder $order) {
return Payment::getPaymentForBadge($order);
})
->orderColumn('id', 'shopping_orders.id $1')
->orderColumn('created_at', 'shopping_orders.created_at $1')
->orderColumn('total_shipping', 'shopping_orders.total_shipping $1')
->orderColumn('txaction', 'shopping_orders.txaction $1')
->orderColumn('shipped', 'shopping_orders.shipped $1')
->rawColumns(['id', 'txaction', 'payment_for', 'total_shipping', 'invoice', 'shipped'])
->make(true);
}
/**
* Bestelldetail anzeigen.
*/
public function myOrderShow(int $id)
{
$user = Auth::guard('customers')->user();
if (! $user->shopping_user_id) {
abort(403, 'Unauthorized action.');
}
$shopping_order = ShoppingOrder::with('shopping_user', 'shopping_order_items.product.images')
->findOrFail($id);
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
if (! $this->orderBelongsToMember($shopping_order, $shopping_user)) {
abort(403, 'Unauthorized action.');
}
return view('portal.order.my_order_show', [
'shopping_order' => $shopping_order,
'shopping_user' => $shopping_user,
]);
}
public function myOrderCreate($id)
/**
* DataTable-Daten für Zahlungen einer Bestellung (server-side).
*/
public function paymentsDatatable(int $id)
{
$user = Auth::guard('customers')->user();
if (! $user->shopping_user_id) {
return \DataTables::of(collect())->make(true);
}
$shopping_order = ShoppingOrder::findOrFail($id);
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
if (! $this->orderBelongsToMember($shopping_order, $shopping_user)) {
abort(403, 'Unauthorized action.');
}
$query = ShoppingPayment::where('shopping_order_id', $id);
$counter = 0;
return \DataTables::eloquent($query)
->addColumn('line_number', function (ShoppingPayment $payment) use (&$counter) {
$counter++;
return $counter;
})
->addColumn('payment_type', function (ShoppingPayment $payment) {
return $payment->getPaymentType();
})
->addColumn('amount', function (ShoppingPayment $payment) {
return $payment->getPaymentAmount();
})
->addColumn('status', function (ShoppingPayment $payment) {
return Payment::getShoppingPaymentBadge($payment);
})
->addColumn('created_at', function (ShoppingPayment $payment) {
return $payment->created_at->format('d.m.Y H:i');
})
->addColumn('reference', function (ShoppingPayment $payment) {
return $payment->reference;
})
->rawColumns(['status'])
->make(true);
}
/**
* Prüft, ob Bestellung zum Mitglied gehört (billing_email + member_id).
*/
private function orderBelongsToMember(ShoppingOrder $order, ShoppingUser $member): bool
{
$orderUser = $order->shopping_user;
return $orderUser
&& $orderUser->billing_email === $member->billing_email
&& $orderUser->member_id === $member->member_id;
}
/**
* Bestellung erneut in den Warenkorb legen.
*/
public function myOrderCreate(int $id)
{
$user = Auth::guard('customers')->user();
$shopping_order = ShoppingOrder::findOrFail($id);
if($shopping_order->shopping_user_id != $user->shopping_user_id){
abort(403, 'Unauthorized action.');
if ($shopping_order->shopping_user_id != $user->shopping_user_id) {
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
if (! $this->orderBelongsToMember($shopping_order, $shopping_user)) {
abort(403, 'Unauthorized action.');
}
}
$shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
$delivery_country = $shopping_user->getDeliveryCountry(true);
@ -76,41 +210,50 @@ class OrderController extends Controller
Shop::initUserShopLang($delivery_country, $this->instance);
//init Yard
foreach($shopping_order->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
$this->addToCard($shopping_order_item->product_id, $shopping_order_item->qty);
foreach ($shopping_order->shopping_order_items as $item) {
if ($item->product) {
$this->addToCart($item->product_id, $item->qty);
}
}
$url = Util::getMyMivitaShopUrl("/user/card/show");
return redirect($url);
return redirect(Util::getMyMivitaShopUrl('/user/card/show'));
}
private function addToCard($id, $quantity = 1)
private function addToCart(int $productId, int $quantity = 1): void
{
$product = Product::find($id);
if($product){
$image = "";
if($product->images->count()){
$image = $product->images->first()->slug;
}
$cartItem = Yard::instance($this->instance)
->add($product->id, $product->getLang('name'), $quantity,
$product->getPriceWith(Yard::instance($this->instance)->getUserTaxFree(), false, Yard::instance($this->instance)->getUserCountry()), false, false,
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
if(Yard::instance($this->instance)->getUserTaxFree()){
Yard::setTax($cartItem->rowId, 0);
}else{
Yard::setTax($cartItem->rowId, $product->getTaxWith(Yard::instance($this->instance)->getUserCountry()));
}
Yard::instance($this->instance)->reCalculateShippingPrice();
\Session()->flash('show-card-after-add', true);
$product = Product::find($productId);
if (! $product) {
return;
}
$image = $product->images->first()?->slug ?? '';
$yard = Yard::instance($this->instance);
$cartItem = $yard->add(
$product->id,
$product->getLang('name'),
$quantity,
$product->getPriceWith($yard->getUserTaxFree(), false, $yard->getUserCountry()),
false,
false,
[
'image' => $image,
'slug' => $product->slug,
'weight' => $product->weight,
'points' => $product->points,
'no_commission' => $product->no_commission,
'no_free_shipping' => $product->no_free_shipping,
'show_on' => $product->show_on,
]
);
if ($yard->getUserTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith($yard->getUserCountry()));
}
$yard->reCalculateShippingPrice();
\Session()->flash('show-card-after-add', true);
}
}

View file

@ -2,20 +2,19 @@
namespace App\Http\Controllers;
use Request;
use App\Models\UserShop;
use App\Services\Payment;
use App\Models\ShoppingUser;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\PaymentTransaction;
use App\Services\CustomerPriority;
use App\Models\ShoppingUser;
use App\Models\UserShop;
use App\Repositories\InvoiceRepository;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\CustomerPriority;
use App\Services\Payment;
use Request;
class SalesController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -28,6 +27,7 @@ class SalesController extends Controller
return redirect(route('admin_sales_users'));
}
$data = [];
return view('admin.sales.users', $data);
}
@ -48,36 +48,38 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_user',
];
return view('admin.sales.user_detail', $data);
}
public function usersStore($id)
{
die("keine funktion");
exit('keine funktion');
$data = [
'shopping_order' => ShoppingOrder::find($id),
'isAdmin' => true,
];
return view('admin.sales.user_detail', $data);
}
public function usersDatatable()
{
$query = ShoppingOrder::with('shopping_user', 'user_shop', 'shopping_payments')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', '!=', NULL);
$query = ShoppingOrder::with('shopping_user', 'user_shop', 'shopping_payments')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', '!=', null);
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
return '<a href="' . route('admin_sales_users_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('admin_sales_users_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
@ -85,27 +87,28 @@ class SalesController extends Controller
->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
if ($ShoppingOrder->payment_for === 8) {
return '<button type="button" class="btn btn-xs btn-info btn-round" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $ShoppingOrder->id . '"
data-id="'.$ShoppingOrder->id.'"
data-action="shop-user-order-shipping-detail"
data-back=""
data-modal="modal-xl"
data-init_from="user"
data-route="' . route('modal_load') . '"><span class="fa fa-eye"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
}
return '<span class="badge badge-pill badge-' . $ShoppingOrder->getShippedColor() . '">' . $ShoppingOrder->getShippedType() . '</span>';
return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
})
->addColumn('dhl_button', function (ShoppingOrder $ShoppingOrder) {
return '<button type="button" class="btn btn-xs btn-' . ($ShoppingOrder->hasDhlShipments() ? 'primary' : 'secondary') . '" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $ShoppingOrder->id . '"
return '<button type="button" class="btn btn-xs btn-'.($ShoppingOrder->hasDhlShipments() ? 'primary' : 'secondary').'" data-toggle="modal" data-target="#modals-load-content"
data-id="'.$ShoppingOrder->id.'"
data-action="create-dhl-shipment"
data-route="' . route('modal_load') . '"><span class="fa fa-shipping-fast"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-shipping-fast"></span></button>';
})
->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
return Payment::getPaymentForBadge($ShoppingOrder);
})
->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']) . '" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']) . '" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
})
->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('reference');
@ -114,11 +117,12 @@ class SalesController extends Controller
return $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->orders : '';
})
->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->user_shop ? '<a href="' . $ShoppingOrder->user_shop->getSubdomain(false) . '" target="_blank">' . $ShoppingOrder->user_shop->getSubdomain(false) . '</span>' : '';
return $ShoppingOrder->user_shop ? '<a href="'.$ShoppingOrder->user_shop->getSubdomain(false).'" target="_blank">'.$ShoppingOrder->user_shop->getSubdomain(false).'</span>' : '';
})
->addColumn('auth_user_shop', function (ShoppingOrder $ShoppingOrder) {
$auth_user_shop = UserShop::whereUserId($ShoppingOrder->auth_user_id)->first();
return $auth_user_shop ? '<a href="' . $auth_user_shop->getSubdomain(false) . '" target="_blank">' . $auth_user_shop->getSubdomain(false) . '</span>' : '-';
return $auth_user_shop ? '<a href="'.$auth_user_shop->getSubdomain(false).'" target="_blank">'.$auth_user_shop->getSubdomain(false).'</span>' : '-';
})
->orderColumn('id', 'id $1')
->orderColumn('txaction', 'txaction $1')
@ -137,6 +141,7 @@ class SalesController extends Controller
set_user_attr('filter_user_shop_id', null);
set_user_attr('filter_txaction', null);
set_user_attr('filter_member_id', null);
return redirect(route('admin_sales_customers'));
}
$filter_user_shops = ShoppingOrder::select('user_shops.id', 'user_shops.slug')
@ -146,28 +151,27 @@ class SalesController extends Controller
->pluck('slug', 'id')
->toArray();
$filter_members = ShoppingOrder::join('users', 'member_id', '=', 'users.id')->groupBy('member_id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->get();
//->pluck('email', 'id')->unique()->toArray();
// ->pluck('email', 'id')->unique()->toArray();
$data = [
'filter_user_shops' => $filter_user_shops,
'filter_members' => $filter_members,
];
return view('admin.sales.customers', $data);
}
public function customersDetail($id)
{
$ShoppingOrder = ShoppingOrder::find($id);
if (!$ShoppingOrder) {
if (! $ShoppingOrder) {
abort(404);
}
if ($ShoppingOrder->payment_for !== 6 && $ShoppingOrder->payment_for !== 7) {
return redirect(route('admin_sales_users_detail', [$ShoppingOrder->id]));
abort(403, 'Beraterbestellung');
}
/*
/*
if($ShoppingOrder->shipped === 0){
$ShoppingOrder->shipped = 1;
$ShoppingOrder->save();
@ -178,6 +182,7 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_customer',
];
return view('admin.sales.customer_detail', $data);
}
@ -186,46 +191,53 @@ class SalesController extends Controller
$data = Request::all();
$change_member_error = false;
if ($data['action'] === 'shopping-order-change-member') {
if (!isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
$change_member_error = "Das Passwort ist falsch.";
if (! isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
$change_member_error = 'Das Passwort ist falsch.';
} else {
//change
// change
$shopping_order = ShoppingOrder::findOrFail($data['id']);
CustomerPriority::newMemberForOrder($shopping_order, $data['change_member_id'], $data['customer_set_member_for']);
\Session()->flash('alert-save', true);
return redirect(route('admin_sales_customers_detail', [$shopping_order->id]));
}
}
if ($data['action'] === 'shopping-user-is-like-member') {
if (!isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
if (! isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
\Session()->flash('alert-error', 'Das Passwort ist falsch.');
return redirect($data['back']);
} else {
if (!isset($data['is_like_shopping_user_id'])) {
if (! isset($data['is_like_shopping_user_id'])) {
\Session()->flash('alert-error', 'Keine Änderung ausgewählt');
return redirect($data['back']);
}
$shopping_user = ShoppingUser::findOrFail($data['id']);
$set_like_shopping_user = ShoppingUser::findOrFail($data['is_like_shopping_user_id']);
$send_member_mail = isset($data['send_member_mail']) ? true : false;
$change_shopping_user = isset($data['change_shopping_user']) ? true : false;
//Mail send in setIsLike
// Mail send in setIsLike
CustomerPriority::setIsLike($shopping_user, $set_like_shopping_user, $send_member_mail, $change_shopping_user);
\Session()->flash('alert-save', true);
return redirect($data['back']);
}
}
if ($data['action'] === 'shopping-order-change-points') {
if (!isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
if (! isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
\Session()->flash('alert-error', 'Das Passwort ist falsch.');
return back();
} else {
if (!isset($data['change_points'])) {
if (! isset($data['change_points'])) {
\Session()->flash('alert-error', 'Keine Änderung ausgewählt');
return back();
}
$shopping_order = ShoppingOrder::findOrFail($data['id']);
SalesPointsVolume::changeSalesPointsVolumeUser($shopping_order, $data['change_member_id']);
return redirect(route('admin_sales_customers_detail', [$shopping_order->id]));
}
}
@ -235,90 +247,94 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_customer',
];
return view('admin.sales.customer_detail', $data);
}
public function customersDatatable()
{
$query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', NULL);
$query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', null);
set_user_attr('filter_user_shop_id', Request::get('filter_user_shop_id'));
if (Request::get('filter_user_shop_id') != "") {
if (Request::get('filter_user_shop_id') != '') {
$query->where('user_shop_id', '=', Request::get('filter_user_shop_id'));
}
set_user_attr('filter_txaction', Request::get('filter_txaction'));
if (Request::get('filter_txaction') != "") {
if (Request::get('filter_txaction') != '') {
if (Request::get('filter_txaction') === 'NULL') {
$query->where('txaction', '=', NULL);
$query->where('txaction', '=', null);
} else {
$query->where('txaction', '=', Request::get('filter_txaction'));
}
}
set_user_attr('filter_member_id', Request::get('filter_member_id'));
if (Request::get('filter_member_id') != "") {
if (Request::get('filter_member_id') != '') {
$query->where('member_id', '=', Request::get('filter_member_id'));
}
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
return '<a href="' . route('admin_sales_customers_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('admin_sales_customers_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
if ($ShoppingOrder->txaction === 'extern_paid') {
$shopping_oder_id = isset($ShoppingOrder->api_notice['shopping_order_id']) ? $ShoppingOrder->api_notice['shopping_order_id'] : null;
if ($shopping_oder_id) {
return '<a class="btn btn-xs btn-default btn-round" href="' . route('admin_sales_users_detail', [$shopping_oder_id]) . '"><i class="fa fa-check fa-check-circle-o"> ' . $shopping_oder_id . '</a>';
return '<a class="btn btn-xs btn-default btn-round" href="'.route('admin_sales_users_detail', [$shopping_oder_id]).'"><i class="fa fa-check fa-check-circle-o"> '.$shopping_oder_id.'</a>';
}
}
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
})
->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
return '<span class="badge badge-pill badge-' . $ShoppingOrder->getShippedColor() . '">' . $ShoppingOrder->getShippedType() . '</span>';
return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
})
->addColumn('dhl_button', function (ShoppingOrder $ShoppingOrder) {
return '<button type="button" class="btn btn-xs btn-' . ($ShoppingOrder->hasDhlShipments() ? 'primary' : 'secondary') . '" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $ShoppingOrder->id . '"
return '<button type="button" class="btn btn-xs btn-'.($ShoppingOrder->hasDhlShipments() ? 'primary' : 'secondary').'" data-toggle="modal" data-target="#modals-load-content"
data-id="'.$ShoppingOrder->id.'"
data-action="create-dhl-shipment"
data-route="' . route('modal_load') . '"><span class="fa fa-shipping-fast"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-shipping-fast"></span></button>';
})
->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
return Payment::getPaymentForBadge($ShoppingOrder);
})
->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
if (($ShoppingOrder->txaction === 'extern' || $ShoppingOrder->txaction === 'extern_paid') && $ShoppingOrder->wp_invoice_path) {
return '<span class="no-line-break"><a href="' . $ShoppingOrder->wp_invoice_path . '" class="btn btn-secondary btn-xs"><i class="fa fa-external-link-alt"></i> <i class="fa fa-download"></i></a> </div>';
return '<span class="no-line-break"><a href="'.$ShoppingOrder->wp_invoice_path.'" class="btn btn-secondary btn-xs"><i class="fa fa-external-link-alt"></i> <i class="fa fa-download"></i></a> </div>';
}
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']) . '" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']) . '" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
})
->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('reference');
})
->addColumn('member_id', function (ShoppingOrder $ShoppingOrder) {
if ($ShoppingOrder->member_id && $ShoppingOrder->member) {
return $ShoppingOrder->member ? '<a href="' . route('admin_lead_edit', [$ShoppingOrder->member_id]) . '">' . $ShoppingOrder->member->getFullName() . '</a>' : 'gelöscht';
return $ShoppingOrder->member ? '<a href="'.route('admin_lead_edit', [$ShoppingOrder->member_id]).'">'.$ShoppingOrder->member->getFullName().'</a>' : 'gelöscht';
}
if ($ShoppingOrder->shopping_user && $ShoppingOrder->shopping_user->is_like) {
return '<button type="button" class="btn btn-xs btn-outline-info" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $ShoppingOrder->shopping_user->id . '"
data-id="'.$ShoppingOrder->shopping_user->id.'"
data-action="shopping-user-is-like-member"
data-back="' . route('admin_sales_customers') . '"
data-back="'.route('admin_sales_customers').'"
data-modal="modal-xl"
data-route="' . route('modal_load') . '"><span class="fa fa-edit"></span> Berater zuordnen</button>';
data-route="'.route('modal_load').'"><span class="fa fa-edit"></span> Berater zuordnen</button>';
}
return '';
})
->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->user_shop ? '<a href="' . $ShoppingOrder->user_shop->getSubdomain(false) . '" target="_blank">' . $ShoppingOrder->user_shop->getSubdomain(false) . '</span>' : '';
return $ShoppingOrder->user_shop ? '<a href="'.$ShoppingOrder->user_shop->getSubdomain(false).'" target="_blank">'.$ShoppingOrder->user_shop->getSubdomain(false).'</span>' : '';
})
->orderColumn('id', 'id $1')
->orderColumn('txaction', 'txaction $1')
@ -334,7 +350,7 @@ class SalesController extends Controller
public function store()
{
$data = Request::all();
if (!isset($data['id'])) {
if (! isset($data['id'])) {
abort(404);
}
if (isset($data['action'])) {
@ -350,11 +366,11 @@ class SalesController extends Controller
PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'transaction',
'request' => 'transaction',
'txid' => 0,
'userid' => 0,
'status' => 'FNCMIV',
'transmitted_data' => NULL,
'transmitted_data' => null,
'txaction' => $data['txaction'],
'mode' => $shopping_payment->mode,
]);
@ -365,10 +381,10 @@ class SalesController extends Controller
$shopping_payment->txaction = $data['txaction'];
$shopping_payment->save();
//TODO can send MAIL
//Bei Zahlung auf Rechnung wurde die Rechnung schon erstellt,
//wenn muss hier die Storno erstellt werden
//Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
// TODO can send MAIL
// Bei Zahlung auf Rechnung wurde die Rechnung schon erstellt,
// wenn muss hier die Storno erstellt werden
// Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
}
}
if (isset($data['back'])) {
@ -381,7 +397,7 @@ class SalesController extends Controller
public function invoice()
{
$data = Request::all();
if (!isset($data['id'])) {
if (! isset($data['id'])) {
abort(404);
}
if (isset($data['action'])) {
@ -398,8 +414,56 @@ class SalesController extends Controller
if (isset($data['view']) && $data['view'] === 'sales_customer') {
return redirect(route('admin_sales_customers_detail', [$shopping_order->id]));
}
return redirect(route('admin_sales_users_detail', [$shopping_order->id]));
}
}
}
/**
* Stornorechnung erstellen mit Punktekorrektur
*/
public function invoiceCancellation()
{
$data = Request::all();
if (! isset($data['id'])) {
abort(404);
}
if (isset($data['action']) && $data['action'] === 'create_cancellation_invoice') {
$shopping_order = ShoppingOrder::findOrFail($data['id']);
// Prüfen ob Rechnung existiert
if (! $shopping_order->isInvoice()) {
\Session()->flash('alert-error', 'Es existiert keine Rechnung für diese Bestellung.');
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
// Prüfen ob bereits storniert
if ($shopping_order->isCancellationInvoice()) {
\Session()->flash('alert-error', 'Diese Rechnung wurde bereits storniert.');
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
try {
$invoice_repo = new InvoiceRepository($shopping_order);
$cancellation_invoice = $invoice_repo->createCancellation($data);
\Session()->flash('alert-success', 'Stornorechnung wurde erfolgreich erstellt und Punkte wurden korrigiert.');
} catch (\Exception $e) {
\Log::error('Fehler beim Erstellen der Stornorechnung: '.$e->getMessage(), [
'order_id' => $shopping_order->id,
'exception' => $e,
]);
\Session()->flash('alert-error', 'Fehler beim Erstellen der Stornorechnung: '.$e->getMessage());
}
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
abort(404);
}
}

View file

@ -5,11 +5,8 @@ namespace App\Http\Controllers;
use App\Models\Setting;
use Request;
class SettingController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -21,10 +18,10 @@ class SettingController extends Controller
$data = [
'values' => [],
];
return view('admin.settings.index', $data);
}
public function store()
{
$data = Request::all();
@ -50,7 +47,9 @@ class SettingController extends Controller
/**
* Get DHL configuration merged from database settings and .env values
* Database settings override .env values
* Priority is controlled by DHL_CONFIG_SOURCE environment variable:
* - 'database' (default): Database settings override .env values
* - 'env': Environment/Config values override database settings
*/
public function getDhlConfig()
{
@ -58,44 +57,49 @@ class SettingController extends Controller
$isTestMode = config('dhl.legacy.test_mode', false) || config('dhl.legacy.sandbox', false);
$baseUrl = $isTestMode ? config('dhl.sandbox_url') : config('dhl.base_url');
// Determine configuration priority
$useEnvPriority = config('dhl.config_source') === 'env';
return [
// API Settings
'base_url' => $isTestMode ? $baseUrl : (Setting::getContentBySlug('dhl_base_url') ?: $baseUrl),
'api_key' => Setting::getContentBySlug('dhl_api_key') ?: config('dhl.api_key'),
'username' => Setting::getContentBySlug('dhl_username') ?: config('dhl.username'),
'password' => Setting::getContentBySlug('dhl_password') ?: config('dhl.password'),
'billing_number' => Setting::getContentBySlug('dhl_billing_number') ?: config('dhl.billing_number'),
'base_url' => $isTestMode ? $baseUrl : $this->getConfigValue('dhl_base_url', $baseUrl, $useEnvPriority),
'api_key' => $this->getConfigValue('dhl_api_key', config('dhl.api_key'), $useEnvPriority),
'api_secret' => config('dhl.legacy.api_secret'), // Used by Tracking API
'username' => $this->getConfigValue('dhl_username', config('dhl.username'), $useEnvPriority),
'password' => $this->getConfigValue('dhl_password', config('dhl.password'), $useEnvPriority),
'billing_number' => $this->getConfigValue('dhl_billing_number', config('dhl.billing_number'), $useEnvPriority),
'sandbox' => config('dhl.legacy.sandbox', true), // Used by Tracking Service
'test_mode' => config('dhl.legacy.test_mode', true),
// Product Settings
'default_product' => Setting::getContentBySlug('dhl_product') ?: config('dhl.default_product'),
'label_format' => Setting::getContentBySlug('dhl_label_format') ?: config('dhl.label_format'),
'print_format' => Setting::getContentBySlug('dhl_print_format') ?: config('dhl.print_format'),
'retoure_print_format' => Setting::getContentBySlug('dhl_retoure_print_format') ?: config('dhl.retoure_print_format'),
'use_queue' => Setting::getContentBySlug('dhl_use_queue') ?: config('dhl.use_queue'),
'default_product' => $this->getConfigValue('dhl_product', config('dhl.default_product'), $useEnvPriority),
'label_format' => $this->getConfigValue('dhl_label_format', config('dhl.label_format'), $useEnvPriority),
'print_format' => $this->getConfigValue('dhl_print_format', config('dhl.print_format'), $useEnvPriority),
'retoure_print_format' => $this->getConfigValue('dhl_retoure_print_format', config('dhl.retoure_print_format'), $useEnvPriority),
'use_queue' => $this->getConfigValue('dhl_use_queue', config('dhl.use_queue'), $useEnvPriority),
// Sender Address
'sender' => [
'company' => Setting::getContentBySlug('dhl_sender_company') ?: config('dhl.sender.company'),
'name' => Setting::getContentBySlug('dhl_sender_name') ?: config('dhl.sender.name'),
'street' => Setting::getContentBySlug('dhl_sender_street') ?: config('dhl.sender.street'),
'houseNumber' => Setting::getContentBySlug('dhl_sender_house_number') ?: config('dhl.sender.houseNumber'),
'postalCode' => Setting::getContentBySlug('dhl_sender_postal_code') ?: config('dhl.sender.postalCode'),
'city' => Setting::getContentBySlug('dhl_sender_city') ?: config('dhl.sender.city'),
'country' => Setting::getContentBySlug('dhl_sender_country') ?: config('dhl.sender.country'),
'email' => Setting::getContentBySlug('dhl_sender_email') ?: config('dhl.sender.email'),
'phone' => Setting::getContentBySlug('dhl_sender_phone') ?: config('dhl.sender.phone'),
'company' => $this->getConfigValue('dhl_sender_company', config('dhl.sender.company'), $useEnvPriority),
'name' => $this->getConfigValue('dhl_sender_name', config('dhl.sender.name'), $useEnvPriority),
'street' => $this->getConfigValue('dhl_sender_street', config('dhl.sender.street'), $useEnvPriority),
'houseNumber' => $this->getConfigValue('dhl_sender_house_number', config('dhl.sender.houseNumber'), $useEnvPriority),
'postalCode' => $this->getConfigValue('dhl_sender_postal_code', config('dhl.sender.postalCode'), $useEnvPriority),
'city' => $this->getConfigValue('dhl_sender_city', config('dhl.sender.city'), $useEnvPriority),
'country' => $this->getConfigValue('dhl_sender_country', config('dhl.sender.country'), $useEnvPriority),
'email' => $this->getConfigValue('dhl_sender_email', config('dhl.sender.email'), $useEnvPriority),
'phone' => $this->getConfigValue('dhl_sender_phone', config('dhl.sender.phone'), $useEnvPriority),
],
// Account Numbers
'account_numbers' => [
'V01PAK' => Setting::getContentBySlug('dhl_account_v01pak') ?: config('dhl.account_numbers.V01PAK'),
'V62WP' => Setting::getContentBySlug('dhl_account_v62wp') ?: config('dhl.account_numbers.V62WP'),
'V53PAK' => Setting::getContentBySlug('dhl_account_v53pak') ?: config('dhl.account_numbers.V53PAK'),
'V07PAK' => Setting::getContentBySlug('dhl_account_v07pak') ?: config('dhl.account_numbers.V07PAK'),
'V01PAK' => $this->getConfigValue('dhl_account_v01pak', config('dhl.account_numbers.V01PAK'), $useEnvPriority),
'V62WP' => $this->getConfigValue('dhl_account_v62wp', config('dhl.account_numbers.V62WP'), $useEnvPriority),
'V53PAK' => $this->getConfigValue('dhl_account_v53pak', config('dhl.account_numbers.V53PAK'), $useEnvPriority),
'V07PAK' => $this->getConfigValue('dhl_account_v07pak', config('dhl.account_numbers.V07PAK'), $useEnvPriority),
'default' => config('dhl.account_numbers.default'),
],
// Dimensions
'dimensions' => [
'V01PAK' => config('dhl.dimensions.V01PAK'),
@ -111,6 +115,27 @@ class SettingController extends Controller
];
}
/**
* Get configuration value based on priority setting
*
* @param string $settingSlug The database setting slug
* @param mixed $configValue The config/env fallback value
* @param bool $useEnvPriority Whether to prioritize env over database
* @return mixed
*/
private function getConfigValue(string $settingSlug, $configValue, bool $useEnvPriority)
{
$dbValue = Setting::getContentBySlug($settingSlug);
if ($useEnvPriority) {
// ENV priority: Use config value if available, otherwise fall back to database
return $configValue ?: $dbValue;
} else {
// Database priority (default): Use database value if available, otherwise fall back to config
return $dbValue ?: $configValue;
}
}
/**
* Update DHL configuration cache after saving settings
*/
@ -125,7 +150,7 @@ class SettingController extends Controller
// You could add a connection test here if needed
\Log::info('DHL configuration updated successfully');
} catch (\Exception $e) {
\Log::error('DHL configuration update failed: ' . $e->getMessage());
\Log::error('DHL configuration update failed: '.$e->getMessage());
}
}
}

View file

@ -4,14 +4,13 @@ namespace App\Http\Controllers\User;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Repositories\AboRepository;
use App\Services\AboHelper;
use App\Services\AboItemHistoryService;
use App\Services\AboOrderCart;
use App\Services\Shop;
use App\Services\UserService;
use App\User;
use Request;
use Yard;
@ -41,7 +40,7 @@ class AboController extends Controller
return view('user.abo.index', [
'user_abos' => [],
'view' => 'me',
'isAdmin' => false
'isAdmin' => false,
]);
}
@ -55,7 +54,7 @@ class AboController extends Controller
return view('user.abo.index', [
'user_abos' => $user_abos,
'view' => 'ot',
'isAdmin' => false
'isAdmin' => false,
]);
}
@ -63,22 +62,19 @@ class AboController extends Controller
return view('user.abo.index', [
'user_abos' => [],
'view' => 'me',
'isAdmin' => false
'isAdmin' => false,
]);
}
public function detail($view, $id)
{
$data = Request::all();
$user_abo = UserAbo::findOrFail($id);
$this->checkPermissions($view, $user_abo);
//init Yard
// init Yard
AboOrderCart::initYard($user_abo);
//holt die aktuellen UserAccount Daten oder die Userdaten des Abo
// holt die aktuellen UserAccount Daten oder die Userdaten des Abo
$customer_detail = AboOrderCart::getCustomerDetail();
AboOrderCart::makeOrderYard($user_abo);
@ -94,113 +90,129 @@ class AboController extends Controller
'view' => $view,
'comp_products' => $comp_products,
];
return view('user.abo.detail', $data);
}
public function update($view, $id)
{
$data = Request::all();
$user_abo = UserAbo::findOrFail($id);
$this->checkPermissions($view, $user_abo);
$isAddOnlyMode = AboHelper::isAddOnlyMode($user_abo, $view);
if (isset($data['action'])) {
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::findOrFail($data['id']);
$this->aboRepository->setModel($user_abo);
$this->aboRepository->update($data);
return redirect(route('user_abos_detail', [$view, $id]));
}
if (Request::ajax()) {
$message = false;
//addProduct
// addProduct
if ($data['action'] === 'addProduct') {
if ($product = Product::find($data['product_id'])) {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('product_id', $product->id)->where('comp', 0)->first()) {
$qtyBefore = $UserAboItem->qty;
$UserAboItem->qty = $UserAboItem->qty + 1;
$UserAboItem->save();
AboItemHistoryService::logProductAdded($user_abo, $UserAboItem, $qtyBefore, $view);
} else {
UserAboItem::create([
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $product->id,
'comp' => 0,
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
}
//updateCart
// updateCart
if ($data['action'] === 'updateCart') {
//product_id | order_item_id | cart_order_id | qty
// product_id | order_item_id | cart_order_id | qty
if (isset($data['product_id']) && $product = Product::find($data['product_id'])) {
if (isset($data['order_item_id']) && $UserAboItem = UserAboItem::find($data['order_item_id'])) {
if (isset($data['qty'])) {
$qtyBefore = $UserAboItem->qty;
$qty = (int) $data['qty'];
$qty = $qty < 1 ? 1 : $qty;
$qty = $qty > 100 ? 100 : $qty;
if ($isAddOnlyMode && $qty < $UserAboItem->qty) {
$qty = $UserAboItem->qty;
}
$UserAboItem->qty = $qty;
$UserAboItem->save();
AboItemHistoryService::logQtyChanged($user_abo, $UserAboItem, $qtyBefore, $qty, $view);
}
}
}
}
//removeFromCart
// removeFromCart
if ($data['action'] === 'removeFromCart') {
if (!isset($data['product_id']) || !($product = Product::find($data['product_id']))) {
if ($isAddOnlyMode) {
return response()->json([
'response' => false,
'message' => __('abo.error_add_only_no_remove'),
], 403);
}
if (! isset($data['product_id']) || ! ($product = Product::find($data['product_id']))) {
$message = __('abo.product_not_found');
}
if (!isset($data['order_item_id']) || !($userAboItem = UserAboItem::find($data['order_item_id']))) {
if (! isset($data['order_item_id']) || ! ($userAboItem = UserAboItem::find($data['order_item_id']))) {
$message = __('abo.abo_item_not_found');
}
$has_basis_product = $this->check_need_basis_product($user_abo, $product, $data['order_item_id']);
if (!$has_basis_product) {
if (! $has_basis_product) {
$message = __('abo.need_basis_product');
}
if (!$message) {
if (! $message) {
AboItemHistoryService::logProductRemoved($user_abo, $userAboItem, $view);
$userAboItem->delete();
$user_abo->refresh(); // Abo neu laden um die aktualisierten Items zu erhalten
}
}
//updateCompProduct
// updateCompProduct
if ($data['action'] === 'updateCompProduct') {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('comp', $data['comp_num'])->first()) {
$oldProduct = $UserAboItem->product;
$UserAboItem->product_id = $data['comp_product_id'];
$UserAboItem->save();
$UserAboItem->load('product');
AboItemHistoryService::logCompProductChanged($user_abo, $UserAboItem, $oldProduct, $UserAboItem->product, $view);
} else {
UserAboItem::create([
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $data['comp_product_id'],
'comp' => $data['comp_num'],
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
AboOrderCart::initYard($user_abo);
AboOrderCart::makeOrderYard($user_abo); //reCalculateShippingPrice
AboOrderCart::checkNumOfCompProducts($user_abo); //after reCalculateShippingPrice check it and remove or add comp product
AboOrderCart::makeOrderYard($user_abo); // reCalculateShippingPrice
AboOrderCart::checkNumOfCompProducts($user_abo); // after reCalculateShippingPrice check it and remove or add comp product
if ($user_abo->is_for === 'me') {
$data['comp_products'] = Shop::getCompProducts('abo-me');
}
$error_message = $message ? $message : false;
$html_cart = view("admin.abo._order_abo_show", ['user_abo' => $user_abo, 'error_message' => $error_message])->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_cart = view('admin.abo._order_abo_show', ['user_abo' => $user_abo, 'error_message' => $error_message, 'add_only_mode' => $isAddOnlyMode])->render();
$html_comp = view('user.order.comp_product', $data)->render();
$amount = $user_abo->getFormattedAmount();
// $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
return response()->json(['response' => true, 'data' => $data, 'html_cart' => $html_cart, 'html_comp' => $html_comp, 'amount' => $amount]);
return response()->json(['response' => true, 'data' => $data, 'html_cart' => $html_cart, 'html_comp' => $html_comp, 'amount' => $amount]);
}
}
}
@ -212,11 +224,14 @@ class AboController extends Controller
return true;
}
// Prüfe ob noch ein anderes Basis-Produkt vorhanden ist
// Prüfe ob noch ein anderes Basis-Produkt vorhanden ist (nur reguläre Items, keine Comp-Produkte)
foreach ($user_abo->user_abo_items as $user_abo_item) {
if ($user_abo_item->id == $order_item_id) {
continue;
}
if ($user_abo_item->comp) {
continue;
}
if (AboHelper::getAboShowOn($user_abo_item->product) === 'base') {
return true;
}
@ -228,11 +243,11 @@ class AboController extends Controller
public function datatable($user_abo_id)
{
$user_abo = UserAbo::findOrFail($user_abo_id);
if (!$user_abo) {
if (! $user_abo) {
abort(404);
}
//$user_abo->is_for === 'me'
// $user_abo->is_for === 'me'
$show_on_ids = ['12', '13'];
$query = Product::select('products.*')
@ -250,45 +265,49 @@ class AboController extends Controller
[$show_on_ids[0], isset($show_on_ids[1]) ? $show_on_ids[1] : $show_on_ids[0]]
);
return \DataTables::eloquent($query)
->addColumn('add_card', function (Product $product) use ($user_abo) {
$ufactor = $user_abo->is_for === 'me' ? true : false;
$tax_free = $user_abo->is_for === 'me' ? true : Yard::instance('shopping')->getUserTaxFree();
return '<button type="button" class="btn btn-sm btn-md-extra btn-secondary add-product-basket" data-product-id="' . $product->id . '">
<strong>&euro; ' . $product->getFormattedPriceWith($tax_free, $ufactor, Yard::instance('shopping')->getUserCountry()) . '</strong>&nbsp; +<span class="ion ion-md-cart"></span>
$tax_free = $user_abo->is_for === 'me' ? true : Yard::instance('shopping')->getUserTaxFree();
$price = $product->getFormattedPriceWith($tax_free, $ufactor, Yard::instance('shopping')->getUserCountry());
return '<button type="button" class="btn btn-sm btn-md-extra btn-secondary add-product-basket" data-product-id="'.$product->id.'" data-product-name="'.e($product->getLang('name')).'" data-product-price="'.$price.' &euro;">
<strong>&euro; '.$price.'</strong>&nbsp; +<span class="ion ion-md-cart"></span>
</button>';
})
->addColumn('picture', function (Product $product) {
if (count($product->images)) {
return '<img class="img-fluid img-extra" alt="" src="' . route('product_image', [$product->images->first()->slug]) . '">';
return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
}
return "";
return '';
})
->addColumn('name', function (Product $product) use ($user_abo) {
return '<strong>' . $product->getLang('name') . '</strong><br>' . get_abo_type_badge_by_product($product);
->addColumn('name', function (Product $product) {
return '<strong>'.$product->getLang('name').'</strong><br>'.get_abo_type_badge_by_product($product);
})
->addColumn('points', function (Product $product) use ($user_abo) {
return '<span class="no-line-break">' . $product->getFormattedPoints() . '</span>';
->addColumn('points', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPoints().'</span>';
})
->addColumn('price_net', function (Product $product) use ($user_abo) {
$ufactor = $user_abo->is_for === 'me' ? true : false;
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, $ufactor, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, $ufactor, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_gross', function (Product $product) use ($user_abo) {
$ufactor = $user_abo->is_for === 'me' ? true : false;
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, $ufactor, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, $ufactor, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('action', function (Product $product) {
return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg"
data-toggle="modal" data-target="#modals-load-content" data-id="' . $product->id . '" data-route="' . route('modal_load') . '"
data-toggle="modal" data-target="#modals-load-content" data-id="'.$product->id.'" data-route="'.route('modal_load').'"
data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
})
->filterColumn('product', function ($query, $keyword) {
if ($keyword != "") {
$query->where('name', 'LIKE', '%' . $keyword . '%');
if ($keyword != '') {
$query->where('name', 'LIKE', '%'.$keyword.'%');
}
})
->orderColumn('name', 'name $1')
@ -304,20 +323,26 @@ class AboController extends Controller
->make(true);
}
private function checkPermissions($view, $user_abo)
{
\Log::info('checkPermissions', ['view' => $view, 'user_abo' => $user_abo]);
$user = \Auth::user();
// Admins dürfen alle Abos bearbeiten
if ($user && $user->isAdmin()) {
return;
}
if ($view === 'me' && $user_abo->is_for !== 'me') {
abort(403, 'Unauthorized action. Is not for me');
}
if ($view === 'ot' && $user_abo->is_for !== 'ot') {
abort(403, 'Unauthorized action. Is not your customer');
}
if ($view === 'me' && $user_abo->user_id !== \Auth::user()->id) {
if ($view === 'me' && $user_abo->user_id !== $user->id) {
abort(403, 'Unauthorized action. Is not my abo');
}
if ($view === 'ot' && $user_abo->member_id !== \Auth::user()->id) {
if ($view === 'ot' && $user_abo->member_id !== $user->id) {
abort(403, 'Unauthorized action. Is not my customer abo');
}
}

View file

@ -2,23 +2,22 @@
namespace App\Http\Controllers\User;
use Auth;
use Util;
use Yard;
use Carbon;
use Request;
use App\User;
use App\Http\Controllers\Controller;
use App\Mail\MailInfo;
use App\Models\Product;
use App\Services\Payment;
use App\Models\UserHistory;
use App\Models\ShoppingOrder;
use App\Services\UserService;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use App\Http\Controllers\Controller;
use App\Models\ShoppingOrder;
use App\Models\UserHistory;
use App\Services\Payment;
use App\Services\UserService;
use App\User;
use Auth;
use Carbon;
use Illuminate\Support\Facades\Mail;
use Request;
use Util;
use Yard;
class MembershipController extends Controller
{
@ -32,19 +31,18 @@ class MembershipController extends Controller
$this->middleware('auth');
}
public function index()
{
$user = User::find(Auth::user()->id);
$diff_months = 0;
if($user->payment_account){
$diff_months = Carbon::now()->diffInMonths(Carbon::parse($user->payment_account)) +1;
if ($user->payment_account) {
$diff_months = Carbon::now()->diffInMonths(Carbon::parse($user->payment_account)) + 1;
}
$userShoppingOrders = ShoppingOrder::with('shopping_user', 'shopping_payments')->select('shopping_orders.*')
->where('auth_user_id', '=', $user->id)
->where('txaction', '!=', NULL)
->where('txaction', '!=', null)
->whereIn('payment_for', [1, 2])
->orderBy('created_at', 'DESC')
->get();
@ -52,34 +50,33 @@ class MembershipController extends Controller
$userHistoryPaymentOrder = null;
$userHistoryUpgradeOrder = null;
/* Bezhalung ist nur 29 Tage vor ablauf möglich */
/* Bezhalung ist nur 29 Tage vor ablauf möglich */
/* isRenewalAccount payment_account date - config('mivita.renewal_days') Vertragsverlängerung */
if($user->isRenewalAccount()){
//Acount ist noch nicht verlängert / bezahlt
if ($user->isRenewalAccount()) {
// Acount ist noch nicht verlängert / bezahlt
if ($user->payment_account) {
//Die Order muss größer als das Datum sein.
$payment_greaterThan = Carbon::parse($user->payment_account)->modify('-'.(config('mivita.renewal_days')+1).' days');
// Die Order muss größer als das Datum sein.
$payment_greaterThan = Carbon::parse($user->payment_account)->modify('-'.(config('mivita.renewal_days') + 1).' days');
$userHistoryPaymentOrder = UserHistory::whereUserId($user->id)->whereAction('payment_order')->where('created_at', '>=', $payment_greaterThan)->get()->last();
}
}
if($user->isActiveAccount() && !$user->isActiveShop()){
$payment_greaterThan = Carbon::parse($user->payment_account)->modify('-'.(config('mivita.renewal_days')+1).' days');
if ($user->isActiveAccount() && ! $user->isActiveShop()) {
$payment_greaterThan = Carbon::parse($user->payment_account)->modify('-'.(config('mivita.renewal_days') + 1).' days');
$userHistoryUpgradeOrder = UserHistory::whereUserId($user->id)->whereAction('upgrade_order')->where('created_at', '>=', $payment_greaterThan)->get()->last();
}
$userHistoryDeleteMembership = UserHistory::whereUserId($user->id)->whereAction('delete_membership')->whereStatus(50)->get()->last();
$shipping_country_id = $this->checkShoppingCountry($user);
if(!$shipping_country_id){
if (! $shipping_country_id) {
abort(403, __('validation.custom.shipping_not_found'));
}
UserService::checkUserTaxShippingCountry($user, $shipping_country_id);
$data = [
'user' => $user,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'upgrade' => Product::where('active', true)->whereJsonContains('show_on', '8')->where('identifier', 'upgrade')->get(),
'diff_months' => $diff_months,
'userHistoryPaymentOrder' => $userHistoryPaymentOrder,
@ -88,86 +85,90 @@ class MembershipController extends Controller
'yard_info' => UserService::getYardInfo(),
'userShoppingOrders' => $userShoppingOrders,
];
return view('user.membership.index', $data);
}
private function checkShoppingCountry($user ){
private function checkShoppingCountry($user)
{
$country_id = null;
if($user->account->same_as_billing){
if ($user->account->same_as_billing) {
$country_id = $user->account->country_id;
}else{
} else {
$country_id = $user->account->shipping_country_id;
}
if($country_id){
if($shipping_country = ShippingCountry::whereCountryId($country_id)->first()){
if ($country_id) {
if ($shipping_country = ShippingCountry::whereCountryId($country_id)->first()) {
return $shipping_country->id;
}
}
return false;
}
public function storePayment($action){
public function storePayment($action)
{
$data = Request::all();
//#### remove_abo
if($action === "remove_abo"){
if(Request::get('abo_options_remove')){
// #### remove_abo
if ($action === 'remove_abo') {
if (Request::get('abo_options_remove')) {
$user = User::find(Auth::user()->id);
$user->abo_options = false;
$user->save();
$user->account->payment_data = null;
$user->account->save();
UserHistory::create(['user_id' => $user->id, 'action'=>'abo_options_remove', 'status'=>10]);
UserHistory::create(['user_id' => $user->id, 'action' => 'abo_options_remove', 'status' => 10]);
\Session()->flash('alert-success', __('msg.abo_deaktivert'));
return back();
}
\Session()->flash('alert-error', __('msg.error_checkbox_not_confirm'));
return back();
}
//#### payment order
//#### shop upgrade
if($action === "upgrade_order" || $action === "payment_order"){
if(Request::get('switchers-package-wizard')){
// #### payment order
// #### shop upgrade
if ($action === 'upgrade_order' || $action === 'payment_order') {
if (Request::get('switchers-package-wizard')) {
$user = User::find(Auth::user()->id);
Yard::instance('shopping')->destroy();
$product = Product::find(Request::get('switchers-package-wizard'));
$showAboOptions = false;
if(Request::get('abo_options')){
$showAboOptions = false; //true Abo Option deaktivert
$user->abo_options = false; //true Abo Option deaktivert
if (Request::get('abo_options')) {
$showAboOptions = false; // true Abo Option deaktivert
$user->abo_options = false; // true Abo Option deaktivert
$user->save();
}
$shipping_country_id = $this->checkShoppingCountry($user);
if(!$shipping_country_id){
if (! $shipping_country_id) {
abort(403, __('validation.custom.shipping_not_found'));
}
UserService::checkUserTaxShippingCountry($user, $shipping_country_id);
Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id);
if($product && $product->active){
$image = "";
if($product->images->count()){
if ($product && $product->active) {
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
$qty = Request::get('qty') ? Request::get('qty') : 1;
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), $qty, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
if(\App\Services\UserService::getTaxFree()){
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), $qty, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
}else{
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith(\App\Services\UserService::$user_country));
}
do {
$identifier = Util::getToken();
} while( ShoppingInstance::where('identifier', $identifier)->count() );
} while (ShoppingInstance::where('identifier', $identifier)->count());
$data = [];
$data['is_from'] = 'membership';
@ -176,9 +177,9 @@ class MembershipController extends Controller
ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => 1, //is first faker shop for nuy intern
'user_shop_id' => 1, // is first faker shop for nuy intern
'auth_user_id' => Auth::user()->id,
'payment' => 3, //Berater Membership
'payment' => 3, // Berater Membership
'subdomain' => url('/'),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
@ -187,54 +188,59 @@ class MembershipController extends Controller
]);
Yard::instance('shopping')->store($identifier);
//add to DB
$path = route('checkout.checkout_card', ['identifier'=>$identifier]);
UserHistory::create(['user_id' => $user->id, 'action'=>$action, 'status'=>1, 'product_id'=>$product->id, 'identifier'=>$identifier, 'abo_options'=>$showAboOptions]);
//$path = str_replace('http', 'https', $path);
// add to DB
$path = route('checkout.checkout_card', ['identifier' => $identifier]);
UserHistory::create(['user_id' => $user->id, 'action' => $action, 'status' => 1, 'product_id' => $product->id, 'identifier' => $identifier, 'abo_options' => $showAboOptions]);
// $path = str_replace('http', 'https', $path);
return redirect()->secure($path);
}
}
}
if($action === "change_order"){
if(Request::get('switchers-package-wizard')){
if ($action === 'change_order') {
if (Request::get('switchers-package-wizard')) {
$user = User::find(Auth::user()->id);
$product = Product::find(Request::get('switchers-package-wizard'));
if($user->payment_order_id == $product->id){
if ($user->payment_order_id == $product->id) {
\Session()->flash('alert-success', __('msg.no_change_made'));
return back();
}
if($product && $product->active){
if ($product && $product->active) {
$user->payment_order_id = $product->id;
$user->save();
UserHistory::create(['user_id' => $user->id, 'action'=>$action, 'status'=>10, 'product_id'=>$product->id]);
UserHistory::create(['user_id' => $user->id, 'action' => $action, 'status' => 10, 'product_id' => $product->id]);
\Session()->flash('alert-success', __('msg.booked_package_has_been_changed'));
return back();
}
}
}
if($action === "delete_membership"){
if(Request::get('delete_membership_mivita')){
//TODO
if ($action === 'delete_membership') {
if (Request::get('delete_membership_mivita')) {
// TODO
$user = User::find(Auth::user()->id);
if($user->isTestMode()){
if ($user->isTestMode()) {
$mail = config('app.info_test_mail');
}else{
} else {
$mail = config('app.info_mail');
}
Mail::to($mail)->send(new MailInfo($user, 'delete_membership'));
UserHistory::create(['user_id' => $user->id, 'action'=>$action, 'status'=>50]);
UserHistory::create(['user_id' => $user->id, 'action' => $action, 'status' => 50]);
\Session()->flash('alert-success', __('msg.cancel_membership_is_requested'));
return back();
}
\Session()->flash('alert-error', __('msg.error_checkbox_not_confirm'));
return back();
}
\Session()->flash('alert-error', __('msg.error_checkbox_not_confirm'));
return back();
}
}
}

View file

@ -11,15 +11,14 @@ use App\Models\ShoppingOrder;
use App\Models\ShoppingUser;
use App\Models\UserHistory;
use App\Services\AboHelper;
use App\Services\MyLog;
use App\Services\OrderPaymentService;
use App\Services\Payment;
use App\Services\Shop;
use App\Services\UserService;
use App\Services\Util;
use App\Services\MyLog;
use App\User;
use Auth;
use Illuminate\Http\Request as IlluminateRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Request;
@ -68,20 +67,20 @@ class OrderController extends Controller
$query = ShoppingOrder::with('shopping_user', 'shopping_payments')
->select('shopping_orders.*')
->where('auth_user_id', '=', $user->id)
->where('txaction', '!=', NULL);
->where('txaction', '!=', null);
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
return '<a href="' . route('user_order_detail', [$ShoppingOrder->id]) . '" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
return '<a href="'.route('user_order_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
@ -89,21 +88,22 @@ class OrderController extends Controller
->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
if ($ShoppingOrder->payment_for === 8) {
return '<button type="button" class="btn btn-xs btn-info btn-round" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $ShoppingOrder->id . '"
data-id="'.$ShoppingOrder->id.'"
data-action="shop-user-order-shipping-detail"
data-back=""
data-modal="modal-xl"
data-init_from="user"
data-route="' . route('modal_load') . '"><span class="fa fa-eye"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
}
return '<span class="badge badge-pill badge-' . $ShoppingOrder->getShippedColor() . '">' . $ShoppingOrder->getShippedType() . '</span>';
return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
})
->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
return Payment::getPaymentForBadge($ShoppingOrder);
})
->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']) . '" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="' . route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']) . '" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
})
->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('reference');
@ -130,16 +130,18 @@ class OrderController extends Controller
$shopping_user = Shop::checkShoppingUser($id, $user);
$delivery_id = $shopping_user->id;
if (!Shop::checkShoppingCountry($for, $delivery_id) && !\Session()->has('custom-error')) {
if (! Shop::checkShoppingCountry($for, $delivery_id) && ! \Session()->has('custom-error')) {
$country = Shop::getDeliveryCountry($for, $delivery_id);
\Session()->flash('custom-error', $country . ": " . __('validation.custom.shipping_not_found'));
\Session()->flash('custom-error', $country.': '.__('validation.custom.shipping_not_found'));
Log::channel(self::LOG_CHANNEL)->error("Shipping country not found for user #{$user->id}, country: {$country}");
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
if ($for === 'abo-ot-customer') {
if (AboHelper::hasAboByEmail($shopping_user->billing_email) && !\Session()->has('custom-error')) {
if (AboHelper::hasAboByEmail($shopping_user->billing_email) && ! \Session()->has('custom-error')) {
\Session()->flash('custom-error', __('abo.error_email_has_abo', ['email' => $shopping_user->billing_email]));
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
}
@ -150,6 +152,7 @@ class OrderController extends Controller
if (strpos(Request::get('switchers-radio-is-for'), 'ot') !== false) {
$delivery_id = $id;
}
return redirect(route('user_order_my_list', [Request::get('switchers-radio-is-for'), $delivery_id]));
}
@ -183,10 +186,11 @@ class OrderController extends Controller
UserService::initCustomerYard($shopping_user, $for);
} else {
$shipping_country_id = Shop::checkShoppingCountry($for, $id);
if (!$shipping_country_id) {
if (! $shipping_country_id) {
$country = Shop::getDeliveryCountry($for, $id);
\Session()->flash('custom-error', $country . ": " . __('validation.custom.shipping_not_found'));
\Session()->flash('custom-error', $country.': '.__('validation.custom.shipping_not_found'));
Log::channel(self::LOG_CHANNEL)->warning("Shipping country not found for user #{$user->id}, country: {$country}");
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
UserService::initUserYard($user, $shipping_country_id, $for);
@ -221,7 +225,6 @@ class OrderController extends Controller
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput(Request::all());
}
@ -229,23 +232,23 @@ class OrderController extends Controller
try {
$this->checkSendYardForPayment($data, $id);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Error checking yard for payment: " . $e->getMessage(), [
Log::channel(self::LOG_CHANNEL)->error('Error checking yard for payment: '.$e->getMessage(), [
'user_id' => $user->id,
'for' => $for,
'id' => $id
'id' => $id,
]);
return back()->with('error', $e->getMessage());
return back()->withErrors(['error' => $e->getMessage()])->withInput(Request::all());
}
if (Yard::instance('shopping')->getNumComp() > 0) {
if (!isset($data['switchers-comp-product'])) {
if (! isset($data['switchers-comp-product'])) {
$validator->errors()->add('switchers-comp-product', __('msg.please_select_compensation_product'));
} else if (!is_array($data['switchers-comp-product'])) {
} elseif (! is_array($data['switchers-comp-product'])) {
$validator->errors()->add('switchers-comp-product', __('msg.please_select_compensation_product'));
} else if (count($data['switchers-comp-product']) !== Yard::instance('shopping')->getNumComp()) {
} elseif (count($data['switchers-comp-product']) !== Yard::instance('shopping')->getNumComp()) {
$validator->errors()->add('switchers-comp-product', __('mdg.please_select_count_compensation_products', ['count' => Yard::instance('shopping')->getNumComp()]));
}
if ($validator->errors()->count()) {
return back()->withErrors($validator)->withInput(Request::all());
}
@ -268,7 +271,6 @@ class OrderController extends Controller
// Remove unnecessary data
unset($data['quantity']);
unset($data['_token']);
if ($for === 'ot-customer' || $for === 'abo-ot-customer') {
return $this->processCustomerPayment($user, $identifier, $data, $id, $for);
} else {
@ -281,13 +283,14 @@ class OrderController extends Controller
*/
private function processCustomerPayment($user, $identifier, $data, $id, $for)
{
$shopping_user = ShoppingUser::find($id);
$shopping_instance = ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => $user->shop->id,
'payment' => 6, // Berater Shop to Customer Shop
'subdomain' => $user->shop->getSubdomain(),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
'language' => $shopping_user->getLocale(), // hier wird die Sprache des Kunden verwendet
'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
'status' => 0,
'shopping_user_id' => $id,
@ -302,9 +305,9 @@ class OrderController extends Controller
try {
$this->customPaymentSendMail($user, $identifier, $yard_shopping_items, $data);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Failed to send custom payment email: " . $e->getMessage(), [
Log::channel(self::LOG_CHANNEL)->error('Failed to send custom payment email: '.$e->getMessage(), [
'identifier' => $identifier,
'user_id' => $user->id
'user_id' => $user->id,
]);
}
@ -314,7 +317,7 @@ class OrderController extends Controller
'status' => 1,
'product_id' => null,
'identifier' => $identifier,
'is_abo' => $data['is_abo']
'is_abo' => $data['is_abo'],
]);
return redirect(route('user_order_my_custom_payment', ['identifier' => $identifier]));
@ -333,7 +336,7 @@ class OrderController extends Controller
'payment' => 2, // Berater Shop
'subdomain' => url('/'),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
'language' => \App::getLocale(), // das ist richtig, hier wird die App-Locale verwendet da es vom user kommt
'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
'status' => 0,
'shopping_user_id' => $id,
@ -349,10 +352,11 @@ class OrderController extends Controller
'status' => 1,
'product_id' => null,
'identifier' => $identifier,
'is_abo' => $data['is_abo']
'is_abo' => $data['is_abo'],
]);
$path = route('checkout.checkout_card', ['identifier' => $identifier]);
return redirect()->secure($path);
}
@ -369,68 +373,68 @@ class OrderController extends Controller
}
$shipping_country_id = Shop::checkShoppingCountry($data['shipping_is_for'], $id);
if (!$shipping_country_id) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
if (! $shipping_country_id) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'no shipping_country_id found | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping country not found", $logData);
MyLog::writeLog('payment', 'error', 'no shipping_country_id found | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping country not found', $logData);
throw new \Exception(__('msg.shipping_country_was_not_found'));
}
// Must be the same shipping country
if ($shipping_country_id != Yard::instance('shopping')->getShippingCountryId()) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_country_id,
'actual' => Yard::instance('shopping')->getShippingCountryId()
'actual' => Yard::instance('shopping')->getShippingCountryId(),
];
MyLog::writeLog('payment', 'error', 'shipping_country_id is not the same from Yard | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping country mismatch", $logData);
MyLog::writeLog('payment', 'error', 'shipping_country_id is not the same from Yard | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping country mismatch', $logData);
throw new \Exception(__('msg.shipping_country_was_not_correctly'));
}
if ($data['shipping_is_for'] !== 'ot-customer') {
if (Yard::instance('shopping')->shipping_free) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'Yard can by not shipping_free | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Yard cannot be shipping free", $logData);
MyLog::writeLog('payment', 'error', 'Yard can by not shipping_free | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Yard cannot be shipping free', $logData);
throw new \Exception(__('msg.shopping_cart_was_shipping_free'));
}
}
if ($data['shipping_is_for'] === 'ot-customer') {
if (!$user->shop) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
if (! $user->shop) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'User has no Shop for an User to Customer order| Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("User has no shop for customer order", $logData);
MyLog::writeLog('payment', 'error', 'User has no Shop for an User to Customer order| Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('User has no shop for customer order', $logData);
throw new \Exception(__('msg.shopping_cart_was_not_user_shop'));
}
@ -438,107 +442,130 @@ class OrderController extends Controller
$shipping_price = Shop::getShippingPriceByShippingCountryId($shipping_country_id, Yard::instance('shopping')->weight());
// For other and has weight - check
// For other and has weight - check
if (strpos($data['shipping_is_for'], 'ot') !== false && $data['shipping_is_for'] !== 'ot-customer' && Yard::instance('shopping')->weight() > 0) {
if (!Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight()
];
// Prüfe ob Versandkostenfreiheit durch Freigrenze legitimiert ist
$shipping_free = Yard::instance('shopping')->getShippingFree();
$total = Yard::instance('shopping')->total(2, '.', '');
$isFreeDueToThreshold = $shipping_free && $total >= $shipping_free && Yard::instance('shopping')->weightByFreeShipping() == 0;
MyLog::writeLog('payment', 'error', 'Yard OT shipping_price is 0 | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price cannot be zero for order with weight", $logData);
if (! Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
// Nur Fehler werfen, wenn Versandpreis 0 NICHT durch Freigrenze legitimiert ist
if (! $isFreeDueToThreshold) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight(),
'total' => $total,
'shipping_free' => $shipping_free,
];
throw new \Exception(__('msg.shipping_cost_cannot_be_0'));
MyLog::writeLog('payment', 'error', 'Yard OT shipping_price is 0 | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping price cannot be zero for order with weight', $logData);
throw new \Exception(__('msg.shipping_cost_cannot_be_0'));
}
}
if (Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard OT shipping_price is not the same from shipping_price | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch", $logData);
MyLog::writeLog('payment', 'error', 'Yard OT shipping_price is not the same from shipping_price | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping price mismatch', $logData);
throw new \Exception(__('msg.shipping_costs_were_not_calculated_correctly'));
}
}
if (($data['shipping_is_for'] == 'me' || $data['shipping_is_for'] == 'abo-me') && Yard::instance('shopping')->weight() > 0) {
if (!Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight()
];
// Prüfe ob Versandkostenfreiheit durch Freigrenze legitimiert ist
$shipping_free = Yard::instance('shopping')->getShippingFree();
$total = Yard::instance('shopping')->total(2, '.', '');
$isFreeDueToThreshold = $shipping_free && $total >= $shipping_free && Yard::instance('shopping')->weightByFreeShipping() == 0;
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is 0 | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price cannot be zero for personal order with weight", $logData);
if (! Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
// Nur Fehler werfen, wenn Versandpreis 0 NICHT durch Freigrenze legitimiert ist
if (! $isFreeDueToThreshold) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight(),
'total' => $total,
'shipping_free' => $shipping_free,
];
throw new \Exception(__('msg.shipping_cost_cannot_be_0'));
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is 0 | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping price cannot be zero for personal order with weight', $logData);
throw new \Exception(__('msg.shipping_cost_cannot_be_0'));
}
}
if (Shop::isCompProducts($data['shipping_is_for'])) {
if (Yard::instance('shopping')->getShippingPrice() != $shipping_price->price_comp) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price_comp) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price_comp,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price with comp products | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch for personal order", $logData);
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price with comp products | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping price mismatch for personal order', $logData);
throw new \Exception(__('msg.shipping_costs_were_not_calculated_correctly'));
}
if (Yard::instance('shopping')->getNumComp() != $shipping_price->num_comp) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->num_comp,
'actual' => Yard::instance('shopping')->getNumComp()
'actual' => Yard::instance('shopping')->getNumComp(),
];
MyLog::writeLog('payment', 'error', 'Yard num_comp is not correct | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Compensation product count mismatch", $logData);
MyLog::writeLog('payment', 'error', 'Yard num_comp is not correct | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Compensation product count mismatch', $logData);
throw new \Exception(__('msg.compensation_products_cannot_be_0'));
}
} else {
if (Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-' . time() . mt_rand(1000000, 9999999);
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price without comp products | Yard identifier: ' . $identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch for personal order", $logData);
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price without comp products | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error('Shipping price mismatch for personal order', $logData);
throw new \Exception(__('msg.shipping_costs_were_not_calculated_correctly'));
}
@ -593,15 +620,16 @@ class OrderController extends Controller
$cartItem = Yard::instance('shopping')->getCartItemByProduct($product->id);
$qty = isset($cartItem->qty) ? $cartItem->qty : 0;
$rowId = isset($cartItem->rowId) ? $cartItem->rowId : '';
return '<strong>' . $product->getLang('name') . '</strong><br>
return '<strong>'.$product->getLang('name').'</strong><br>
<div class="no-line-break input-group-min-w">
<div class="input-group d-inline-flex w-auto">
<span class="input-group-prepend">
<button type="button" class="btn btn-secondary icon-btn md-btn-extra remove-product-basket" data-row-id="' . $rowId . '" data-product-id="' . $product->id . '">-</button>
<button type="button" class="btn btn-secondary icon-btn md-btn-extra remove-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">-</button>
</span>
<input type="text" class="form-control text-center input-extra table-input-event-onchange" name="product_qty_' . $product->id . '" data-row-id="' . $rowId . '" data-product-id="' . $product->id . '" value="' . $qty . '">
<input type="text" class="form-control text-center input-extra table-input-event-onchange" name="product_qty_'.$product->id.'" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'" value="'.$qty.'">
<span class="input-group-append">
<button type="button" class="btn btn-secondary icon-btn md-btn-extra add-product-basket" data-row-id="' . $rowId . '" data-product-id="' . $product->id . '">+</button>
<button type="button" class="btn btn-secondary icon-btn md-btn-extra add-product-basket" data-row-id="'.$rowId.'" data-product-id="'.$product->id.'">+</button>
</span>
</div>
</div>';
@ -611,39 +639,40 @@ class OrderController extends Controller
})
->addColumn('picture', function (Product $product) {
if (count($product->images)) {
return '<img class="img-fluid img-extra" alt="" src="' . route('product_image', [$product->images->first()->slug]) . '">';
return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
}
return "";
return '';
})
->addColumn('points', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPoints() . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPoints().'</span>';
})
->addColumn('price_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, true, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, true, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, true, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, true, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_vk_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('customer_price_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('customer_price_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('my_commission_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry(), true) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry(), true) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry(), true).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry(), true).'</span>';
})
->addColumn('action', function (Product $product) {
return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg"
data-toggle="modal" data-target="#modals-load-content" data-id="' . $product->id . '" data-route="' . route('modal_load') . '"
data-toggle="modal" data-target="#modals-load-content" data-id="'.$product->id.'" data-route="'.route('modal_load').'"
data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
})
->filterColumn('product', function ($query, $keyword) {
if ($keyword != "") {
$query->where('name', 'LIKE', '%' . $keyword . '%');
if ($keyword != '') {
$query->where('name', 'LIKE', '%'.$keyword.'%');
}
})
->orderColumn('name', 'name $1')
@ -668,8 +697,9 @@ class OrderController extends Controller
*/
public function performRequest()
{
if (!Request::ajax()) {
Log::channel(self::LOG_CHANNEL)->warning("Non-AJAX request to performRequest method");
if (! Request::ajax()) {
Log::channel(self::LOG_CHANNEL)->warning('Non-AJAX request to performRequest method');
return response()->json(['response' => false, 'message' => 'Only AJAX requests are allowed']);
}
@ -678,9 +708,9 @@ class OrderController extends Controller
$data['for'] = $is_for;
$data['comp_products'] = Shop::getCompProducts($is_for);
Log::channel(self::LOG_CHANNEL)->info("Performing cart action", [
Log::channel(self::LOG_CHANNEL)->info('Performing cart action', [
'action' => $data['action'] ?? 'unknown',
'is_for' => $is_for
'is_for' => $is_for,
]);
if ($data['action'] === 'updateCart' && isset($data['product_id'])) {
@ -689,6 +719,7 @@ class OrderController extends Controller
if ($data['action'] === 'clearCart') {
Yard::instance('shopping')->destroy();
return response()->json(['response' => true, 'data' => Yard::instance('shopping')->count(), 'html_card' => '', 'html_comp' => '']);
}
@ -700,7 +731,8 @@ class OrderController extends Controller
return $this->handleUpdateCompProduct($data, $is_for);
}
Log::channel(self::LOG_CHANNEL)->warning("Unknown action in performRequest", ['action' => $data['action'] ?? 'not set']);
Log::channel(self::LOG_CHANNEL)->warning('Unknown action in performRequest', ['action' => $data['action'] ?? 'not set']);
return response()->json(['response' => false, 'data' => $data]);
}
@ -710,12 +742,13 @@ class OrderController extends Controller
private function handleUpdateCart($data, $is_for)
{
$product = Product::find($data['product_id']);
if (!$product) {
Log::channel(self::LOG_CHANNEL)->warning("Product not found for cart update", ['product_id' => $data['product_id']]);
if (! $product) {
Log::channel(self::LOG_CHANNEL)->warning('Product not found for cart update', ['product_id' => $data['product_id']]);
return response()->json(['response' => false, 'message' => 'Product not found']);
}
$image = "";
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
@ -730,7 +763,7 @@ class OrderController extends Controller
round($product->getPriceWith(Yard::instance('shopping')->getUserTaxFree(), false, Yard::instance('shopping')->getUserCountry()), 1),
false,
false,
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
} else {
$cartItem = Yard::instance('shopping')
@ -741,7 +774,7 @@ class OrderController extends Controller
$product->getPriceWith(Yard::instance('shopping')->getUserTaxFree(), true, Yard::instance('shopping')->getUserCountry()),
false,
false,
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
}
@ -761,8 +794,8 @@ class OrderController extends Controller
Yard::instance('shopping')->reCalculateShippingPrice();
$this->checkCompProduct(Yard::instance('shopping')->getNumComp());
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -778,14 +811,14 @@ class OrderController extends Controller
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country->id, $is_for);
$this->checkCompProduct(Yard::instance('shopping')->getNumComp());
} else {
Log::channel(self::LOG_CHANNEL)->warning("Shipping country not found", [
'shipping_country_id' => $data['shipping_country_id']
Log::channel(self::LOG_CHANNEL)->warning('Shipping country not found', [
'shipping_country_id' => $data['shipping_country_id'],
]);
}
}
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -798,8 +831,8 @@ class OrderController extends Controller
$this->updateCompProduct($data);
Yard::instance('shopping')->reCalculateShippingPrice();
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -826,8 +859,8 @@ class OrderController extends Controller
foreach (Yard::instance('shopping')->content() as $row) {
// If count_comp_products is smaller, the product was removed due to quantity
// if comp_num equals the comp product, the product was removed due to new shipping costs
//count_comp_products wie viele comp products werden gebraucht
//comp_num welches comp product wird hinzugefügt
// count_comp_products wie viele comp products werden gebraucht
// comp_num welches comp product wird hinzugefügt
if ($row->options->comp && ($row->options->comp == intval($data['comp_num']) || $row->options->comp > intval($data['count_comp_products']))) {
Yard::instance('shopping')->remove($row->rowId);
}
@ -836,7 +869,7 @@ class OrderController extends Controller
if (isset($data['comp_product_id'])) {
$product = Product::find($data['comp_product_id']);
if ($product) {
$image = "";
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
@ -853,14 +886,14 @@ class OrderController extends Controller
'weight' => 0,
'points' => 0,
'comp' => intval($data['comp_num']),
'product_id' => $product->id
'product_id' => $product->id,
]
);
Yard::setTax($cartItem->rowId, 0);
} else {
Log::channel(self::LOG_CHANNEL)->warning("Compensation product not found", [
'comp_product_id' => $data['comp_product_id']
Log::channel(self::LOG_CHANNEL)->warning('Compensation product not found', [
'comp_product_id' => $data['comp_product_id'],
]);
}
}
@ -873,9 +906,10 @@ class OrderController extends Controller
{
try {
$data = OrderPaymentService::getCustomPayment($identifier);
return view('user.order.payment.custom_payment', $data);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Error accessing custom payment: " . $e->getMessage(), ['identifier' => $identifier]);
Log::channel(self::LOG_CHANNEL)->error('Error accessing custom payment: '.$e->getMessage(), ['identifier' => $identifier]);
abort(404, 'Custom payment not found');
}
}
@ -888,22 +922,22 @@ class OrderController extends Controller
$bcc = [];
$shopping_instance = ShoppingInstance::where('identifier', $identifier)->first();
if (!$shopping_instance) {
Log::channel(self::LOG_CHANNEL)->error("Shopping instance not found for email", ['identifier' => $identifier]);
if (! $shopping_instance) {
Log::channel(self::LOG_CHANNEL)->error('Shopping instance not found for email', ['identifier' => $identifier]);
throw new \Exception(__('msg.shopping_instance_not_found'));
}
$shopping_user = $data['shopping_user_id'] ? ShoppingUser::find($data['shopping_user_id']) : null;
if (!$shopping_user) {
Log::channel(self::LOG_CHANNEL)->error("Shopping user not found for email", ['shopping_user_id' => $data['shopping_user_id']]);
if (! $shopping_user) {
Log::channel(self::LOG_CHANNEL)->error('Shopping user not found for email', ['shopping_user_id' => $data['shopping_user_id']]);
throw new \Exception(__('msg.shopping_user_not_found'));
}
$route = route('checkout.checkout_card', ['identifier' => $identifier]);
$billing_email = $shopping_user->billing_email;
if (!$billing_email) {
if (! $billing_email) {
$billing_email = $data['mode'] === 'test' ? config('app.checkout_test_mail') : config('app.checkout_mail');
}

View file

@ -1,28 +1,28 @@
<?php
namespace App\Http\Controllers\User;
use Carbon;
use Request;
use App\User;
use App\Services\Credit;
use App\Models\UserCredit;
use App\Models\UserPayCredit;
use App\Models\UserCreditItem;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Services\Credit;
use App\User;
use Request;
class PaymentController extends Controller
{
private $startYear;
private $endYear;
private $rangeYears;
private $activeYear;
public function __construct()
{
$this->middleware('auth');
/* $this->startYear = 2021;
/* $this->startYear = 2021;
$this->endYear = date('Y');
$this->rangeYears = range($this->startYear, $this->endYear);
$this->activeYear = $this->endYear;*/
@ -34,11 +34,12 @@ class PaymentController extends Controller
$data = [
'user' => $user,
];
return view('user.payment.credit', $data);
}
public function credit_datatable(){
public function credit_datatable()
{
$user = \Auth::user();
$query = UserCredit::with('user', 'user.account')->select('user_credits.*')->where('user_id', $user->id);
@ -46,29 +47,35 @@ class PaymentController extends Controller
return \DataTables::eloquent($query)
->addColumn('view', function (UserCredit $UserCredit) {
$ret = "";
if(Credit::isCredit($UserCredit)){
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a><br>';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'html']).'" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']).'" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
}else{
$ret = "-";
$ret = '';
if (Credit::isCredit($UserCredit)) {
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download']).'" class="btn btn-primary btn-xs mb-2 mr-1"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream']).'" target="_blank" class="btn btn-warning btn-xs mb-2 mr-1"><i class="fa fa-eye"></i></a>';
$availableLocales = $UserCredit->getAvailableLocales();
foreach ($availableLocales as $locale) {
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download', $locale]).'" class="btn btn-outline-primary btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-download"></i> '.strtoupper($locale).'</a>';
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream', $locale]).'" class="btn btn-outline-warning btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-eye"></i> '.strtoupper($locale).'</a>';
}
$ret .= '<br>';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'html']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1 "><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
} else {
$ret = '-';
}
return $ret;
})
->addColumn('total', function (UserCredit $UserCredit) {
return $UserCredit->getFormattedTotal()."";
return $UserCredit->getFormattedTotal().' €';
})
->addColumn('credits', function (UserCredit $UserCredit) {
$ret = "";
if($UserCredit->user_credit_items){
foreach($UserCredit->user_credit_items as $user_credit_item){
$ret .= nl2br($user_credit_item->getTransMessage())." / ".$user_credit_item->created_at->format('d.m.Y')."<br>";
$ret = '';
if ($UserCredit->user_credit_items) {
foreach ($UserCredit->user_credit_items as $user_credit_item) {
$ret .= nl2br($user_credit_item->getTransMessage()).' / '.$user_credit_item->created_at->format('d.m.Y').'<br>';
}
}
return $ret;
})
->addColumn('status', function (UserCredit $UserCredit) {
@ -81,18 +88,19 @@ class PaymentController extends Controller
->make(true);
}
public function credit_item_datatable(){
public function credit_item_datatable()
{
$user = \Auth::user();
$query = UserCreditItem::select('user_credit_items.*')->where('user_id', $user->id);
return \DataTables::eloquent($query)
->addColumn('message', function (UserCreditItem $user_credit_item) {
return nl2br($user_credit_item->getTransMessage());
})
->addColumn('credit', function (UserCreditItem $user_credit_item) {
return formatNumber($user_credit_item->credit)."";
return formatNumber($user_credit_item->credit).' €';
})
->addColumn('created_at', function (UserCreditItem $user_credit_item) {
return formatDate($user_credit_item->created_at);
@ -101,11 +109,11 @@ class PaymentController extends Controller
return '<span class="badge badge-pill badge-'.$user_credit_item->getStatusColor().'">'.$user_credit_item->getStatusType().'</span> ';
})
->addColumn('paid', function (UserCreditItem $user_credit_item) {
return ($user_credit_item->paid && $user_credit_item->user_credit) ?
'<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> '.$user_credit_item->user_credit->full_number.'</span>'
return ($user_credit_item->paid && $user_credit_item->user_credit) ?
'<span class="badge badge-pill badge-success"><i class="fa fa-check"></i> '.$user_credit_item->user_credit->full_number.'</span>'
: '<span class="badge badge-pill badge-warning"><i class="fa fa-times"></i></span>';
})
->orderColumn('message', 'message $1')
->orderColumn('credit', 'credit $1')
->orderColumn('created_at', 'created_at $1')
@ -114,13 +122,12 @@ class PaymentController extends Controller
->make(true);
}
/*private function setActiveYears(){
if(Request::get('filter_year')){
$this->activeYear = Request::get('filter_year');
}
}
public function revenue()
{
$this->setActiveYears();
@ -134,4 +141,4 @@ class PaymentController extends Controller
];
return view('user.payment.revenue', $data);
}*/
}
}

View file

@ -1,13 +1,12 @@
<?php
namespace App\Http\Controllers\User;
use App\Exports\UserTeamExport;
use App\Http\Controllers\Controller;
use App\Models\UserBusiness;
use App\Models\UserLevel;
use App\Models\UserSalesVolume;
use App\Services\AboHelper;
use App\Services\BusinessPlan\ExportBot;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
@ -17,16 +16,12 @@ use App\Services\LevelReportService;
use App\Services\NextLevelBadgeHelper;
use App\Services\TranslationHelper;
use App\User;
use Auth;
use Carbon\Carbon;
use function Ramsey\Uuid\v1;
use Maatwebsite\Excel\Facades\Excel;
use Request;
/**
* Team Controller für User-Bereich
*
*
* Erweitert um optimierte Versionen:
* - show(): Optimierte Team-Übersicht mit Performance-Monitoring
* - structure(): Nutzt TreeCalcBotOptimized für bessere Performance
@ -36,9 +31,13 @@ use Request;
class TeamController extends Controller
{
private $filter_active = [1 => '', 2 => '', 3 => '']; // Wird in getFilterActive() übersetzt
private $filter_next_level = [0 => '', 1 => '', 2 => '', 3 => '']; // Wird in getFilterNextLevel() übersetzt
private $month;
private $year;
private $forceLiveCalculation;
public function __construct()
@ -46,8 +45,6 @@ class TeamController extends Controller
$this->middleware('active.account');
}
/**
* Zeigt die Team-Übersicht mit optimierter TreeCalcBotOptimized-Datenverarbeitung
* Lädt Team-Daten für DataTable-Anzeige
@ -67,19 +64,19 @@ class TeamController extends Controller
$forceLiveCalculation = Request::get('force_live_calculation', false) || Request::get('live', false);
$forceLiveCalculation = false;
\Log::info("TeamController: Building optimized team overview for user {$user->id} ({$this->month}/{$this->year})" .
($forceLiveCalculation === true ? " with forced live calculation" : "not live calculation"));
\Log::info("TeamController: Building optimized team overview for user {$user->id} ({$this->month}/{$this->year})".
($forceLiveCalculation === true ? ' with forced live calculation' : 'not live calculation'));
// Verwende TreeCalcBotOptimized für bessere Performance
//$TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
//$TreeCalcBot->initStructureUser($user->id);
// $TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
// $TreeCalcBot->initStructureUser($user->id);
$endTime = microtime(true);
$endMemory = memory_get_usage();
$executionTime = round(($endTime - $startTime) * 1000, 2);
$memoryUsed = $this->formatBytes($endMemory - $startMemory);
$calculationType = $forceLiveCalculation ? " (LIVE)" : " (CACHE)";
$calculationType = $forceLiveCalculation ? ' (LIVE)' : ' (CACHE)';
\Log::info("TeamController: Optimized team overview built in {$executionTime}ms, Memory: {$memoryUsed}{$calculationType}");
$data = [
@ -88,21 +85,22 @@ class TeamController extends Controller
'filter_active' => $this->getFilterActive(),
'filter_levels' => $this->getFilterLevels(),
'filter_next_level' => $this->getFilterNextLevel(),
//'TreeCalcBot' => $TreeCalcBot,
// 'TreeCalcBot' => $TreeCalcBot,
'performance' => [
'execution_time' => $executionTime,
'memory_used' => $memoryUsed,
'user_id' => $user->id,
'user_count' => 0, //$TreeCalcBot->getTotalUserCount(),
'user_count' => 0, // $TreeCalcBot->getTotalUserCount(),
'version' => 'Optimized',
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache'
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache',
],
'optimized' => true,
'forceLiveCalculation' => $forceLiveCalculation,
];
return view('user.team.show', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error in optimized show for user {$user->id}: " . $e->getMessage());
\Log::error("TeamController: Error in optimized show for user {$user->id}: ".$e->getMessage());
// Fallback mit minimalen Daten
$endTime = microtime(true);
@ -114,12 +112,12 @@ class TeamController extends Controller
'filter_active' => $this->getFilterActive(),
'filter_levels' => $this->getFilterLevels(),
'filter_next_level' => $this->getFilterNextLevel(),
'error' => __('team.error_loading_optimized_overview') . $e->getMessage(),
'error' => __('team.error_loading_optimized_overview').$e->getMessage(),
'performance' => [
'execution_time' => $executionTime,
'memory_used' => 'N/A',
'version' => 'Fallback',
'calculation_type' => 'Error'
'calculation_type' => 'Error',
],
'optimized' => false,
];
@ -175,8 +173,8 @@ class TeamController extends Controller
$executionTime = round(($endTime - $startTime) * 1000, 2);
$memoryUsed = $this->formatBytes($endMemory - $startMemory);
$versionInfo = ($optimizedUsed ? "OPTIMIZED" : "STANDARD") .
($forceLiveCalculation ? " + LIVE" : " + CACHE");
$versionInfo = ($optimizedUsed ? 'OPTIMIZED' : 'STANDARD').
($forceLiveCalculation ? ' + LIVE' : ' + CACHE');
\Log::info("TeamController: Structure built for user {$user->id} in {$executionTime}ms, Memory: {$memoryUsed} ({$versionInfo})");
@ -191,7 +189,7 @@ class TeamController extends Controller
? $TreeCalcBot->getTotalUserCount()
: '-',
'version' => $optimizedUsed ? 'Optimized' : 'Standard',
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache'
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache',
],
'optimized' => $optimizedUsed,
'forceLiveCalculation' => $forceLiveCalculation,
@ -199,7 +197,7 @@ class TeamController extends Controller
return view('user.team.structure', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error in structure for user {$user->id}: " . $e->getMessage());
\Log::error("TeamController: Error in structure for user {$user->id}: ".$e->getMessage());
// Fallback zur Standard-Implementierung
$TreeCalcBot = new TreeCalcBot(session('team_user_filter_month'), session('team_user_filter_year'), 'member');
@ -212,13 +210,13 @@ class TeamController extends Controller
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2022),
'TreeCalcBot' => $TreeCalcBot,
'error' => 'Fehler aufgetreten, Standard-Version wird verwendet: ' . $e->getMessage(),
'error' => 'Fehler aufgetreten, Standard-Version wird verwendet: '.$e->getMessage(),
'performance' => [
'execution_time' => $executionTime,
'memory_used' => 'N/A',
'user_count' => '-',
'version' => 'Fallback',
'calculation_type' => $forceLiveCalculation ? __('team.live_not_supported_fallback') : __('team.cache')
'calculation_type' => $forceLiveCalculation ? __('team.live_not_supported_fallback') : __('team.cache'),
],
'optimized' => false,
'forceLiveCalculation' => $forceLiveCalculation,
@ -227,6 +225,7 @@ class TeamController extends Controller
return view('user.team.structure', $data);
}
}
public function structureOld()
{
abort(403, 'This page is removed');
@ -237,17 +236,17 @@ class TeamController extends Controller
$this->setFilterVars();
$TreeCalcBot = new TreeCalcBot(session('team_user_filter_month'), session('team_user_filter_year'), 'member');
$TreeCalcBot->initStructureUser($user->id);
//for testing
//$TreeCalcBot->initUser(56);
// for testing
// $TreeCalcBot->initUser(56);
$data = [
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2022),
'TreeCalcBot' => $TreeCalcBot,
];
return view('user.team.structure', $data);
}
/**
* Optimierte DataTable für Team-Übersicht mit TreeCalcBotOptimized-Daten
* Nutzt bereits berechnete Business-Daten für bessere Performance
@ -265,8 +264,8 @@ class TeamController extends Controller
// Prüfe ob Live-Berechnung erzwungen werden soll
$forceLiveCalculation = Request::get('force_live_calculation', false) || Request::get('live', false);
$forceLiveCalculation = false;
\Log::info("TeamController: Building optimized datatable for user {$user->id} ({$this->month}/{$this->year})" .
($forceLiveCalculation == true ? " with forced live calculation" : ""));
\Log::info("TeamController: Building optimized datatable for user {$user->id} ({$this->month}/{$this->year})".
($forceLiveCalculation == true ? ' with forced live calculation' : ''));
// Lade TreeCalcBotOptimized-Daten
$TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
@ -277,30 +276,36 @@ class TeamController extends Controller
// KRITISCH: Bereinige die Objekte für DataTables (entferne zirkuläre Referenzen)
$teamUsers = collect($this->cleanBusinessUserItemsForDataTable($teamUsersRaw));
\Log::info("TeamController: TeamUsers cleaned for DataTable: " . $teamUsers->count());
\Log::info('TeamController: TeamUsers cleaned for DataTable: '.$teamUsers->count());
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
$this->forceLiveCalculation = $forceLiveCalculation;
\Log::info("TeamController: Optimized datatable data prepared in {$executionTime}ms for " . $teamUsers->count() . " users");
\Log::info("TeamController: Optimized datatable data prepared in {$executionTime}ms for ".$teamUsers->count().' users');
return \DataTables::of($teamUsers)
->addColumn('id', function ($teamUser) {
return '<button type="button" class="btn icon-btn btn-xs btn-secondary" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $teamUser->user_id . '"
data-id="'.$teamUser->user_id.'"
data-action="business-user-detail"
data-back=""
data-modal="modal-xl"
data-init_from="member"
data-live="' . $this->forceLiveCalculation . '"
data-live="'.$this->forceLiveCalculation.'"
data-optimized="1"
data-route="' . route('modal_load') . '"><span class="fa fa-calculator"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-calculator"></span></button>';
})
->addColumn('m_account', function ($teamUser) {
return $teamUser->m_account;
})
->addColumn('email', function ($teamUser) {
return e($teamUser->email);
$button = '<a href="#" class="text-black" data-toggle="modal" data-target="#modals-load-content" '.
'data-id="'.$teamUser->user_id.'" data-action="business-user-show" data-back="" '.
'data-modal="modal-md" data-init_from="member" data-route="'.route('modal_load').'">'.
'<span class="mr-1 ion ion-ios-contact"></span> '.
'</a>';
return $button.e($teamUser->email);
})
->addColumn('first_name', function ($teamUser) {
return e($teamUser->first_name);
@ -313,6 +318,7 @@ class TeamController extends Controller
})
->addColumn('is_qual_kp', function ($teamUser) {
$user = User::find($teamUser->user_id);
return TreeHelperOptimized::generateQualKPBadgeForUser($user, $this->month, $this->year);
})
->addColumn('sales_volume_KP_points', function ($teamUser) {
@ -331,18 +337,19 @@ class TeamController extends Controller
if ($userBusiness) {
return NextLevelBadgeHelper::generateBadgeFromUserBusiness($userBusiness);
}
return NextLevelBadgeHelper::renderNoDataBadge();
})
->addColumn('active_account', function ($teamUser) {
return get_active_badge($teamUser->active_account);
})
->addColumn('payment_account_date', function ($teamUser) {
return $teamUser->active_date ? formatDate($teamUser->active_date) : "-";
return $teamUser->active_date ? formatDate($teamUser->active_date) : '-';
})
->rawColumns(['id', 'next_level_qualified', 'active_account', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total'])
->rawColumns(['id', 'email', 'next_level_qualified', 'active_account', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total'])
->make(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error in optimized datatable: " . $e->getMessage());
\Log::error('TeamController: Error in optimized datatable: '.$e->getMessage());
// Fallback zur Standard-DataTable
return $this->datatable();
@ -361,12 +368,12 @@ class TeamController extends Controller
return \DataTables::eloquent($query)
->addColumn('id', function (User $teamUser) {
return '<button type="button" class="btn icon-btn btn-xs btn-secondary" data-toggle="modal" data-target="#modals-load-content"
data-id="' . $teamUser->id . '"
data-id="'.$teamUser->id.'"
data-action="team-user-detail"
data-back=""
data-modal="modal-xl"
data-init_from="member"
data-route="' . route('modal_load') . '"><span class="fa fa-eye"></span></button>';
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
})
->addColumn('m_account', function (User $teamUser) {
return $teamUser->account ? e($teamUser->account->m_account) : '';
@ -375,7 +382,7 @@ class TeamController extends Controller
return $teamUser->user_level ? e($teamUser->user_level->getLang('name')) : '';
})
->addColumn('is_qual_kp', function (User $teamUser) {
if (!$teamUser->user_level) {
if (! $teamUser->user_level) {
return '-';
}
$qualKP = (int) $teamUser->user_level->qual_kp;
@ -384,7 +391,8 @@ class TeamController extends Controller
$pointsSum = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_KP_sum');
$isQual = $pointsSum >= $qualKP;
$badgeClass = $isQual ? 'badge-outline-success' : 'badge-outline-warning-dark';
return '<span class="badge ' . $badgeClass . '"> KU ' . $qualKP . '</span>';
return '<span class="badge '.$badgeClass.'"> KU '.$qualKP.'</span>';
})
->addColumn('sales_volume_KP_points', function (User $teamUser) {
$month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
@ -392,8 +400,9 @@ class TeamController extends Controller
$total = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_KP_sum');
$individual = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_KP_points');
$shop = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_shop');
return '<div class="no-line-break">' . $total . '</div>' .
'<span class="small no-line-break">E: ' . $individual . ' | S: ' . $shop . '</span>';
return '<div class="no-line-break">'.$total.'</div>'.
'<span class="small no-line-break">E: '.$individual.' | S: '.$shop.'</span>';
})
->addColumn('sales_volume_total', function (User $teamUser) {
$month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
@ -401,8 +410,9 @@ class TeamController extends Controller
$total = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total_sum');
$individual = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total');
$shop = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total_shop');
return '<div class="no-line-break">' . formatNumber($total) . ' &euro;</div>' .
'<span class="small no-line-break">E: ' . formatNumber($individual) . ' | S: ' . formatNumber($shop) . ' &euro;</span>';
return '<div class="no-line-break">'.formatNumber($total).' &euro;</div>'.
'<span class="small no-line-break">E: '.formatNumber($individual).' | S: '.formatNumber($shop).' &euro;</span>';
})
->addColumn('email', function (User $teamUser) {
return e($teamUser->email);
@ -414,24 +424,25 @@ class TeamController extends Controller
return $teamUser->account ? e($teamUser->account->last_name) : '';
})
->addColumn('sponsor', function (User $teamUser) {
if (!$teamUser->user_sponsor) {
if (! $teamUser->user_sponsor) {
return '-';
}
$sponsor = $teamUser->user_sponsor;
$html = '';
if ($sponsor->account) {
$html .= e($sponsor->account->first_name . ' ' . $sponsor->account->last_name);
$html .= '<br><span class="small no-line-break">' . e($sponsor->email);
$html .= ' | ' . e($sponsor->account->m_account);
$html .= e($sponsor->account->first_name.' '.$sponsor->account->last_name);
$html .= '<br><span class="small no-line-break">'.e($sponsor->email);
$html .= ' | '.e($sponsor->account->m_account);
$html .= '</span>';
}
return $html;
})
->addColumn('active_account', function (User $teamUser) {
return get_active_badge($teamUser->isActiveAccount());
})
->addColumn('payment_account_date', function (User $teamUser) {
return $teamUser->payment_account ? $teamUser->getPaymentAccountDateFormat(false) : "-";
return $teamUser->payment_account ? $teamUser->getPaymentAccountDateFormat(false) : '-';
})
->addColumn('next_level_qualified', function (User $teamUser) {
// Verwende bereits berechnete UserBusiness-Daten für bessere Performance
@ -450,29 +461,29 @@ class TeamController extends Controller
return NextLevelBadgeHelper::renderNoDataBadge();
})
->filterColumn('m_account', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('m_account', 'LIKE', '%' . $keyword . '%');
$q->where('m_account', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('first_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('first_name', 'LIKE', '%' . $keyword . '%');
$q->where('first_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('last_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('last_name', 'LIKE', '%' . $keyword . '%');
$q->where('last_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('email', function ($query, $keyword) {
if ($keyword != "") {
$query->where('email', 'LIKE', '%' . $keyword . '%');
if ($keyword != '') {
$query->where('email', 'LIKE', '%'.$keyword.'%');
}
})
->orderColumn('id', 'users.id $1')
@ -484,10 +495,10 @@ class TeamController extends Controller
->rawColumns(['id', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total', 'sponsor', 'active_account', 'next_level_qualified'])
->make(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error in userDatatable: " . $e->getMessage());
\Log::error('TeamController: Error in userDatatable: '.$e->getMessage());
return response()->json([
'error' => 'Team-Datatable konnte nicht geladen werden: ' . $e->getMessage()
'error' => 'Team-Datatable konnte nicht geladen werden: '.$e->getMessage(),
], 500);
}
}
@ -510,7 +521,7 @@ class TeamController extends Controller
$onlyNotUpdated = Request::boolean('not_updated', false);
// Prüfe ob Live-Berechnung erzwungen werden soll
$forceLiveCalculation = false; //Request::get('force_live_calculation', false) || Request::get('live', false);
$forceLiveCalculation = false; // Request::get('force_live_calculation', false) || Request::get('live', false);
\Log::info("TeamController: Building level reports for user {$user->id} ({$month}/{$year})");
@ -519,7 +530,7 @@ class TeamController extends Controller
$treeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
// Lade Level-Reports für Team
$levelReportService = new LevelReportService();
$levelReportService = new LevelReportService;
$filters = ['only_not_updated' => $onlyNotUpdated];
$promotions = $levelReportService->getTeamLevelPromotions($treeCalcBot, $month, $year, $filters);
$statistics = $levelReportService->getStatistics($promotions);
@ -527,7 +538,7 @@ class TeamController extends Controller
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
\Log::info("TeamController: Level reports loaded for user {$user->id} in {$executionTime}ms - " . $promotions->count() . " promotions found");
\Log::info("TeamController: Level reports loaded for user {$user->id} in {$executionTime}ms - ".$promotions->count().' promotions found');
$availableYears = range(date('Y'), date('Y') - 5);
$availableMonths = [
@ -542,7 +553,7 @@ class TeamController extends Controller
9 => __('cal.months.September'),
10 => __('cal.months.October'),
11 => __('cal.months.November'),
12 => __('cal.months.December')
12 => __('cal.months.December'),
];
$data = [
@ -551,22 +562,22 @@ class TeamController extends Controller
'filters' => [
'month' => $month,
'year' => $year,
'only_not_updated' => $onlyNotUpdated
'only_not_updated' => $onlyNotUpdated,
],
'availableYears' => $availableYears,
'availableMonths' => $availableMonths,
'performance' => [
'execution_time' => $executionTime,
'user_id' => $user->id
]
'user_id' => $user->id,
],
];
return view('user.team.level-reports', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error loading level reports: " . $e->getMessage());
\Log::error('TeamController: Error loading level reports: '.$e->getMessage());
return view('user.team.level-reports', [
'error' => 'Fehler beim Laden der Level-Reports: ' . $e->getMessage(),
'error' => 'Fehler beim Laden der Level-Reports: '.$e->getMessage(),
'promotions' => collect([]),
'statistics' => ['total_count' => 0, 'level_stats' => [], 'period_stats' => []],
'filters' => ['month' => date('m'), 'year' => date('Y'), 'only_not_updated' => false],
@ -583,8 +594,8 @@ class TeamController extends Controller
9 => __('cal.months.September'),
10 => __('cal.months.October'),
11 => __('cal.months.November'),
12 => __('cal.months.December')
]
12 => __('cal.months.December'),
],
]);
}
}
@ -608,7 +619,7 @@ class TeamController extends Controller
$treeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
// Lade Level-Reports
$levelReportService = new LevelReportService();
$levelReportService = new LevelReportService;
$filters = ['only_not_updated' => $onlyNotUpdated];
$promotions = $levelReportService->getTeamLevelPromotions($treeCalcBot, $month, $year, $filters);
@ -617,13 +628,14 @@ class TeamController extends Controller
}
// CSV erstellen
$filename = 'team_level_promotions_' . date('Y-m-d_H-i-s') . '.csv';
$filename = 'team_level_promotions_'.date('Y-m-d_H-i-s').'.csv';
$filepath = $levelReportService->exportToCsv($promotions, $filename);
return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error exporting level reports: " . $e->getMessage());
return redirect()->back()->with('error', 'Fehler beim Export: ' . $e->getMessage());
\Log::error('TeamController: Error exporting level reports: '.$e->getMessage());
return redirect()->back()->with('error', 'Fehler beim Export: '.$e->getMessage());
}
}
@ -654,19 +666,19 @@ class TeamController extends Controller
'currentUser' => $user,
'currentLevel' => $currentLevel,
'performance' => [
'execution_time' => $executionTime
]
'execution_time' => $executionTime,
],
];
return view('user.team.marketingplan', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error loading marketingplan: " . $e->getMessage());
\Log::error('TeamController: Error loading marketingplan: '.$e->getMessage());
return view('user.team.marketingplan', [
'error' => __('marketingplan.loading_error') . ' ' . $e->getMessage(),
'error' => __('marketingplan.loading_error').' '.$e->getMessage(),
'userLevels' => collect(),
'currentUser' => null,
'currentLevel' => null
'currentLevel' => null,
]);
}
}
@ -678,14 +690,15 @@ class TeamController extends Controller
{
$user = User::find(\Auth::user()->id);
if ($user->isActiveShop() && $user->shop) {
$shop_register_link = $user->shop->getSubdomain(false) . "/reg";
$shop_register_link = $user->shop->getSubdomain(false).'/reg';
} else {
$member_id = 'm' . ($user->id + config('mivita.add_number_id'));
$shop_register_link = config('app.protocol') . config('app.domain') . config('app.tld_care') . '/reg/' . $member_id;
$member_id = 'm'.($user->id + config('mivita.add_number_id'));
$shop_register_link = config('app.protocol').config('app.domain').config('app.tld_care').'/reg/'.$member_id;
}
$data = [
'shop_register_link' => $shop_register_link
'shop_register_link' => $shop_register_link,
];
return view('user.team.members', $data);
}
@ -697,24 +710,8 @@ class TeamController extends Controller
$user = User::find(\Auth::user()->id);
$this->setFilterVars();
// Nutze TreeCalcBotOptimized um das Team zu bekommen
$month = session('team_user_filter_month');
$year = session('team_user_filter_year');
// Lade Team-Struktur
$TreeCalcBot = new TreeCalcBotOptimized($month, $year, 'member', false);
$TreeCalcBot->initStructureUser($user->id, false);
// Hole flache Liste aller Team-Mitglieder
$teamUsersRaw = $this->getTeamUsersFromStructure($TreeCalcBot);
// Sammle User-IDs für Abo-Abfrage
$teamUserIds = [];
foreach ($teamUsersRaw as $teamUser) {
if ($teamUser->user_id && $teamUser->user_id != $user->id) {
$teamUserIds[] = $teamUser->user_id;
}
}
// Hole Team-Mitglieder-IDs effizient via Sponsor-Hierarchie
$teamUserIds = AboHelper::getTeamUserIds($user->id);
// Hole Abos der Team-Mitglieder
$abos = \App\Models\UserAbo::whereIn('user_id', $teamUserIds)
@ -740,24 +737,8 @@ class TeamController extends Controller
$user = User::find(\Auth::user()->id);
$user_abo = \App\Models\UserAbo::findOrFail($id);
// Prüfe ob das Abo zu einem Team-Mitglied gehört
$this->setFilterVars();
$month = session('team_user_filter_month');
$year = session('team_user_filter_year');
$TreeCalcBot = new TreeCalcBotOptimized($month, $year, 'member', false);
$TreeCalcBot->initStructureUser($user->id, false);
$teamUsersRaw = $this->getTeamUsersFromStructure($TreeCalcBot);
$teamUserIds = [];
foreach ($teamUsersRaw as $teamUser) {
if ($teamUser->user_id) {
$teamUserIds[] = $teamUser->user_id;
}
}
// Prüfe Berechtigung
if (!in_array($user_abo->user_id, $teamUserIds)) {
// Prüfe ob das Abo zu einem Team-Mitglied gehört (effizient via Sponsor-Kette)
if (! AboHelper::isUserInTeam($user->id, $user_abo->user_id)) {
abort(403, 'Unauthorized action. This subscription does not belong to your team.');
}
@ -819,6 +800,7 @@ class TeamController extends Controller
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2022),
];
return view('user.team.points', $data);
}
@ -826,27 +808,28 @@ class TeamController extends Controller
{
$user = User::find(\Auth::user()->id);
if (!$user->isVIP()) {
if (! $user->isVIP()) {
abort(404);
}
$ExportBot = new ExportBot('member');
$ExportBot->initStructureUser($user, 'list'); //tree or list
$ExportBot->initStructureUser($user, 'list'); // tree or list
$data = [
'ExportBot' => $ExportBot,
];
return view('user.team.export', $data);
}
public function userTeamExport()
{
if (Request::get('action') === "export") {
if (Request::get('action') === 'export') {
$user = User::find(\Auth::user()->id);
$ExportBot = new ExportBot('member');
$ExportBot->initStructureUser($user, 'list'); //tree or list
$ExportBot->initStructureUser($user, 'list'); // tree or list
$columns = [];
$filename = __('team.filename_export') . date('Y-m-d-H-i-s');
$headers = array(
$filename = __('team.filename_export').date('Y-m-d-H-i-s');
$headers = [
__('tables.line'),
__('tables.level'),
__('tables.email'),
@ -864,10 +847,10 @@ class TeamController extends Controller
__('tables.account'),
__('tables.account_to'),
__('tables.sponsor'),
);
];
if (isset($ExportBot->user_list->childs)) {
foreach ($ExportBot->user_list->childs as $child) {
$columns[] = array(
$columns[] = [
__('tables.line') => $child->line,
__('tables.level') => $child->level_name,
__('tables.email') => $child->email,
@ -885,38 +868,39 @@ class TeamController extends Controller
__('tables.account') => ($child->active_account == 1 ? __('yes') : __('no')),
__('tables.account_to') => $child->payment_account_date,
__('tables.sponsor') => $child->sponsor_name,
);
];
}
}
return Excel::download(new UserTeamExport($columns, $headers), $filename . '.xls');
return Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
}
}
private function setFilterVars()
{
if (!session('team_user_filter_month')) {
if (! session('team_user_filter_month')) {
session(['team_user_filter_month' => intval(date('m'))]);
}
if (!session('team_user_filter_month_prev')) {
if (! session('team_user_filter_month_prev')) {
session(['team_user_filter_month_prev' => intval(date('m') - 1)]);
}
if (!session('team_user_filter_year')) {
if (! session('team_user_filter_year')) {
session(['team_user_filter_year' => intval(date('Y'))]);
}
if (!session('team_user_points_filter_month')) {
if (! session('team_user_points_filter_month')) {
session(['team_user_points_filter_month' => intval(date('m'))]);
}
if (!session('team_user_points_filter_year')) {
if (! session('team_user_points_filter_year')) {
session(['team_user_points_filter_year' => intval(date('Y'))]);
}
if (!session('team_user_filter_active')) {
if (! session('team_user_filter_active')) {
session(['team_user_filter_active' => 1]);
}
if (!session('team_user_filter_level')) {
if (! session('team_user_filter_level')) {
session(['team_user_filter_level' => 0]);
}
if (!session('team_user_filter_next_level')) {
if (! session('team_user_filter_next_level')) {
session(['team_user_filter_next_level' => 0]);
}
@ -964,38 +948,39 @@ class TeamController extends Controller
return $query;
}
public function datatablePoints()
{
$query = $this->initSearchPoints();
return \DataTables::eloquent($query)
->addColumn('order', function (UserSalesVolume $UserSalesVolume) {
if ($UserSalesVolume->shopping_order) {
if ($UserSalesVolume->status === 1 && $UserSalesVolume->shopping_order->auth_user_id === $UserSalesVolume->user_id) {
return '<a href="' . route('user_order_detail', [$UserSalesVolume->shopping_order->id]) . '" class="btn btn-xs btn-primary">' . $UserSalesVolume->shopping_order->id . '</a>';
return '<a href="'.route('user_order_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-primary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
if (($UserSalesVolume->status === 2 || $UserSalesVolume->status === 3) && $UserSalesVolume->shopping_order->member_id === $UserSalesVolume->user_id) {
return '<a href="' . route('user_shop_order_detail', [$UserSalesVolume->shopping_order->id]) . '" class="btn btn-xs btn-secondary">' . $UserSalesVolume->shopping_order->id . '</a>';
if (($UserSalesVolume->status === 2 || $UserSalesVolume->status === 3) && $UserSalesVolume->shopping_order->member_id === $UserSalesVolume->user_id) {
return '<a href="'.route('user_shop_order_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-secondary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
}
return '';
})
->addColumn('total_net', function (UserSalesVolume $UserSalesVolume) {
return formatNumber($UserSalesVolume->total_net) . ' &euro;';
return formatNumber($UserSalesVolume->total_net).' &euro;';
})
->addColumn('status_turnover', function (UserSalesVolume $UserSalesVolume) {
return '<span class="badge badge-pill badge-' . $UserSalesVolume->getStatusTurnoverColor() . '">' . $UserSalesVolume->getStatusTurnoverType() . '</span>';
return '<span class="badge badge-pill badge-'.$UserSalesVolume->getStatusTurnoverColor().'">'.$UserSalesVolume->getStatusTurnoverType().'</span>';
})
->addColumn('status', function (UserSalesVolume $UserSalesVolume) {
return '<span class="badge badge-pill badge-' . $UserSalesVolume->getStatusColor() . '">' . $UserSalesVolume->getStatusType() . '</span>';
return '<span class="badge badge-pill badge-'.$UserSalesVolume->getStatusColor().'">'.$UserSalesVolume->getStatusType().'</span>';
})
->addColumn('message', function (UserSalesVolume $UserSalesVolume) {
return '<span class="no-line-break">' . $UserSalesVolume->message . '</span>';
return '<span class="no-line-break">'.$UserSalesVolume->message.'</span>';
})
->addColumn('info', function (UserSalesVolume $UserSalesVolume) {
return '<span class="no-line-break">' . $UserSalesVolume->info . '</span>';
return '<span class="no-line-break">'.$UserSalesVolume->info.'</span>';
})
->orderColumn('id', 'id $1')
@ -1018,7 +1003,8 @@ class TeamController extends Controller
'userSalesVolume' => $userSalesVolume,
];
$html = view('user.team._points_sum', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html' => $html]);
return response()->json(['response' => true, 'data' => $data, 'html' => $html]);
}
/**
@ -1026,13 +1012,13 @@ class TeamController extends Controller
*/
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];
}
/**
@ -1058,7 +1044,7 @@ class TeamController extends Controller
return [
1 => __('team.filter_active'),
2 => __('team.filter_not_active'),
3 => __('team.filter_all')
3 => __('team.filter_all'),
];
}
@ -1071,7 +1057,7 @@ class TeamController extends Controller
0 => __('team.all_status'),
1 => __('team.qualified_green'),
2 => __('team.in_progress_yellow'),
3 => __('team.no_level_red')
3 => __('team.no_level_red'),
];
}
@ -1089,20 +1075,20 @@ class TeamController extends Controller
// Debug: Prüfe TreeCalcBot-Inhalt
$businessUsers = $treeCalcBot->getItems();
\Log::info("TeamController: TreeCalcBot root items count: " . count($businessUsers));
\Log::info('TeamController: TreeCalcBot root items count: '.count($businessUsers));
// Sammle alle Root-User UND deren verschachtelte businessUserItems
foreach ($businessUsers as $businessUser) {
// WICHTIG: user_id korrekt über b_user abrufen (Magic Method Problem mit isset())
$userId = $businessUser->user_id; // Über __get() Method
\Log::debug("TeamController: Processing root businessUser", [
\Log::debug('TeamController: Processing root businessUser', [
'user_id' => $userId,
'businessUserItems_count' => count($businessUser->businessUserItems ?? []),
]);
// WICHTIG: Root-User selbst hinzufügen (korrigierte user_id Prüfung)
//nur User können auch children haben - businessUserItems
if ($userId && !isset($processedIds[$userId])) {
// nur User können auch children haben - businessUserItems
if ($userId && ! isset($processedIds[$userId])) {
$processedIds[$userId] = true;
$businessUser->deep = 0;
$allUsers[] = $businessUser;
@ -1121,7 +1107,7 @@ class TeamController extends Controller
if ($userId) {
// Prüfe ob dieser parentless User bereits gesammelt wurde
if (!isset($processedIds[$userId])) {
if (! isset($processedIds[$userId])) {
$processedIds[$userId] = true;
$businessUser->deep = 0;
$allUsers[] = $businessUser;
@ -1134,17 +1120,17 @@ class TeamController extends Controller
\Log::debug("TeamController: Parentless-User übersprungen: {$userId} (bereits verarbeitet)");
}
} else {
\Log::warning("TeamController: Parentless BusinessUser ohne user_id übersprungen");
\Log::warning('TeamController: Parentless BusinessUser ohne user_id übersprungen');
}
}
}
}
}
\Log::info("TeamController: AllUsers before filtering: " . count($allUsers));
\Log::info('TeamController: AllUsers before filtering: '.count($allUsers));
// Filter anwenden
$filteredUsers = $this->applyTeamFiltersToBusinessUsers($allUsers);
\Log::info("TeamController: AllUsers after filtering: " . count($filteredUsers));
\Log::info('TeamController: AllUsers after filtering: '.count($filteredUsers));
return $filteredUsers;
}
@ -1161,9 +1147,9 @@ class TeamController extends Controller
\Log::info("TeamController: Applying filters - Active: {$activeFilter}, Level: {$levelFilter}, NextLevel: {$nextLevelFilter}");
// Debug: Zeige verfügbare Eigenschaften des ersten BusinessUsers
if (!empty($businessUsers)) {
if (! empty($businessUsers)) {
$firstUser = $businessUsers[0];
\Log::debug("TeamController: First BusinessUser properties", [
\Log::debug('TeamController: First BusinessUser properties', [
'user_id' => $firstUser->user_id ?? 'not set',
'active_account' => $firstUser->active_account ?? 'not set',
'm_level_id' => $firstUser->m_level_id ?? 'not set',
@ -1175,7 +1161,7 @@ class TeamController extends Controller
$filtered = array_filter($businessUsers, function ($businessUser) use ($activeFilter, $levelFilter, $nextLevelFilter) {
// Active Filter anwenden
if ($activeFilter == 1) { // Nur aktive
if (!$businessUser->active_account) {
if (! $businessUser->active_account) {
return false;
}
} elseif ($activeFilter == 2) { // Nur inaktive
@ -1199,12 +1185,12 @@ class TeamController extends Controller
switch ($nextLevelFilter) {
case 1: // Qualifiziert (grün) - hat next_qual_user_level
if (!$hasNextQual) {
if (! $hasNextQual) {
return false;
}
break;
case 2: // In Arbeit (gelb) - hat next_can_user_level aber kein next_qual_user_level
if ($hasNextQual || !$hasNextCan) {
if ($hasNextQual || ! $hasNextCan) {
return false;
}
break;
@ -1233,6 +1219,7 @@ class TeamController extends Controller
$maxDepth = 20;
if ($depth > $maxDepth) {
\Log::warning("TeamController: Maximale Sammlungstiefe ({$maxDepth}) erreicht bei Tiefe {$depth}");
return;
}
@ -1244,6 +1231,7 @@ class TeamController extends Controller
// KRITISCHER SCHUTZ: Prüfe ob User bereits gesammelt wurde
if (isset($processedIds[$userId])) {
\Log::debug("TeamController: Überspringe bereits gesammelten User {$userId} (Duplikat verhindert)");
continue;
}
@ -1255,8 +1243,8 @@ class TeamController extends Controller
\Log::debug("TeamController: Flach gesammelt - User ID: {$userId} at depth {$depth}");
// Rekursiv ALLE verschachtelten businessUserItems sammeln
if (isset($businessUserItem->businessUserItems) && is_array($businessUserItem->businessUserItems) && !empty($businessUserItem->businessUserItems)) {
\Log::debug("TeamController: Sammle " . count($businessUserItem->businessUserItems) . " verschachtelte Items von User {$userId}");
if (isset($businessUserItem->businessUserItems) && is_array($businessUserItem->businessUserItems) && ! empty($businessUserItem->businessUserItems)) {
\Log::debug('TeamController: Sammle '.count($businessUserItem->businessUserItems)." verschachtelte Items von User {$userId}");
$this->collectAllBusinessUserItemsFlat($businessUserItem->businessUserItems, $allUsers, $processedIds, $depth + 1);
}
} else {
@ -1276,11 +1264,12 @@ class TeamController extends Controller
$maxDepth = 20;
if ($deep > $maxDepth) {
\Log::warning("TeamController: Maximale Sammlungstiefe ({$maxDepth}) erreicht");
return;
}
if (isset($businessUser->businessUserItems) && is_array($businessUser->businessUserItems)) {
\Log::debug("TeamController: Collecting from businessUser with " . count($businessUser->businessUserItems) . " sub-items at depth {$deep}");
\Log::debug('TeamController: Collecting from businessUser with '.count($businessUser->businessUserItems)." sub-items at depth {$deep}");
foreach ($businessUser->businessUserItems as $subBusinessUser) {
if ($subBusinessUser) {
@ -1291,6 +1280,7 @@ class TeamController extends Controller
// KRITISCHER BUGFIX: Prüfe ob User bereits gesammelt wurde
if (isset($processedIds[$userId])) {
\Log::debug("TeamController: Überspringe bereits gesammelten User {$userId} (zirkuläre Referenz verhindert)");
continue;
}
@ -1320,13 +1310,13 @@ class TeamController extends Controller
$cleanedUsers = [];
foreach ($businessUserItems as $businessUserItem) {
if (!$businessUserItem) {
if (! $businessUserItem) {
continue;
}
try {
// Extrahiere nur die Properties, die für DataTable benötigt werden
$cleanedUser = new \stdClass();
$cleanedUser = new \stdClass;
// Basis Properties (direkt über Magic Method __get)
$cleanedUser->user_id = $businessUserItem->user_id;
@ -1354,13 +1344,14 @@ class TeamController extends Controller
\Log::debug("TeamController: Cleaned user {$cleanedUser->user_id} for DataTable");
} catch (\Exception $e) {
\Log::error("TeamController: Error cleaning BusinessUserItem for DataTable: " . $e->getMessage());
\Log::error('TeamController: Error cleaning BusinessUserItem for DataTable: '.$e->getMessage());
// Skip diesen User, statt alles abzubrechen
continue;
}
}
\Log::info("TeamController: Cleaned " . count($cleanedUsers) . " users for DataTable (from " . count($businessUserItems) . " raw items)");
\Log::info('TeamController: Cleaned '.count($cleanedUsers).' users for DataTable (from '.count($businessUserItems).' raw items)');
return $cleanedUsers;
}

View file

@ -11,7 +11,6 @@ use App\Models\ShoppingUser;
use App\Repositories\CheckoutRepository;
use App\Services\AboHelper;
use App\Services\CustomerPriority;
use App\Services\OrderPaymentService;
use App\Services\Payment;
use App\Services\Shop;
use App\Services\Util;
@ -24,6 +23,7 @@ use Yard;
class CheckoutController extends Controller
{
private $checkoutRepo;
private $instance = 'checkout';
/**
@ -38,18 +38,18 @@ class CheckoutController extends Controller
/**
* Zeigt die Checkout-Seite an
*
*
* @return \Illuminate\View\View
*/
public function checkout()
{
/*
@if(Auth::guard('customers')->check())
<a href="{{ route('portal.logout') }}" class="btn btn-sm btn-default mt-3"><i class="fa fa-power-off"></i> {{ __('navigation.logout') }} </a>
@else
<a href="{{ Util::getMyMivitaPortalUrl() }}" class="btn btn-primary btn-block mt-3 faa-parent animated-hover"><i class="fa fa-sign-in"></i> {{ __('website.to_customer_portal') }} </a>
@endif
@if(Auth::guard('user')->check())
<a href="{{ route('portal.logout') }}" class="btn btn-sm btn-default mt-3"><i class="fa fa-power-off"></i> {{ __('navigation.logout') }} </a>
@else
<a href="{{ Util::getMyMivitaPortalUrl() }}" class="btn btn-primary btn-block mt-3 faa-parent animated-hover"><i class="fa fa-sign-in"></i> {{ __('website.to_customer_portal') }} </a>
@endif
@if(Auth::guard('user')->check())
*/
$shopping_data = Yard::instance($this->instance)->getYardExtra('shopping_data');
$is_from = $shopping_data['is_from'] ?? 'shopping';
@ -97,28 +97,26 @@ class CheckoutController extends Controller
'is_checkout' => true,
'yard_instance' => $this->instance,
];
return view('web.templates.checkout', $data);
}
/**
* Bereitet die ShoppingUser-Daten vor
*
* @param ShoppingUser $shopping_user
*
* @return void
*/
private function prepareShoppingUserData(ShoppingUser $shopping_user)
{
if ($shopping_user->same_as_billing === NULL) {
if ($shopping_user->same_as_billing === null) {
$shopping_user->same_as_billing = false;
}
if (!$shopping_user->billing_country_id) {
if (! $shopping_user->billing_country_id) {
$shopping_user->billing_country_id = Yard::instance($this->instance)->getUserCountryId();
// Die Zeile unten entfernen, da die Relation automatisch geladen wird
// $shopping_user->billing_country = Yard::instance($this->instance)->getUserCountry();
}
if (!$shopping_user->shipping_country_id) {
if (! $shopping_user->shipping_country_id) {
$shopping_user->shipping_country_id = Yard::instance($this->instance)->getUserCountryId();
// Die Zeile unten entfernen, da die Relation automatisch geladen wird
// $shopping_user->shipping_country = Yard::instance($this->instance)->getUserCountry();
@ -135,7 +133,7 @@ class CheckoutController extends Controller
/**
* Verarbeitet den Checkout-Prozess
*
*
* @return \Illuminate\Http\RedirectResponse
*/
public function checkoutFinal()
@ -180,13 +178,13 @@ class CheckoutController extends Controller
/**
* Verarbeitet den Länderwechsel
*
* @param array $data
*
* @param array $data
* @return \Illuminate\Http\RedirectResponse
*/
private function handleCountryChange($data)
{
if (!Request::get('same_as_billing')) {
if (! Request::get('same_as_billing')) {
Yard::instance($this->instance)->setShippingCountryWithPrice($data['billing_state'], $data['is_for']);
} else {
Yard::instance($this->instance)->setShippingCountryWithPrice($data['shipping_state'], $data['is_for']);
@ -197,7 +195,7 @@ class CheckoutController extends Controller
/**
* Validiert die Checkout-Daten
*
*
* @return \Illuminate\Validation\Validator
*/
private function validateCheckoutData()
@ -220,7 +218,7 @@ class CheckoutController extends Controller
'shipping_address' => 'required',
'shipping_zipcode' => 'required',
'shipping_city' => 'required',
'shipping_salutation' => 'required'
'shipping_salutation' => 'required',
]);
}
@ -229,10 +227,10 @@ class CheckoutController extends Controller
/**
* Verarbeitet die Zahlungsmethode
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
* @return mixed
*/
private function processPaymentMethod($data, $shopping_user, $shopping_order)
@ -243,7 +241,7 @@ class CheckoutController extends Controller
// Kreditkarte prüfen
if ($payment_method === 'cc') {
$result = $this->checkCreditCard($data, $shopping_user, $shopping_order);
if (!is_array($result) || !isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
}
}
@ -251,13 +249,13 @@ class CheckoutController extends Controller
// SEPA prüfen
if ($payment_method === 'elv') {
$result = $this->checkSepaAccount($data, $shopping_user, $shopping_order);
if (!is_array($result) || !isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
}
}
// Zahlung vorbereiten
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$reference = $pay->setPrePayment($payment_method, $amount, 'EUR', $result);
@ -269,15 +267,15 @@ class CheckoutController extends Controller
/**
* Prüft die Kreditkartendaten
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
* @return bool|\Illuminate\Http\RedirectResponse
*/
private function checkCreditCard($data, $shopping_user, $shopping_order)
{
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$ret['cc'] = $pay->checkCreditCard($data);
@ -285,24 +283,26 @@ class CheckoutController extends Controller
Session::flash('cc-error', 1);
Session::flash('errormessage', $ret['cc']['errormessage']);
Session::flash('customermessage', $ret['cc']['customermessage']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
$ret['returnstatus'] = 'VALID';
return $ret;
}
/**
* Prüft die SEPA-Kontodaten
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
*
* @param array $data
* @param ShoppingUser $shopping_user
* @param ShoppingOrder $shopping_order
* @return bool|\Illuminate\Http\RedirectResponse
*/
private function checkSepaAccount($data, $shopping_user, $shopping_order)
{
if (is_null(Request::get('mandate_identification'))) {
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$ret['elv'] = $pay->checkBankAccount($data, $amount, 'EUR', $shopping_user);
@ -311,14 +311,16 @@ class CheckoutController extends Controller
Session::flash('elv-error', 1);
Session::flash('errormessage', $ret['elv']['errormessage']);
Session::flash('customermessage', $ret['elv']['customermessage']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
if ($ret['elv']['status'] === 'APPROVED' && $ret['elv']['mandate_status'] !== "active") {
if ($ret['elv']['status'] === 'APPROVED' && $ret['elv']['mandate_status'] !== 'active') {
Session::flash('elv-managemandate', 1);
Session::flash('elv-mandate_identification', $ret['elv']['mandate_identification']);
Session::flash('elv-mandate_text', $ret['elv']['mandate_text']);
Session::flash('elv-creditor_identifier', $ret['elv']['creditor_identifier']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
@ -329,18 +331,19 @@ class CheckoutController extends Controller
'creditor_identifier' => Request::get('creditor_identifier'),
'iban' => $data['elv_iban'],
'bic' => $data['elv_bic'],
'bankaccountholder' => $data['elv_bankaccountholder']
'bankaccountholder' => $data['elv_bankaccountholder'],
];
$this->storeUserPaymentsData($shopping_user, $ret);
}
$ret['returnstatus'] = 'VALID';
return $ret;
}
/**
* Leitet zur Abschlussseite weiter
*
*
* @return \Illuminate\View\View
*/
public function redirectToIsFinal()
@ -354,53 +357,105 @@ class CheckoutController extends Controller
return view('web.templates.checkout-is-final', $data);
}
/**
* Verarbeitet den Transaktionsstatus (POST-Anfragen)
* Einige Zahlungsanbieter senden POST-Anfragen zurück
*
* @param string $status
* @param string $reference
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
*/
public function transactionStatusPost($status, $reference)
{
return $this->transactionStatus($status, $reference);
}
/**
* Verarbeitet den Transaktionsstatus
*
* @param string $status
* @param string $reference
*
* @param string $status
* @param string $reference
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
*/
public function transactionStatus($status, $reference)
{
$shopping_order_id = $this->checkoutRepo->getSessionPayments('shopping_order_id');
$ShoppingPayment = ShoppingPayment::where('shopping_order_id', $shopping_order_id)
->where('reference', $reference)
->first();
// Suche ShoppingPayment nur über reference (nicht Session-abhängig)
// Dies ist wichtig, da die Session bei Redirect-Zahlungen verloren gehen kann
$ShoppingPayment = ShoppingPayment::where('reference', $reference)->first();
if (!$ShoppingPayment) {
if (! $ShoppingPayment) {
Util::setUserHistoryValue(['status' => 21]);
Session::flash('checkout-error', 'Der Zahlungsvorgang konnte nicht abgeschlossen werden, die Zahlung wurde nicht gefunden: ' . $reference);
return redirect(route('checkout.checkout_card'));
\Log::warning('CheckoutController::transactionStatus - ShoppingPayment nicht gefunden', [
'reference' => $reference,
'status' => $status,
]);
// Zeige eine dedizierte Fehlerseite anstatt zur Hauptseite weiterzuleiten
return $this->showTransactionError(
__('payment.payment_not_found'),
__('payment.payment_not_found_description', ['reference' => $reference])
);
}
$ShoppingPayment->status = $status;
$ShoppingPayment->save();
if ($status === "success") {
if ($status === 'success') {
return $this->handleSuccessfulTransaction($ShoppingPayment, $reference);
}
if ($status === "cancel") {
if ($status === 'cancel') {
Util::setUserHistoryValue(['status' => 22]);
Util::setInstanceStatus(5); // link_canceled
Session::flash('checkout-error', 'Der Zahlungsvorgang wurde abgebrochen, die Bestellung konnte nicht ausgeführt werden.');
return redirect(route('checkout.checkout_card'));
Util::setInstanceStatusByPayment($ShoppingPayment, 6); // link_canceled
return $this->showTransactionError(
__('payment.payment_canceled'),
__('payment.payment_canceled_description')
);
}
if ($status === "error") {
if ($status === 'error') {
Util::setUserHistoryValue(['status' => 23]);
Util::setInstanceStatus(6); // link_failed
Session::flash('checkout-error', 'Der Zahlungsvorgang wurde abgebrochen, die Bestellung konnte nicht ausgeführt werden.');
return redirect(route('checkout.checkout_card'));
Util::setInstanceStatusByPayment($ShoppingPayment, 5); // link_failed
return $this->showTransactionError(
__('payment.payment_error'),
__('payment.payment_error_description')
);
}
// Fallback für unbekannte Status
return $this->showTransactionError(
__('payment.payment_unknown_status'),
__('payment.payment_unknown_status_description')
);
}
/**
* Zeigt eine Transaktionsfehlerseite an
*
* @param string $title
* @param string $message
* @return \Illuminate\View\View
*/
private function showTransactionError($title, $message)
{
$data = [
'user_shop' => Util::getUserShop(),
'is_checkout' => true,
'yard_instance' => $this->instance,
'error_title' => $title,
'error_message' => $message,
];
return view('web.templates.checkout-error', $data);
}
/**
* Verarbeitet eine erfolgreiche Transaktion
*
* @param ShoppingPayment $ShoppingPayment
* @param string $reference
*
* @param ShoppingPayment $ShoppingPayment
* @param string $reference
* @return \Illuminate\View\View
*/
private function handleSuccessfulTransaction($ShoppingPayment, $reference)
@ -428,9 +483,9 @@ class CheckoutController extends Controller
/**
* Verarbeitet eine genehmigte Transaktion
*
* @param int $transactionId
* @param string $reference
*
* @param int $transactionId
* @param string $reference
* @return \Illuminate\View\View
*/
public function transactionApproved($transactionId, $reference)
@ -466,9 +521,9 @@ class CheckoutController extends Controller
/**
* Speichert die Zahlungsdaten des Benutzers
*
* @param ShoppingUser $shopping_user
* @param array $ret
*
* @param ShoppingUser $shopping_user
* @param array $ret
* @return void
*/
private function storeUserPaymentsData($shopping_user, $ret)
@ -486,8 +541,7 @@ class CheckoutController extends Controller
/**
* Verarbeitet den direkten Zahlungsstatus (Rechnung MIV)
*
* @param PaymentTransaction $payt
*
* @return void
*/
private function directPaymentStatus(PaymentTransaction $payt)
@ -517,34 +571,36 @@ class CheckoutController extends Controller
/**
* Initialisiert oder ruft einen Shopping-Benutzer ab
*
* @param string|null $is_from = shopping | user_order | user_order_ot | user_order_abo | user_order_abo_ot | user_order_ot_customer | user_order_abo_ot_customer
* @param string|null $is_for = me | ot | abo-me | abo-ot | ot-customer | abo-ot-customer
* @param array|null $shopping_data
* @param int|null $homeparty_id
* @param string|null $is_from = shopping | user_order | user_order_ot | user_order_abo | user_order_abo_ot | user_order_ot_customer | user_order_abo_ot_customer
* @param string|null $is_for = me | ot | abo-me | abo-ot | ot-customer | abo-ot-customer
* @param array|null $shopping_data
* @param int|null $homeparty_id
* @return \App\Models\ShoppingUser
*/
private function initializeShoppingUserSession($is_from, $is_for, $shopping_data = null, $homeparty_id = null)
{
//check if shopping_user_id is set - der user ist bereits angelegt
// check if shopping_user_id is set - der user ist bereits angelegt
if ($this->checkoutRepo->getSessionPayments('shopping_user_id')) {
return $this->getExistingShoppingUser();
}
//kommt vom Salescenter
// kommt vom Salescenter
if ($shopping_data && $is_from !== 'shopping') {
$shopping_user = $this->checkoutRepo->shoppingUserAuthData($is_from, $is_for, $shopping_data);
$shopping_user->save();
$this->checkoutRepo->putSessionPayments('shopping_user_id', $shopping_user->id);
return $shopping_user;
}
//kommt aus dem Salescenter mit bestelllink oder aus dem Webshop
// kommt aus dem Salescenter mit bestelllink oder aus dem Webshop
if ($is_from === 'shopping') {
//Bestelllink
// Bestelllink
if ($is_for === 'ot-customer' || $is_for === 'abo-ot-customer') {
//customer shop mit den Daten aus dem Salescenter shopping_data
// customer shop mit den Daten aus dem Salescenter shopping_data
return $this->checkoutRepo->makeCustomerShoppingUser($shopping_data, $is_for, $is_from);
}
//Webshop
// Webshop
return $this->checkoutRepo->initShoppingUser($is_for, $is_from, $homeparty_id);
}
@ -553,7 +609,7 @@ class CheckoutController extends Controller
/**
* Holt den existierenden ShoppingUser und bereitet ihn vor
*
*
* @return ShoppingUser
*/
private function getExistingShoppingUser()

View file

@ -2,34 +2,32 @@
namespace App\Http\Controllers;
use Auth;
use Hash;
use Yard;
use Request;
use App\User;
use Validator;
use App\Mail\MailAccountActive;
use App\Mail\MailAutoReleaseAccount;
use App\Mail\MailReleaseAccount;
use App\Models\File;
use App\Services\Util;
use App\Models\Product;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Services\UserService;
use App\Mail\MailAccountActive;
use App\Models\ShippingCountry;
use App\Mail\MailReleaseAccount;
use App\Models\ShoppingInstance;
use App\Mail\MailAutoReleaseAccount;
use App\Repositories\ContractPDFRepository;
use App\Repositories\FileRepository;
use App\Repositories\UserRepository;
use App\Services\UserService;
use App\Services\Util;
use App\User;
use Auth;
use Hash;
use Illuminate\Support\Facades\Mail;
use App\Repositories\ContractPDFRepository;
use Request;
use Validator;
use Yard;
class WizardController extends Controller
{
protected $fileRepo;
/**
* Create a new controller instance.
*
@ -42,19 +40,20 @@ class WizardController extends Controller
public function create()
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
$user = User::findOrFail(Auth::user()->id);
if (!$user->account) {
if (! $user->account) {
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_create'));
}
$step = !$user->wizard ? 0 : $user->wizard;
$step = ! $user->wizard ? 0 : $user->wizard;
if ($step >= 20) {
return redirect('/home');
@ -64,8 +63,12 @@ class WizardController extends Controller
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
'userHistoryWizardPayment' => $userHistoryWizardPayment,
];
@ -79,18 +82,19 @@ class WizardController extends Controller
public function register()
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
$user = User::findOrFail(Auth::user()->id);
if (!$user->account) {
if (! $user->account) {
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_register'));
}
$step = !$user->wizard ? 0 : $user->wizard;
$step = ! $user->wizard ? 0 : $user->wizard;
if ($step >= 10) {
return redirect('/home');
@ -99,14 +103,19 @@ class WizardController extends Controller
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
];
if ($step == 5) {
if ($user->active) {
$user->active = false;
$user->save();
}
return view('user.wizard.register_release', $data);
}
@ -115,39 +124,43 @@ class WizardController extends Controller
public function payment()
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
$user = User::findOrFail(Auth::user()->id);
if (!$user->account) {
if (! $user->account) {
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_payment'));
}
$userHistoryWizardPayment = UserHistory::whereUserId($user->id)->whereAction('wizard_payment')->get()->last();
$shipping_country_id = $this->checkShoppingCountry($user);
if (!$shipping_country_id) {
if (! $shipping_country_id) {
abort(403, __('validation.custom.shipping_not_found'));
}
UserService::checkUserTaxShippingCountry($user, $shipping_country_id);
//Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id, $for);
//Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
// Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id, $for);
// Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
$data = [
'user' => Auth::user(),
'step' => 0,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
'userHistoryWizardPayment' => $userHistoryWizardPayment,
'yard_info' => UserService::getYardInfo(),
];
if ($user->wizard == 20) {
return view('user.wizard.register_payment', $data);
}
@ -169,43 +182,45 @@ class WizardController extends Controller
return $shipping_country->id;
}
}
return false;
}
public function storeRegister($step = false)
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
$user = User::findOrFail(Auth::user()->id);
if (!$user->account) {
$user->account = new UserAccount();
if (! $user->account) {
$user->account = new UserAccount;
}
$data = Request::all();
if ($step == 7 && Request::get('user_country_id')) {
$user->account->country_id = Request::get('user_country_id');
$user->account->save();
return redirect(route('wizard_register', [1]));
}
if ($step == 0) {
$rules = array(
$rules = [
'accepted_data_protection' => 'required',
'accepted_active' => 'required',
'accepted_contract' => 'required'
);
'accepted_contract' => 'required',
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
];
$user->wizard = 0;
$user->save();
return view('user.wizard.register', $data)->withErrors($validator);
}
$account = $user->account;
@ -222,26 +237,29 @@ class WizardController extends Controller
$user->wizard = 1;
$user->save();
return redirect(route('wizard_register'));
}
if ($step == 1) {
$data = Request::all();
if (isset($data['action']) && $data['action'] == "reverse_charge_validate") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate') {
$user->wizard = 1;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_validate($data, $user, route('wizard_register', [0]));
}
if (isset($data['action']) && $data['action'] == "reverse_charge_delete") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete') {
$user->wizard = 1;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_delete($data, $user, route('wizard_register', [0]));
}
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -255,9 +273,9 @@ class WizardController extends Controller
'bank_owner' => 'required',
'bank_iban' => 'required',
'bank_bic' => 'required',
);
];
if (!Request::get('same_as_billing')) {
if (! Request::get('same_as_billing')) {
$rules = array_merge($rules, [
'shipping_firstname' => 'required',
'shipping_lastname' => 'required',
@ -272,12 +290,14 @@ class WizardController extends Controller
if ($validator->fails()) {
$user->wizard = 1;
$user->save();
return redirect(route('wizard_register', [1]))->withErrors($validator)->withInput(Request::all());
}
$data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
$data['same_as_billing'] = Request::get('same_as_billing') == null ? 0 : 1;
$user->account->fill($data)->save();
$user->wizard = 2;
$user->save();
return redirect(route('wizard_register'));
}
@ -288,40 +308,45 @@ class WizardController extends Controller
$validator->errors()->add('field', __('msg.no_id_card_deposited_please_upload_first'));
$user->wizard = 2;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
}
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'));
}
$this->fileRepo->_set('disk', 'user');
$this->fileRepo->_set('dir', '/' . $user->id . '/verification/');
$this->fileRepo->_set('dir', '/'.$user->id.'/verification/');
$this->fileRepo->_set('user_id', $user->id);
$this->fileRepo->_set('identifier', 'id_card');
return $this->fileRepo->uploadFile(Request::all());
return $this->fileRepo->uploadFile(Request::all());
}
if ($step == 3) {
if (Request::get('submit') === 'do') {
$data = Request::all();
if ($data['business_license_choose'] === "now") {
if ($data['business_license_choose'] === 'now') {
if (File::whereUserId($user->id)->whereIdentifier('business_license')->count() == 0) {
$validator = Validator::make(Request::all(), []);
$validator->errors()->add('field', __('msg.no_trade_licence_deposited_please_upload_first'));
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
}
}
if ($data['business_license_choose'] === "later") {
if ($data['business_license_choose'] === 'later') {
}
if ($data['business_license_choose'] === "non") {
if (!$data['non_business_license_reason'] || $data['non_business_license_reason'] == "") {
if ($data['business_license_choose'] === 'non') {
if (! $data['non_business_license_reason'] || $data['non_business_license_reason'] == '') {
$validator = Validator::make(Request::all(), []);
$validator->errors()->add('field', __('msg.please_enter_reason_why_you_not_need_trade_licence'));
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
} else {
$user->account->setNotice('business_license_reason', $data['non_business_license_reason']);
@ -335,10 +360,11 @@ class WizardController extends Controller
return redirect(route('wizard_register'));
}
$this->fileRepo->_set('disk', 'user');
$this->fileRepo->_set('dir', '/' . $user->id . '/verification/');
$this->fileRepo->_set('dir', '/'.$user->id.'/verification/');
$this->fileRepo->_set('user_id', $user->id);
$this->fileRepo->_set('identifier', 'business_license');
return $this->fileRepo->uploadFile(Request::all());
return $this->fileRepo->uploadFile(Request::all());
}
if ($step == 4) {
@ -363,7 +389,7 @@ class WizardController extends Controller
}
}
//auto release account
// auto release account
public function releaseAccount($user)
{
@ -373,15 +399,15 @@ class WizardController extends Controller
$user->account->m_account = UserAccount::withTrashed()->max('m_account') + 1;
$user->account->save();
$user->save();
//create PDF
// create PDF
$pdf = new ContractPDFRepository($user);
$pdf->_set('disk', 'user');
$pdf->_set('dir', '/' . $user->id . '/documents/');
$pdf->_set('dir', '/'.$user->id.'/documents/');
$pdf->_set('user_id', $user->id);
$pdf->_set('identifier', 'contract');
$pdf->createContractPDF();
//set wizard tp payments
// set wizard tp payments
$user->wizard = 20;
$user->active = 1;
$user->active_date = now();
@ -391,7 +417,7 @@ class WizardController extends Controller
$user->confirmation_code_remider = 0;
$user->save();
//mail with code to user?
// mail with code to user?
if ($user->isTestMode()) {
$mail = config('app.info_test_mail');
} else {
@ -402,36 +428,38 @@ class WizardController extends Controller
Mail::to($user->email)->locale($user->getLocale())->send(new MailAccountActive($user));
UserHistory::create(['user_id' => $user->id, 'action' => 'released_completed', 'status' => 0]);
\Session()->flash('alert-success', __('msg.account_released'));
return redirect(route('wizard_payment'));
}
public function storeCreate($step = 0)
{
if (!Auth::check()) {
if (! Auth::check()) {
return redirect('login');
}
$user = User::findOrFail(Auth::user()->id);
if (!$user->account) {
$user->account = new UserAccount();
if (! $user->account) {
$user->account = new UserAccount;
}
if ($step == 10) {
$rules = array(
$rules = [
'accepted_data_protection' => 'required',
'accepted_active' => 'required',
);
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
];
$user->wizard = 10;
$user->save();
return view('user.wizard.create', $data)->withErrors($validator);
}
$account = $user->account;
@ -455,50 +483,54 @@ class WizardController extends Controller
if ($user->isPasswort()) {
$user->wizard = 12;
$user->save();
return redirect(route('wizard_create', [12]));
}
$rules = array(
$rules = [
'password' => 'required|string|min:6|confirmed',
);
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
];
return view('user.wizard.create', $data)->withErrors($validator);
}
$user->fill([
'password' => Hash::make(Request::get('password'))
'password' => Hash::make(Request::get('password')),
])->save();
$user->wizard = 12;
$user->save();
return redirect(route('wizard_create', [12]));
}
if ($step == 12) {
$data = Request::all();
if (isset($data['action']) && $data['action'] == "reverse_charge_validate") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate') {
$user->wizard = 12;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_validate($data, $user, route('wizard_create', [12]));
}
if (isset($data['action']) && $data['action'] == "reverse_charge_delete") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete') {
$user->wizard = 12;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_delete($data, $user, route('wizard_create', [12]));
}
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -509,16 +541,16 @@ class WizardController extends Controller
'mobil' => 'required_without:phone',
'country_id' => 'required|integer|min:1',
'birthday' => '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_city' => 'required',
'shipping_salutation' => 'required'
'shipping_salutation' => 'required',
]);
}
@ -528,7 +560,7 @@ class WizardController extends Controller
}
$data = Request::all();
$data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
$data['same_as_billing'] = Request::get('same_as_billing') == null ? 0 : 1;
$user->account->fill($data)->save();
$user->wizard = 13;
@ -538,11 +570,11 @@ class WizardController extends Controller
$user->confirmation_code_to = null;
$user->confirmation_code_remider = 0;
$user->save();
return redirect(route('wizard_create', [13]));
}
}
public function storePayment($step = 0)
{
@ -552,13 +584,13 @@ class WizardController extends Controller
$product = Product::find(Request::get('switchers-package-wizard'));
$showAboOptions = false;
if (Request::get('abo_options')) {
$showAboOptions = false; //true Abo Option deaktivert
$user->abo_options = false; //true Abo Option deaktivert
$showAboOptions = false; // true Abo Option deaktivert
$user->abo_options = false; // true Abo Option deaktivert
$user->save();
}
$shipping_country_id = $this->checkShoppingCountry($user);
if (!$shipping_country_id) {
if (! $shipping_country_id) {
abort(403, __('validation.custom.shipping_not_found'));
}
@ -566,37 +598,19 @@ class WizardController extends Controller
Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id);
if ($product && $product->active) {
//set membership product
$image = "";
// set membership product
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'free_shipping_consultant' => $product->free_shipping_consultant, 'show_on' => $product->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith(\App\Services\UserService::$user_country));
}
//set onboarding products
if (Request::get('products_on_board')) {
foreach (Request::get('products_on_board') as $product_on_board_id) {
$product_on_board = Product::find($product_on_board_id);
$image = "";
if ($product_on_board->images->count()) {
$image = $product_on_board->images->first()->slug;
}
$cartItem = Yard::instance('shopping')->add($product_on_board->id, $product_on_board->getLang('name'), 1, $product_on_board->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product_on_board->slug, 'weight' => $product_on_board->weight, 'points' => $product_on_board->points, 'no_commission' => $product_on_board->no_commission, 'show_on' => $product_on_board->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith(\App\Services\UserService::$user_country));
}
}
}
do {
$identifier = Util::getToken();
} while (ShoppingInstance::where('identifier', $identifier)->count());
@ -608,9 +622,9 @@ class WizardController extends Controller
ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => 1, //is first faker shop for buy intern
'user_shop_id' => 1, // is first faker shop for buy intern
'auth_user_id' => Auth::user()->id,
'payment' => 4, //Berater Wizard
'payment' => 4, // Berater Wizard
'subdomain' => url('/'),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
@ -619,14 +633,16 @@ class WizardController extends Controller
]);
Yard::instance('shopping')->store($identifier);
//add to DB
// add to DB
$path = route('checkout.checkout_card', ['identifier' => $identifier]);
UserHistory::create(['user_id' => $user->id, 'action' => 'wizard_payment', 'status' => 1, 'product_id' => $product->id, 'identifier' => $identifier, 'abo_options' => $showAboOptions]);
//$path = str_replace('http', 'https', $path);
// $path = str_replace('http', 'https', $path);
return redirect()->secure($path);
}
}
\Session()->flash('alert-error', "Fehler beim Produkt");
\Session()->flash('alert-error', 'Fehler beim Produkt');
return back();
}
@ -636,11 +652,12 @@ class WizardController extends Controller
if ($relation === 'upload') {
$user = User::findOrFail(Auth::user()->id);
$file = $user->files()->findOrFail($id);
//remove file
\Storage::disk('user')->delete($file->dir . $file->filename);
// remove file
\Storage::disk('user')->delete($file->dir.$file->filename);
$file->delete();
\Session()->flash('alert-success', __('msg.file_deleted'));
}
return back();
}
}

View file

@ -2,8 +2,8 @@
namespace App\Http\Middleware;
use Closure;
use Auth;
use Closure;
class ActiveAccount
{
@ -11,16 +11,14 @@ class ActiveAccount
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ( Auth::check() && Auth::user()->isActiveAccount() )
{
if (Auth::check() && (Auth::user()->isAdmin() || Auth::user()->isActiveAccount())) {
return $next($request);
}
return redirect('/home');
return redirect('/home');
}
}

View file

@ -16,7 +16,7 @@ use Illuminate\Support\Facades\Log;
/**
* Job to create DHL return labels asynchronously
*
*
* This job handles the creation of DHL return labels in the background,
* preventing API timeouts and improving user experience.
*/
@ -50,9 +50,6 @@ class CreateReturnLabelJob implements ShouldQueue
/**
* Create a new job instance.
*
* @param DhlShipment $originalShipment
* @param array $options
*/
public function __construct(DhlShipment $originalShipment, array $options = [])
{
@ -80,7 +77,7 @@ class CreateReturnLabelJob implements ShouldQueue
]);
// Get DHL configuration
$settingController = new SettingController();
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Initialize DHL client
@ -136,15 +133,22 @@ class CreateReturnLabelJob implements ShouldQueue
$order = $this->originalShipment->shoppingOrder;
$recipient = $this->originalShipment->recipient ?? [];
return [
'order_id' => $order->id,
'original_shipment_id' => $this->originalShipment->id,
'weight_kg' => $this->originalShipment->weight_kg,
'label_format' => $this->originalShipment->label_format ?? 'PDF',
// Check if this is a Packstation delivery - use billing address as return sender
$hasPostNumber = ! empty($recipient['postnumber'] ?? $recipient['postNumber'] ?? '');
// Shipper: Customer sends back to us (swap addresses)
'shipper' => [
'name' => trim(($recipient['firstname'] ?? '') . ' ' . ($recipient['lastname'] ?? '')),
if ($hasPostNumber) {
Log::info('[DHL Queue] Packstation detected - using billing address for return sender', [
'shipment_id' => $this->originalShipment->id,
'order_id' => $order->id,
]);
// Load billing address from order
$shippingUser = $order->shopping_user;
$shipperAddress = $this->getBillingAddressForReturn($shippingUser, $recipient);
} else {
// Use original recipient address (normal delivery)
$shipperAddress = [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => $recipient['street'] ?? '',
'houseNumber' => $recipient['houseNumber'] ?? '',
@ -153,7 +157,17 @@ class CreateReturnLabelJob implements ShouldQueue
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
],
];
}
return [
'order_id' => $order->id,
'original_shipment_id' => $this->originalShipment->id,
'weight_kg' => $this->originalShipment->weight_kg,
'label_format' => $this->originalShipment->label_format ?? 'PDF',
// Shipper: Customer sends back to us (using billing address for Packstation)
'shipper' => $shipperAddress,
// Consignee: Our warehouse (from settings)
'consignee' => [
@ -170,10 +184,56 @@ class CreateReturnLabelJob implements ShouldQueue
];
}
/**
* Get billing address for return label (used when original delivery was to Packstation)
*/
private function getBillingAddressForReturn($shippingUser, array $recipient): array
{
if (! $shippingUser) {
Log::warning('[DHL Queue] No shipping user found, using recipient data', [
'recipient' => $recipient,
]);
// Fallback: use recipient data but without Packstation fields
return [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => 'Adresse fehlt',
'houseNumber' => '',
'postalCode' => $recipient['postalCode'] ?? '',
'city' => $recipient['city'] ?? '',
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
];
}
// Parse billing address to extract street and house number
$billingAddress = trim($shippingUser->billing_address ?? '');
$street = $billingAddress;
$houseNumber = '';
// Try to extract house number from address
if (preg_match('/^(.+?)\s+(\d+[a-zA-Z]?[-\/\d]*)$/u', $billingAddress, $matches)) {
$street = trim($matches[1]);
$houseNumber = trim($matches[2]);
}
return [
'name' => trim(($shippingUser->billing_firstname ?? '').' '.($shippingUser->billing_lastname ?? '')),
'name2' => $shippingUser->billing_company ?? '',
'street' => $street,
'houseNumber' => $houseNumber,
'postalCode' => $shippingUser->billing_zipcode ?? '',
'city' => $shippingUser->billing_city ?? '',
'country' => $shippingUser->billing_country?->code ?? 'DEU',
'email' => $shippingUser->billing_email ?? '',
'phone' => $shippingUser->billing_phone ?? '',
];
}
/**
* Handle a job failure.
*
* @param Exception $exception
*/
public function failed(Exception $exception): void
{

View file

@ -1,29 +1,38 @@
<?php
namespace App\Libraries;
use setasign\Fpdi\Fpdi;
class ContractPDF extends Fpdi
{
protected $_tplIdx;
protected $_site = 1;
protected $_locale = 'de';
/**
* Setzt die Sprache für das Contract-Template
*/
public function setLocale(string $locale): void
{
$this->_locale = $locale;
}
public function Header()
{
if (null === $this->_tplIdx) {
$this->setSourceFile('./pdf/mivita_template_contract_de.pdf');
if ($this->_tplIdx === null) {
// Template basierend auf Locale wählen
$availableTemplates = config('localization.availableTemplates', ['de']);
$locale = in_array($this->_locale, $availableTemplates) ? $this->_locale : 'de';
$this->setSourceFile('./pdf/mivita_template_contract_'.$locale.'.pdf');
}
$this->_tplIdx = $this->importPage($this->_site++);
$this->useTemplate($this->_tplIdx);
}
function Footer() {
} // end of footer
public function Footer() {} // end of footer
}

View file

@ -1,16 +1,12 @@
<?php
namespace App\Mail;
use Storage;
use App\User;
use App\Services\Credit;
use App\Services\Invoice;
use App\Models\UserCredit;
use App\Models\ShoppingOrder;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Storage;
class MailCredit extends Mailable
{
@ -20,38 +16,65 @@ class MailCredit extends Mailable
public $subject;
public function __construct(UserCredit $user_credit)
{
$this->user_credit = $user_credit;
$this->subject = __('email.credit_title');
}
public function build()
{
$title = 'Hallo ';
$title = 'Hallo ';
$copy1line = __('email.credit_copy1line');
if(isset($this->user_credit->user->account)){
$title .= $this->user_credit->user->account->m_first_name.",";
if (isset($this->user_credit->user->account)) {
$title .= $this->user_credit->user->account->m_first_name.',';
}
$filename = $this->user_credit->filename;
$disk = $this->user_credit->disk;
$path = $this->user_credit->getDownloadPath();
if (!Storage::disk($disk)->exists($path)) {
$disk = $this->user_credit->disk;
// 1. Deutsches Original immer anhängen
$pathDe = $this->user_credit->getDownloadPath();
$filenameDe = $this->user_credit->filename;
if (! Storage::disk($disk)->exists($pathDe)) {
return;
}
$file = Storage::disk($disk)->path($path);
$file = str_replace('//', '/', $file);
$mime = Storage::disk($disk)->mimeType($path);
return $this->view('emails.blank')->with([
$fileDe = Storage::disk($disk)->path($pathDe);
$fileDe = str_replace('//', '/', $fileDe);
$mimeDe = Storage::disk($disk)->mimeType($pathDe);
$mail = $this->view('emails.blank')->with([
'title' => $title,
'copy1line' => $copy1line,
])->attach($file,[
'as' => $filename,
'mime' => $mime,
]); // attach file;
'copy1line' => $copy1line,
])->attach($fileDe, [
'as' => $filenameDe,
'mime' => $mimeDe,
]);
// 2. Lokalisierte Version zusätzlich anhängen (wenn vorhanden und != DE)
$locale = $this->user_credit->user
? $this->user_credit->user->getLocale()
: 'de';
if ($locale && $locale !== 'de') {
$pathLocale = $this->user_credit->getDownloadPathLocale($locale);
$filenameLocale = $this->user_credit->getFilenameLocale($locale);
// Nur anhängen wenn lokalisierte Version existiert und nicht gleich dem Original ist
if (Storage::disk($disk)->exists($pathLocale) && $pathLocale !== $pathDe) {
$fileLocale = Storage::disk($disk)->path($pathLocale);
$fileLocale = str_replace('//', '/', $fileLocale);
$mimeLocale = Storage::disk($disk)->mimeType($pathLocale);
$mail->attach($fileLocale, [
'as' => $filenameLocale,
'mime' => $mimeLocale,
]);
}
}
return $mail;
}
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace App\Mail;
use App\Models\UserMessage;
@ -6,20 +7,24 @@ use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MailCustomMessage extends Mailable
{
use Queueable, SerializesModels;
protected $data;
protected $user;
protected $sender;
public $subject;
public $message;
public $message_last;
protected $save;
protected $user;
protected $sender;
public $subject;
public $message;
public $message_last;
protected $save;
public function __construct(User $user, $data, $sender, $save = false)
{
@ -32,47 +37,45 @@ class MailCustomMessage extends Mailable
$this->message_last = isset($data['message_last']) ? $data['message_last'] : '';
}
public function build()
{
$salutation = __('email.salutation').",";
if($this->user->account){
if($this->user->account->salutation === "mr"){
$salutation = __('email.dear_sir')." ".$this->user->account->first_name.",";
}else{
$salutation = __('email.dear_mrs')." ".$this->user->account->first_name.",";
$salutation = __('email.salutation').',';
if ($this->user->account) {
if ($this->user->account->salutation === 'mr') {
$salutation = __('email.dear_sir').' '.$this->user->account->first_name.',';
} else {
$salutation = __('email.dear_mrs').' '.$this->user->account->first_name.',';
}
}
if($this->save){
if ($this->save) {
UserMessage::create([
'user_id' => $this->user->id,
'user_id' => $this->user->id,
'send_user_id' => $this->sender->id,
'email' => $this->user->email,
'subject' => $this->subject,
'message' => $this->message." ".$this->message_last,
'message' => $this->message.' '.$this->message_last,
'send' => true,
'sent_at' => now(),
]);
}
$url = "";
$button = "";
if(isset($this->data['confirmation_code'])){
$url = '';
$button = '';
if (isset($this->data['confirmation_code'])) {
$url = route('register_verify', $this->data['confirmation_code']);
$button = __('email.button_account');
$button = __('email.button_account');
}
if(isset($this->data['url'])){
$url =$this->data['url'];
$button = $this->data['button'];
if (isset($this->data['url'])) {
$url = $this->data['url'];
$button = $this->data['button'];
}
return $this->view('emails.custom')->with([
'url' => $url,
'title' => $salutation,
'button' => $button,
'content' => $this->message,
'content_last' => $this->message_last,
'content' => $this->message,
'content_last' => $this->message_last,
'copy2line' => __('email.copy2line'),
'copy3line' => __('email.copy3line'),
'greetings' => __('email.greetings'),

View file

@ -1,7 +1,7 @@
<?php
namespace App\Mail;
use App\Services\Invoice;
use App\Models\ShoppingOrder;
use App\Models\UserInvoice;
use Illuminate\Bus\Queueable;
@ -14,39 +14,83 @@ class MailInvoice extends Mailable
use Queueable, SerializesModels;
protected $shopping_order;
protected $user_invoice;
public $subject;
public function __construct(ShoppingOrder $shopping_order, UserInvoice $user_invoice)
{
$this->shopping_order = $shopping_order;
$this->user_invoice = $user_invoice;
$this->subject = __('email.invoice_subject').': '.$shopping_order->getLastShoppingPayment('reference') ;
// Unterscheide zwischen Stornorechnung und normaler Rechnung
$isCancellation = $user_invoice->cancellation && ! $user_invoice->cancellation_id;
if ($isCancellation) {
$this->subject = __('email.cancellation_invoice_subject').': '.$shopping_order->getLastShoppingPayment('reference');
} else {
$this->subject = __('email.invoice_subject').': '.$shopping_order->getLastShoppingPayment('reference');
}
}
public function build()
{
$title = __('email.invoice_title');
$copy1line = __('email.invoice_copy1line').$this->shopping_order->getLastShoppingPayment('reference');
// Unterscheide zwischen Stornorechnung und normaler Rechnung
$isCancellation = $this->user_invoice->cancellation && ! $this->user_invoice->cancellation_id;
$filename = $this->user_invoice->filename;
$disk = $this->user_invoice->disk;
$path = $this->user_invoice->getDownloadPath();
if (!Storage::disk($disk)->exists($path)) {
if ($isCancellation) {
$title = __('email.cancellation_invoice_title');
$copy1line = __('email.cancellation_invoice_copy1line').$this->shopping_order->getLastShoppingPayment('reference');
} else {
$title = __('email.invoice_title');
$copy1line = __('email.invoice_copy1line').$this->shopping_order->getLastShoppingPayment('reference');
}
$disk = $this->user_invoice->disk;
// 1. Deutsches Original immer anhängen
$pathDe = $this->user_invoice->getDownloadPath();
$filenameDe = $this->user_invoice->filename;
if (! Storage::disk($disk)->exists($pathDe)) {
return;
}
$file = Storage::disk($disk)->path($path);
$file = str_replace('//', '/', $file);
$mime = Storage::disk($disk)->mimeType($path);
return $this->view('emails.blank')->with([
$fileDe = Storage::disk($disk)->path($pathDe);
$fileDe = str_replace('//', '/', $fileDe);
$mimeDe = Storage::disk($disk)->mimeType($pathDe);
$mail = $this->view('emails.blank')->with([
'title' => $title,
'copy1line' => $copy1line,
])->attach($file,[
'as' => $filename,
'mime' => $mime,
]); // attach file;
'copy1line' => $copy1line,
])->attach($fileDe, [
'as' => $filenameDe,
'mime' => $mimeDe,
]);
// 2. Lokalisierte Version zusätzlich anhängen (wenn vorhanden und != DE)
$locale = $this->shopping_order->shopping_user
? $this->shopping_order->shopping_user->getLocale()
: 'de';
if ($locale && $locale !== 'de') {
$pathLocale = $this->user_invoice->getDownloadPathLocale($locale);
$filenameLocale = $this->user_invoice->getFilenameLocale($locale);
// Nur anhängen wenn lokalisierte Version existiert und nicht gleich dem Original ist
if (Storage::disk($disk)->exists($pathLocale) && $pathLocale !== $pathDe) {
$fileLocale = Storage::disk($disk)->path($pathLocale);
$fileLocale = str_replace('//', '/', $fileLocale);
$mimeLocale = Storage::disk($disk)->mimeType($pathLocale);
$mail->attach($fileLocale, [
'as' => $filenameLocale,
'mime' => $mimeLocale,
]);
}
}
return $mail;
}
}
}

View file

@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Model;
* @property \Illuminate\Support\Carbon|null $display_date
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
*
* @mixin \Eloquent
*/
class DashboardNews extends Model
@ -55,9 +56,10 @@ class DashboardNews extends Model
return $this->{$key};
}
$trans = $this->getTrans($key, $lang);
if (!$trans || $trans == '') {
if (! $trans || $trans == '') {
return $this->{$key};
}
return $trans;
}
@ -66,29 +68,44 @@ class DashboardNews extends Model
*/
public function getTrans($key, $lang)
{
$transKey = 'trans_' . $key;
if (!empty($this->{$transKey}[$lang])) {
$transKey = 'trans_'.$key;
if (! empty($this->{$transKey}[$lang])) {
return $this->{$transKey}[$lang];
}
return "";
return '';
}
/**
* Get active news
*/
public static function getActiveNews()
public static function getActiveNews(): ?self
{
return self::where('active', true)
->orderBy('created_at', 'DESC')
->first();
}
/**
* Get all archived (non-active) news ordered by display date descending
*
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function getArchiveNews(): \Illuminate\Database\Eloquent\Collection
{
return self::where('active', false)
->orderBy('display_date', 'DESC')
->orderBy('created_at', 'DESC')
->get();
}
/**
* Get formatted display date or created_at as fallback
*/
public function getDisplayDateFormatted()
{
$date = $this->display_date ?: $this->created_at;
return $date ? $date->format('d.m.Y') : '';
}
@ -97,11 +114,11 @@ class DashboardNews extends Model
*/
public function getFileLinks($lang = null)
{
if (!$lang) {
if (! $lang) {
$lang = \App::getLocale();
}
if (!$this->file_links || !isset($this->file_links[$lang])) {
if (! $this->file_links || ! isset($this->file_links[$lang])) {
return [];
}
@ -115,6 +132,7 @@ class DashboardNews extends Model
];
}
}
return null;
})->filter()->values();
}

170
app/Models/DatevExport.php Normal file
View file

@ -0,0 +1,170 @@
<?php
namespace App\Models;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class DatevExport extends Model
{
use SoftDeletes;
protected $table = 'datev_exports';
// Status-Konstanten
const STATUS_DRAFT = 0;
const STATUS_GENERATED = 1;
const STATUS_DOWNLOADED = 2;
const STATUS_LOCKED = 3;
const STATUS_LABELS = [
self::STATUS_DRAFT => 'Entwurf',
self::STATUS_GENERATED => 'Generiert',
self::STATUS_DOWNLOADED => 'Heruntergeladen',
self::STATUS_LOCKED => 'Gesperrt',
];
const STATUS_BADGES = [
self::STATUS_DRAFT => 'secondary',
self::STATUS_GENERATED => 'info',
self::STATUS_DOWNLOADED => 'success',
self::STATUS_LOCKED => 'dark',
];
protected $fillable = [
'period_from',
'period_to',
'month',
'year',
'status',
'berater_nr',
'mandant_nr',
'invoice_count',
'credit_count',
'cancellation_count',
'total_revenue',
'total_commissions',
'filename',
'file_path',
'file_hash',
'created_by',
'warning_count',
'error_count',
'validation_summary',
];
protected $casts = [
'period_from' => 'date',
'period_to' => 'date',
'total_revenue' => 'decimal:2',
'total_commissions' => 'decimal:2',
'validation_summary' => 'array',
];
/*
|--------------------------------------------------------------------------
| Relationships
|--------------------------------------------------------------------------
*/
public function lines()
{
return $this->hasMany(DatevExportLine::class, 'datev_export_id');
}
public function creator()
{
return $this->belongsTo(User::class, 'created_by');
}
/*
|--------------------------------------------------------------------------
| Scopes
|--------------------------------------------------------------------------
*/
public function scopeForPeriod($query, int $month, int $year)
{
return $query->where('month', $month)->where('year', $year);
}
public function scopeGenerated($query)
{
return $query->where('status', '>=', self::STATUS_GENERATED);
}
public function scopeLocked($query)
{
return $query->where('status', self::STATUS_LOCKED);
}
/*
|--------------------------------------------------------------------------
| Accessors
|--------------------------------------------------------------------------
*/
public function getStatusLabelAttribute(): string
{
return self::STATUS_LABELS[$this->status] ?? '-';
}
public function getStatusBadgeAttribute(): string
{
$badge = self::STATUS_BADGES[$this->status] ?? 'secondary';
return '<span class="badge badge-'.$badge.'">'.$this->status_label.'</span>';
}
public function getPeriodLabelAttribute(): string
{
return str_pad($this->month, 2, '0', STR_PAD_LEFT).'/'.$this->year;
}
public function getTotalLinesAttribute(): int
{
return $this->invoice_count + $this->credit_count + $this->cancellation_count;
}
/*
|--------------------------------------------------------------------------
| Methods
|--------------------------------------------------------------------------
*/
public function isLocked(): bool
{
return $this->status === self::STATUS_LOCKED;
}
public function isGenerated(): bool
{
return $this->status >= self::STATUS_GENERATED;
}
public function markAsDownloaded(): void
{
if ($this->status === self::STATUS_GENERATED) {
$this->update(['status' => self::STATUS_DOWNLOADED]);
}
}
public function lock(): void
{
$this->update(['status' => self::STATUS_LOCKED]);
}
public function getStoragePath(): string
{
return config('datev.storage_path').'/'.$this->year.'/'.str_pad($this->month, 2, '0', STR_PAD_LEFT);
}
public function getFullFilePath(): string
{
return $this->getStoragePath().'/'.$this->filename;
}
}

View file

@ -0,0 +1,100 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DatevExportLine extends Model
{
protected $table = 'datev_export_lines';
// Source Types
const SOURCE_INVOICE = 'invoice';
const SOURCE_CREDIT = 'credit';
const SOURCE_CANCELLATION = 'cancellation';
protected $fillable = [
'datev_export_id',
'source_type',
'source_id',
'line_number',
'amount_gross',
'soll_haben',
'konto',
'gegenkonto',
'bu_schluessel',
'belegdatum',
'belegfeld1',
'buchungstext',
'eu_ustid',
'eu_land',
'row_csv',
];
protected $casts = [
'amount_gross' => 'decimal:2',
'belegdatum' => 'date',
];
/*
|--------------------------------------------------------------------------
| Relationships
|--------------------------------------------------------------------------
*/
public function datev_export()
{
return $this->belongsTo(DatevExport::class, 'datev_export_id');
}
/*
|--------------------------------------------------------------------------
| Scopes
|--------------------------------------------------------------------------
*/
public function scopeInvoices($query)
{
return $query->where('source_type', self::SOURCE_INVOICE);
}
public function scopeCredits($query)
{
return $query->where('source_type', self::SOURCE_CREDIT);
}
public function scopeCancellations($query)
{
return $query->where('source_type', self::SOURCE_CANCELLATION);
}
/*
|--------------------------------------------------------------------------
| Accessors
|--------------------------------------------------------------------------
*/
public function getSourceTypeLabelAttribute(): string
{
return match ($this->source_type) {
self::SOURCE_INVOICE => 'Rechnung',
self::SOURCE_CREDIT => 'Gutschrift',
self::SOURCE_CANCELLATION => 'Storno',
default => $this->source_type,
};
}
public function getFormattedAmountAttribute(): string
{
$prefix = $this->soll_haben === 'S' ? '-' : '';
return $prefix.number_format(abs($this->amount_gross), 2, ',', '.').' €';
}
public function getFormattedBelegdatumAttribute(): string
{
return $this->belegdatum ? $this->belegdatum->format('d.m.Y') : '-';
}
}

View file

@ -189,6 +189,8 @@ class Product extends Model
'active' => 'bool',
'no_commission' => 'bool',
'no_free_shipping' => 'bool',
'free_shipping_consultant' => 'bool',
'is_membership_only' => 'bool',
'buying_restriction' => 'bool',
'buying_restriction_amount' => 'int',
'sponsor_buying_points' => 'bool',
@ -212,6 +214,8 @@ class Product extends Model
'weight',
'no_commission',
'no_free_shipping',
'free_shipping_consultant',
'is_membership_only',
'contents',
'contents_total',
'unit',

View file

@ -17,6 +17,7 @@ use Illuminate\Database\Eloquent\Model;
* @property-read \App\User|null $auth_user
* @property-read \App\Models\Country $country
* @property-read \App\Models\UserShop $user_shop
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance query()
@ -27,24 +28,38 @@ use Illuminate\Database\Eloquent\Model;
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance whereSubdomain($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance whereUserShopId($value)
*
* @property int|null $payment
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance wherePayment($value)
*
* @property array|null $shopping_data
* @property string|null $back
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance whereBack($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingInstance whereShoppingData($value)
*
* @property string|null $language
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingInstance whereLanguage($value)
*
* @property int|null $status
* @property float|null $amount
* @property int|null $shopping_user_id
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingInstance whereAmount($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingInstance whereShoppingUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingInstance whereStatus($value)
*
* @mixin \Eloquent
*/
class ShoppingInstance extends Model
{
protected $primaryKey = 'identifier';
public $incrementing = false;
protected $keyType = 'string';
public $paymentTypes = [
1 => 'Customer Shop',
@ -72,17 +87,30 @@ class ShoppingInstance extends Model
protected $casts = ['shopping_data' => 'array', 'amount' => 'float'];
protected $fillable = [
'identifier', 'user_shop_id', 'auth_user_id', 'status', 'payment', 'subdomain', 'language', 'country_id', 'amount', 'shopping_user_id', 'shopping_data', 'back'
'identifier',
'user_shop_id',
'auth_user_id',
'status',
'payment',
'subdomain',
'language',
'country_id',
'amount',
'shopping_user_id',
'shopping_data',
'back',
];
public function getStatus(){
public function getStatus()
{
return isset($this->statuses[$this->status]) ? $this->statuses[$this->status] : 'link_sent';
}
public function getLocale(){
public function getLocale()
{
return $this->language ? $this->language : \App::getLocale();
}
public function user_shop()
{
return $this->belongsTo('App\Models\UserShop', 'user_shop_id');
@ -93,17 +121,14 @@ class ShoppingInstance extends Model
return $this->belongsTo('App\Models\Country', 'country_id');
}
//can null
// can null
public function auth_user()
{
return $this->belongsTo('App\User','auth_user_id');
return $this->belongsTo('App\User', 'auth_user_id');
}
public function getAmountFormatted(){
public function getAmountFormatted()
{
return formatNumber($this->amount);
}
}

View file

@ -32,6 +32,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property-read int|null $shopping_payments_count
* @property-read \App\Models\ShoppingUser $shopping_user
* @property-read \App\Models\UserShop $user_shop
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder query()
@ -51,21 +52,28 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereUserShopId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereWeight($value)
*
* @property int|null $payment_for
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder wherePaymentFor($value)
*
* @property int|null $member_id
* @property string|null $mode
* @property-read \App\User|null $member
* @property-read \App\Models\UserHistory|null $user_history
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereMemberId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereMode($value)
*
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property string|null $user_deleted_at
*
* @method static \Illuminate\Database\Query\Builder|\App\Models\ShoppingOrder onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereUserDeletedAt($value)
* @method static \Illuminate\Database\Query\Builder|\App\Models\ShoppingOrder withTrashed()
* @method static \Illuminate\Database\Query\Builder|\App\Models\ShoppingOrder withoutTrashed()
*
* @property-read \App\Models\ShippingCountry $shipping_country
* @property float|null $shipping_net
* @property float|null $subtotal_ws
@ -73,40 +81,53 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property int|null $shipped
* @property string|null $tracking
* @property string|null $wp_invoice_path
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder wherePoints($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereShipped($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereShippingNet($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereSubtotalWs($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereTracking($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ShoppingOrder whereWpInvoicePath($value)
*
* @property int|null $homeparty_id
* @property array|null $api_notice
* @property int|null $api_status
* @property-read \App\Models\Homeparty|null $homeparty
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereHomepartyId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereWpNotice($value)
*
* @property array|null $tax_split
* @property-read \App\Models\UserInvoice|null $user_invoice
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\UserSalesVolume[] $user_sales_volume
* @property-read int|null $user_sales_volume_count
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereTaxSplit($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereApiNotice($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereApiStatus($value)
*
* @property-read \App\Models\ShoppingCollectOrder|null $shopping_collect_order
* @property array|null $net_split
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereNetSplit($value)
*
* @property string|null $language
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereLanguage($value)
*
* @property bool|null $is_abo
* @property int|null $abo_interval
*
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereAboInterval($value)
* @method static \Illuminate\Database\Eloquent\Builder|ShoppingOrder whereIsAbo($value)
*
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Acme\Dhl\Models\DhlShipment> $dhlOutboundShipments
* @property-read int|null $dhl_outbound_shipments_count
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Acme\Dhl\Models\DhlShipment> $dhlReturnShipments
* @property-read int|null $dhl_return_shipments_count
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Acme\Dhl\Models\DhlShipment> $dhlShipments
* @property-read int|null $dhl_shipments_count
*
* @mixin \Eloquent
*/
class ShoppingOrder extends Model
@ -114,6 +135,7 @@ class ShoppingOrder extends Model
protected $table = 'shopping_orders';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
@ -145,7 +167,7 @@ class ShoppingOrder extends Model
'api_status',
'mode',
'shipped',
'tracking'
'tracking',
];
protected $casts = [
@ -163,16 +185,16 @@ class ShoppingOrder extends Model
2 => 'shipped',
3 => 'completed',
4 => 'trade_fair',
10 => 'cancelled'
10 => 'cancelled',
];
public static $apiShippedTypes = [
0 => 'open', //(Fullfilment durch Händler)',
1 => 'process', //(Fullfilment durch MIVITA: nicht Versand)
2 => 'sent', //(Fullfilment durch MIVITA: Versand erfolgt)'
3 => 'close', //(Fullfilment durch MIVITA: Versand erfolgt)',
4 => 'trade', //(Fullfilment durch MIVITA: Versand erfolgt)',
10 => 'cancel'
0 => 'open', // (Fullfilment durch Händler)',
1 => 'process', // (Fullfilment durch MIVITA: nicht Versand)
2 => 'sent', // (Fullfilment durch MIVITA: Versand erfolgt)'
3 => 'close', // (Fullfilment durch MIVITA: Versand erfolgt)',
4 => 'trade', // (Fullfilment durch MIVITA: Versand erfolgt)',
10 => 'cancel',
];
public static $apiStatusTypes = [
@ -181,12 +203,14 @@ class ShoppingOrder extends Model
2 => 'paid',
5 => 'removed',
];
public static $apiStatusColors = [
0 => 'warning',
1 => 'warning',
2 => 'success',
5 => 'danger',
];
public static $shippedColors = [
0 => 'warning',
1 => 'info',
@ -221,11 +245,10 @@ class ShoppingOrder extends Model
8 => 'info',
9 => 'default',
10 => 'info',
11 => 'default'
11 => 'default',
];
public function shopping_user()
{
return $this->belongsTo('App\Models\ShoppingUser', 'shopping_user_id');
@ -251,12 +274,13 @@ class ShoppingOrder extends Model
return $this->belongsTo('App\Models\UserShop', 'user_shop_id');
}
//can null
// can null
public function member()
{
return $this->belongsTo('App\User', 'member_id');
}
//can null
// can null
public function auth_user()
{
return $this->belongsTo('App\User', 'auth_user_id');
@ -267,9 +291,42 @@ class ShoppingOrder extends Model
return $this->hasOne('App\Models\UserHistory', 'shopping_order_id')->latest();
}
/**
* Original-Rechnung (nicht die Stornorechnung)
*
* Unterscheidung: Die Original-Rechnung hat entweder cancellation=false/null (vor Storno)
* oder cancellation_id gesetzt (nach Storno, zeigt auf die Stornorechnung).
* Die Stornorechnung hat cancellation=true UND cancellation_id=null.
*/
public function user_invoice()
{
return $this->hasOne('App\Models\UserInvoice', 'shopping_order_id', '');
return $this->hasOne('App\Models\UserInvoice', 'shopping_order_id', 'id')
->where(function ($query) {
$query->where('cancellation', false)
->orWhereNull('cancellation')
->orWhereNotNull('cancellation_id');
});
}
/**
* Stornorechnung für diese Bestellung
*
* Die Stornorechnung hat cancellation=true und KEINEN cancellation_id
* (cancellation_id wird nur auf der Original-Rechnung gesetzt).
*/
public function user_cancellation_invoice()
{
return $this->hasOne('App\Models\UserInvoice', 'shopping_order_id', 'id')
->where('cancellation', true)
->whereNull('cancellation_id');
}
/**
* Alle Rechnungen (Original + Storno) für diese Bestellung
*/
public function user_invoices()
{
return $this->hasMany('App\Models\UserInvoice', 'shopping_order_id', 'id');
}
public function shopping_collect_order()
@ -294,7 +351,7 @@ class ShoppingOrder extends Model
public function user_sales_volume_no_userid()
{
return $this->hasOne('App\Models\UserSalesVolume', 'shopping_order_id')->where('user_id', '=', NULL)->first();
return $this->hasOne('App\Models\UserSalesVolume', 'shopping_order_id')->where('user_id', '=', null)->first();
}
public function getUserAbo()
@ -303,6 +360,7 @@ class ShoppingOrder extends Model
if ($UserAboOrder && $UserAboOrder->user_abo) {
return $UserAboOrder->user_abo;
}
return null;
}
@ -332,7 +390,8 @@ class ShoppingOrder extends Model
return $shopping_payment->reference;
}
}
return "";
return '';
}
public function getLastShoppingPaymentTransaction()
@ -346,40 +405,43 @@ class ShoppingOrder extends Model
}
}
}
return false;
}
public function getShippedType()
{
return isset(self::$shippedTypes[$this->shipped]) ? __('payment.' . self::$shippedTypes[$this->shipped]) : "";
return isset(self::$shippedTypes[$this->shipped]) ? __('payment.'.self::$shippedTypes[$this->shipped]) : '';
}
public static function getTransShippedType()
{
$ret = [];
foreach (self::$shippedTypes as $key => $val) {
$ret[$key] = trans('payment.' . $val);
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
public function getAPIShippedType()
{
return isset(self::$apiShippedTypes[$this->shipped]) ? self::$apiShippedTypes[$this->shipped] : "free";
return isset(self::$apiShippedTypes[$this->shipped]) ? self::$apiShippedTypes[$this->shipped] : 'free';
}
public function getShippedColor()
{
return isset(self::$shippedColors[$this->shipped]) ? self::$shippedColors[$this->shipped] : "default";
return isset(self::$shippedColors[$this->shipped]) ? self::$shippedColors[$this->shipped] : 'default';
}
public function getAPIStatusType()
{
return isset(self::$apiStatusTypes[$this->api_status]) ? __('payment.' . self::$apiStatusTypes[$this->api_status]) : "bestellt";
return isset(self::$apiStatusTypes[$this->api_status]) ? __('payment.'.self::$apiStatusTypes[$this->api_status]) : 'bestellt';
}
public function getAPIStatusColor()
{
return isset(self::$apiStatusColors[$this->api_status]) ? self::$apiStatusColors[$this->api_status] : "warning";
return isset(self::$apiStatusColors[$this->api_status]) ? self::$apiStatusColors[$this->api_status] : 'warning';
}
public function getFormattedTotal()
@ -429,7 +491,7 @@ class ShoppingOrder extends Model
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? formatNumber($this->attributes['points']) : "";
return isset($this->attributes['points']) ? formatNumber($this->attributes['points']) : '';
}
public function getPriceVkNetBy($product_id)
@ -439,16 +501,18 @@ class ShoppingOrder extends Model
return $product->getPriceWith(true, false, $this->shipping_country->country);
}
}
return 0;
}
public function getPaymentForType()
{
return isset(self::$paymentForTypes[$this->payment_for]) ? __('payment.' . self::$paymentForTypes[$this->payment_for]) : "";
return isset(self::$paymentForTypes[$this->payment_for]) ? __('payment.'.self::$paymentForTypes[$this->payment_for]) : '';
}
public function getPaymentForColor()
{
return isset(self::$paymentForColors[$this->payment_for]) ? self::$paymentForColors[$this->payment_for] : "";
return isset(self::$paymentForColors[$this->payment_for]) ? self::$paymentForColors[$this->payment_for] : '';
}
public function getUserDiscount()
@ -459,6 +523,7 @@ class ShoppingOrder extends Model
if ($this->member && $this->member->user_level) {
return $this->member->user_level->getFormattedMargin();
}
return 0;
}
@ -470,21 +535,49 @@ class ShoppingOrder extends Model
$count += $shopping_order_item->qty;
}
}
return $count;
}
public function isInvoice()
{
return $this->user_invoice ? true : false;
}
/**
* Prüft ob eine Stornorechnung für diese Bestellung existiert.
* Die echte Stornorechnung hat cancellation=true und cancellation_id=null.
*/
public function isCancellationInvoice()
{
return \App\Models\UserInvoice::where('shopping_order_id', $this->id)
->where('cancellation', true)
->whereNull('cancellation_id')
->exists();
}
/**
* Holt die Stornorechnung für diese Bestellung.
* Die echte Stornorechnung hat cancellation=true und cancellation_id=null.
*/
public function getCancellationInvoice()
{
return \App\Models\UserInvoice::where('shopping_order_id', $this->id)
->where('cancellation', true)
->whereNull('cancellation_id')
->first();
}
public function getStatusByOrder()
{
if ($this->payment_for) {
if ($this->payment_for === 6) { //Kunde-Shop
if ($this->payment_for === 6) { // Kunde-Shop
return 2;
}
return 1;
}
return 0;
}
@ -538,7 +631,7 @@ class ShoppingOrder extends Model
}
if (isset($tax_split[5])) {
if (!isset($tax_split[16])) {
if (! isset($tax_split[16])) {
$tax_split[16] = ['vk_tax' => $order_vk_tax, 'ek_tax' => $order_ek_tax];
$net_split[16] = ['vk_net' => $order_vk_net, 'ek_net' => $order_ek_net];
}
@ -548,7 +641,7 @@ class ShoppingOrder extends Model
$net_split[16]['ek_net'] = round($net_split[16]['ek_net'] - $net_split[5]['ek_net'], 2);
}
if (isset($tax_split[7])) {
if (!isset($tax_split[19])) {
if (! isset($tax_split[19])) {
$tax_split[19] = ['vk_tax' => $order_vk_tax, 'ek_tax' => $order_ek_tax];
$net_split[19] = ['vk_net' => $order_vk_net, 'ek_net' => $order_ek_net];
}
@ -558,7 +651,6 @@ class ShoppingOrder extends Model
$net_split[19]['ek_net'] = round($net_split[19]['ek_net'] - $net_split[7]['ek_net'], 2);
}
foreach ($tax_split as $key => $value) {
$tax_split[$key]['vk_tax'] = number_format($value['vk_tax'], 2);
$tax_split[$key]['ek_tax'] = number_format($value['ek_tax'], 2);
@ -569,14 +661,13 @@ class ShoppingOrder extends Model
$net_split[$key]['ek_net'] = number_format($value['ek_net'], 2);
}
}
if (!isset($tax_split[16]) && !isset($tax_split[19])) {
$tax_split = NULL;
if (! isset($tax_split[16]) && ! isset($tax_split[19])) {
$tax_split = null;
}
if (!isset($net_split[16]) && !isset($net_split[19])) {
$net_split = NULL;
if (! isset($net_split[16]) && ! isset($net_split[19])) {
$net_split = null;
}
$this->tax_split = $tax_split;
$this->net_split = $net_split;
$this->save();
@ -584,8 +675,8 @@ class ShoppingOrder extends Model
public function makeTaxSplit()
{
$tax_split = NULL;
$net_split = NULL;
$tax_split = null;
$net_split = null;
if ($this->tax > 0) {
$tax_split = [];
@ -613,7 +704,7 @@ class ShoppingOrder extends Model
}
if (isset($tax_split[5])) {
if (!isset($tax_split[16])) {
if (! isset($tax_split[16])) {
$tax_split[16] = $this->tax;
$net_split[16] = $this->subtotal_ws;
}
@ -621,7 +712,7 @@ class ShoppingOrder extends Model
$net_split[16] = round($net_split[16] - $net_split[5], 2);
}
if (isset($tax_split[7])) {
if (!isset($tax_split[19])) {
if (! isset($tax_split[19])) {
$tax_split[19] = $this->tax;
$net_split[19] = $this->subtotal_ws;
}
@ -647,12 +738,12 @@ class ShoppingOrder extends Model
if ($this->shopping_user) {
$fullname = $this->shopping_user->getFullNameAsArray();
$ret = "";
$ret .= $fullname['company'] ? $fullname['company'] . ' | ' : '';
$ret .= $fullname['salutation'] ? \App\Services\HTMLHelper::getSalutationLang($fullname['salutation']) . ' ' : '';
$ret .= $fullname['firstname'] ? $fullname['firstname'] . ' ' : '';
$ret = '';
$ret .= $fullname['company'] ? $fullname['company'].' | ' : '';
$ret .= $fullname['salutation'] ? \App\Services\HTMLHelper::getSalutationLang($fullname['salutation']).' ' : '';
$ret .= $fullname['firstname'] ? $fullname['firstname'].' ' : '';
$ret .= $fullname['lastname'] ? $fullname['lastname'] : '';
$ret .= $fullname['email'] ? ' | ' . $fullname['email'] . '' : '';
$ret .= $fullname['email'] ? ' | '.$fullname['email'].'' : '';
}
return $ret;

View file

@ -243,9 +243,43 @@ class ShoppingUser extends Model
return $this->hasOne('App\Models\ShoppingOrder', 'shopping_user_id');
}
public function getLocale()
/**
* Accessor für das language Attribut.
* Gibt die App-Locale zurück, wenn keine Sprache gesetzt ist.
*
* @param string|null $value
* @return string Sprachcode (de, en, es)
*/
public function getLanguageAttribute($value): string
{
return $this->language ? $this->language : \App::getLocale();
return $value ?: \App::getLocale();
}
/**
* Alias für getLanguageAttribute - für Konsistenz mit anderen Models.
*
* @return string Sprachcode (de, en, es)
*/
public function getLocale(): string
{
return $this->language;
}
/**
* Liefert die verfügbaren Sprachen aus der Config als Array für Select-Felder.
*
* @return array ['code' => 'Native Name', ...]
*/
public static function getAvailableLanguages(): array
{
$locales = config('localization.supportedLocales', []);
$languages = [];
foreach ($locales as $code => $locale) {
$languages[$code] = $locale['native'] ?? $locale['name'] ?? $code;
}
return $languages;
}
public function setNotice($key, $value)

View file

@ -6,11 +6,11 @@
namespace App\Models;
use App\Services\Util;
use App\User;
use Carbon\Carbon;
use App\Services\Util;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
@ -34,7 +34,6 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property Carbon|null $user_deleted_at
* @property User $user
* @property Collection|UserAboOrder[] $user_abo_orders
* @package App\Models
* @property int|null $member_id
* @property int $shopping_user_id
* @property string|null $email
@ -48,6 +47,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property-read Collection<int, \App\Models\UserAboItem> $user_abo_items
* @property-read int|null $user_abo_items_count
* @property-read int|null $user_abo_orders_count
*
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo onlyTrashed()
@ -76,177 +76,213 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo whereWallettype($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withoutTrashed()
*
* @mixin \Eloquent
*/
class UserAbo extends Model
{
use SoftDeletes;
protected $table = 'user_abos';
use SoftDeletes;
protected $casts = [
'user_id' => 'int',
'member_id' => 'int',
'shopping_user_id' => 'int',
'payone_userid' => 'int',
'active' => 'bool',
'status' => 'int',
'abo_interval' => 'int',
'amount' => 'int',
'start_date' => 'datetime',
'last_date' => 'datetime',
'next_date' => 'datetime',
'cancel_date' => 'datetime',
'user_deleted_at' => 'datetime',
'carddata' => 'array'
protected $table = 'user_abos';
];
protected $casts = [
'user_id' => 'int',
'member_id' => 'int',
'shopping_user_id' => 'int',
'payone_userid' => 'int',
'active' => 'bool',
'status' => 'int',
'abo_interval' => 'int',
'amount' => 'int',
'start_date' => 'datetime',
'last_date' => 'datetime',
'next_date' => 'datetime',
'cancel_date' => 'datetime',
'user_deleted_at' => 'datetime',
'carddata' => 'array',
protected $fillable = [
'user_id',
'member_id',
'shopping_user_id',
'is_for',
'email',
'payone_userid',
'clearingtype',
'wallettype',
'carddata',
'amount',
'active',
'status',
'abo_interval',
'start_date',
'last_date',
'next_date',
'cancel_date',
'user_deleted_at'
];
];
public static $aboDeliveryDays = [5, 10, 20, 25];
protected $fillable = [
'user_id',
'member_id',
'shopping_user_id',
'is_for',
'email',
'payone_userid',
'clearingtype',
'wallettype',
'carddata',
'amount',
'active',
'status',
'abo_interval',
'start_date',
'last_date',
'next_date',
'cancel_date',
'user_deleted_at',
];
public static $statusTypes = [
0 => 'abo_new',
1 => 'abo_new',
2 => 'abo_okay',
3 => 'abo_hold',
4 => 'abo_cancel',
5 => 'abo_finish',
6 => 'abo_inactive',
7 => 'abo_grace'
];
public static $aboDeliveryDays = [5, 10, 20, 25];
public static $statusColors = [
0 => 'success',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'danger',
5 => 'info',
6 => 'warning',
7 => 'danger'
];
public static $statusTypes = [
0 => 'abo_new',
1 => 'abo_new',
2 => 'abo_okay',
3 => 'abo_hold',
4 => 'abo_cancel',
5 => 'abo_finish',
6 => 'abo_inactive',
7 => 'abo_grace',
];
public static $statusColors = [
0 => 'success',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'danger',
5 => 'info',
6 => 'warning',
7 => 'danger',
];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function member()
{
return $this->belongsTo(User::class, 'member_id');
}
public function member()
{
return $this->belongsTo(User::class, 'member_id');
}
public function shopping_user()
{
return $this->belongsTo('App\Models\ShoppingUser', 'shopping_user_id');
}
public function shopping_user()
{
return $this->belongsTo('App\Models\ShoppingUser', 'shopping_user_id');
}
public function user_abo_orders()
{
return $this->hasMany(UserAboOrder::class);
}
public function user_abo_orders()
{
return $this->hasMany(UserAboOrder::class);
}
public function user_abo_items()
{
return $this->hasMany(UserAboItem::class);
}
public function user_abo_items()
{
return $this->hasMany(UserAboItem::class);
}
public function user_abo_item_histories()
{
return $this->hasMany(UserAboItemHistory::class);
}
public function getCountOrders()
{
//sind bezahlte Bestellungen
return $this->user_abo_orders->where('status', '>=', 2)->count();
}
public function getInitialItems()
{
return $this->user_abo_item_histories()
->where('is_initial', true)
->where('comp', 0)
->orderBy('created_at')
->get();
}
public function getCountPaidOrders()
{
//sind bezahlte Bestellungen
return $this->user_abo_orders->where('status', '>=', 2)->where('paid', true)->count();
}
public function getInitialCompItems()
{
return $this->user_abo_item_histories()
->where('is_initial', true)
->where('comp', '>', 0)
->orderBy('comp')
->get();
}
public function setStartDateAttribute($value)
{
$this->attributes['start_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getStartDateAttribute()
{
return $this->attributes['start_date'] ? Carbon::parse($this->attributes['start_date'])->format(\Util::formatDateDB()) : '';
}
public function getChangeHistory()
{
return $this->user_abo_item_histories()
->where('is_initial', false)
->orderByDesc('created_at')
->get();
}
public function setLastDateAttribute($value)
{
$this->attributes['last_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getLastDateAttribute()
{
return $this->attributes['last_date'] ? Carbon::parse($this->attributes['last_date'])->format(\Util::formatDateDB()) : '';
}
public function getCountOrders()
{
// sind bezahlte Bestellungen
return $this->user_abo_orders->where('status', '>=', 2)->count();
}
public function setNextDateAttribute($value)
{
$this->attributes['next_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getNextDateAttribute()
{
return $this->attributes['next_date'] ? Carbon::parse($this->attributes['next_date'])->format(\Util::formatDateDB()) : '';
}
public function getCountPaidOrders()
{
// sind bezahlte Bestellungen
return $this->user_abo_orders->where('status', '>=', 2)->where('paid', true)->count();
}
public function setCancelDateAttribute($value)
{
$this->attributes['cancel_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getCancelDateAttribute()
{
return $this->attributes['cancel_date'] ? Carbon::parse($this->attributes['cancel_date'])->format(\Util::formatDateDB()) : '';
}
public function setStartDateAttribute($value)
{
$this->attributes['start_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getFormattedAmount()
{
return isset($this->attributes['amount']) ? Util::formatNumber($this->attributes['amount'] / 100) : "";
}
public function getIsForFormated()
{
return $this->attributes['is_for'] === 'me' ? '<span class="badge badge-outline-warning-dark">' . __('tables.adviser') . '</span>' : '<span class="badge badge-outline-info">' . __('tables.customer') . '</span>';
}
public function getStartDateAttribute()
{
return $this->attributes['start_date'] ? Carbon::parse($this->attributes['start_date'])->format(\Util::formatDateDB()) : '';
}
public function getStatusFormated()
{
return '<span class="badge badge-pill badge-' . $this->getStatusColor() . '">' . $this->getStatusType() . '</span>';
}
public function setLastDateAttribute($value)
{
$this->attributes['last_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('abo.' . self::$statusTypes[$this->status]) : "";
}
public function getLastDateAttribute()
{
return $this->attributes['last_date'] ? Carbon::parse($this->attributes['last_date'])->format(\Util::formatDateDB()) : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
}
public function setNextDateAttribute($value)
{
$this->attributes['next_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getPaymentType()
{
return $this->clearingtype === 'wlt' ? __('payment.paypal') : __('payment.credit_card');
}
public function getNextDateAttribute()
{
return $this->attributes['next_date'] ? Carbon::parse($this->attributes['next_date'])->format(\Util::formatDateDB()) : '';
}
public function setCancelDateAttribute($value)
{
$this->attributes['cancel_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getCancelDateAttribute()
{
return $this->attributes['cancel_date'] ? Carbon::parse($this->attributes['cancel_date'])->format(\Util::formatDateDB()) : '';
}
public function getFormattedAmount()
{
return isset($this->attributes['amount']) ? Util::formatNumber($this->attributes['amount'] / 100) : '';
}
public function getIsForFormated()
{
return $this->attributes['is_for'] === 'me' ? '<span class="badge badge-outline-warning-dark">'.__('tables.adviser').'</span>' : '<span class="badge badge-outline-info">'.__('tables.customer').'</span>';
}
public function getStatusFormated()
{
return '<span class="badge badge-pill badge-'.$this->getStatusColor().'">'.$this->getStatusType().'</span>';
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('abo.'.self::$statusTypes[$this->status]) : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getPaymentType()
{
return $this->clearingtype === 'wlt' ? __('payment.paypal') : __('payment.credit_card');
}
}

View file

@ -0,0 +1,187 @@
<?php
namespace App\Models;
use App\Services\Util;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class UserAboItemHistory extends Model
{
protected $table = 'user_abo_item_histories';
const ACTION_INITIAL = 'initial';
const ACTION_ADDED = 'added';
const ACTION_REMOVED = 'removed';
const ACTION_QTY_CHANGED = 'qty_changed';
const ACTION_COMP_CHANGED = 'comp_product_changed';
const ACTION_COMP_ADDED = 'comp_added';
const ACTION_COMP_REMOVED = 'comp_removed';
const ACTION_ROLLBACK = 'rollback';
const CHANNEL_ADMIN = 'admin';
const CHANNEL_USER_ME = 'user_me';
const CHANNEL_USER_OT = 'user_ot';
const CHANNEL_PORTAL = 'portal';
const CHANNEL_SYSTEM = 'system';
public static $actionLabels = [
'initial' => 'abo_history.action_initial',
'added' => 'abo_history.action_added',
'removed' => 'abo_history.action_removed',
'qty_changed' => 'abo_history.action_qty_changed',
'comp_product_changed' => 'abo_history.action_comp_changed',
'comp_added' => 'abo_history.action_comp_added',
'comp_removed' => 'abo_history.action_comp_removed',
'rollback' => 'abo_history.action_rollback',
];
public static $actionColors = [
'initial' => 'info',
'added' => 'success',
'removed' => 'danger',
'qty_changed' => 'warning',
'comp_product_changed' => 'primary',
'comp_added' => 'success',
'comp_removed' => 'danger',
'rollback' => 'dark',
];
public static $channelLabels = [
'admin' => 'abo_history.channel_admin',
'user_me' => 'abo_history.channel_user_me',
'user_ot' => 'abo_history.channel_user_ot',
'portal' => 'abo_history.channel_portal',
'system' => 'abo_history.channel_system',
];
public static $channelColors = [
'admin' => 'danger',
'user_me' => 'warning',
'user_ot' => 'info',
'portal' => 'secondary',
'system' => 'default',
];
protected $casts = [
'user_abo_id' => 'int',
'user_abo_item_id' => 'int',
'product_id' => 'int',
'unit_price' => 'float',
'total_price' => 'float',
'qty_before' => 'int',
'qty_after' => 'int',
'old_product_id' => 'int',
'comp' => 'int',
'changed_by_user_id' => 'int',
'is_initial' => 'bool',
];
protected $fillable = [
'user_abo_id',
'user_abo_item_id',
'product_id',
'action',
'product_name',
'product_number',
'unit_price',
'total_price',
'qty_before',
'qty_after',
'old_product_id',
'old_product_name',
'comp',
'changed_by_user_id',
'changed_by_name',
'channel',
'batch_id',
'is_initial',
];
public function user_abo()
{
return $this->belongsTo(UserAbo::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
public function old_product()
{
return $this->belongsTo(Product::class, 'old_product_id');
}
public function changed_by()
{
return $this->belongsTo(User::class, 'changed_by_user_id');
}
public function getActionBadge()
{
$label = isset(self::$actionLabels[$this->action]) ? __(self::$actionLabels[$this->action]) : $this->action;
$color = self::$actionColors[$this->action] ?? 'secondary';
return '<span class="badge badge-'.$color.'">'.$label.'</span>';
}
public function getChannelBadge()
{
$label = isset(self::$channelLabels[$this->channel]) ? __(self::$channelLabels[$this->channel]) : $this->channel;
$color = self::$channelColors[$this->channel] ?? 'secondary';
return '<span class="badge badge-outline-'.$color.'">'.$label.'</span>';
}
public function getChangeDescription()
{
switch ($this->action) {
case self::ACTION_INITIAL:
return __('abo_history.desc_initial', ['qty' => $this->qty_after]);
case self::ACTION_ADDED:
return __('abo_history.desc_added', ['qty' => $this->qty_after]);
case self::ACTION_REMOVED:
return __('abo_history.desc_removed');
case self::ACTION_QTY_CHANGED:
return __('abo_history.desc_qty_changed', ['from' => $this->qty_before, 'to' => $this->qty_after]);
case self::ACTION_COMP_CHANGED:
return __('abo_history.desc_comp_changed', ['old' => $this->old_product_name]);
case self::ACTION_COMP_ADDED:
return __('abo_history.desc_comp_added');
case self::ACTION_COMP_REMOVED:
return __('abo_history.desc_comp_removed');
case self::ACTION_ROLLBACK:
return __('abo_history.desc_rollback');
default:
return '';
}
}
public function getFormattedUnitPrice()
{
return Util::formatNumber($this->unit_price);
}
public function getFormattedTotalPrice()
{
return Util::formatNumber($this->total_price);
}
public function getFormattedDate()
{
return Carbon::parse($this->created_at)->format('d.m.Y H:i');
}
}

View file

@ -2,10 +2,9 @@
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
/**
* App\Models\UserAccount
@ -18,6 +17,7 @@ use Carbon\Carbon;
* @property-read \App\Models\Country $pre_mobil
* @property-read \App\Models\Country $pre_phone
* @property-read \App\User $user
*
* @method static bool|null forceDelete()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount newQuery()
@ -26,6 +26,7 @@ use Carbon\Carbon;
* @method static bool|null restore()
* @method static \Illuminate\Database\Query\Builder|\App\Models\UserAccount withTrashed()
* @method static \Illuminate\Database\Query\Builder|\App\Models\UserAccount withoutTrashed()
*
* @property int $id
* @property string|null $salutation
* @property string|null $first_name
@ -63,6 +64,7 @@ use Carbon\Carbon;
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property-read \App\Models\Country $shipping_country
* @property-read \App\Models\Country|null $shipping_pre_phone
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereAddress($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereAddress2($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereBirthday($value)
@ -100,41 +102,53 @@ use Carbon\Carbon;
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereWebsite($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereZipcode($value)
*
* @property string|null $m_account
* @property string|null $m_salutation
* @property string|null $m_first_name
* @property string|null $m_last_name
* @property string|null $m_notes
* @property int|null $taxable_sales
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereMAccount($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereMFirstName($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereMLastName($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereMNotes($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereMSalutation($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereTaxableSales($value)
*
* @property array|null $payment_data
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount wherePaymentData($value)
*
* @property string|null $accepted_contract
* @property array|null $notice
*
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereAcceptedContract($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserAccount whereNotice($value)
*
* @property int $reverse_charge
* @property string|null $reverse_charge_code
* @property string|null $reverse_charge_valid
*
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereReverseCharge($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereReverseChargeCode($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereReverseChargeValid($value)
*
* @property string|null $bank_owner
* @property string|null $bank_iban
* @property string|null $bank_bic
*
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereBankBic($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereBankIban($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereBankOwner($value)
*
* @mixin \Eloquent
*/
class UserAccount extends Model
{
protected $table = 'user_accounts';
protected $fillable = [
'm_account',
'm_salutation',
@ -178,19 +192,20 @@ class UserAccount extends Model
'bank_owner',
'bank_iban',
'bank_bic',
'notice'
'notice',
'language',
];
//'reverse_charge', 'reverse_charge_valid'
// 'reverse_charge', 'reverse_charge_valid'
protected $casts = [
'payment_data' => 'array',
'notice' => 'array',
//'reverse_charge' => 'bool'
// 'reverse_charge' => 'bool'
];
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $dates = ['deleted_at'];
public function user()
{
@ -224,38 +239,42 @@ class UserAccount extends Model
public function getBirthdayAttribute($value)
{
if (!$value) {
return "";
if (! $value) {
return '';
}
return Carbon::parse($value)->format(\Util::formatDateDB());
}
public function setBirthdayAttribute($value)
{
$this->attributes['birthday'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['birthday'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getDataProtectionFormat()
{
if (!$this->attributes['data_protection']) {
return "";
if (! $this->attributes['data_protection']) {
return '';
}
return Carbon::parse($this->attributes['data_protection'])->format(\Util::formatDateTimeDB());
}
public function getAcceptContractFormat()
{
if (!$this->attributes['accept_contract']) {
return "";
if (! $this->attributes['accept_contract']) {
return '';
}
return Carbon::parse($this->attributes['accept_contract'])->format(\Util::formatDateTimeDB());
}
public function getReverseChargeValidFormat()
{
if (!$this->attributes['reverse_charge_valid']) {
return "";
if (! $this->attributes['reverse_charge_valid']) {
return '';
}
return Carbon::parse($this->attributes['reverse_charge_valid'])->format(\Util::formatDateTimeDB());
}
@ -268,10 +287,12 @@ class UserAccount extends Model
if ($as) {
return $as;
}
return true;
}
}
return "";
return '';
}
public function setNotice($key, $value)
@ -289,35 +310,77 @@ class UserAccount extends Model
public function getPhoneNumber()
{
if ($this->mobil && $this->mobil !== "") {
return ($this->pre_mobil ? $this->pre_mobil->phone : '') . " " . $this->mobil;
if ($this->mobil && $this->mobil !== '') {
return ($this->pre_mobil ? $this->pre_mobil->phone : '').' '.$this->mobil;
}
if ($this->phone && $this->phone !== "") {
return ($this->pre_phone ? $this->pre_phone->phone : '') . " " . $this->phone;
if ($this->phone && $this->phone !== '') {
return ($this->pre_phone ? $this->pre_phone->phone : '').' '.$this->phone;
}
}
public function getPhoneFull()
{
if ($this->phone && $this->phone !== "") {
return ($this->pre_phone ? $this->pre_phone->phone : '') . " " . $this->phone;
if ($this->phone && $this->phone !== '') {
return ($this->pre_phone ? $this->pre_phone->phone : '').' '.$this->phone;
}
return "";
return '';
}
public function getMobilFull()
{
if ($this->mobil && $this->mobil !== "") {
return ($this->pre_mobil ? $this->pre_mobil->phone : '') . " " . $this->mobil;
if ($this->mobil && $this->mobil !== '') {
return ($this->pre_mobil ? $this->pre_mobil->phone : '').' '.$this->mobil;
}
return "";
return '';
}
public function getShippingPhoneFull()
{
if ($this->shipping_phone && $this->shipping_phone !== "") {
return ($this->shipping_pre_phone ? $this->shipping_pre_phone->phone : '') . " " . $this->shipping_phone;
if ($this->shipping_phone && $this->shipping_phone !== '') {
return ($this->shipping_pre_phone ? $this->shipping_pre_phone->phone : '').' '.$this->shipping_phone;
}
return "";
return '';
}
/**
* Accessor für das language Attribut.
* Gibt die App-Locale zurück, wenn keine Sprache gesetzt ist.
*
* @param string|null $value
* @return string Sprachcode (de, en, es)
*/
public function getLanguageAttribute($value): string
{
return $value ?: \App::getLocale();
}
/**
* Alias für getLanguageAttribute - für Konsistenz mit anderen Models.
*
* @return string Sprachcode (de, en, es)
*/
public function getLocale(): string
{
return $this->language;
}
/**
* Liefert die verfügbaren Sprachen aus der Config als Array für Select-Felder.
*
* @return array ['code' => 'Native Name', ...]
*/
public static function getAvailableLanguages(): array
{
$locales = config('localization.supportedLocales', []);
$languages = [];
foreach ($locales as $code => $locale) {
$languages[$code] = $locale['native'] ?? $locale['name'] ?? $code;
}
return $languages;
}
}

View file

@ -8,8 +8,8 @@ namespace App\Models;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
@ -41,9 +41,9 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property string|null $deleted_at
* @property User $user
* @property Collection|UserCreditItem[] $user_credit_items
* @package App\Models
* @property bool $taxable
* @property-read int|null $user_credit_items_count
*
* @method static \Illuminate\Database\Eloquent\Builder|UserCredit newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserCredit newQuery()
* @method static \Illuminate\Database\Query\Builder|UserCredit onlyTrashed()
@ -75,146 +75,246 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|UserCredit whereYear($value)
* @method static \Illuminate\Database\Query\Builder|UserCredit withTrashed()
* @method static \Illuminate\Database\Query\Builder|UserCredit withoutTrashed()
*
* @mixin \Eloquent
*/
class UserCredit extends Model
{
use SoftDeletes;
protected $table = 'user_credits';
use SoftDeletes;
protected $casts = [
'user_id' => 'int',
'month' => 'int',
'year' => 'int',
'number' => 'int',
'net' => 'float',
'tax_rate' => 'float',
'tax' => 'float',
'taxable' => 'int',
'total' => 'float',
'paid_out' => 'bool',
'cancellation' => 'bool',
'cancellation_id' => 'int',
'status' => 'int',
'infos' => 'array'
];
protected $table = 'user_credits';
protected $dates = [
'date',
'paid_out_date',
'cancellation_date'
];
protected $casts = [
'user_id' => 'int',
'month' => 'int',
'year' => 'int',
'number' => 'int',
'net' => 'float',
'tax_rate' => 'float',
'tax' => 'float',
'taxable' => 'int',
'total' => 'float',
'paid_out' => 'bool',
'cancellation' => 'bool',
'cancellation_id' => 'int',
'status' => 'int',
'infos' => 'array',
];
protected $fillable = [
'user_id',
'month',
'year',
'date',
'full_number',
'number',
'net',
'tax_rate',
'tax',
'total',
'taxable',
'filename',
'dir',
'disk',
'infos',
'paid_out',
'paid_out_date',
'cancellation',
'cancellation_id',
'cancellation_date',
'status'
];
protected $dates = [
'date',
'paid_out_date',
'cancellation_date',
];
public static $statusTypes = [
protected $fillable = [
'user_id',
'month',
'year',
'date',
'full_number',
'number',
'net',
'tax_rate',
'tax',
'total',
'taxable',
'filename',
'dir',
'disk',
'infos',
'paid_out',
'paid_out_date',
'cancellation',
'cancellation_id',
'cancellation_date',
'status',
];
public static $statusTypes = [
0 => 'open',
1 => 'paid',
2 => 'check',
10 => 'cancelled'
10 => 'cancelled',
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
1 => 'success',
2 => 'secondary',
10 => 'danger',
10 => 'danger',
];
public static $taxableTypes = [
public static $taxableTypes = [
0 => '',
1 => 'umsatzsteuerpflichtig / DE', //payment.to_sales_tax_de
2 => 'nicht umsatzsteuerpflichtig / DE', //payment.not_to_sales_tax_de
3 => 'nicht umsatzsteuerpflichtig / Ausland' //payment.not_to_sales_tax_foreign
1 => 'umsatzsteuerpflichtig / DE', // payment.to_sales_tax_de
2 => 'nicht umsatzsteuerpflichtig / DE', // payment.not_to_sales_tax_de
3 => 'nicht umsatzsteuerpflichtig / Ausland', // payment.not_to_sales_tax_foreign
];
public function user()
{
return $this->belongsTo(User::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function user_credit_items()
{
return $this->hasMany(UserCreditItem::class);
}
public function user_credit_items()
{
return $this->hasMany(UserCreditItem::class);
}
public function isCredit(){
public function isCredit()
{
return $this->filename ? true : false;
}
public function getDateAttribute($value)
public function getDateAttribute($value)
{
return $value ? Carbon::parse($value)->format(\Util::formatDateDB()) : "";
return $value ? Carbon::parse($value)->format(\Util::formatDateDB()) : '';
}
public function setDateAttribute( $value ) {
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getDateRaw(){
return isset($this->attributes['date']) ? $this->attributes['date'] : NULL;
public function setDateAttribute($value)
{
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getFormattedTax()
public function getDateRaw()
{
return isset($this->attributes['date']) ? $this->attributes['date'] : null;
}
public function getFormattedTax()
{
return formatNumber($this->attributes['tax']);
}
public function getFormattedNet()
public function getFormattedNet()
{
return formatNumber($this->attributes['net']);
}
public function getFormattedTotal()
public function getFormattedTotal()
{
return formatNumber($this->attributes['total']);
}
public function getStatusType(){
//trans('payment.cancelled')
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : "";
public function getStatusType()
{
// trans('payment.cancelled')
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : '';
}
public function getStatusColor(){
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public static function getTransStatusType(){
$ret = [];
foreach(self::$statusTypes as $key=>$val){
$ret[$key] = trans('payment.'.$val);
}
return $ret;
public static function getTransStatusType()
{
$ret = [];
foreach (self::$statusTypes as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
public function getDownloadPath($full = false){
if(!$full){
public function getDownloadPath($full = false)
{
if (! $full) {
return $this->dir.$this->filename;
}
return \Storage::disk($this->disk)->path($this->dir.$this->filename);
}
/**
* Gibt den Download-Pfad für die lokalisierte Gutschrift zurück.
* Bei 'de' oder nicht vorhandener Locale-Version wird das Original zurückgegeben.
*
* @param string|null $locale Sprachcode (de, en, es)
* @param bool $full Vollständiger Dateisystempfad oder relativer Pfad
* @return string
*/
public function getDownloadPathLocale($locale = null, $full = false)
{
// Bei Deutsch oder keiner Angabe: Original zurückgeben
if (! $locale || $locale === 'de') {
return $this->getDownloadPath($full);
}
// Dateiname mit Locale-Suffix
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
// Prüfen ob Locale-Version existiert, sonst Fallback auf DE
if (! \Storage::disk($this->disk)->exists($path)) {
return $this->getDownloadPath($full);
}
return $full ? \Storage::disk($this->disk)->path($path) : $path;
}
/**
* Gibt den lokalisierten Dateinamen für die Gutschrift zurück.
*
* @param string|null $locale
* @return string
*/
public function getFilenameLocale($locale = null)
{
if (! $locale || $locale === 'de') {
return $this->filename;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
// Fallback auf Original wenn nicht vorhanden
if (! \Storage::disk($this->disk)->exists($path)) {
return $this->filename;
}
return $filename;
}
/**
* Gibt alle verfügbaren lokalisierten Versionen der Gutschrift zurück (außer DE).
*
* @return array Array mit Sprachcodes, z.B. ['en', 'es']
*/
public function getAvailableLocales(): array
{
$availableTemplates = config('localization.availableTemplates', ['de']);
$locales = [];
foreach ($availableTemplates as $locale) {
if ($locale === 'de') {
continue;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
if (\Storage::disk($this->disk)->exists($path)) {
$locales[] = $locale;
}
}
return $locales;
}
/**
* Prüft ob eine lokalisierte Version für die angegebene Sprache existiert.
*/
public function hasLocale(string $locale): bool
{
if ($locale === 'de') {
return true;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
return \Storage::disk($this->disk)->exists($path);
}
}

View file

@ -25,8 +25,8 @@ use Illuminate\Database\Eloquent\Model;
* @property Carbon|null $updated_at
* @property UserCredit|null $user_credit
* @property User $user
* @package App\Models
* @property int|null $user_business_id
*
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem query()
@ -40,103 +40,109 @@ use Illuminate\Database\Eloquent\Model;
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem whereUserBusinessId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem whereUserCreditId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem whereUserId($value)
*
* @property int|null $from_month
* @property int|null $from_year
*
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem whereFromMonth($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserCreditItem whereFromYear($value)
*
* @mixin \Eloquent
*/
class UserCreditItem extends Model
{
public static $statusTypes = [
1 => 'commission_shop',
2 => 'commission_payline',
3 => 'credit_added',
4 => 'commission',
5 => 'commission_growth_bonus',
public static $statusTypes = [
1 => 'commission_shop',
2 => 'commission_payline',
3 => 'credit_added',
4 => 'commission',
5 => 'commission_growth_bonus',
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'info',
5 => 'secondary',
10 => 'danger',
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'info',
5 => 'secondary',
10 => 'danger',
];
protected $table = 'user_credit_items';
protected $table = 'user_credit_items';
protected $casts = [
'user_id' => 'int',
'user_credit_id' => 'int',
'user_business_id' => 'int',
'credit' => 'float',
'status' => 'int',
'from_month' => 'int',
'from_year' => 'int',
'paid' => 'bool'
];
protected $casts = [
'user_id' => 'int',
'user_credit_id' => 'int',
'user_business_id' => 'int',
'credit' => 'float',
'status' => 'int',
'from_month' => 'int',
'from_year' => 'int',
'paid' => 'bool',
];
protected $fillable = [
'user_id',
'user_credit_id',
'user_business_id',
'credit',
'message',
'status',
'from_month',
'from_year',
'paid'
];
protected $fillable = [
'user_id',
'user_credit_id',
'user_business_id',
'credit',
'message',
'status',
'from_month',
'from_year',
'paid',
];
public function user_credit()
{
return $this->belongsTo(UserCredit::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function deleteTime(){
$time = '+100 min';
if(Carbon::parse($this->created_at)->modify($time)->gt(Carbon::now())){
return Carbon::now()->diffInMinutes(Carbon::parse($this->created_at)->modify($time));
}
return false;
}
public function getStatusType(){
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : "";
public function user_credit()
{
return $this->belongsTo(UserCredit::class);
}
public function getStatusColor(){
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
public function user()
{
return $this->belongsTo(User::class);
}
public function getTransMessage(){
$ret = "";
if(strpos($this->message, '#')){
$em = explode("#", $this->message);
if(isset($em[0])){ //Provision
$ret .= trans($em[0])." ";
}
if(isset($em[1])){ //month
$ret .= HTMLHelper::getMonth($em[1])." ";
}
if(isset($em[2])){ //year
$ret .= $em[2];
}
}
return $ret;
}
public function deleteTime()
{
$time = '+100 min';
if (Carbon::parse($this->created_at)->modify($time)->gt(Carbon::now())) {
return Carbon::now()->diffInMinutes(Carbon::parse($this->created_at)->modify($time));
}
return false;
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getTransMessage()
{
$ret = '';
if (strpos($this->message, '#')) {
$em = explode('#', $this->message);
if (isset($em[0])) { // Provision
$ret .= trans($em[0]).' ';
}
if (isset($em[1])) { // month
$ret .= HTMLHelper::getMonth($em[1]).' ';
}
if (isset($em[2])) { // year
$ret .= $em[2];
}
} else {
$ret = $this->message;
}
return $ret;
}
}

View file

@ -32,12 +32,12 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property Carbon|null $updated_at
* @property string|null $deleted_at
* @property ShoppingOrder $shopping_order
* @package App\Models
* @property string|null $filename
* @property string|null $dir
* @property string|null $delivery_filename
* @property string|null $delivery_dir
* @property string|null $disk
*
* @method static \Illuminate\Database\Eloquent\Builder|UserInvoice newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserInvoice newQuery()
* @method static \Illuminate\Database\Query\Builder|UserInvoice onlyTrashed()
@ -66,143 +66,285 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|UserInvoice whereYear($value)
* @method static \Illuminate\Database\Query\Builder|UserInvoice withTrashed()
* @method static \Illuminate\Database\Query\Builder|UserInvoice withoutTrashed()
*
* @mixin \Eloquent
*/
class UserInvoice extends Model
{
use SoftDeletes;
protected $table = 'user_invoices';
use SoftDeletes;
protected $casts = [
'shopping_order_id' => 'int',
'month' => 'int',
'year' => 'int',
'number' => 'int',
'paid' => 'bool',
'cancellation' => 'bool',
'cancellation_id' => 'int',
'status' => 'int',
'infos' => 'array',
];
protected $table = 'user_invoices';
protected $dates = [
'date',
'paid_date',
'cancellation_date'
];
protected $casts = [
'shopping_order_id' => 'int',
'month' => 'int',
'year' => 'int',
'number' => 'int',
'paid' => 'bool',
'cancellation' => 'bool',
'cancellation_id' => 'int',
'status' => 'int',
'infos' => 'array',
];
protected $fillable = [
'shopping_order_id',
'month',
'year',
'date',
'full_number',
'number',
'filename',
'dir',
'delivery_filename',
'delivery_dir',
'disk',
'infos',
'paid',
'paid_date',
'cancellation',
'cancellation_id',
'cancellation_date',
'status'
];
protected $dates = [
'date',
'paid_date',
'cancellation_date',
];
public static $monthNames = [
1 => 'Januar',
2 => 'Februar',
3 => 'März',
4 => 'April',
5 => 'Mai',
6 => 'Juni',
7 => 'Juli',
8 => 'August',
9 => 'September',
10 => 'Oktober',
11 => 'November',
12 => 'Dezember'
];
protected $fillable = [
'shopping_order_id',
'month',
'year',
'date',
'full_number',
'number',
'filename',
'dir',
'delivery_filename',
'delivery_dir',
'disk',
'infos',
'paid',
'paid_date',
'cancellation',
'cancellation_id',
'cancellation_date',
'status',
];
public static $statusTypes = [
0 => '-',
public static $monthNames = [
1 => 'Januar',
2 => 'Februar',
3 => 'März',
4 => 'April',
5 => 'Mai',
6 => 'Juni',
7 => 'Juli',
8 => 'August',
9 => 'September',
10 => 'Oktober',
11 => 'November',
12 => 'Dezember',
];
public static $statusTypes = [
0 => '-',
1 => 'Bestellung',
2 => 'Shop',
11 => 'storniert B.',
12 => 'storniert Shop',
12 => 'storniert Shop',
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
1 => 'success',
2 => 'secondary',
11 => 'danger',
12 => 'danger',
11 => 'danger',
12 => 'danger',
];
public function shopping_order(){
return $this->belongsTo(ShoppingOrder::class);
}
public function getDateAttribute($value){
return $this->attributes['date'] ? Carbon::parse($this->attributes['date'])->format(\Util::formatDateDB()) : '';
}
public function setDateAttribute( $value ) {
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getDateRaw(){
return isset($this->attributes['date']) ? $this->attributes['date'] : NULL;
}
public function getPaidDateAttribute($value){
return $this->attributes['paid_date'] ? Carbon::parse($this->attributes['paid_date'])->format(\Util::formatDateDB()) : '';
}
public function setPaidDateAttribute( $value ) {
$this->attributes['paid_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getPaidDateRaw(){
return isset($this->attributes['paid_date']) ? $this->attributes['paid_date'] : NULL;
}
public function getCancellationDateAttribute($value){
return $this->attributes['cancellation_date'] ? Carbon::parse($this->attributes['cancellation_date'])->format(\Util::formatDateDB()) : '';
}
public function setCancellationDateAttribute( $value ) {
$this->attributes['cancellation_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getCancellationDateRaw(){
return isset($this->attributes['cancellation_date']) ? $this->attributes['cancellation_date'] : NULL;
}
public static function getMonthName($month)
public function shopping_order()
{
return isset(self::$monthNames[$month]) ? self::$monthNames[$month] : $month;
return $this->belongsTo(ShoppingOrder::class);
}
public function getStatusType(){
return isset(self::$statusTypes[$this->status]) ? self::$statusTypes[$this->status] : "";
public function getDateAttribute($value)
{
return $this->attributes['date'] ? Carbon::parse($this->attributes['date'])->format(\Util::formatDateDB()) : '';
}
public function getStatusColor(){
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
public function setDateAttribute($value)
{
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getDownloadPath($full = false){
if(!$full){
public function getDateRaw()
{
return isset($this->attributes['date']) ? $this->attributes['date'] : null;
}
public function getPaidDateAttribute($value)
{
return $this->attributes['paid_date'] ? Carbon::parse($this->attributes['paid_date'])->format(\Util::formatDateDB()) : '';
}
public function setPaidDateAttribute($value)
{
$this->attributes['paid_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getPaidDateRaw()
{
return isset($this->attributes['paid_date']) ? $this->attributes['paid_date'] : null;
}
public function getCancellationDateAttribute($value)
{
return $this->attributes['cancellation_date'] ? Carbon::parse($this->attributes['cancellation_date'])->format(\Util::formatDateDB()) : '';
}
public function setCancellationDateAttribute($value)
{
$this->attributes['cancellation_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getCancellationDateRaw()
{
return isset($this->attributes['cancellation_date']) ? $this->attributes['cancellation_date'] : null;
}
public static function getMonthName($month)
{
return isset(self::$monthNames[$month]) ? self::$monthNames[$month] : $month;
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? self::$statusTypes[$this->status] : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getDownloadPath($full = false)
{
if (! $full) {
return $this->dir.$this->filename;
}
return \Storage::disk($this->disk)->path($this->dir.$this->filename);
}
public function getDownloadPathDelivery($full = false){
if(!$full){
public function getDownloadPathDelivery($full = false)
{
if (! $full) {
return $this->delivery_dir.$this->delivery_filename;
}
return \Storage::disk($this->disk)->path($this->delivery_dir.$this->delivery_filename);
}
}
/**
* Gibt den Download-Pfad für die lokalisierte Rechnung zurück.
* Bei 'de' oder nicht vorhandener Locale-Version wird das Original zurückgegeben.
*
* @param string|null $locale Sprachcode (de, en, es)
* @param bool $full Vollständiger Dateisystempfad oder relativer Pfad
* @return string
*/
public function getDownloadPathLocale($locale = null, $full = false)
{
// Bei Deutsch oder keiner Angabe: Original zurückgeben
if (! $locale || $locale === 'de') {
return $this->getDownloadPath($full);
}
// Dateiname mit Locale-Suffix
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
// Prüfen ob Locale-Version existiert, sonst Fallback auf DE
if (! \Storage::disk($this->disk)->exists($path)) {
return $this->getDownloadPath($full);
}
return $full ? \Storage::disk($this->disk)->path($path) : $path;
}
/**
* Gibt den Download-Pfad für den lokalisierten Lieferschein zurück.
* Bei 'de' oder nicht vorhandener Locale-Version wird das Original zurückgegeben.
*
* @param string|null $locale Sprachcode (de, en, es)
* @param bool $full Vollständiger Dateisystempfad oder relativer Pfad
* @return string
*/
public function getDownloadPathDeliveryLocale($locale = null, $full = false)
{
// Bei Deutsch oder keiner Angabe: Original zurückgeben
if (! $locale || $locale === 'de') {
return $this->getDownloadPathDelivery($full);
}
// Dateiname mit Locale-Suffix
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->delivery_filename);
$path = $this->delivery_dir.$filename;
// Prüfen ob Locale-Version existiert, sonst Fallback auf DE
if (! \Storage::disk($this->disk)->exists($path)) {
return $this->getDownloadPathDelivery($full);
}
return $full ? \Storage::disk($this->disk)->path($path) : $path;
}
/**
* Gibt den lokalisierten Dateinamen für die Rechnung zurück.
*
* @param string|null $locale
* @return string
*/
public function getFilenameLocale($locale = null)
{
if (! $locale || $locale === 'de') {
return $this->filename;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
// Fallback auf Original wenn nicht vorhanden
if (! \Storage::disk($this->disk)->exists($path)) {
return $this->filename;
}
return $filename;
}
/**
* Gibt alle verfügbaren lokalisierten Versionen der Rechnung zurück (außer DE).
*
* @return array Array mit Sprachcodes, z.B. ['en', 'es']
*/
public function getAvailableLocales(): array
{
$availableTemplates = config('localization.availableTemplates', ['de']);
$locales = [];
foreach ($availableTemplates as $locale) {
if ($locale === 'de') {
continue;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
if (\Storage::disk($this->disk)->exists($path)) {
$locales[] = $locale;
}
}
return $locales;
}
/**
* Prüft ob eine lokalisierte Version für die angegebene Sprache existiert.
*/
public function hasLocale(string $locale): bool
{
if ($locale === 'de') {
return true;
}
$filename = str_replace('.pdf', '-'.$locale.'.pdf', $this->filename);
$path = $this->dir.$filename;
return \Storage::disk($this->disk)->exists($path);
}
}

View file

@ -6,10 +6,9 @@
namespace App\Models;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use App\Models\ShoppingOrder;
use App\User;
/**
* Class UserSalesVolume
@ -32,11 +31,11 @@ use App\User;
* @property Carbon|null $updated_at
* @property ShoppingOrder|null $shopping_order
* @property User $user
* @package App\Models
* @property int|null $user_invoice_id
* @property int|null $month_shop_points
* @property float|null $month_shop_total_net
* @property-read \App\Models\UserInvoice|null $user_invoice
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume query()
@ -57,275 +56,293 @@ use App\User;
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereUserInvoiceId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereYear($value)
*
* @property array|null $syslog
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereSyslog($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereInfo($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereStatusPoints($value)
*
* @property int|null $month_KP_points
* @property int|null $month_TP_points
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereMonthKPPoints($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereMonthTPPoints($value)
*
* @property int|null $status_turnover
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereStatusTurnover($value)
*
* @mixin \Eloquent
*/
class UserSalesVolume extends Model
{
protected $table = 'user_sales_volumes';
protected $table = 'user_sales_volumes';
protected $casts = [
'user_id' => 'int',
'shopping_order_id' => 'int',
'user_invoice_id' => 'int',
'month' => 'int',
'year' => 'int',
'points' => 'float',
'month_KP_points' => 'float',
'month_TP_points' => 'float',
'month_shop_points' => 'float',
'status_points' => 'int',
'status_turnover' => 'int',
'total_net' => 'float',
'month_total_net' => 'float',
'month_shop_total_net' => 'float',
'status' => 'int',
'syslog' => 'array'
];
protected $casts = [
'user_id' => 'int',
'shopping_order_id' => 'int',
'user_invoice_id' => 'int',
'month' => 'int',
'year' => 'int',
'points' => 'float',
'month_KP_points' => 'float',
'month_TP_points' => 'float',
'month_shop_points' => 'float',
'status_points' => 'int',
'status_turnover' => 'int',
'total_net' => 'float',
'month_total_net' => 'float',
'month_shop_total_net' => 'float',
'status' => 'int',
'syslog' => 'array',
];
protected $dates = [
'date'
];
protected $dates = [
'date',
];
protected $fillable = [
'user_id',
'shopping_order_id',
'user_invoice_id',
'month',
'year',
'date',
'points',
'month_KP_points',
'month_TP_points',
'month_shop_points',
'status_points',
'status_turnover',
'total_net',
'month_total_net',
'month_shop_total_net',
'message',
'info',
'status',
'syslog'
];
protected $fillable = [
'user_id',
'shopping_order_id',
'user_invoice_id',
'month',
'year',
'date',
'points',
'month_KP_points',
'month_TP_points',
'month_shop_points',
'status_points',
'status_turnover',
'total_net',
'month_total_net',
'month_shop_total_net',
'message',
'info',
'status',
'syslog',
];
public static $statusPointsTypes = [
1 => 'KU + TP', // Eigene + Team
2 => 'KU', // nur Eigene nicht Team
];
public static $statusPointsTypes = [
1 => 'KU + TP', //Eigene + Team
2 => 'KU', //nur Eigene nicht Team
];
public static $statusTurnoverTypes = [
1 => 'advisor_order', // hinzugefügt aus
2 => 'shoporder', // hinzugefügt aus
];
public static $statusTurnoverTypes = [
1 => 'advisor_order', //hinzugefügt aus
2 => 'shoporder', //hinzugefügt aus
];
public static $statusTypes = [
0 => 'not_assigned',
1 => 'advisor_order', // hinzugefügt aus
2 => 'shoporder', // hinzugefügt aus
3 => 'shoporder_pending', // hinzugefügt aus
4 => 'credit', // hinzugefügt aus
5 => 'registration', // hinzugefügt aus
6 => 'cancelled', // Stornorechnung
// 10 => ''
];
public static $statusTypes = [
0 => 'not_assigned',
1 => 'advisor_order', //hinzugefügt aus
2 => 'shoporder', //hinzugefügt aus
3 => 'shoporder_pending', //hinzugefügt aus
4 => 'credit', //hinzugefügt aus
5 => 'registration', //hinzugefügt aus
// 10 => ''
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'info',
5 => 'info',
6 => 'danger',
10 => 'danger',
];
public static $statusColors = [
0 => 'warning',
1 => 'success',
2 => 'secondary',
3 => 'warning',
4 => 'info',
5 => 'info',
10 => 'danger',
];
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 user_invoice()
{
return $this->belongsTo(UserInvoice::class);
}
public function user_invoice()
{
return $this->belongsTo(UserInvoice::class);
}
public function getDateAttribute()
{
return $this->attributes['date'] ? Carbon::parse($this->attributes['date'])->format(\Util::formatDateDB()) : '';
}
public function getDateAttribute()
{
return $this->attributes['date'] ? Carbon::parse($this->attributes['date'])->format(\Util::formatDateDB()) : '';
}
public function setDateAttribute($value)
{
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
}
public function getDateRaw()
{
return isset($this->attributes['date']) ? $this->attributes['date'] : NULL;
}
public function setDateAttribute($value)
{
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
// Points Setter/Getter für deutsches Zahlenformat
public function setPointsAttribute($value)
{
$this->attributes['points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function getDateRaw()
{
return isset($this->attributes['date']) ? $this->attributes['date'] : null;
}
public function setMonthKPPointsAttribute($value)
{
$this->attributes['month_KP_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
// Points Setter/Getter für deutsches Zahlenformat
public function setPointsAttribute($value)
{
$this->attributes['points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function setMonthTPPointsAttribute($value)
{
$this->attributes['month_TP_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function setMonthKPPointsAttribute($value)
{
$this->attributes['month_KP_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function setMonthShopPointsAttribute($value)
{
$this->attributes['month_shop_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function setMonthTPPointsAttribute($value)
{
$this->attributes['month_TP_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? \Util::formatNumber($this->attributes['points']) : "";
}
public function setMonthShopPointsAttribute($value)
{
$this->attributes['month_shop_points'] = $value !== null ? \Util::reFormatNumber($value) : null;
}
public function getFormattedMonthKPPoints()
{
return isset($this->attributes['month_KP_points']) ? \Util::formatNumber($this->attributes['month_KP_points']) : 0;
}
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? \Util::formatNumber($this->attributes['points']) : '';
}
public function getFormattedMonthTPPoints()
{
return isset($this->attributes['month_TP_points']) ? \Util::formatNumber($this->attributes['month_TP_points']) : 0;
}
public function getFormattedMonthKPPoints()
{
return isset($this->attributes['month_KP_points']) ? \Util::formatNumber($this->attributes['month_KP_points']) : 0;
}
public function getFormattedMonthShopPoints()
{
return isset($this->attributes['month_shop_points']) ? \Util::formatNumber($this->attributes['month_shop_points']) : 0;
}
public function getFormattedMonthTPPoints()
{
return isset($this->attributes['month_TP_points']) ? \Util::formatNumber($this->attributes['month_TP_points']) : 0;
}
public function getPointsKPSum()
{
return $this->month_KP_points + $this->month_shop_points; //only KP für SUM - KP is for User
}
public function getPointsTPSum()
{
return $this->month_TP_points + $this->month_shop_points; //only TP für SUM - TP is only for Payline
}
public function getFormattedMonthShopPoints()
{
return isset($this->attributes['month_shop_points']) ? \Util::formatNumber($this->attributes['month_shop_points']) : 0;
}
public function getTotalNetSum()
{
return $this->month_total_net + $this->month_shop_total_net;
}
public function getPointsKPSum()
{
return $this->month_KP_points + $this->month_shop_points; // only KP für SUM - KP is for User
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('payment.' . self::$statusTypes[$this->status]) : "";
}
public function getPointsTPSum()
{
return $this->month_TP_points + $this->month_shop_points; // only TP für SUM - TP is only for Payline
}
public static function getTransStatusType()
{
$ret = [];
foreach (self::$statusTypes as $key => $val) {
$ret[$key] = trans('payment.' . $val);
}
return $ret;
}
public function getTotalNetSum()
{
return $this->month_total_net + $this->month_shop_total_net;
}
public static function getTransTurnoverTypes()
{
$ret = [];
foreach (self::$statusTurnoverTypes as $key => $val) {
$ret[$key] = trans('payment.' . $val);
}
return $ret;
}
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
}
public static function getTransStatusType()
{
$ret = [];
foreach (self::$statusTypes as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
public function getStatusPointsType()
{
return isset(self::$statusPointsTypes[$this->status_points]) ? self::$statusPointsTypes[$this->status_points] : "";
}
public function getStatusPointsColor()
{
return isset(self::$statusColors[$this->status_points]) ? self::$statusColors[$this->status_points] : "default";
}
return $ret;
}
public function getStatusTurnoverType()
{
switch ($this->status) {
case 1: //Bestellung Berater
return 'E';
case 2: //Shop
return 'S';
case 4: //Gutschrift
if ($this->status_turnover === 2) {
return 'S';
} else {
return 'E';
}
case 5: //Registrierung
return 'E';
}
return "";
}
public function getStatusTurnoverColor()
{
public static function getTransTurnoverTypes()
{
$ret = [];
foreach (self::$statusTurnoverTypes as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
switch ($this->status) {
case 1: //Bestellung Berater
return 'success';
case 2: //Shop
return 'secondary';
case 4: //Gutschrift
if ($this->status_turnover === 2) {
return 'secondary';
} else {
return 'success';
}
case 5: //Registrierung
return 'success';
}
return "default";
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getFormatedMonthYear()
{
return str_pad($this->month, 2, "0", STR_PAD_LEFT) . "/" . $this->year;
}
public function getStatusPointsType()
{
return isset(self::$statusPointsTypes[$this->status_points]) ? self::$statusPointsTypes[$this->status_points] : '';
}
public function isCurrentMonthYear()
{
if ($this->month === intval(date('m')) && $this->year === intval(date('Y'))) {
return true;
}
return false;
}
public function getStatusPointsColor()
{
return isset(self::$statusColors[$this->status_points]) ? self::$statusColors[$this->status_points] : 'default';
}
public function caluCommissonTotalNet($margin)
{
if ($this->total_net > 0 && $margin > 0) {
return $this->total_net / 100 * $margin;
}
return 0;
}
public function getStatusTurnoverType()
{
switch ($this->status) {
case 1: // Bestellung Berater
return 'E';
case 2: // Shop
return 'S';
case 4: // Gutschrift
if ($this->status_turnover === 2) {
return 'S';
} else {
return 'E';
}
case 5: // Registrierung
return 'E';
}
return '';
}
public function getStatusTurnoverColor()
{
switch ($this->status) {
case 1: // Bestellung Berater
return 'success';
case 2: // Shop
return 'secondary';
case 4: // Gutschrift
if ($this->status_turnover === 2) {
return 'secondary';
} else {
return 'success';
}
case 5: // Registrierung
return 'success';
}
return 'default';
}
public function getFormatedMonthYear()
{
return str_pad($this->month, 2, '0', STR_PAD_LEFT).'/'.$this->year;
}
public function isCurrentMonthYear()
{
if ($this->month === intval(date('m')) && $this->year === intval(date('Y'))) {
return true;
}
return false;
}
public function caluCommissonTotalNet($margin)
{
if ($this->total_net > 0 && $margin > 0) {
return $this->total_net / 100 * $margin;
}
return 0;
}
}

View file

@ -2,20 +2,16 @@
namespace App\Repositories;
use Carbon;
use App\Models\UserAbo;
use App\Services\AboHelper;
class AboRepository extends BaseRepository
{
public function __construct()
{
//$this->model = $model;
// $this->model = $model;
}
public function setModel(UserAbo $model)
{
$this->model = $model;
@ -28,14 +24,17 @@ class AboRepository extends BaseRepository
if ($this->validate($data)) {
$this->updateStatus($data);
$this->model->abo_interval = $data['abo_interval'];
$this->model->next_date = AboHelper::setNextDate(now(), $data['abo_interval']);
$this->model->next_date = AboHelper::setNextDate(now(), $data['abo_interval']);
$this->model->save();
\Session()->flash('alert-success', 'Einstellungen gespeichert');
return true;
}
return false;
}
}
return false;
}
@ -50,52 +49,57 @@ class AboRepository extends BaseRepository
$this->model->active = false;
$this->model->cancel_date = now();
$this->model->save();
return;
}
$active = (isset($data['abo_is_active']) && $data['abo_is_active']) ? true : false;
//if status is active and active is false, set status to inactive
if ($this->model->active && !$active) {
if ($this->model->status == 2) { //okay
$this->model->status = 6; //inactive
// if status is active and active is false, set status to inactive
if ($this->model->active && ! $active) {
if ($this->model->status == 2) { // okay
$this->model->status = 6; // inactive
$this->model->active = false;
$this->model->save();
}
}
if (!$this->model->active && $active) {
if ($this->model->status = 6) { //inactive
$this->model->status = 2; //okay
if (! $this->model->active && $active) {
if ($this->model->status = 6) { // inactive
$this->model->status = 2; // okay
$this->model->active = true;
$this->model->save();
}
}
$this->model->active = $active;
return;
}
private function validate($data)
{
if ($data['view'] !== 'admin') {
if ($data['view'] !== 'admin' && $data['view'] !== 'portal') {
if ($this->model->is_for === 'me' && $this->model->user_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($this->model->is_for === 'ot' && $this->model->member_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($data['view'] === 'me' && $this->model->is_for !== 'me') {
\Session()->flash('alert-error', 'Unauthorized action. Is not for me');
return false;
}
if ($data['view'] === 'ot' && $this->model->is_for !== 'ot') {
\Session()->flash('alert-error', 'Unauthorized action. Is not your customer');
return false;
}
}
if (!in_array($data['abo_interval'], \App\Models\UserAbo::$aboDeliveryDays)) {
//to check if user is not admin
if (! in_array($data['abo_interval'], \App\Models\UserAbo::$aboDeliveryDays)) {
// to check if user is not admin
\Session()->flash('alert-error', __('abo.error_abo_interval'));
return false;
}
@ -104,8 +108,9 @@ class AboRepository extends BaseRepository
// da setNextDate das nächste Ausführungsdatum sonst auf den nächsten Monat setzt und dieser Monat übersprungen wird.
$executedThisMonth = $this->model->last_date && \Carbon\Carbon::parse($this->model->last_date)->isCurrentMonth();
if (!$executedThisMonth && $data['abo_interval'] <= now()->day) {
if (! $executedThisMonth && $data['abo_interval'] <= now()->day) {
\Session()->flash('alert-error', __('abo.error_abo_interval_in_the_past'));
return false;
}

View file

@ -2,24 +2,22 @@
namespace App\Repositories;
use Yard;
use App\Services\Util;
use App\Models\ShoppingUser;
use App\Models\Homeparty;
use App\Models\ShoppingCollectOrder;
use App\Models\PaymentMethod;
use App\Models\ShoppingCollectOrder;
use App\Models\ShoppingOrder;
use Illuminate\Session\SessionManager;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Services\Util;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Collection;
use Yard;
class CheckoutRepository extends BaseRepository
{
private $session;
private $instance;
private $instance;
public function __construct(SessionManager $session)
{
@ -33,10 +31,10 @@ class CheckoutRepository extends BaseRepository
$user_shop = Util::getUserShop();
if ($shopping_user->is_from === 'homeparty') {
//get data
// get data
$homeparty = Homeparty::find($shopping_user->homeparty_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
// set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); // ek_price
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
@ -44,7 +42,7 @@ class CheckoutRepository extends BaseRepository
'language' => \App::getLocale(),
'user_shop_id' => $user_shop->id,
'payment_for' => $shopping_user->getOrderPaymentFor(),
'homeparty_id' => $shopping_user->homeparty_id,
'homeparty_id' => $shopping_user->homeparty_id,
'total' => $total,
'subtotal' => $homeparty->order['ek_price_net'],
'shipping' => $homeparty->order['shipping_price'],
@ -58,10 +56,10 @@ class CheckoutRepository extends BaseRepository
'mode' => Util::getUserShoppingMode(),
];
} elseif ($shopping_user->is_from === 'collection') {
//get data
// get data
$ShoppingCollectOrder = ShoppingCollectOrder::find($shopping_user->shopping_collect_order_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
// set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); // ek_price
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
@ -75,7 +73,7 @@ class CheckoutRepository extends BaseRepository
'shipping_net' => 0,
'subtotal_ws' => $ShoppingCollectOrder->price_total_net,
'tax' => $ShoppingCollectOrder->tax_total,
'tax_split' => $ShoppingCollectOrder->tax_split,
'tax_split' => $ShoppingCollectOrder->tax_split,
'total_shipping' => Yard::instance($this->instance)->totalWithShipping(2, '.', ''),
'points' => round($ShoppingCollectOrder->points, 2),
'weight' => 0,
@ -114,7 +112,7 @@ class CheckoutRepository extends BaseRepository
$shopping_order->save();
}
}
if (!$shopping_order) {
if (! $shopping_order) {
$shopping_order = ShoppingOrder::create($data);
if ($shopping_user->is_from === 'collection' && $ShoppingCollectOrder) {
$ShoppingCollectOrder->shopping_order_id = $shopping_order->id;
@ -131,7 +129,7 @@ class CheckoutRepository extends BaseRepository
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
@ -153,20 +151,22 @@ class CheckoutRepository extends BaseRepository
$data['product_id'] = null;
}
$model->fill($data)->save();
return false;
}
}
return $model->delete();
});
foreach ($items as $item) {
if (!ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
if (! ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
$price_net = Yard::instance($this->instance)->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
@ -177,7 +177,7 @@ class CheckoutRepository extends BaseRepository
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
'slug' => $item->options->slug,
];
if ($shopping_user->is_from === 'homeparty') {
@ -196,16 +196,18 @@ class CheckoutRepository extends BaseRepository
if ($shopping_user->is_from === 'homeparty') {
$shopping_order->makeHomepartyTaxSplit();
} elseif ($shopping_user->is_from === 'collection') {
//is set on create / filll.
// is set on create / filll.
} else {
$shopping_order->makeTaxSplit();
}
return $shopping_order;
}
public function makeShoppingUser($data)
{
$data['same_as_billing'] = isset($data['same_as_billing']) ? false : true; //reinvert
$data['same_as_billing'] = isset($data['same_as_billing']) ? false : true; // reinvert
$data['accepted_data_checkbox'] = isset($data['accepted_data_checkbox']) ? true : false;
$shopping_user = false;
if ($this->getSessionPayments('shopping_user_id')) {
@ -216,7 +218,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->save();
}
}
if (!$shopping_user) {
if (! $shopping_user) {
$shopping_user = ShoppingUser::create($data);
}
$this->putSessionPayments('shopping_user_id', $shopping_user->id);
@ -240,6 +242,7 @@ class CheckoutRepository extends BaseRepository
} else {
$payment_methods['active'] = \App\Models\PaymentMethod::where('active', true)->get()->pluck('id', 'short')->toArray();
}
return $payment_methods;
}
@ -259,44 +262,46 @@ class CheckoutRepository extends BaseRepository
public function makeCustomerShoppingUser($shopping_data, $is_for, $is_from)
{
// $shopping_user = ShoppingUser::findOrFail($shopping_data['shopping_user_id']);
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->fill($shopping_data);
$shopping_user->faker_mail = false;
$shopping_user->auth_user_id = null;
$shopping_user->homeparty_id = null;
$shopping_user->same_as_billing = $shopping_user->same_as_billing ? false : true; //reinvert
$shopping_user->same_as_billing = $shopping_user->same_as_billing ? false : true; // reinvert
// $shopping_user->id = null;
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
return $shopping_user;
}
public function initShoppingUser($is_for, $is_from, $homeparty_id = null)
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->homeparty_id = $homeparty_id;
$shopping_user->language = \App::getLocale();
//eingeloggter Kunde
// eingeloggter Kunde
if (\Auth::guard('customers')->check()) {
$shopping_user = $this->shoppingUserByAuthCustomer(\Auth::guard('customers')->user());
}
//eingeloggter User Berater
// eingeloggter User Berater
if (\Auth::guard('user')->check()) {
$shopping_user = $this->shoppingUserByAuthUser(\Auth::guard('user')->user(), $is_from, $is_for);
}
$shopping_user->mode = 'prev';
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
return $shopping_user;
}
public function shoppingUserByAuthCustomer(\App\Models\Customer $user)
{
//clone shopping user!
// clone shopping user!
if ($user->shopping_user_id) {
$find_shopping_user = ShoppingUser::find($user->shopping_user_id);
if ($find_shopping_user) {
@ -305,7 +310,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->shipping_country_id = null;
}
} else {
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
}
@ -315,7 +320,7 @@ class CheckoutRepository extends BaseRepository
public function shoppingUserByAuthUser(\App\User $user, $is_from, $is_for)
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
$shopping_user->billing_salutation = $user->account->salutation;
@ -326,16 +331,16 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_address_2 = $user->account->address_2;
$shopping_user->billing_zipcode = $user->account->zipcode;
$shopping_user->billing_city = $user->account->city;
//$shopping_user->billing_country_id = $user->account->country_id;
// $shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
//Lieferadresse
// Lieferadresse
$shopping_user->same_as_billing = $user->account->same_as_billing ? false : true;
$shopping_user->shipping_salutation = $user->account->shipping_salutation;
$shopping_user->shipping_company = $user->account->shipping_company;
@ -345,11 +350,10 @@ class CheckoutRepository extends BaseRepository
$shopping_user->shipping_address_2 = $user->account->shipping_address_2;
$shopping_user->shipping_zipcode = $user->account->shipping_zipcode;
$shopping_user->shipping_city = $user->account->shipping_city;
//$shopping_user->shipping_country_id = $user->account->shipping_country_id;
// $shopping_user->shipping_country_id = $user->account->shipping_country_id;
$shopping_user->shipping_phone = $user->account->shipping_phone;
$shopping_user->shipping_postnumber = $user->account->shipping_postnumber;
return $shopping_user;
}
@ -357,7 +361,7 @@ class CheckoutRepository extends BaseRepository
{
$user = Util::getAuthUser();
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->auth_user_id = $user->id;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
@ -375,6 +379,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
@ -382,7 +387,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->homeparty_id = isset($data['homeparty_id']) ? $data['homeparty_id'] : null;
$shopping_user->shopping_collect_order_id = isset($data['shopping_collect_order_id']) ? $data['shopping_collect_order_id'] : null;
//Lieferadresse
// Lieferadresse
if ($is_from === 'user_order') {
if (isset($data['shopping_user_id']) && strpos($data['is_for'], 'ot') !== false) {
$s_user = ShoppingUser::findOrFail($data['shopping_user_id']);
@ -399,7 +404,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $s_user->billing_email;
;*/
$shopping_user->faker_mail = $s_user->faker_mail;
if (!$s_user->faker_mail) {
if (! $s_user->faker_mail) {
$shopping_user->shipping_email = $s_user->billing_email;
}
$shopping_user->shopping_user_id = $data['shopping_user_id'];
@ -449,13 +454,14 @@ class CheckoutRepository extends BaseRepository
if ($content->has($key)) {
return $content->get($key);
}
return false;
}
public function sessionDestroy($with_shopping = false)
{
if ($with_shopping) {
if (session('user_shop_payment') === 1) { //ShoppingInstance payment 1 = webshop
if (session('user_shop_payment') === 1) { // ShoppingInstance payment 1 = webshop
Yard::instance('webshop')->destroy();
} else {
Yard::instance('shopping')->destroy();
@ -469,6 +475,7 @@ class CheckoutRepository extends BaseRepository
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
}

View file

@ -7,37 +7,77 @@ use App\Models\File;
use App\User;
use Storage;
class ContractPDFRepository extends BaseRepository {
class ContractPDFRepository extends BaseRepository
{
protected $disk;
protected $dir;
protected $user_id;
protected $identifier;
public function __construct(User $model){
protected $locale;
protected $contract_date;
public function __construct(User $model)
{
$this->model = $model;
// Benutzersprache aus Account ermitteln (mit Fallback auf de)
$this->locale = $model->account && $model->account->language
? $model->account->language
: 'de';
}
public function _set($name, $value){
public function _set($name, $value)
{
$this->{$name} = $value;
}
private function convert($str){
$search = array('Ő', 'ő', 'Ű', 'ű');
$replace = array('Ö', 'ö', 'Ü', 'ü');
private function convert($str)
{
$search = ['Ő', 'ő', 'Ű', 'ű'];
$replace = ['Ö', 'ö', 'Ü', 'ü'];
$str = str_replace($search, $replace, $str);
return iconv('UTF-8', 'windows-1252//IGNORE', $str);
return iconv('UTF-8', 'windows-1252//IGNORE', $str);
}
public function createContractPDF() {
public function createContractPDF()
{
$pdf = new ContractPDF();
if (! Storage::disk($this->disk)->exists($this->dir)) {
Storage::disk($this->disk)->makeDirectory($this->dir); // creates directory
}
$pdf->AddPage('P', array(210, 297));
// Lösche alle alten Vertrags-Einträge für diesen User
File::where('user_id', $this->model->id)
->where('identifier', $this->identifier)
->delete();
// 1. IMMER deutsches Original erstellen
$this->createContractPDFForLocale('de');
// 2. Wenn Benutzersprache != DE, lokalisierte Version erstellen
if ($this->locale && $this->locale !== 'de') {
$this->createContractPDFForLocale($this->locale);
}
return true;
}
/**
* Erstellt einen Beratervertrag in der angegebenen Sprache
*/
private function createContractPDFForLocale(string $locale)
{
$pdf = new ContractPDF;
$pdf->setLocale($locale);
$pdf->AddPage('P', [210, 297]);
$pdf->SetFont('Helvetica', '', 11);
$pdf->SetDrawColor(160, 160, 160);
@ -48,22 +88,21 @@ class ContractPDFRepository extends BaseRepository {
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->m_account));
$pdf->SetXY($x2, $y);
$pdf->Write(0, now()->format("d.m.Y"));
$contractDate = $this->contract_date ?? now();
$pdf->Write(0, $contractDate->format('d.m.Y'));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->company));
$pdf->SetXY($x2, $y);
$pre = $this->model->account->pre_phone_id != "" ? $this->convert($this->model->account->pre_phone->phone)." " : "";
$pre = $this->model->account->pre_phone_id != '' ? $this->convert($this->model->account->pre_phone->phone).' ' : '';
$pdf->Write(0, $pre.$this->convert($this->model->account->phone));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->m_first_name));
$pdf->SetXY($x2, $y);
$pre = $this->model->account->pre_mobil_id != "" ? $this->convert($this->model->account->pre_mobil->phone)." " : "";
$pre = $this->model->account->pre_mobil_id != '' ? $this->convert($this->model->account->pre_mobil->phone).' ' : '';
$pdf->Write(0, $pre.$this->convert($this->model->account->mobil));
$y += $nl;
@ -80,14 +119,14 @@ class ContractPDFRepository extends BaseRepository {
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->zipcode)." ".$this->convert($this->model->account->city));
$pdf->Write(0, $this->convert($this->model->account->zipcode).' '.$this->convert($this->model->account->city));
$y += $nl;
$pdf->SetXY($x1, $y);
$pre = $this->model->account->country_id ? $this->convert($this->model->account->country->de)." " : "";
$pre = $this->model->account->country_id ? $this->convert($this->model->account->country->de).' ' : '';
$pdf->Write(0, $pre);
if($this->model->m_sponsor && $this->model->user_sponsor->account){
if ($this->model->m_sponsor && $this->model->user_sponsor->account) {
$y += 48;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->company));
@ -96,49 +135,44 @@ class ContractPDFRepository extends BaseRepository {
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->m_first_name)." ".$this->convert($this->model->user_sponsor->account->m_last_name));
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->m_first_name).' '.$this->convert($this->model->user_sponsor->account->m_last_name));
$website = $this->model->user_sponsor->shop()->count() ? $this->model->user_sponsor->shop->getSubdomain(false) : "www.mivita.care";
}else{
$website = "www.mivita.care";
$website = $this->model->user_sponsor->shop()->count() ? $this->model->user_sponsor->shop->getSubdomain(false) : 'www.mivita.care';
} else {
$website = 'www.mivita.care';
}
$pdf->AddPage('P', array(210, 297));
$pdf->AddPage('P', [210, 297]);
$pdf->SetFont('Helvetica', '', 10);
$pdf->SetDrawColor(160, 160, 160);
$pdf->SetXY(52, 56);
$pdf->Write(0, $website);
$pdf->SetXY($x1, 65);
$pdf->Write(0, $this->convert($this->model->account->m_first_name)." ".$this->convert($this->model->account->m_last_name));
$pdf->SetXY($x2, 65);
$pdf->Write(0, $this->convert($this->model->account->m_account));
$pdf->Write(0, $website.' (ID: '.$this->convert($this->model->account->m_account).')');
$pdf->AddPage('P', array(210, 297));
$pdf->SetXY($x1, 80);
$pdf->Write(0, $this->convert($this->model->account->m_first_name));
$pdf->SetXY($x2, 80);
$pdf->Write(0, $this->convert($this->model->account->m_last_name));
$pdf->AddPage('P', [210, 297]);
// Dateiname mit übersetztem Vertragsnamen
$contractName = __('pdf.contract_filename', [], $locale);
$filename = "MIVITA_{$contractName}.pdf";
if(!Storage::disk($this->disk)->exists( $this->dir )){
Storage::disk($this->disk)->makeDirectory($this->dir); //creates directory
}
$filename = "MIVITA_Beratervertrag.pdf";
Storage::disk($this->disk)->put($this->dir.$filename, $pdf->Output('S'));
$size = Storage::disk($this->disk)->size($this->dir.$filename);
$size = Storage::disk($this->disk)->size($this->dir.$filename);
$mine = Storage::disk($this->disk)->mimeType($this->dir.$filename);
// Erstelle Datenbank-Eintrag für diesen Vertrag
File::create([
'user_id' => $this->model->id,
'identifier' => $this->identifier,
'filename' => $filename,
'dir' => $this->dir,
'original_name' => $filename,
'ext' => "pdf",
'ext' => 'pdf',
'mine' => $mine,
'size' => $size
'size' => $size,
]);
return true;
}
}
}

View file

@ -2,21 +2,22 @@
namespace App\Repositories;
use PDF;
use Storage;
use App\User;
use App\Services\Credit;
use App\Models\UserCredit;
use Response;
use App\Libraries\CreditDetailsPDF;
use App\Libraries\MyPDFMerger;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Models\UserSalesVolume;
use App\Libraries\CreditDetailsPDF;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\Credit;
use App\User;
use PDF;
use Response;
use Storage;
class CreditRepository extends BaseRepository {
class CreditRepository extends BaseRepository
{
private $user_credit;
public function __construct(User $model)
{
$this->model = $model;
@ -24,16 +25,16 @@ class CreditRepository extends BaseRepository {
public function create($request = [])
{
//need invoice $data
$number = Credit::getCreditNumber();
$credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format("d.m.Y");
$credit_send_mail = isset($request['credit_send_mail']) ? true: false;
// need invoice $data
$number = Credit::getCreditNumber();
$credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format('d.m.Y');
$credit_send_mail = isset($request['credit_send_mail']) ? true : false;
$credit_number = Credit::createCreditNumber($number, $credit_date);
$this->user_credit = new UserCredit();
$this->user_credit = new UserCredit;
$user_credit_items = $this->makeUserCredit();
if(!count($user_credit_items)){
return false;
if (! count($user_credit_items)) {
return false;
}
$data = [
'user' => $this->model,
@ -42,24 +43,33 @@ class CreditRepository extends BaseRepository {
'user_credits' => $this->user_credit,
'user_credit_items' => $user_credit_items,
];
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$dir = Credit::getCreditStorageDir($credit_date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
if (! Storage::disk('public')->exists($dir)) {
Storage::disk('public')->makeDirectory($dir); // creates directory
}
$path = Storage::disk('public')->path('');
// Benutzersprache ermitteln
$userLocale = $this->model->account ? $this->model->account->getLocale() : 'de';
$originalLocale = \App::getLocale();
// Deutsches Original-Dateiname (wird in DB gespeichert)
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
// 1. IMMER deutsches Original erstellen (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createCreditPDF($data, $path, $dir, $filename, 'de', false);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
Storage::disk('public')->put($dir.$filename, $file);
// 2. Wenn Benutzersprache != DE, Kopie in Benutzersprache erstellen
if ($userLocale && $userLocale !== 'de') {
\App::setLocale($userLocale);
$localizedFilename = Credit::makeCreditFilenameLocale($credit_number, $userLocale);
$this->createCreditPDF($data, $path, $dir, $localizedFilename, $userLocale, true);
}
// Locale zurücksetzen
\App::setLocale($originalLocale);
$this->user_credit->user_id = $this->model->id;
$this->user_credit->year = \Carbon::parse($credit_date)->format('Y');
@ -72,35 +82,76 @@ class CreditRepository extends BaseRepository {
$this->user_credit->full_number = $credit_number;
$this->user_credit->save();
if($credit_send_mail){
if ($credit_send_mail) {
Credit::sendCreditMail($this->user_credit);
}
$this->finishUserCredit($this->user_credit->id, $user_credit_items);
return true;
}
private function finishUserCredit($user_credit_id, $user_credit_items){
//next credits
/**
* Erstellt eine Gutschrift-PDF-Datei.
*
* @param string $locale Sprachcode für das Template (de, en, es, fr)
* @param bool $is_copy Ob es sich um eine Kopie handelt (nicht das Original)
*/
private function createCreditPDF(array $data, string $path, string $dir, string $filename, string $locale = 'de', bool $is_copy = false)
{
// Kopie-Flag an Template übergeben
$data['is_copy'] = $is_copy;
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);
// Template basierend auf Locale
$template = $this->getTemplateForLocale($locale);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, $template);
Storage::disk('public')->put($dir.$filename, $file);
}
/**
* Gibt das PDF-Template für die angegebene Locale zurück.
* Verfügbare Templates werden aus config/localization.php geladen.
*/
private function getTemplateForLocale(string $locale): string
{
$availableTemplates = config('localization.availableTemplates', ['de']);
if (in_array($locale, $availableTemplates)) {
return 'template_invoice_'.$locale;
}
return 'template_invoice_de';
}
private function finishUserCredit($user_credit_id, $user_credit_items)
{
// next credits
Credit::makeNextCreditNumber();
//mark as payed
//$UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach($user_credit_items as $user_credit_item){
// mark as payed
// $UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach ($user_credit_items as $user_credit_item) {
$user_credit_item->paid = true;
$user_credit_item->user_credit_id = $user_credit_id;
$user_credit_item->save();
}
}
private function makeUserCredit(){
private function makeUserCredit()
{
$this->user_credit->net = 0;
$this->user_credit->infos = [];
$infos = [];
$user_credit_items = [];
$UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach($UserCreditItems as $userCreditItem){
foreach ($UserCreditItems as $userCreditItem) {
$user_credit_items[] = $userCreditItem;
$infos[] = ['id' => $userCreditItem->id, 'credit' => $userCreditItem->credit];
$this->user_credit->net += $userCreditItem->credit;
@ -108,37 +159,37 @@ class CreditRepository extends BaseRepository {
/* taxable_sales //user tax
1 //umsatzsteuerpflichtig / DE
2 // nicht umsatzsteuerpflichtig /DE
3 // nicht umsatzsteuerpflichtig / Ausland
3 // nicht umsatzsteuerpflichtig / Ausland
*/
if($this->model->account){
if ($this->model->account) {
$this->user_credit->taxable = $this->model->account->taxable_sales;
if($this->model->account->country_id !== 1){
if ($this->model->account->country_id !== 1) {
$this->user_credit->taxable = 3;
}
if($this->user_credit->taxable === 1){
if ($this->user_credit->taxable === 1) {
$this->user_credit->tax_rate = config('app.main_tax_rate');
$this->user_credit->total = round($this->user_credit->net * config('app.main_tax'), 2);
$this->user_credit->tax = $this->user_credit->total - $this->user_credit->net;
}else{
} else {
$this->user_credit->tax_rate = 0;
$this->user_credit->total = $this->user_credit->net;
$this->user_credit->tax = 0;
}
}
$this->user_credit->infos = $infos;
return $user_credit_items;
return $user_credit_items;
}
/*
Erstellt einen detalierten Report zur Gutschrift
Erstellt einen detalierten Report zur Gutschrift
Alle Postionen werden einzeln aufgelistet
//$do ?= html, pdf
*/
public function create_report(UserCredit $user_credit, $do = 'html')
{
//collect all data
$collection = new \stdClass();
public function create_report(UserCredit $user_credit, $do = 'html')
{
// collect all data
$collection = new \stdClass;
$collection->calc_bot = [];
$collection->commission_shop = [];
$collection->commission_payline = [];
@ -147,48 +198,45 @@ class CreditRepository extends BaseRepository {
$collection->commission_registration = [];
$collection->commission_credit = [];
$dates = [];
/* für jede Postion aus der Gutschrift nach Status */
foreach($user_credit->user_credit_items as $user_credit_item){
foreach ($user_credit->user_credit_items as $user_credit_item) {
$date = $user_credit_item->from_month.'-'.$user_credit_item->from_year;
if(!isset($dates[$date])){
if (! isset($dates[$date])) {
$dates[$date] = ['year' => $user_credit_item->from_year, 'month' => $user_credit_item->from_month];
}
/*
//calc bot for the month year
*/
if(!isset($collection->calc_bot[$date])){
if (! isset($collection->calc_bot[$date])) {
$TreeCalcBot = new TreeCalcBot($user_credit_item->from_month, $user_credit_item->from_year, 'admin');
$TreeCalcBot->initBusinesslUserDetail($user_credit->user);
$TreeCalcBot->initStructureUser($user_credit->user->id);
$collection->calc_bot[$date] = $TreeCalcBot;
}
/*
status === 1 commission_shop
Auswertung der Shopbestellungen vom User für einen Monat / Jahr
Auslistung der Positonen / Gesamter Umsatz / Marge / Provision
Auswertung der Shopbestellungen vom User für einen Monat / Jahr
Auslistung der Positonen / Gesamter Umsatz / Marge / Provision
*/
if($user_credit_item->status === 1){
if ($user_credit_item->status === 1) {
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) //'shoporder', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) // 'shoporder', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$user_sales_volumes_total = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) //'shoporder', //hinzugefügt aus
->orderBy('id', 'DESC')->first();
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) // 'shoporder', //hinzugefügt aus
->orderBy('id', 'DESC')->first();
$obj = new \stdClass();
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->user_sales_volumes_total = $user_sales_volumes_total;
$obj->user_credit_item = $user_credit_item;
@ -200,165 +248,155 @@ class CreditRepository extends BaseRepository {
Listen der hinzufegügten Gutschriften vom User für einen Monat / Jahr
*/
$user_sales_volumes_credit = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 4) //'credit', //hinzugefügt aus
->where('status_turnover', 2) //VE shop
->orderBy('id', 'ASC')->get();
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 4) // 'credit', //hinzugefügt aus
->where('status_turnover', 2) // VE shop
->orderBy('id', 'ASC')->get();
$collection->commission_credit[$date] = $user_sales_volumes_credit;
}
}
/*
status === 2 commission_payline
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
/*
status === 5 commission_growth_bonus
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
/*
status === 5 commission_growth_bonus
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
}
/*
nicht enhalten in der Gutschrift
für alle Monate / Jahr die in der Gutschrift enthalten sind
*/
foreach($dates as $date => $dateObj){
/*
foreach ($dates as $date => $dateObj) {
/*
UserSalesVolume::status
1 => 'advisor_order', own_order //hinzugefügt aus
1 => 'advisor_order', own_order //hinzugefügt aus
Listen der Beraterbestellungen vom User für einen Monat / Jahr
*/
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->sum('total_net'); //sum('total_net');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->sum('points'); //sum('points');
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) // 'own_order', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
if($user_sales_volumes->count() > 0){
$obj = new \stdClass();
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->own_order[$date] = $obj;
}
/*
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) // 'own_order', //hinzugefügt aus
->sum('total_net'); // sum('total_net');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) // 'own_order', //hinzugefügt aus
->sum('points'); // sum('points');
if ($user_sales_volumes->count() > 0) {
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->own_order[$date] = $obj;
}
/*
UserSalesVolume::status
5 => 'registration', //hinzugefügt aus
5 => 'registration', //hinzugefügt aus
Listen der Gutschriften aus Reg vom User für einen Monat / Jahr
Enthält nur Punkte wird separat aufgeführt
turnover = immer E / 1 verrechnung mit Eigenem Umsatz
*/
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->where('status', 5) // 'registration', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->sum('total_net'); //sum('total_net');
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) // 'registration', //hinzugefügt aus
->sum('total_net'); // sum('total_net');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->sum('points'); //sum('points');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) // 'registration', //hinzugefügt aus
->sum('points'); // sum('points');
if($user_sales_volumes->count() > 0){
$obj = new \stdClass();
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->commission_registration[$date] = $obj;
}
if ($user_sales_volumes->count() > 0) {
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->commission_registration[$date] = $obj;
}
}
/*
//need this?
$user_credit_item->status = 3; //credit_added
$user_credit_item->status = 4; //commission
*/
/*
//need this?
$user_credit_item->status = 3; //credit_added
$user_credit_item->status = 4; //commission
*/
$data = [
'dates' => $dates,
'user_credit' => $user_credit,
'collection' => $collection,
];
if($do === 'html'){
if ($do === 'html') {
return view('admin.payment.credit_detail', $data);
}
if($do === 'pdf'){
if ($do === 'pdf') {
$dir = Credit::getCreditDetailStorageDir($user_credit->date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
if (! Storage::disk('public')->exists($dir)) {
Storage::disk('public')->makeDirectory($dir); // creates directory
}
$path = Storage::disk('public')->path('');
$filename = Credit::makeCreditDetailFilename($user_credit->full_number);
$pdf = new CreditDetailsPDF('pdf.credit_details');
//return $pdf->create($data, 'credit_details.pdf', 'stream');
// return $pdf->create($data, 'credit_details.pdf', 'stream');
$pdf->create($data, $filename, 'save', $path.$dir);
/*$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);*/
$pdfMerger = new MyPDFMerger();
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_report_de');
Storage::disk('public')->put($dir.$filename, $file);
$path = $dir.$filename;
//$file = Storage::disk('public')->get($path);
// $file = Storage::disk('public')->get($path);
$mime = Storage::disk('public')->mimeType($path);
return Response::make($file, 200)
->header("Content-Type", $mime)
->header('Content-disposition','inline; filename="'.$filename.'"');
->header('Content-Type', $mime)
->header('Content-disposition', 'inline; filename="'.$filename.'"');
//return $dir.$filename;
/*
// return $dir.$filename;
/*
$dir = Credit::getCreditStorageDir($credit_date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
}
$path = Storage::disk('public')->path('');
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
@ -366,4 +404,4 @@ class CreditRepository extends BaseRepository {
*/
}
}
}
}

View file

@ -2,140 +2,153 @@
namespace App\Repositories\DC;
use Request;
use App\Models\DcTag;
use App\Models\DcCategory;
use App\Models\DcTag;
use App\Repositories\BaseRepository;
use Request;
class TagRepository extends BaseRepository {
public function __construct()
{
}
class TagRepository extends BaseRepository
{
public function __construct() {}
public function storeItem($obj, $data)
{
if($obj === 'category' && isset($data['dc_category_name'])){
if ($obj === 'category' && isset($data['dc_category_name'])) {
$category = new DcCategory;
$category->name = $data['dc_category_name'];
$category->pos = 0 ;
$category->pos = 0;
$category->save();
\Session()->flash('alert-success', 'Kategorie erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'tag' && isset($data['dc_tag_name'])){
if ($obj === 'tag' && isset($data['dc_tag_name'])) {
$data = Request::all();
$tag = new DcTag;
$tag->name = $data['dc_tag_name'];
$tag->pos = 0;
$tag->save();
\Session()->flash('alert-success', 'Tag erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'structure' && isset($data['nestable'])){
if ($obj === 'structure' && isset($data['nestable'])) {
$bool = $this->updateStructure($data);
if(Request::ajax()){
if (Request::ajax()) {
return response()->json([
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true])
]);
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true]),
]);
}
}
if($obj === 'update_ajax' && isset($data['action'])){
if ($obj === 'update_ajax' && isset($data['action'])) {
$active = $this->updateAjax($data);
if(Request::ajax()){
if (Request::ajax()) {
return response()->json([
'success' => $data['action'],
'active' => $active,
]);
'success' => $data['action'],
'active' => $active,
]);
}
}
return true;
}
}
protected function updateAjax($data){
protected function updateAjax($data)
{
if($data['action'] == 'update-tag-active' && isset($data['id'])){
if ($data['action'] == 'update-tag-active' && isset($data['id'])) {
$tag = DcTag::findOrFail($data['id']);
$tag->active = $tag->active ? 0 : 1;
$tag->save();
return $tag->active;
}
if($data['action'] == 'update-category-active' && isset($data['id'])){
return $tag->active;
}
if ($data['action'] == 'update-category-active' && isset($data['id'])) {
$category = DcCategory::findOrFail($data['id']);
$category->active = $category->active ? 0 : 1;
$category->save();
return $category->active;
}
return false;
}
protected function updateStructure($data)
{
if(empty($data['nestable']) || !is_array($data['nestable'])){
if (empty($data['nestable']) || ! is_array($data['nestable'])) {
return false;
}
$tags = DcTag::all();
foreach ($tags as $value) {
$value->category_id = null;
$value->pos = NULL;
$value->pos = null;
$value->save();
}
$this->saveStructureLevel($data['nestable']);
return true;
}
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false){
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false)
{
foreach ($nestable as $key => $value) {
if($value['id'] == 0){
if ($value['id'] == 0) {
continue;
}
if($deep == 0){
$cat = DcCategory::findOrFail($value['id']);
$cat->pos = $key;
$cat->save();
if ($deep == 0) {
$cat = DcCategory::find($value['id']);
if (! $cat) {
// Kategorie existiert nicht mehr, überspringen
continue;
}
$cat->pos = $key;
$cat->save();
}
if($deep == 1){
$tag = DcTag::findOrFail($value['id']);
if ($deep == 1) {
$tag = DcTag::find($value['id']);
if (! $tag) {
// Tag existiert nicht mehr, überspringen
continue;
}
$tag->category_id = $category_id;
$tag->pos = $key;
$tag->save();
}
if(!empty($value['children'])){
$this->saveStructureLevel($value['children'], $deep+1, $value['id']);
if (! empty($value['children'])) {
$this->saveStructureLevel($value['children'], $deep + 1, $value['id']);
}
}
}
public function deleteItem($obj, $id){
if($obj == 'category'){
public function deleteItem($obj, $id)
{
if ($obj == 'category') {
$this->deleteCategory($id);
}
if($obj == 'tag'){
$this->deleteTag($id);
if ($obj == 'tag') {
$this->deleteTag($id);
}
}
public function deleteCategory($id){
public function deleteCategory($id)
{
$cat = DcCategory::findOrFail($id);
$tags = DcTag::where('category_id', $cat->id)->get();
foreach ($tags as $tag) {
$this->deleteTag($tag->id);
$this->deleteTag($tag->id);
}
$cat->delete();
}
}
public function deleteTag($id){
public function deleteTag($id)
{
$tag = DcTag::findOrFail($id);
$tag->delete();
}
}
}
}

View file

@ -2,31 +2,34 @@
namespace App\Repositories;
use PDF;
use Storage;
use App\Services\Invoice;
use App\Models\UserInvoice;
use App\Libraries\InvoicePDF;
use App\Models\ShoppingOrder;
use App\Libraries\MyPDFMerger;
use App\Services\UserService;
use App\Models\ShoppingOrder;
use App\Models\UserInvoice;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\Invoice;
use App\Services\UserService;
use Storage;
class InvoiceRepository extends BaseRepository {
class InvoiceRepository extends BaseRepository
{
/** @var \App\Models\ShoppingOrder */
protected $model;
private $invoice_date;
private $invoice_number;
private $filename;
private $dir;
private $user_sales_volume;
private $delivery_dir;
private $delivery_filename;
private $delivery_filename;
public function __construct(ShoppingOrder $model)
{
@ -35,54 +38,60 @@ class InvoiceRepository extends BaseRepository {
public function create($request = [])
{
//need invoice $data
$number = Invoice::getInvoiceNumber();
if($payt = $this->model->getLastShoppingPaymentTransaction()){
$invoice_date = $payt->created_at->format("d.m.Y");
}
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $invoice_date;
$invoice_send_mail = isset($request['invoice_send_mail']) ? false : true;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->delivery_dir = Invoice::getDeliveryStorageDir($this->invoice_date);
$this->delivery_filename = Invoice::makeDeliveryFilename($this->invoice_number);
// Wrap entire invoice creation in transaction to ensure atomicity
return \DB::transaction(function () use ($request) {
// Get and increment invoice number atomically (includes its own lock)
$number = Invoice::makeNextInvoiceNumber();
$this->makePDF();
$user_invoice = UserInvoice::create([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($this->invoice_date)->format('Y'),
'month' => \Carbon::parse($this->invoice_date)->format('m'),
'date' => $this->invoice_date,
'full_number' => $this->invoice_number,
'number' => $number,
'filename' => $this->filename,
'dir' => $this->dir,
'delivery_filename' => $this->delivery_filename,
'delivery_dir' => $this->delivery_dir,
'disk' => 'public',
'status' => $this->model->getStatusByOrder()
]);
Invoice::makeNextInvoiceNumber();
if($invoice_send_mail){
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
}
public function update($request = []){
if($user_invoice = $this->model->user_invoice){
$number = $user_invoice->number;
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $user_invoice->date;
$invoice_send_mail = isset($request['invoice_send_mail']) ? false: true;
if ($payt = $this->model->getLastShoppingPaymentTransaction()) {
$invoice_date = $payt->created_at->format('d.m.Y');
}
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $invoice_date;
$invoice_send_mail = isset($request['invoice_send_mail']) && $request['invoice_send_mail'] ? true : false;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->delivery_dir = Invoice::getDeliveryStorageDir($this->invoice_date);
$this->delivery_filename = Invoice::makeDeliveryFilename($this->invoice_number);
$this->user_sales_volume = UserSalesVolume::where('user_invoice_id', $this->model->user_invoice->id)->first();
$this->makePDF();
$user_invoice = UserInvoice::create([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($this->invoice_date)->format('Y'),
'month' => \Carbon::parse($this->invoice_date)->format('m'),
'date' => $this->invoice_date,
'full_number' => $this->invoice_number,
'number' => $number,
'filename' => $this->filename,
'dir' => $this->dir,
'delivery_filename' => $this->delivery_filename,
'delivery_dir' => $this->delivery_dir,
'disk' => 'public',
'status' => $this->model->getStatusByOrder(),
]);
if ($invoice_send_mail) {
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
});
}
public function update($request = [])
{
if ($user_invoice = $this->model->user_invoice) {
$number = $user_invoice->number;
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $user_invoice->date;
$invoice_send_mail = isset($request['invoice_send_mail']) ? false : true;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->delivery_dir = Invoice::getDeliveryStorageDir($this->invoice_date);
$this->delivery_filename = Invoice::makeDeliveryFilename($this->invoice_number);
$this->user_sales_volume = UserSalesVolume::where('user_invoice_id', $this->model->user_invoice->id)->first();
$this->makePDF();
$user_invoice->fill([
@ -99,16 +108,23 @@ class InvoiceRepository extends BaseRepository {
'disk' => 'public',
])->save();
if($invoice_send_mail){
if ($invoice_send_mail) {
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
}
return $user_invoice;
}
return null;
}
private function makePDF(){
/**
* Erstellt die PDFs für Rechnung und Lieferschein.
* Das deutsche Original wird immer erstellt (Finanzamt-Anforderung).
* Bei anderer Kundensprache wird zusätzlich eine Kopie in der Kundensprache erstellt.
*/
private function makePDF()
{
$data = [
'shopping_order' => $this->model,
'invoice_date' => $this->invoice_date,
@ -116,43 +132,89 @@ class InvoiceRepository extends BaseRepository {
'user_sales_volume' => $this->user_sales_volume,
];
if($this->model->auth_user_id){
if ($this->model->auth_user_id) {
UserService::checkUserTaxShippingCountry($this->model->auth_user, $this->model->country_id);
$data = array_merge($data, UserService::getYardInfo());
}
if(!Storage::disk('public')->exists( $this->dir )){
Storage::disk('public')->makeDirectory($this->dir); //creates directory
}
if(!Storage::disk('public')->exists( $this->delivery_dir )){
Storage::disk('public')->makeDirectory($this->delivery_dir); //creates directory
}
if (! Storage::disk('public')->exists($this->dir)) {
Storage::disk('public')->makeDirectory($this->dir);
}
if (! Storage::disk('public')->exists($this->delivery_dir)) {
Storage::disk('public')->makeDirectory($this->delivery_dir);
}
// Kundensprache ermitteln
$customerLocale = $this->model->shopping_user ? $this->model->shopping_user->getLocale() : 'de';
$originalLocale = \App::getLocale();
// 1. IMMER deutsches Original erstellen (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createPDFFiles($data, 'de');
// 2. Wenn Kundensprache != DE, Kopie in Kundensprache erstellen
if ($customerLocale && $customerLocale !== 'de') {
\App::setLocale($customerLocale);
$this->createPDFFiles($data, $customerLocale);
}
// Locale zurücksetzen
\App::setLocale($originalLocale);
}
/**
* Erstellt die PDF-Dateien für eine bestimmte Sprache.
*/
private function createPDFFiles(array $data, string $locale)
{
$path = Storage::disk('public')->path('');
//invoice
// Dateinamen für diese Sprache
$invoiceFilename = Invoice::makeInvoiceFilenameLocale($this->invoice_number, $locale);
$deliveryFilename = Invoice::makeDeliveryFilenameLocale($this->invoice_number, $locale);
// Kopie-Flag: true wenn nicht Deutsch (das Original)
$data['is_copy'] = ($locale !== 'de');
// Template basierend auf Locale
$template = $this->getTemplateForLocale($locale);
// Rechnung erstellen
$pdf_file = new InvoicePDF('pdf.invoice');
$pdf_file->create($data, $this->filename, 'save', $path.$this->dir);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$this->dir.$this->filename);
$file = $pdfMerger->myMerge('string', $this->filename, 'template_invoice_de');
Storage::disk('public')->put($this->dir.$this->filename, $file);
if(!$this->model->shopping_collect_order){
$pdf_file->create($data, $invoiceFilename, 'save', $path.$this->dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$this->dir.$invoiceFilename);
$file = $pdfMerger->myMerge('string', $invoiceFilename, $template);
Storage::disk('public')->put($this->dir.$invoiceFilename, $file);
// Lieferschein erstellen (außer bei Sammelbestellung)
if (! $this->model->shopping_collect_order) {
$pdf_file = new InvoicePDF('pdf.delivery');
$pdf_file->create($data, $this->delivery_filename, 'save', $path.$this->delivery_dir);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$this->delivery_dir.$this->delivery_filename);
$file = $pdfMerger->myMerge('string', $this->delivery_filename, 'template_invoice_de');
Storage::disk('public')->put($this->delivery_dir.$this->delivery_filename, $file);
$pdf_file->create($data, $deliveryFilename, 'save', $path.$this->delivery_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$this->delivery_dir.$deliveryFilename);
$file = $pdfMerger->myMerge('string', $deliveryFilename, $template);
Storage::disk('public')->put($this->delivery_dir.$deliveryFilename, $file);
}
}
public function userSalesVolume()
/**
* Gibt das PDF-Template für die angegebene Locale zurück.
* Verfügbare Templates werden aus config/localization.php geladen.
*/
private function getTemplateForLocale(string $locale): string
{
$availableTemplates = config('localization.availableTemplates', ['de']);
if (in_array($locale, $availableTemplates)) {
return 'template_invoice_'.$locale;
}
return 'template_invoice_de';
}
public function userSalesVolume() {}
public function createAndSalesVolume($request = [])
{
$this->user_sales_volume = SalesPointsVolume::addSalesPointsVolumeUser($this->model);
@ -160,4 +222,225 @@ class InvoiceRepository extends BaseRepository {
$this->user_sales_volume->user_invoice_id = $user_invoice->id;
$this->user_sales_volume->save();
}
}
/**
* Erstellt eine Stornorechnung mit Punktekorrektur
*
* @param array $request
* @return UserInvoice
*/
public function createCancellation($request = [])
{
return \DB::transaction(function () use ($request) {
$original_invoice = $this->model->user_invoice;
if (! $original_invoice) {
throw new \Exception('Keine Originalrechnung gefunden.');
}
// Nächste Rechnungsnummer für Storno holen
$number = Invoice::makeNextInvoiceNumber();
// Stornodatum
$cancellation_date = isset($request['cancellation_date'])
? $request['cancellation_date']
: now()->format('d.m.Y');
$cancellation_send_mail = isset($request['cancellation_send_mail']) && $request['cancellation_send_mail'] ? true : false;
// Rechnungsnummer erstellen
$cancellation_number = Invoice::createInvoiceNumber($number, $cancellation_date);
$cancellation_dir = Invoice::getInvoiceStorageDir($cancellation_date);
$cancellation_filename = Invoice::makeCancellationFilename($cancellation_number);
$cancellation_delivery_dir = Invoice::getDeliveryStorageDir($cancellation_date);
$cancellation_delivery_filename = Invoice::makeCancellationDeliveryFilename($cancellation_number);
// Stornorechnung PDF erstellen
$this->makeCancellationPDF(
$cancellation_date,
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename,
$original_invoice
);
// Stornorechnung in DB speichern
$cancellation_invoice = UserInvoice::create([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($cancellation_date)->format('Y'),
'month' => \Carbon::parse($cancellation_date)->format('m'),
'date' => $cancellation_date,
'full_number' => $cancellation_number,
'number' => $number,
'filename' => $cancellation_filename,
'dir' => $cancellation_dir,
'delivery_filename' => $cancellation_delivery_filename,
'delivery_dir' => $cancellation_delivery_dir,
'disk' => 'public',
'cancellation' => true,
'status' => $original_invoice->status === 1 ? 11 : 12, // 11 = storniert B., 12 = storniert Shop
]);
// Original-Rechnung als storniert markieren
$original_invoice->cancellation = true;
$original_invoice->cancellation_id = $cancellation_invoice->id;
$original_invoice->cancellation_date = $cancellation_date;
$original_invoice->save();
// Bestellstatus auf "storniert" setzen
$this->model->txaction = 'cancelled';
// Versandstatus auf "storniert" (10) setzen, wenn noch nicht versendet
if (in_array($this->model->shipped, [0, 1])) {
$this->model->shipped = 10;
}
$this->model->save();
\Log::info('Bestellstatus aktualisiert nach Storno', [
'order_id' => $this->model->id,
'txaction' => $this->model->txaction,
'shipped' => $this->model->shipped,
]);
// Punktekorrektur durchführen (nach Erstellung der Stornorechnung)
$this->correctPointsForCancellation($original_invoice, $cancellation_invoice);
// Optional: E-Mail versenden
if ($cancellation_send_mail) {
Invoice::sendInvoiceMail($this->model, $cancellation_invoice);
}
return $cancellation_invoice;
});
}
/**
* Erstellt die Storno-PDFs (Rechnung und Lieferschein)
*/
private function makeCancellationPDF(
$cancellation_date,
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename,
$original_invoice
) {
$data = [
'shopping_order' => $this->model,
'invoice_date' => $cancellation_date,
'invoice_number' => $cancellation_number,
'original_invoice' => $original_invoice,
'is_cancellation' => true,
];
if ($this->model->auth_user_id) {
UserService::checkUserTaxShippingCountry($this->model->auth_user, $this->model->country_id);
$data = array_merge($data, UserService::getYardInfo());
}
// Verzeichnisse erstellen
if (! Storage::disk('public')->exists($cancellation_dir)) {
Storage::disk('public')->makeDirectory($cancellation_dir);
}
if (! Storage::disk('public')->exists($cancellation_delivery_dir)) {
Storage::disk('public')->makeDirectory($cancellation_delivery_dir);
}
// Kundensprache ermitteln
$customerLocale = $this->model->shopping_user ? $this->model->shopping_user->getLocale() : 'de';
$originalLocale = \App::getLocale();
// Deutsches Original (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createCancellationPDFFiles(
$data,
'de',
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename
);
// Lokalisierte Version wenn gewünscht
if ($customerLocale && $customerLocale !== 'de') {
\App::setLocale($customerLocale);
$data['is_copy'] = true;
$localizedFilename = str_replace('.pdf', '-'.$customerLocale.'.pdf', $cancellation_filename);
$localizedDeliveryFilename = str_replace('.pdf', '-'.$customerLocale.'.pdf', $cancellation_delivery_filename);
$this->createCancellationPDFFiles(
$data,
$customerLocale,
$cancellation_number,
$cancellation_dir,
$localizedFilename,
$cancellation_delivery_dir,
$localizedDeliveryFilename
);
}
\App::setLocale($originalLocale);
}
/**
* Erstellt die PDF-Dateien für eine Stornorechnung in einer bestimmten Sprache
*/
private function createCancellationPDFFiles(
array $data,
string $locale,
string $cancellation_number,
string $cancellation_dir,
string $cancellation_filename,
string $cancellation_delivery_dir,
string $cancellation_delivery_filename
) {
$path = Storage::disk('public')->path('');
$template = $this->getTemplateForLocale($locale);
// Stornorechnung erstellen
$pdf_file = new InvoicePDF('pdf.cancellation');
$pdf_file->create($data, $cancellation_filename, 'save', $path.$cancellation_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$cancellation_dir.$cancellation_filename);
$file = $pdfMerger->myMerge('string', $cancellation_filename, $template);
Storage::disk('public')->put($cancellation_dir.$cancellation_filename, $file);
// Storno-Lieferschein erstellen (außer bei Sammelbestellung)
if (! $this->model->shopping_collect_order) {
$pdf_file = new InvoicePDF('pdf.cancellation_delivery');
$pdf_file->create($data, $cancellation_delivery_filename, 'save', $path.$cancellation_delivery_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$cancellation_delivery_dir.$cancellation_delivery_filename);
$file = $pdfMerger->myMerge('string', $cancellation_delivery_filename, $template);
Storage::disk('public')->put($cancellation_delivery_dir.$cancellation_delivery_filename, $file);
}
}
/**
* Korrigiert die Punkte nach Stornierung einer Rechnung
* Nutzt den SalesPointsVolume Service für konsistente Berechnung
*
* @param UserInvoice $original_invoice Die ursprüngliche Rechnung
* @param UserInvoice $cancellation_invoice Die Stornorechnung
*/
private function correctPointsForCancellation($original_invoice, $cancellation_invoice)
{
// Original UserSalesVolume finden
$original_sales_volume = UserSalesVolume::where('user_invoice_id', $original_invoice->id)->first();
if (! $original_sales_volume) {
\Log::warning('Keine UserSalesVolume gefunden für Rechnung', [
'invoice_id' => $original_invoice->id,
'order_id' => $this->model->id,
]);
return;
}
// Service-Methode verwenden für konsistente Punktekorrektur
SalesPointsVolume::cancelSalesPointsVolume($original_sales_volume, $cancellation_invoice->id);
}
}

View file

@ -27,6 +27,8 @@ class ProductRepository extends BaseRepository
$data['shipping_addon'] = isset($data['shipping_addon']) ? 1 : 0;
$data['no_commission'] = isset($data['no_commission']) ? 1 : 0;
$data['no_free_shipping'] = isset($data['no_free_shipping']) ? 1 : 0;
$data['free_shipping_consultant'] = isset($data['free_shipping_consultant']) ? 1 : 0;
$data['is_membership_only'] = isset($data['is_membership_only']) ? 1 : 0;
$data['buying_restriction'] = isset($data['buying_restriction']) ? 1 : 0;
$data['sponsor_buying_points'] = isset($data['sponsor_buying_points']) ? 1 : 0;
$data['show_on'] = isset($data['show_on']) ? $data['show_on'] : null;
@ -217,7 +219,7 @@ class ProductRepository extends BaseRepository
public function copy($model)
{
$this->model = $model->replicate();
$this->model->name = 'Kopie: ' . $this->model->name;
$this->model->name = 'Kopie: '.$this->model->name;
$this->model->wp_number = null;
$this->model->save();
@ -240,12 +242,12 @@ class ProductRepository extends BaseRepository
// images
foreach ($model->images as $image) {
$name = \App\Services\Slim::sanitizeFileName($image->original_name);
$name = uniqid() . '_' . $name;
$name = uniqid().'_'.$name;
// copy
$data = \Storage::disk('public')->copy(
'images/product/' . $image->product_id . '/' . $image->filename,
'images/product/' . $this->model->id . '/' . $name
'images/product/'.$image->product_id.'/'.$image->filename,
'images/product/'.$this->model->id.'/'.$name
);
ProductImage::create([

View file

@ -3,25 +3,22 @@
namespace App\Services;
use App\Models\Product;
use Yard;
use App\User;
use Carbon\Carbon;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserAboOrder;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserAboOrder;
use App\User;
use Carbon\Carbon;
class AboHelper
{
public static $txaction_filter_text = [
'paid' => 'paymend_paid',
'appointed' => 'paymend_open',
'failed' => 'paymend_failed',
'extern' => 'extern_open', //offen
'extern' => 'extern_open', // offen
'extern_paid' => 'extern_paid',
'invoice_open' => 'invoice_open',
'invoice_paid' => 'invoice_paid',
@ -29,18 +26,19 @@ class AboHelper
'NULL' => 'no_payment',
];
public static function userHasAbo(User $user)
{
$user = $user ? $user : \Auth::user();
return UserAbo::where('user_id', $user->id)->where('is_for', 'me')->where('status', '>', 1)->first() === null ? false : true;
}
public static function memberHasAbo(ShoppingUser $shopping_user)
{
if (!$shopping_user) {
if (! $shopping_user) {
return false;
}
return UserAbo::where('email', $shopping_user->billing_email)->where('is_for', 'ot')->where('status', '>', 1)->first() === null ? false : true;
}
@ -52,19 +50,20 @@ class AboHelper
public static function setAboStatus(ShoppingOrder $shopping_order, $status, $paid = false)
{
$user_abo = $shopping_order->getUserAbo();
if ($user_abo && $user_abo->status < 2) { //status < 2 is not active
if ($user_abo && $user_abo->status < 2) { // status < 2 is not active
$user_abo->update(['status' => $status]);
}
UserAboOrder::where('user_abo_id', $user_abo->id)->where('shopping_order_id', $shopping_order->id)->update(['status' => $status, 'paid' => $paid]);
}
public static function setAboActive(ShoppingOrder $shopping_order, $status, $paid = false)
{
self::setAboStatus($shopping_order, $status, $paid);
//delete UserAbo is not active status = 1
//is_for = me
// delete UserAbo is not active status = 1
// is_for = me
UserAbo::where('user_id', $shopping_order->auth_user_id)->where('is_for', 'me')->where('status', 1)->delete();
//is_for = ot
// is_for = ot
UserAbo::where('member_id', $shopping_order->member_id)->where('email', $shopping_order->shopping_user->billing_email)->where('is_for', 'ot')->where('status', 1)->delete();
}
@ -80,14 +79,29 @@ class AboHelper
return true;
}
$paidOrdersCount = $user_abo->getCountPaidOrders();
return $paidOrdersCount >= (int) $minDuration;
}
public static function isAddOnlyMode(UserAbo $user_abo, $view = 'user'): bool
{
if ($view === 'admin') {
return false;
}
return ! self::canCancelAbo($user_abo, $view);
}
public static function canEditAbo($user_abo, $view = 'user')
{
if ($view !== 'admin' && ($user_abo->user_id != \Auth::user()->id && $user_abo->member_id != \Auth::user()->id)) {
if ($view === 'portal') {
return true;
}
$user = \Auth::user();
if ($view !== 'admin' && (! $user || ($user_abo->user_id != $user->id && $user_abo->member_id != $user->id))) {
return false;
}
return true;
}
@ -100,8 +114,10 @@ class AboHelper
}
}
}
return false;
}
public static function getAboShowOn(Product $product)
{
$show_on = $product->show_on;
@ -111,16 +127,19 @@ class AboHelper
if (in_array('13', $show_on)) {
return 'upgrade';
}
return false;
}
public static function getAboTypeBadge($abo_type)
{
if ($abo_type === 'base') {
return '<span class="badge badge-pill badge-warning"><i class="fas fa-star"></i> ' . __('abo.' . $abo_type) . '</span></a>';
return '<span class="badge badge-pill badge-warning"><i class="fas fa-star"></i> '.__('abo.'.$abo_type).'</span></a>';
}
if ($abo_type === 'upgrade') {
return '<span class="badge badge-pill badge-info"><i class="far fa-star"></i> ' . __('abo.' . $abo_type) . '</span></a>';
return '<span class="badge badge-pill badge-info"><i class="far fa-star"></i> '.__('abo.'.$abo_type).'</span></a>';
}
return '';
}
@ -128,6 +147,7 @@ class AboHelper
{
$nextDate = Carbon::parse($date)->firstOfMonth();
$nextDate->addDays($abo_interval - 1);
return $nextDate->gt($date) ? $nextDate : $nextDate->addMonth(1);
}
@ -135,19 +155,20 @@ class AboHelper
{
$nextDate = Carbon::parse($date)->firstOfMonth()->addMonth(1);
$nextDate->addDays($abo_interval - 1);
return $nextDate->gt($date) ? $nextDate : $nextDate->addMonth(1);
}
public static function createNewAbo(ShoppingPayment $shopping_payment)
{
//is Abo - create init Abo from PP or else
// is Abo - create init Abo from PP or else
if ($shopping_payment->shopping_order->is_abo && $shopping_payment->shopping_order->abo_interval > 0) {
$payment_transaction = $shopping_payment->payment_transactions->last();
//next_date immer im nächsten Monat starten
//is auth_user_id = Berater bestellung
//is member_id = Kunden bestellung
//is for = me = mich oder ot = kunde
// next_date immer im nächsten Monat starten
// is auth_user_id = Berater bestellung
// is member_id = Kunden bestellung
// is for = me = mich oder ot = kunde
$user_abo = UserAbo::create([
'user_id' => $shopping_payment->shopping_order->auth_user_id,
'member_id' => $shopping_payment->shopping_order->member_id,
@ -188,15 +209,82 @@ class AboHelper
'status' => 1,
]);
}
}
$user_abo->load('user_abo_items');
AboItemHistoryService::logInitialCreation($user_abo, 'system');
}
public static function getTransStatusFilterText()
{
$ret = [];
foreach (self::$txaction_filter_text as $key => $val) {
$ret[$key] = trans('payment.' . $val);
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
/**
* Prüft effizient, ob ein User im Team eines anderen Users ist (Downline).
* Traversiert die Sponsor-Hierarchie rekursiv (m_sponsor) statt die komplette
* TreeCalcBot-Struktur aufzubauen.
*
* @param int $teamOwnerId ID des Team-Users (Berechtigter)
* @param int $userToCheckId ID des zu prüfenden Users (z.B. Abo-Besitzer)
* @param int $maxDepth Max. Tiefe (Schutz vor zirkulären Referenzen)
* @return bool True wenn userToCheckId im Team von teamOwnerId ist
*/
public static function isUserInTeam(int $teamOwnerId, int $userToCheckId, int $maxDepth = 100): bool
{
if ($teamOwnerId === $userToCheckId) {
return true;
}
$currentId = $userToCheckId;
$depth = 0;
while ($depth < $maxDepth) {
$currentUser = User::where('id', $currentId)->select('m_sponsor')->first();
if (! $currentUser || ! $currentUser->m_sponsor) {
return false;
}
if ($currentUser->m_sponsor === $teamOwnerId) {
return true;
}
$currentId = $currentUser->m_sponsor;
$depth++;
}
return false;
}
/**
* Liefert alle User-IDs im Team (Downline) eines Users.
* Traversiert die Sponsor-Hierarchie rekursiv nach unten statt TreeCalcBot.
*
* @param int $teamOwnerId ID des Team-Users
* @param int $maxDepth Max. Tiefe (Schutz vor Endlosschleifen)
* @return int[]
*/
public static function getTeamUserIds(int $teamOwnerId, int $maxDepth = 50): array
{
$teamUserIds = [];
$toProcess = [$teamOwnerId];
$depth = 0;
while (! empty($toProcess) && $depth < $maxDepth) {
$children = User::whereIn('m_sponsor', $toProcess)
->whereNull('deleted_at')
->pluck('id')
->toArray();
$teamUserIds = array_merge($teamUserIds, $children);
$toProcess = $children;
$depth++;
}
return array_values(array_unique($teamUserIds));
}
}

View file

@ -0,0 +1,361 @@
<?php
namespace App\Services;
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserAboItemHistory;
use Illuminate\Support\Str;
class AboItemHistoryService
{
/**
* Log alle Items eines neu erstellten Abos als initial-Einträge.
*/
public static function logInitialCreation(UserAbo $userAbo, string $channel = 'system'): void
{
$batchId = Str::uuid()->toString();
$actor = self::resolveActor();
foreach ($userAbo->user_abo_items as $item) {
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => UserAboItemHistory::ACTION_INITIAL,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => null,
'qty_after' => $item->qty,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => $channel,
'batch_id' => $batchId,
'is_initial' => true,
]);
}
}
/**
* Log: Produkt hinzugefügt oder Menge erhöht (bei bereits vorhandenem Produkt).
*/
public static function logProductAdded(UserAbo $userAbo, UserAboItem $item, int $qtyBefore, string $view): void
{
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
$actor = self::resolveActor();
$channel = self::resolveChannel($view);
$action = $qtyBefore === 0
? UserAboItemHistory::ACTION_ADDED
: UserAboItemHistory::ACTION_QTY_CHANGED;
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => $action,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => $qtyBefore > 0 ? $qtyBefore : null,
'qty_after' => $item->qty,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => $channel,
]);
}
/**
* Log: Menge eines Produkts geändert.
*/
public static function logQtyChanged(UserAbo $userAbo, UserAboItem $item, int $qtyBefore, int $qtyAfter, string $view): void
{
if ($qtyBefore === $qtyAfter) {
return;
}
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
$actor = self::resolveActor();
$channel = self::resolveChannel($view);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => UserAboItemHistory::ACTION_QTY_CHANGED,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $qtyAfter,
'qty_before' => $qtyBefore,
'qty_after' => $qtyAfter,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => $channel,
]);
}
/**
* Log: Produkt entfernt (vor dem delete aufrufen!).
*/
public static function logProductRemoved(UserAbo $userAbo, UserAboItem $item, string $view): void
{
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
$actor = self::resolveActor();
$channel = self::resolveChannel($view);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => UserAboItemHistory::ACTION_REMOVED,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => $item->qty,
'qty_after' => 0,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => $channel,
]);
}
/**
* Log: Comp-Produkt getauscht.
*/
public static function logCompProductChanged(UserAbo $userAbo, UserAboItem $item, Product $oldProduct, Product $newProduct, string $view): void
{
// Item hat bereits das neue Produkt — getPrice() liefert den korrekten Anzeige-Preis
$unitPrice = self::resolveItemPrice($item);
$actor = self::resolveActor();
$channel = self::resolveChannel($view);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $newProduct->id,
'action' => UserAboItemHistory::ACTION_COMP_CHANGED,
'product_name' => $newProduct->getLang('name'),
'product_number' => $newProduct->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'old_product_id' => $oldProduct->id,
'old_product_name' => $oldProduct->getLang('name'),
'comp' => $item->comp,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => $channel,
]);
}
/**
* Log: System hat Comp-Produkt hinzugefügt.
*/
public static function logSystemCompAdded(UserAbo $userAbo, UserAboItem $item): void
{
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => UserAboItemHistory::ACTION_COMP_ADDED,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_after' => $item->qty,
'comp' => $item->comp,
'changed_by_user_id' => null,
'changed_by_name' => 'System',
'channel' => UserAboItemHistory::CHANNEL_SYSTEM,
]);
}
/**
* Log: System hat Comp-Produkt entfernt (vor dem delete aufrufen!).
*/
public static function logSystemCompRemoved(UserAbo $userAbo, UserAboItem $item): void
{
$product = $item->product;
$unitPrice = self::resolveItemPrice($item);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $product->id,
'action' => UserAboItemHistory::ACTION_COMP_REMOVED,
'product_name' => $product->getLang('name'),
'product_number' => $product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => $item->qty,
'qty_after' => 0,
'comp' => $item->comp,
'changed_by_user_id' => null,
'changed_by_name' => 'System',
'channel' => UserAboItemHistory::CHANNEL_SYSTEM,
]);
}
/**
* Setzt das Abo auf den Ursprungszustand zurück.
*/
public static function rollbackToInitial(UserAbo $userAbo): bool
{
$initialItems = $userAbo->user_abo_item_histories()
->where('is_initial', true)
->get();
if ($initialItems->isEmpty()) {
return false;
}
$batchId = Str::uuid()->toString();
$actor = self::resolveActor();
// Aktuelle Items loggen und löschen
foreach ($userAbo->user_abo_items as $item) {
$unitPrice = self::resolveItemPrice($item);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $item->product_id,
'action' => UserAboItemHistory::ACTION_ROLLBACK,
'product_name' => $item->product->getLang('name'),
'product_number' => $item->product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => $item->qty,
'qty_after' => 0,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => $actor['id'],
'changed_by_name' => $actor['name'],
'channel' => UserAboItemHistory::CHANNEL_ADMIN,
'batch_id' => $batchId,
]);
}
// Alle aktuellen Items löschen
UserAboItem::where('user_abo_id', $userAbo->id)->delete();
// Neue Items aus Initial-History erstellen
foreach ($initialItems as $historyItem) {
UserAboItem::create([
'user_abo_id' => $userAbo->id,
'product_id' => $historyItem->product_id,
'comp' => $historyItem->comp,
'qty' => $historyItem->qty_after,
'status' => 1,
]);
}
return true;
}
/**
* Ermittelt den exakten Anzeige-Preis des UserAboItems.
* Nutzt UserAboItem::getPrice() das ist genau der Preis, der dem User
* in der Produktliste und im Warenkorb angezeigt wird (netto+UserFactor
* für Berater, brutto für Kunden, länderspezifisch).
*
* Fallback-Kette wenn Yard nicht verfügbar:
* 1. getPriceWith() ohne Country (netto/ufactor je nach is_for)
* 2. Rohpreis des Produkts
*/
private static function resolveItemPrice(UserAboItem $item): float
{
// 1. Exakter Anzeige-Preis via UserAboItem::getPrice() (nutzt Yard)
try {
return (float) $item->getPrice();
} catch (\Throwable $e) {
// Yard nicht initialisiert — weiter zum Fallback
}
// 2. Manuelle Berechnung ohne Yard (ohne Country-spezifische Preise)
try {
$isMe = $item->user_abo->is_for === 'me';
return (float) $item->product->getPriceWith($isMe, $isMe);
} catch (\Throwable $e) {
// Letzter Fallback
}
// 3. Roher Produktpreis
return (float) ($item->product->price ?? 0);
}
/**
* Aktuellen Benutzer ermitteln (CRM Auth oder Kunden-Guard).
*/
private static function resolveActor(): array
{
// CRM User (Admin/Berater)
$user = \Auth::user();
if ($user) {
$name = '';
if ($user->account) {
$name = trim($user->account->first_name.' '.$user->account->last_name);
}
if (! $name) {
$name = $user->email ?? 'User #'.$user->id;
}
return ['id' => $user->id, 'name' => $name];
}
// Portal Kunde
$customer = \Auth::guard('customers')->user();
if ($customer) {
return ['id' => null, 'name' => $customer->name ?? $customer->email ?? 'Kunde'];
}
return ['id' => null, 'name' => 'System'];
}
/**
* Channel aus View-Parameter und Auth-Kontext ableiten.
*/
private static function resolveChannel(string $view): string
{
if ($view === 'portal') {
return UserAboItemHistory::CHANNEL_PORTAL;
}
if ($view === 'admin') {
return UserAboItemHistory::CHANNEL_ADMIN;
}
// Bei user views: Prüfen ob Admin die Änderung vornimmt
$user = \Auth::user();
if ($user && $user->isAdmin()) {
return UserAboItemHistory::CHANNEL_ADMIN;
}
if ($view === 'me') {
return UserAboItemHistory::CHANNEL_USER_ME;
}
if ($view === 'ot') {
return UserAboItemHistory::CHANNEL_USER_OT;
}
return UserAboItemHistory::CHANNEL_SYSTEM;
}
}

View file

@ -2,24 +2,20 @@
namespace App\Services;
use Yard;
use App\User;
use Carbon\Carbon;
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\ShoppingUser;
use App\Models\UserAboOrder;
use App\Models\ShoppingOrder;
use App\Models\ShippingCountry;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserAboItem;
use App\User;
use Yard;
class AboOrderCart
{
private static $user_abo;
private static $is_for;
private static $customer_detail;
private static $is_for;
private static $customer_detail;
public static function initYard($user_abo)
{
@ -37,12 +33,12 @@ class AboOrderCart
\Log::info('AboOrderCart::initYard: Yard geleert', [
'abo_id' => $user_abo->id,
'items_vor_destroy' => $itemsBeforeDestroy
'items_vor_destroy' => $itemsBeforeDestroy,
]);
$itemsAfterDestroy = $yard->content()->count();
\Log::info('AboOrderCart::initYard: Yard geleert', [
'abo_id' => $user_abo->id,
'items_after_destroy' => $itemsAfterDestroy
'items_after_destroy' => $itemsAfterDestroy,
]);
self::$customer_detail = self::makeCustomerDetail($user_abo);
@ -56,6 +52,7 @@ class AboOrderCart
if ($country_id && $shipping_country = ShippingCountry::whereCountryId($country_id)->first()) {
if ($shipping_country->shipping && $shipping_country->shipping->active) {
UserService::initUserYard($user_abo->user, $shipping_country->id, 'abo-me');
return true;
}
}
@ -64,6 +61,7 @@ class AboOrderCart
if ($user_abo->is_for === 'ot') {
self::$is_for = 'abo-ot-customer';
UserService::initCustomerYard(self::$customer_detail, 'abo-ot-customer');
return true;
}
@ -90,7 +88,7 @@ class AboOrderCart
if ($itemsBefore > 0) {
\Log::warning('AboOrderCart::makeOrderYard: Yard war nicht leer vor makeOrderYard und wurde geleert', [
'abo_id' => $user_abo->id,
'items_before' => $itemsBefore
'items_before' => $itemsBefore,
]);
}
@ -105,9 +103,9 @@ class AboOrderCart
'id' => $item->id,
'product_id' => $item->product_id,
'qty' => $item->qty,
'comp' => $item->comp
'comp' => $item->comp,
];
})->toArray()
})->toArray(),
]);
foreach ($abo_items as $abo_item) {
@ -141,10 +139,11 @@ class AboOrderCart
'weight' => 0,
'points' => 0,
'comp' => $item->comp,
'product_id' => $product->id
'product_id' => $product->id,
]
);
Yard::setTax($cartItem->rowId, 0);
return true;
}
if (self::$is_for === 'ot-customer' || self::$is_for === 'abo-ot-customer') {
@ -153,10 +152,10 @@ class AboOrderCart
$product->id,
$product->getLang('name'),
$item->qty,
round($product->getPriceWith($tax_free, false, $user_country, false, self::$user_abo->user), 1),
round($product->getPriceWith($tax_free, false, $user_country, false, self::$user_abo->user), 1),
false,
false,
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
} else {
$cartItem = Yard::instance('shopping')
@ -164,10 +163,10 @@ class AboOrderCart
$product->id,
$product->getLang('name'),
$item->qty,
$product->getPriceWith($tax_free, true, $user_country, false, self::$user_abo->user),
$product->getPriceWith($tax_free, true, $user_country, false, self::$user_abo->user),
false,
false,
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
}
if ($tax_free) {
@ -189,7 +188,7 @@ class AboOrderCart
return true;
}
//need to add
// need to add
if (count($UserAboItems) < $needNumComp) {
$product = Product::whereActive(true)->where('shipping_addon', true)->whereJsonContains('show_on', '12')->orderBy('pos', 'DESC')->first();
for ($i = count($UserAboItems); $i <= $needNumComp; $i++) {
@ -200,13 +199,15 @@ class AboOrderCart
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logSystemCompAdded($user_abo, $UserAboItem);
self::addProductToCart($UserAboItem);
}
}
//need to remove
// need to remove
if (count($UserAboItems) > $needNumComp) {
foreach ($UserAboItems as $UserAboItem) {
if ($UserAboItem->comp > $needNumComp) {
AboItemHistoryService::logSystemCompRemoved($user_abo, $UserAboItem);
$UserAboItem->delete();
}
}
@ -230,20 +231,20 @@ class AboOrderCart
{
if ($user_abo->is_for === 'me') {
//only on Abo!
// only on Abo!
$user = $user_abo->user;
// WICHTIG: Wenn bereits ein shopping_user existiert, diesen replizieren um alle Felder zu behalten
// Ansonsten neues Objekt erstellen
if ($user_abo->shopping_user) {
$shopping_user = $user_abo->shopping_user->replicate();
\Log::info('AboOrderCart::makeCustomerDetail: ShoppingUser repliziert für Abo ID: ' . $user_abo->id, [
\Log::info('AboOrderCart::makeCustomerDetail: ShoppingUser repliziert für Abo ID: '.$user_abo->id, [
'abo_id' => $user_abo->id,
'original_shopping_user_id' => $user_abo->shopping_user->id
'original_shopping_user_id' => $user_abo->shopping_user->id,
]);
} else {
$shopping_user = new ShoppingUser();
\Log::info('AboOrderCart::makeCustomerDetail: Neuer ShoppingUser erstellt für Abo ID: ' . $user_abo->id);
$shopping_user = new ShoppingUser;
\Log::info('AboOrderCart::makeCustomerDetail: Neuer ShoppingUser erstellt für Abo ID: '.$user_abo->id);
}
// Account-Daten überschreiben/aktualisieren
@ -258,9 +259,10 @@ class AboOrderCart
$shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email ?? null;
$shopping_user->language = $user->account->getLocale();
// Auth User ID setzen falls noch nicht gesetzt
if (!$shopping_user->auth_user_id) {
if (! $shopping_user->auth_user_id) {
$shopping_user->auth_user_id = $user->id;
}
if ($user->account->same_as_billing) {
@ -293,9 +295,10 @@ class AboOrderCart
}
if ($user_abo->is_for === 'ot') {
//look for the primary user of this abo
// look for the primary user of this abo
$shopping_user = $user_abo->shopping_user->replicate();
}
return $shopping_user;
}
}

View file

@ -34,12 +34,12 @@ class SalesPointsVolume
$form_user = User::find($form_user_id);
$shoppingOrder->user_sales_volume->user_id = $to_user_id;
$shoppingOrder->user_sales_volume->message = 'zugewiesen: ' . date('d.m.Y');
$shoppingOrder->user_sales_volume->message = 'zugewiesen: '.date('d.m.Y');
$syslog = $shoppingOrder->user_sales_volume->syslog;
$from_email = $form_user ? $form_user->email : '';
$to_email = $to_user ? $to_user->email : '';
$syslog[date('d.m.Y-h:i:s')] = 'change form: #' . $form_user_id . ' ' . $from_email . ' to: #' . $to_user_id . ' ' . $to_email;
$syslog[date('d.m.Y-h:i:s')] = 'change form: #'.$form_user_id.' '.$from_email.' to: #'.$to_user_id.' '.$to_email;
$shoppingOrder->user_sales_volume->syslog = $syslog;
$shoppingOrder->user_sales_volume->save();
@ -100,6 +100,17 @@ class SalesPointsVolume
case 5: // Registrierung
$month_points = self::add_KP_TP_Points($userSalesVolume, $month_points);
$month_total_net += $userSalesVolume->total_net;
break;
case 6: // Storno - negative Punkte und Beträge
$month_points = self::add_KP_TP_Points($userSalesVolume, $month_points);
if ($userSalesVolume->status_turnover === 2) {
$month_shop_points += $userSalesVolume->points; // bereits negativ
$month_shop_total_net += $userSalesVolume->total_net; // bereits negativ
} else {
$month_total_net += $userSalesVolume->total_net; // bereits negativ
}
break;
}
$userSalesVolume->month_shop_points = $month_shop_points;
@ -200,13 +211,13 @@ class SalesPointsVolume
$user_sales_volume->total_net = Util::reFormatNumber($data['total_net']);
$user_sales_volume->points = Util::reFormatNumber($data['points']);
$user_sales_volume->message = 'geändert: ' . date('d.m.Y');
$user_sales_volume->message = 'geändert: '.date('d.m.Y');
$user_sales_volume->info = $data['info'];
$user_sales_volume->status_points = $data['status_points'];
$user_sales_volume->status_turnover = isset($data['status_turnover']) ? intval($data['status_turnover']) : null;
$syslog = $user_sales_volume->syslog;
$syslog[date('d.m.Y-h:i:s')] = 'edit points: #' . $old_points . ' ' . $user_sales_volume->points . ' total: #' . $old_total_net . ' ' . $user_sales_volume->total_net;
$syslog[date('d.m.Y-h:i:s')] = 'edit points: #'.$old_points.' '.$user_sales_volume->points.' total: #'.$old_total_net.' '.$user_sales_volume->total_net;
$user_sales_volume->syslog = $syslog;
$user_sales_volume->save();
@ -231,7 +242,7 @@ class SalesPointsVolume
$total_net = isset($data['total_net']) ? Util::reFormatNumber($data['total_net']) : 0;
$points = isset($data['points']) ? Util::reFormatNumber($data['points']) : 0;
$syslog[date('d.m.Y-h:i:s')] = 'add points: #' . $points . ' total: #' . $total_net;
$syslog[date('d.m.Y-h:i:s')] = 'add points: #'.$points.' total: #'.$total_net;
$status = isset($data['status']) ? intval($data['status']) : 4;
$status_turnover = isset($data['status_turnover']) ? intval($data['status_turnover']) : null;
@ -245,7 +256,7 @@ class SalesPointsVolume
'status_points' => $data['status_points'],
'status_turnover' => $status_turnover,
'total_net' => $total_net,
'message' => 'hinzugefügt: ' . date('d.m.Y'),
'message' => 'hinzugefügt: '.date('d.m.Y'),
'info' => $data['info'],
'syslog' => $syslog,
'status' => $status,
@ -255,4 +266,61 @@ class SalesPointsVolume
\Session()->flash('alert-success', 'Points hinzugefügt');
}
/**
* Erstellt einen Storno-Eintrag für eine stornierte Rechnung
* Negative Punkte werden dem aktuellen Monat zugeordnet
*
* @param UserSalesVolume $original_sales_volume Der ursprüngliche Sales Volume Eintrag
* @param int $cancellation_invoice_id Die ID der Stornorechnung
* @return UserSalesVolume
*/
public static function cancelSalesPointsVolume(UserSalesVolume $original_sales_volume, $cancellation_invoice_id)
{
$month = date('m');
$year = date('Y');
$date = date('d.m.Y');
$syslog = [
date('d.m.Y H:i:s') => 'Stornorechnung erstellt - Punkte korrigiert (Original Invoice: #'.$original_sales_volume->user_invoice_id.')',
];
// Negativen Eintrag erstellen (alle Werte negativ)
$cancellation_sales_volume = UserSalesVolume::create([
'user_id' => $original_sales_volume->user_id,
'shopping_order_id' => $original_sales_volume->shopping_order_id,
'user_invoice_id' => $cancellation_invoice_id,
'month' => $month,
'year' => $year,
'date' => $date,
'points' => -$original_sales_volume->points, // Negativ!
'month_points' => 0, // Wird durch reCalculate gesetzt
'month_KP_points' => 0,
'month_TP_points' => 0,
'month_shop_points' => 0,
'total_net' => -$original_sales_volume->total_net, // Negativ!
'month_total_net' => 0,
'status' => 6, // Status 6 = cancelled/storniert
'status_points' => $original_sales_volume->status_points,
'status_turnover' => $original_sales_volume->status_turnover,
'message' => 'Storniert am '.date('d.m.Y'),
'info' => 'Storno für Invoice #'.$original_sales_volume->user_invoice_id,
'syslog' => $syslog,
]);
// Neuberechnung für aktuellen Monat
self::reCalculateSalesPointsVolume($original_sales_volume->user_id, $month, $year);
\Log::info('Punktekorrektur für Stornorechnung durchgeführt', [
'original_invoice_id' => $original_sales_volume->user_invoice_id,
'cancellation_invoice_id' => $cancellation_invoice_id,
'original_points' => $original_sales_volume->points,
'cancellation_points' => $cancellation_sales_volume->points,
'user_id' => $original_sales_volume->user_id,
'month' => $month,
'year' => $year,
]);
return $cancellation_sales_volume;
}
}

View file

@ -1,90 +1,116 @@
<?php
namespace App\Services;
use App\Services\Util;
use App\Models\Setting;
use App\Mail\MailCredit;
use App\Models\Setting;
use App\Models\UserCredit;
use Illuminate\Support\Facades\Mail;
class Credit
{
public static function getCreditNumber(){
//return (int) Setting::getContentBySlug('credit-number');
public static function getCreditNumber()
{
// return (int) Setting::getContentBySlug('credit-number');
return (int) Setting::getContentBySlug('invoice-number');
}
public static function makeNextCreditNumber(){
public static function makeNextCreditNumber()
{
$credit_number = self::getCreditNumber();
$credit_number = $credit_number+1;
//Setting::setContentBySlug('credit-number', $credit_number, 'int');
$credit_number = $credit_number + 1;
// Setting::setContentBySlug('credit-number', $credit_number, 'int');
Setting::setContentBySlug('invoice-number', $credit_number, 'int');
return $credit_number;
}
public static function createCreditNumber($credit_number, $credit_date){
public static function createCreditNumber($credit_number, $credit_date)
{
$prefix = "GS".\Carbon::parse($credit_date)->format('Y');
$prefix = 'GS'.\Carbon::parse($credit_date)->format('Y');
$credit_number = str_pad($credit_number, 5, '0', STR_PAD_LEFT);
return $prefix.$credit_number;
}
public static function getCreditStorageDir($credit_date){
return "/credit/".\Carbon::parse($credit_date)->format('Y/m/');
public static function getCreditStorageDir($credit_date)
{
return '/credit/'.\Carbon::parse($credit_date)->format('Y/m/');
}
public static function getCreditDetailStorageDir($credit_date){
return "/credit_details/".\Carbon::parse($credit_date)->format('Y/m/');
public static function getCreditDetailStorageDir($credit_date)
{
return '/credit_details/'.\Carbon::parse($credit_date)->format('Y/m/');
}
public static function makeCreditFilename($credit_number){
return $credit_number."-MIVITA-Gutschrift.pdf";
public static function makeCreditFilename($credit_number)
{
return $credit_number.'-MIVITA-Gutschrift.pdf';
}
public static function makeCreditDetailFilename($credit_number){
return $credit_number."-MIVITA-Report.pdf";
public static function makeCreditDetailFilename($credit_number)
{
return $credit_number.'-MIVITA-Report.pdf';
}
public static function isCredit(UserCredit $user_credit){
/**
* Erstellt den Dateinamen für eine lokalisierte Gutschrift.
* Deutsch (de) ist das Original ohne Suffix.
*
* @param string $credit_number
* @param string $locale
* @return string
*/
public static function makeCreditFilenameLocale($credit_number, $locale)
{
if ($locale === 'de' || ! $locale) {
return self::makeCreditFilename($credit_number);
}
return $credit_number.'-MIVITA-Gutschrift-'.$locale.'.pdf';
}
public static function isCredit(UserCredit $user_credit)
{
return $user_credit->isCredit();
}
/*public static function getFilename(UserCredit $user_credit){
return $user_credit->filename;
/*public static function getFilename(UserCredit $user_credit){
return $user_credit->filename;
}
public static function getDir(UserCredit $user_credit){
return $user_credit->dir;
return $user_credit->dir;
}
public static function getDownloadURL(UserCredit $user_credit, $do = false){
return route('storage_file', [$user_credit->id, 'cms_download_file', $do]);
return route('storage_file', [$user_credit->id, 'cms_download_file', $do]);
}
public static function getDownloadPath(UserCredit $user_credit, $full = false){
$dir = self::getDir($user_credit);
$filename = self::getFilename($user_credit);
if(!$full){
return $dir.$filename;
}
return \Storage::disk('public')->path($dir.$filename);
$dir = self::getDir($user_credit);
$filename = self::getFilename($user_credit);
if(!$full){
return $dir.$filename;
}
return \Storage::disk('public')->path($dir.$filename);
}*/
public static function sendCreditMail(UserCredit $user_credit){
public static function sendCreditMail(UserCredit $user_credit)
{
$bcc = [];
$email = $user_credit->user->email;
if(!$email){
if($user_credit->user->mode === 'test'){
}else{
if (! $email) {
if ($user_credit->user->mode === 'test') {
} else {
$email = config('app.checkout_mail');
}
}
if($user_credit->user->mode === 'test'){
if ($user_credit->user->mode === 'test') {
$bcc[] = config('app.checkout_test_mail');
}else{
} else {
$bcc[] = config('app.checkout_mail');
}
Mail::to($email)->bcc($bcc)->locale($user_credit->user->getLocale())->send(new MailCredit($user_credit));

File diff suppressed because it is too large Load diff

View file

@ -3,9 +3,11 @@
namespace App\Services;
use Acme\Dhl\Models\DhlShipment;
use Acme\Dhl\Models\DhlTrackingEvent;
use App\Http\Controllers\SettingController;
use App\Jobs\TrackShipmentJob;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
@ -42,6 +44,7 @@ class DhlTrackingService
Log::info('[DHL Tracking Service] Tracking shipment with Unified API', [
'tracking_number' => $trackingNumber,
'is_sandbox' => $this->isSandbox,
'has_api_key' => ! empty($this->apiKey),
]);
$response = Http::withHeaders([
@ -60,16 +63,21 @@ class DhlTrackingService
CURLOPT_CONNECTTIMEOUT => config('dhl.ssl.connect_timeout', 10),
CURLOPT_TIMEOUT => config('dhl.ssl.timeout', 30),
CURLOPT_USERAGENT => 'acme-laravel-dhl/1.0',
]
],
])
->get('https://api.dhl.com/track/shipments', [
->get('https://api-eu.dhl.com/track/shipments', [
'trackingNumber' => $trackingNumber,
'service' => 'express,parcel',
'requesterCountryCode' => 'DE',
'originCountryCode' => 'DE',
'language' => 'de',
]);
Log::info('[DHL Tracking Service] Unified API response', [
'tracking_number' => $trackingNumber,
'status_code' => $response->status(),
'successful' => $response->successful(),
]);
if ($response->successful()) {
$data = $response->json();
@ -80,8 +88,8 @@ class DhlTrackingService
'success' => true,
'tracking_number' => $shipment['id'],
'status' => $shipment['status']['statusCode'] ?? 'unknown',
'status_text' => $shipment['status']['status'] ?? 'Unbekannt',
'description' => $shipment['status']['description'] ?? '',
'status_text' => $shipment['status']['description'] ?? ($shipment['status']['status'] ?? 'Unbekannt'),
'description' => $shipment['status']['remark'] ?? ($shipment['status']['description'] ?? ''),
'last_update' => $shipment['status']['timestamp'] ?? null,
'origin' => $shipment['origin']['address']['addressLocality'] ?? null,
'destination' => $shipment['destination']['address']['addressLocality'] ?? null,
@ -91,6 +99,12 @@ class DhlTrackingService
}
}
Log::warning('[DHL Tracking Service] Unified API did not find shipment, trying Parcel DE API', [
'tracking_number' => $trackingNumber,
'status_code' => $response->status(),
'response_snippet' => mb_substr($response->body(), 0, 500),
]);
// If Unified API fails, try Parcel DE API
return $this->trackShipmentDE($trackingNumber, $options);
} catch (Exception $e) {
@ -113,13 +127,14 @@ class DhlTrackingService
Log::info('[DHL Tracking Service] Tracking shipment with Parcel DE API', [
'tracking_number' => $trackingNumber,
'is_sandbox' => $this->isSandbox,
'has_api_key' => ! empty($this->apiKey),
'has_api_secret' => ! empty($this->apiSecret),
]);
$response = Http::withBasicAuth($this->apiKey, $this->apiSecret)
->withHeaders([
'Accept' => 'application/json',
'dhl-api-key' => $this->apiKey,
])
$response = Http::withHeaders([
'DHL-API-Key' => $this->apiKey,
'Accept' => 'application/json',
])
->withOptions([
'verify' => config('dhl.ssl.verify_peer', true),
'http_errors' => false,
@ -132,13 +147,20 @@ class DhlTrackingService
CURLOPT_CONNECTTIMEOUT => config('dhl.ssl.connect_timeout', 10),
CURLOPT_TIMEOUT => config('dhl.ssl.timeout', 30),
CURLOPT_USERAGENT => 'acme-laravel-dhl/1.0',
]
],
])
->get('https://api.dhl.com/parcel/de/tracking/v1/shipments', [
'trackingNumber' => $trackingNumber,
->get('https://api-eu.dhl.com/parcel/de/tracking/v0/shipments', [
'shipmentId' => $trackingNumber,
'language' => 'de',
]);
Log::info('[DHL Tracking Service] Parcel DE API response', [
'tracking_number' => $trackingNumber,
'status_code' => $response->status(),
'successful' => $response->successful(),
'response_body' => $response->body(),
]);
if ($response->successful()) {
$data = $response->json();
@ -158,21 +180,33 @@ class DhlTrackingService
}
}
// Log detailed error information
Log::warning('[DHL Tracking Service] Shipment not found or not yet tracked', [
'tracking_number' => $trackingNumber,
'status_code' => $response->status(),
'response_body' => $response->body(),
]);
return [
'success' => false,
'message' => 'Sendung nicht gefunden oder noch nicht im System erfasst.',
'message' => 'Sendung nicht gefunden oder noch nicht im System erfasst. HTTP Status: '.$response->status(),
'tracking_number' => $trackingNumber,
'api_used' => 'parcel_de',
'debug_info' => [
'status_code' => $response->status(),
'response' => $response->json(),
],
];
} catch (Exception $e) {
Log::error('[DHL Tracking Service] Parcel DE API failed', [
'tracking_number' => $trackingNumber,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return [
'success' => false,
'message' => 'Fehler beim Abrufen der Tracking-Informationen: ' . $e->getMessage(),
'message' => 'Fehler beim Abrufen der Tracking-Informationen: '.$e->getMessage(),
'tracking_number' => $trackingNumber,
'api_used' => 'parcel_de',
];
@ -208,11 +242,10 @@ class DhlTrackingService
CURLOPT_CONNECTTIMEOUT => config('dhl.ssl.connect_timeout', 10),
CURLOPT_TIMEOUT => config('dhl.ssl.timeout', 30),
CURLOPT_USERAGENT => 'acme-laravel-dhl/1.0',
]
],
])
->get('https://api.dhl.com/track/shipments', [
->get('https://api-eu.dhl.com/track/shipments', [
'trackingNumber' => implode(',', $trackingNumbers),
'service' => 'parcel',
'requesterCountryCode' => 'DE',
'language' => 'de',
]);
@ -250,7 +283,7 @@ class DhlTrackingService
return [
'success' => false,
'message' => 'Fehler beim Abrufen der Tracking-Informationen: ' . $e->getMessage(),
'message' => 'Fehler beim Abrufen der Tracking-Informationen: '.$e->getMessage(),
];
}
}
@ -302,7 +335,7 @@ class DhlTrackingService
return [
'success' => false,
'message' => 'Fehler beim Einreihen des Tracking-Updates: ' . $e->getMessage(),
'message' => 'Fehler beim Einreihen des Tracking-Updates: '.$e->getMessage(),
'queued' => false,
];
}
@ -333,17 +366,31 @@ class DhlTrackingService
$result = $this->trackShipment($shipment->dhl_shipment_no);
if ($result['success']) {
$internalStatus = $this->mapDhlStatusToInternal($result['status']);
// Update shipment with tracking data
$shipment->update([
'status' => $this->mapDhlStatusToInternal($result['status']),
$updateData = [
'status' => $internalStatus,
'tracking_status' => $result['status_text'],
'last_tracked_at' => now(),
]);
];
// Mark tracking as completed if terminal status reached
if (in_array($internalStatus, DhlShipment::TERMINAL_STATUSES)) {
$updateData['tracking_completed_at'] = now();
}
$shipment->update($updateData);
// Save tracking events
$this->saveTrackingEvents($shipment, $result['events'] ?? []);
Log::info('[DHL Tracking Service] Tracking updated successfully (sync)', [
'shipment_id' => $shipment->id,
'dhl_shipment_no' => $shipment->dhl_shipment_no,
'tracking_status' => $result['status'],
'tracking_completed' => in_array($internalStatus, DhlShipment::TERMINAL_STATUSES),
'events_count' => count($result['events'] ?? []),
'api_used' => $result['api_used'],
]);
@ -353,6 +400,7 @@ class DhlTrackingService
'queued' => false,
'shipment_id' => $shipment->id,
'tracking_status' => $result['status'],
'tracking_completed' => in_array($internalStatus, DhlShipment::TERMINAL_STATUSES),
'tracking_details' => $result,
];
} else {
@ -371,13 +419,177 @@ class DhlTrackingService
return [
'success' => false,
'message' => 'Fehler beim Aktualisieren der Tracking-Informationen: ' . $e->getMessage(),
'message' => 'Fehler beim Aktualisieren der Tracking-Informationen: '.$e->getMessage(),
'queued' => false,
'shipment_id' => $shipment->id,
];
}
}
/**
* Update tracking for a batch of DHL shipments using the multi-tracking API.
* Processes shipments in chunks of 10 (DHL API limit) with rate-limiting pauses.
*
* @param Collection<DhlShipment> $shipments
* @return array{updated: int, failed: int, completed: int, results: array}
*/
public function updateTrackingBatch(Collection $shipments): array
{
$stats = [
'updated' => 0,
'failed' => 0,
'completed' => 0,
'results' => [],
];
// Process in chunks of 10 (DHL API limit)
$chunks = $shipments->chunk(10);
$chunkIndex = 0;
foreach ($chunks as $chunk) {
// Rate limiting: pause 1 second between batch API calls
if ($chunkIndex > 0) {
sleep(1);
}
$chunkIndex++;
// Build tracking number => shipment mapping
$shipmentMap = [];
foreach ($chunk as $shipment) {
$shipmentMap[$shipment->dhl_shipment_no] = $shipment;
}
$trackingNumbers = array_keys($shipmentMap);
try {
$batchResult = $this->trackMultipleShipments($trackingNumbers);
if ($batchResult['success'] && ! empty($batchResult['shipments'])) {
// Process each result from the batch API
foreach ($batchResult['shipments'] as $trackingResult) {
$trackingNo = $trackingResult['tracking_number'];
$shipment = $shipmentMap[$trackingNo] ?? null;
if (! $shipment) {
Log::warning('[DHL Tracking Service] Batch: tracking number not mapped', [
'tracking_number' => $trackingNo,
]);
continue;
}
// Remove from map so we can detect missing ones later
unset($shipmentMap[$trackingNo]);
$internalStatus = $this->mapDhlStatusToInternal($trackingResult['status']);
$updateData = [
'status' => $internalStatus,
'tracking_status' => $trackingResult['status_text'],
'last_tracked_at' => now(),
];
// Mark tracking as completed if terminal status reached
$isCompleted = in_array($internalStatus, DhlShipment::TERMINAL_STATUSES);
if ($isCompleted) {
$updateData['tracking_completed_at'] = now();
$stats['completed']++;
}
$shipment->update($updateData);
// Save tracking events
$this->saveTrackingEvents($shipment, $trackingResult['events'] ?? []);
$stats['updated']++;
$stats['results'][] = [
'shipment_id' => $shipment->id,
'tracking_number' => $trackingNo,
'status' => $internalStatus,
'completed' => $isCompleted,
'success' => true,
];
}
// Any remaining shipments in the map were not returned by the API
foreach ($shipmentMap as $trackingNo => $shipment) {
// Update last_tracked_at so we don't immediately retry
$shipment->update(['last_tracked_at' => now()]);
$stats['failed']++;
$stats['results'][] = [
'shipment_id' => $shipment->id,
'tracking_number' => $trackingNo,
'success' => false,
'message' => 'Nicht in Batch-Antwort enthalten',
];
}
} else {
// Entire batch failed - fall back to individual tracking
Log::warning('[DHL Tracking Service] Batch tracking failed, falling back to individual tracking', [
'tracking_numbers' => $trackingNumbers,
'message' => $batchResult['message'] ?? 'Unknown error',
]);
foreach ($chunk as $shipment) {
try {
$result = $this->updateTracking($shipment, ['auto_retrack' => false]);
if ($result['success']) {
$stats['updated']++;
if (! empty($result['tracking_completed'])) {
$stats['completed']++;
}
} else {
$stats['failed']++;
}
$stats['results'][] = [
'shipment_id' => $shipment->id,
'tracking_number' => $shipment->dhl_shipment_no,
'success' => $result['success'],
'fallback' => true,
];
} catch (Exception $e) {
$stats['failed']++;
$stats['results'][] = [
'shipment_id' => $shipment->id,
'tracking_number' => $shipment->dhl_shipment_no,
'success' => false,
'message' => $e->getMessage(),
'fallback' => true,
];
}
}
}
} catch (Exception $e) {
Log::error('[DHL Tracking Service] Batch tracking exception', [
'tracking_numbers' => $trackingNumbers,
'error' => $e->getMessage(),
]);
// Mark all as failed but update last_tracked_at
foreach ($chunk as $shipment) {
$shipment->update(['last_tracked_at' => now()]);
$stats['failed']++;
$stats['results'][] = [
'shipment_id' => $shipment->id,
'tracking_number' => $shipment->dhl_shipment_no,
'success' => false,
'message' => $e->getMessage(),
];
}
}
}
Log::info('[DHL Tracking Service] Batch tracking completed', [
'total' => $shipments->count(),
'updated' => $stats['updated'],
'failed' => $stats['failed'],
'completed' => $stats['completed'],
'chunks' => $chunks->count(),
]);
return $stats;
}
/**
* Map DHL status codes to internal status
*/
@ -414,6 +626,39 @@ class DhlTrackingService
return $descriptions[$statusCode] ?? 'Unbekannter Status';
}
/**
* Save tracking events from API response to database
*/
private function saveTrackingEvents(DhlShipment $shipment, array $events): void
{
if (empty($events)) {
return;
}
foreach ($events as $event) {
$eventTime = isset($event['timestamp']) ? \Carbon\Carbon::parse($event['timestamp']) : now();
// Upsert: avoid duplicates based on shipment + event_time + status_code
DhlTrackingEvent::updateOrCreate(
[
'shipment_id' => $shipment->id,
'event_time' => $eventTime,
'status_code' => $event['statusCode'] ?? ($event['status'] ?? 'unknown'),
],
[
'status_text' => $event['description'] ?? ($event['remark'] ?? 'Unbekannt'),
'location' => $event['location']['address']['addressLocality'] ?? null,
'raw' => $event,
]
);
}
Log::info('[DHL Tracking Service] Tracking events saved', [
'shipment_id' => $shipment->id,
'events_saved' => count($events),
]);
}
/**
* Get SSL version constant based on configuration
*/

View file

@ -1,4 +1,5 @@
<?php
namespace App\Services;
use App\Mail\MailInvoice;
@ -8,60 +9,171 @@ use Illuminate\Support\Facades\Mail;
class Invoice
{
public static function getInvoiceNumber(){
public static function getInvoiceNumber()
{
return (int) Setting::getContentBySlug('invoice-number');
}
public static function makeNextInvoiceNumber(){
$invoice_number = self::getInvoiceNumber();
$invoice_number = $invoice_number+1;
Setting::setContentBySlug('invoice-number', $invoice_number, 'int');
return $invoice_number;
/**
* Atomically get and increment the invoice number with database locking
* to prevent race conditions when multiple invoices are created simultaneously
*/
public static function makeNextInvoiceNumber()
{
return \DB::transaction(function () {
// Lock the setting row for update to prevent concurrent reads
$setting = Setting::where('slug', 'invoice-number')
->lockForUpdate()
->first();
if (! $setting) {
// Create if not exists
$setting = Setting::create([
'slug' => 'invoice-number',
'type' => 'int',
'int' => 1,
]);
return 1;
}
$invoice_number = (int) $setting->int;
$invoice_number = $invoice_number + 1;
// Update directly on the locked row
$setting->int = $invoice_number;
$setting->save();
return $invoice_number;
});
}
public static function createInvoiceNumber($invoice_number, $invoice_date){
public static function createInvoiceNumber($invoice_number, $invoice_date)
{
$prefix = \Carbon::parse($invoice_date)->format('Y');
$invoice_number = str_pad($invoice_number, 5, '0', STR_PAD_LEFT);
return $prefix.$invoice_number;
}
public static function getInvoiceStorageDir($invoice_date){
return "invoice/".\Carbon::parse($invoice_date)->format('Y/m/');
public static function getInvoiceStorageDir($invoice_date)
{
return 'invoice/'.\Carbon::parse($invoice_date)->format('Y/m/');
}
public static function getDeliveryStorageDir($invoice_date){
return "delivery/".\Carbon::parse($invoice_date)->format('Y/m/');
public static function getDeliveryStorageDir($invoice_date)
{
return 'delivery/'.\Carbon::parse($invoice_date)->format('Y/m/');
}
public static function makeInvoiceFilename($invoice_number){
return $invoice_number."-MIVITA-Rechnung.pdf";
public static function makeInvoiceFilename($invoice_number)
{
return $invoice_number.'-MIVITA-Rechnung.pdf';
}
public static function makeDeliveryFilename($invoice_number){
return $invoice_number."-MIVITA-Lieferschein.pdf";
public static function makeDeliveryFilename($invoice_number)
{
return $invoice_number.'-MIVITA-Lieferschein.pdf';
}
public static function isInvoice(ShoppingOrder $shopping_order){
/**
* Erstellt den Dateinamen für eine Stornorechnung
*
* @param string $invoice_number
* @return string
*/
public static function makeCancellationFilename($invoice_number)
{
return $invoice_number.'-MIVITA-Stornorechnung.pdf';
}
/**
* Erstellt den Dateinamen für einen Storno-Lieferschein
*
* @param string $invoice_number
* @return string
*/
public static function makeCancellationDeliveryFilename($invoice_number)
{
return $invoice_number.'-MIVITA-Storno-Lieferschein.pdf';
}
/**
* Erstellt den Dateinamen für eine lokalisierte Rechnung.
* Deutsch (de) ist das Original ohne Suffix.
*
* @param string $invoice_number
* @param string $locale
* @return string
*/
public static function makeInvoiceFilenameLocale($invoice_number, $locale)
{
if ($locale === 'de' || ! $locale) {
return self::makeInvoiceFilename($invoice_number);
}
return $invoice_number.'-MIVITA-Rechnung-'.$locale.'.pdf';
}
/**
* Erstellt den Dateinamen für einen lokalisierten Lieferschein.
* Deutsch (de) ist das Original ohne Suffix.
*
* @param string $invoice_number
* @param string $locale
* @return string
*/
public static function makeDeliveryFilenameLocale($invoice_number, $locale)
{
if ($locale === 'de' || ! $locale) {
return self::makeDeliveryFilename($invoice_number);
}
return $invoice_number.'-MIVITA-Lieferschein-'.$locale.'.pdf';
}
public static function isInvoice(ShoppingOrder $shopping_order)
{
return $shopping_order->isInvoice();
}
public static function sendInvoiceMail($shopping_order, $user_invoice){
/**
* Holt die Rechnungsnummer einer Bestellung
*
* @return string|null
*/
public static function getNumber(ShoppingOrder $shopping_order)
{
return $shopping_order->user_invoice ? $shopping_order->user_invoice->full_number : null;
}
/**
* Holt das Rechnungsdatum einer Bestellung
*
* @return string|null
*/
public static function getDate(ShoppingOrder $shopping_order)
{
return $shopping_order->user_invoice ? $shopping_order->user_invoice->date : null;
}
public static function sendInvoiceMail($shopping_order, $user_invoice)
{
$bcc = [];
$billing_email = $shopping_order->shopping_user->billing_email;
if(!$billing_email){
if($shopping_order->mode === 'test'){
if (! $billing_email) {
if ($shopping_order->mode === 'test') {
$billing_email = config('app.checkout_test_mail');
}else{
} else {
$billing_email = config('app.checkout_mail');
}
}
if($shopping_order->mode === 'test'){
if ($shopping_order->mode === 'test') {
$bcc[] = config('app.checkout_test_mail');
}else{
} else {
$bcc[] = config('app.checkout_mail');
}
Mail::to($billing_email)->bcc($bcc)->locale($shopping_order->getLocale())->send(new MailInvoice($shopping_order, $user_invoice));
}
}

View file

@ -2,19 +2,18 @@
namespace App\Services;
use App\Models\ShoppingUser;
use App\Models\ShoppingInstance;
use App\Models\ShoppingUser;
use Yard;
class OrderPaymentService
{
public static function deleteInstance($identifier)
{
Yard::instance('shopping')->deleteStoredCart($identifier);
\App\Models\ShoppingInstance::where('identifier', $identifier)->delete();
//delete session
\App\Models\ShoppingInstance::where('identifier', $identifier)->delete();
// delete session
/* if(\Session::has('user_shop_payment') && \Session::get('user_shop_payment') === 6){
$user_shop_identifier = \Session::get('user_shop_identifier');
Yard::instance('shopping')->deleteStoredCart($identifier);
@ -24,7 +23,7 @@ class OrderPaymentService
public static function updateInstanceStatus($identifier, $status, $lower = true)
{
if (!ShoppingInstance::where('identifier', $identifier)->exists()) {
if (! ShoppingInstance::where('identifier', $identifier)->exists()) {
return false;
}
if ($lower) {
@ -39,9 +38,10 @@ class OrderPaymentService
public static function getInstanceStatus($identifier)
{
$shopping_instance = ShoppingInstance::where('identifier', $identifier)->first();
if (!$shopping_instance) {
if (! $shopping_instance) {
return false;
}
return $shopping_instance->getStatus();
}
@ -49,33 +49,39 @@ class OrderPaymentService
{
$isFor = $shoppingInstance->shopping_data['is_for'] ?? '-';
if ($isFor === 'abo-ot-customer') {
return ' <span class="badge badge-pill badge-warning">' . __('abo.abo') . '</span>';
return ' <span class="badge badge-pill badge-warning">'.__('abo.abo').'</span>';
}
if ($isFor === 'ot-customer') {
return ' <span class="badge badge-pill badge-secondary">' . __('order.order') . '</span>';
return ' <span class="badge badge-pill badge-secondary">'.__('order.order').'</span>';
}
return "";
return '';
}
public static function getStatusBadgeClasses()
{
return [
'link_sent' => 'default',
'link_openly' => 'info',
'link_check' => 'warning',
'link_pending' => 'warning',
'link_appointed' => 'warning',
'link_paid' => 'secondary',
'link_failed' => 'danger',
'link_canceled' => 'danger',
];
}
public static function getStatusBadge(ShoppingInstance $shoppingInstance)
{
$status = $shoppingInstance->getStatus();
$badgeClasses = [
'link_sent' => 'info',
'link_openly' => 'info',
'link_paid' => 'secondary',
'link_check' => 'warning',
'link_pending' => 'warning',
'link_appointed' => 'warning',
'link_failed' => 'danger',
'link_canceled' => 'danger'
];
$badgeClasses = self::getStatusBadgeClasses();
if (isset($badgeClasses[$status])) {
return sprintf(
' <span class="badge badge-pill badge-%s">%s</span>',
$badgeClasses[$status],
__('payment.' . $status)
__('payment.'.$status)
);
}
@ -100,7 +106,7 @@ class OrderPaymentService
return sprintf(
' <div class="alert alert-%s">%s</div>',
$badgeClasses[$status],
__('payment.alert_' . $status)
__('payment.alert_'.$status)
);
}
@ -111,12 +117,12 @@ class OrderPaymentService
{
$shopping_instance = ShoppingInstance::where('identifier', $identifier)->first();
if (!$shopping_instance) {
if (! $shopping_instance) {
abort(403, __('msg.shopping_instance_not_found'));
}
$shopping_data = $shopping_instance->shopping_data;
$shopping_user = $shopping_data['shopping_user_id'] ? ShoppingUser::find($shopping_data['shopping_user_id']) : null;
if (!$shopping_user) {
if (! $shopping_user) {
abort(403, __('msg.shopping_user_not_found'));
}
$yard_shopping_items = self::getRestoredYardShoppingItems($shopping_instance);
@ -130,6 +136,7 @@ class OrderPaymentService
'is_for' => $shopping_instance->shopping_data['is_for'] ?? false,
'backlink' => false,
];
return $data;
}
@ -145,7 +152,6 @@ class OrderPaymentService
Yard::instance('shopping')->setUserPriceInfos($shopping_instance->shopping_data['user_price_infos']);
Yard::instance('shopping')->setShippingCountryWithPrice($shopping_instance->country_id, $is_for);
$rows = Yard::instance('shopping')->getContentByOrder();
$ret = [];
$ret['items'] = [];
@ -154,12 +160,12 @@ class OrderPaymentService
foreach ($rows as $row) {
$product = \App\Models\Product::find($row->id);
$item = new \stdClass();
$item = new \stdClass;
$item->image = $row->options->has('image') ? $row->options->image : null;
$item->price_net = (float) Yard::instance('shopping')->rowPriceNet($row, 3, '.', '');
$item->price_net_total = (float) Yard::instance('shopping')->rowSubtotalNet($row, 2, '.', '');
$item->price_currency = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('rowPriceNetCurrency', $row, 3) . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency_total = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('rowSubtotalCurrency', $row, 3) . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('rowPriceNetCurrency', $row, 3).' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency_total = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('rowSubtotalCurrency', $row, 3).' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price = $row->price;
$item->price_total = ($row->qty * $row->price);
$item->qty = $row->qty;
@ -174,16 +180,16 @@ class OrderPaymentService
$ret['tax_free'] = $tax_free;
$ret['total']['subtotal'] = Yard::instance('shopping')->subtotal();
$ret['total']['subtotal_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('subtotal') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotal_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('subtotal').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['shippingCountryName'] = Yard::instance('shopping')->getShippingCountryName();
$ret['total']['shippingNet'] = Yard::instance('shopping')->shippingNet();
$ret['total']['shippingNet currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('shippingNet') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['shippingNet currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('shippingNet').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotalWithShipping'] = Yard::instance('shopping')->subtotalWithShipping();
$ret['total']['subtotalWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('subtotalWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotalWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('subtotalWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['taxWithShipping'] = Yard::instance('shopping')->taxWithShipping();
$ret['total']['taxWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('taxWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['taxWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('taxWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['totalWithShipping'] = Yard::instance('shopping')->totalWithShipping();
$ret['total']['totalWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('totalWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['totalWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('totalWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
return $ret;
}

View file

@ -2,7 +2,6 @@
namespace App\Services;
use App\Mail\MailCheckout;
use App\Models\ProductBuying;
use App\Models\ShoppingOrder;
@ -10,26 +9,22 @@ use App\Models\ShoppingPayment;
use App\Models\UserCreditItem;
use App\Models\UserLevel;
use App\Repositories\InvoiceRepository;
use App\Services\AboHelper;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\ShopApiOrderCart;
use App\Services\UserUtil;
use App\Services\Util;
use App\User;
use Illuminate\Support\Facades\Mail;
class Payment
{
public static $txaction_text = [
'paid' => 'paid',
'appointed' => 'open',
'failed' => 'failed',
'extern' => 'open', //offen
'extern' => 'open', // offen
'extern_paid' => 'paid',
'invoice_open' => 'open',
'invoice_paid' => 'paid',
'invoice_non' => 'no_payment',
'cancelled' => 'cancelled',
'NULL' => 'no_payment',
];
@ -37,11 +32,12 @@ class Payment
'paid' => 'paymend_paid',
'appointed' => 'paymend_open',
'failed' => 'paymend_failed',
'extern' => 'extern_open', //offen
'extern' => 'extern_open', // offen
'extern_paid' => 'extern_paid',
'invoice_open' => 'invoice_open',
'invoice_paid' => 'invoice_paid',
'invoice_non' => 'invoice_no_payment',
'cancelled' => 'cancelled',
'NULL' => 'no_payment',
];
@ -60,15 +56,16 @@ class Payment
'invoice_open' => 'warning',
'invoice_paid' => 'success',
'invoice_non' => 'failed',
'cancelled' => 'danger',
];
public static function getFormattedTxaction($txaction)
{
if ($txaction && isset(self::$txaction_text[$txaction])) {
return __('payment.' . self::$txaction_text[$txaction]);
return __('payment.'.self::$txaction_text[$txaction]);
}
return __('payment.' . self::$txaction_text['NULL']);
return __('payment.'.self::$txaction_text['NULL']);
}
public static function getFormattedTxactionColor($txaction)
@ -76,15 +73,17 @@ class Payment
if ($txaction && isset(self::$txaction_color[$txaction])) {
return self::$txaction_color[$txaction];
}
return "warning";
return 'warning';
}
public static function getTransTxactionFilterText()
{
$ret = [];
foreach (self::$txaction_filter_text as $key => $val) {
$ret[$key] = trans('payment.' . $val);
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
@ -92,8 +91,9 @@ class Payment
{
$ret = [];
foreach (self::$txaction_invoice as $key => $val) {
$ret[$key] = trans('payment.' . $val);
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
@ -101,29 +101,32 @@ class Payment
{
if ($shopping_order->mode === 'test') {
return '<span class="badge badge-pill badge-default">' . strtoupper($shopping_order->mode) . ' - ' . self::getFormattedTxaction($shopping_order->txaction) . '</span>';
return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
if ($shopping_order->mode === 'dev') {
return '<span class="badge badge-pill badge-info">' . strtoupper($shopping_order->mode) . ' - ' . self::getFormattedTxaction($shopping_order->txaction) . '</span>';
return '<span class="badge badge-pill badge-info">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
return '<span class="badge badge-pill badge-' . self::getFormattedTxactionColor($shopping_order->txaction) . '">' . self::getFormattedTxaction($shopping_order->txaction) . '</span>';
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_order->txaction).'">'.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
public static function getPaymentForBadge(ShoppingOrder $shopping_order)
{
$abo = '';
if ($shopping_order->is_abo) {
$abo = ' <span class="badge badge-pill badge-success">' . __('abo.abo') . '</span>';
$abo = ' <span class="badge badge-pill badge-success">'.__('abo.abo').'</span>';
}
return '<span class="badge badge-pill badge-' . $shopping_order->getPaymentForColor() . '">' . $shopping_order->getPaymentForType() . '</span>' . $abo;
return '<span class="badge badge-pill badge-'.$shopping_order->getPaymentForColor().'">'.$shopping_order->getPaymentForType().'</span>'.$abo;
}
public static function getShoppingPaymentBadge(ShoppingPayment $shopping_payment)
{
if ($shopping_payment->mode === 'test') {
return '<span class="badge badge-pill badge-default">' . strtoupper($shopping_payment->mode) . ' - ' . self::getFormattedTxaction($shopping_payment->txaction) . '</span>';
return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_payment->mode).' - '.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
}
return '<span class="badge badge-pill badge-' . self::getFormattedTxactionColor($shopping_payment->txaction) . '">' . self::getFormattedTxaction($shopping_payment->txaction) . '</span>';
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_payment->txaction).'">'.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
}
public static function addUserCreditMargin(User $user, $credit, $status, $message)
@ -133,7 +136,7 @@ class Payment
'credit' => $credit,
'message' => $message,
'from_month' => date('n'),
'from_year' => date('Y'),
'from_year' => date('Y'),
'status' => $status,
]);
}
@ -143,7 +146,7 @@ class Payment
ProductBuying::create([
'user_id' => $user->id,
'product_id' => $product_id,
'amount' => 1
'amount' => 1,
]);
}
@ -155,9 +158,9 @@ class Payment
'user_id' => $user->user_sponsor->id,
'total_net' => 0,
'points' => $product->sponsor_buying_points_amount,
'info' => 'VP: ' . $user->getFullName(false) . ' | ' . $product->name,
'info' => 'VP: '.$user->getFullName(false).' | '.$product->name,
'status_points' => 2,
'status' => 5
'status' => 5,
];
SalesPointsVolume::addSalesPointsVolume($data);
}
@ -165,7 +168,7 @@ class Payment
public static function updateUserLevel(User $user, $to_level_id)
{
//nur updaten, wenn der user->m_level kleiner ist als $to_level_id
// nur updaten, wenn der user->m_level kleiner ist als $to_level_id
if ($user->user_level) {
$ToUserLevel = UserLevel::find($to_level_id);
if ($user->user_level->pos < $ToUserLevel->pos) {
@ -190,7 +193,7 @@ class Payment
$shopping_order->paid = $paid;
$shopping_order->save();
//if product has actions
// if product has actions
if ($shopping_order->shopping_order_items && $shopping_order->auth_user_id) {
foreach ($shopping_order->shopping_order_items as $shopping_order_item) {
if ($shopping_order_item->product) {
@ -204,17 +207,19 @@ class Payment
}
if ($shopping_order_item->product->action) {
$send_link = true;
//new date
// new date
$date = \Carbon::now()->modify('1 year');
if ($user->payment_account && $user->daysActiveAccount() > 0) {
$date = \Carbon::parse($user->payment_account)->modify('1 year');
}
foreach ($shopping_order_item->product->action as $do) {
// bzw. product_id 34 = 0 => payment_for_account => payment_order_id = 35 = 0 => payment_for_account, 1 => payment_for_shop, 2 => payment_for_shop_upgrade
// 0 => payment_for_account, 1 => payment_for_shop, 2 => payment_for_shop_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_account') {
$user->payment_order_id = $shopping_order_item->product->id; //34
$user->payment_order_id = $shopping_order_item->product->id;
$user->payment_account = $date;
$user->wizard = 100;
//only date is > now and acount is deactive.
// only date is > now and acount is deactive.
if ($date > \Carbon::now()) {
if ($user->active === 0) {
$user->active = true;
@ -224,19 +229,22 @@ class Payment
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 1 => payment_for_shop
if ($shopping_order_item->product->getActionName($do) === 'payment_for_shop') {
$user->payment_order_id = $shopping_order_item->product->id; //35
$user->payment_order_id = $shopping_order_item->product->id; // 35
$user->payment_shop = $date;
$user->wizard = 100;
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 2 => payment_for_shop_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_shop_upgrade') {
if ($shopping_order_item->product->upgrade_to_id) {
$user->payment_order_id = $shopping_order_item->product->upgrade_to_id;
}
$user->payment_shop = $user->payment_account; //same Date, is upgrade
$user->payment_shop = $user->payment_account; // same Date, is upgrade
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 4 => payment_for_lead_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_lead_upgrade') {
if ($shopping_order_item->product->upgrade_to_id) {
self::updateUserLevel($user, $shopping_order_item->product->upgrade_to_id);
@ -259,20 +267,26 @@ class Payment
$shopping_order->setUserHistoryValue(['status' => 9]);
ShopApiOrderCart::finishOrder($shopping_order->shopping_collect_order);
}
//the Order is Pay, so we can set the Status in the Abo
// Set payment link status to paid for all orders
if ($shopping_payment) {
Util::setInstanceStatusByPayment($shopping_payment, 10); // link_paid
$shopping_payment->identifier = null;
$shopping_payment->save();
}
// the Order is Pay, so we can set the Status in the Abo
if ($shopping_order->is_abo) {
if ($shopping_payment) {
Util::setInstanceStatusByPayment($shopping_payment, 10); //link_paid
$shopping_payment->identifier = null;
$shopping_payment->save();
}
AboHelper::setAboActive($shopping_order, 2, true);
}
//make Invoice is not exist and is live
// make Invoice is not exist and is live
if ($shopping_order->mode === 'live' || Util::isTestSystem(true)) {
$invoice_repo = new InvoiceRepository($shopping_order);
if (!$shopping_order->isInvoice()) {
// Reload the shopping order to check for invoice again (defense against race conditions)
$shopping_order->refresh();
if (! $shopping_order->isInvoice()) {
$invoice_repo = new InvoiceRepository($shopping_order);
$invoice_repo->createAndSalesVolume();
}
}
@ -287,15 +301,15 @@ class Payment
// Überprüfung der Billing-E-Mail-Adresse
if (!$billing_email) {
if (! $billing_email) {
if ($data['mode'] === 'test') {
$billing_email = config('app.checkout_test_mail');
} else {
$billing_email = config('app.checkout_mail');
}
}
if (!filter_var($billing_email, FILTER_VALIDATE_EMAIL)) {
\Log::channel('payment')->error("Invalid billing email at shopping_order " . $shopping_order->id, ['billing_email' => $billing_email]);
if (! filter_var($billing_email, FILTER_VALIDATE_EMAIL)) {
\Log::channel('payment')->error('Invalid billing email at shopping_order '.$shopping_order->id, ['billing_email' => $billing_email]);
$billing_email = config('app.checkout_mail');
}
@ -305,7 +319,7 @@ class Payment
$bcc[] = config('app.checkout_mail');
}
if (!$shopping_order->shopping_user->is_like && $shopping_order->shopping_user->member) {
if (! $shopping_order->shopping_user->is_like && $shopping_order->shopping_user->member) {
$bcc[] = $shopping_order->shopping_user->member->email;
}
$data['payment_error'] = isset($data['payment_error']) ? $data['payment_error'] : false;

View file

@ -2,24 +2,20 @@
namespace App\Services;
use Yard;
use App\User;
use App\Models\UserHistory;
use App\Models\ShoppingUser;
use App\Http\Controllers\Pay\PayoneController;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\PaymentTransaction;
use App\Http\Controllers\Pay\PayoneController;
use App\Models\ShoppingUser;
use App\Models\UserHistory;
use Yard;
class PaymentHelper
{
public function setProduct($product)
{
Yard::instance('shopping')->destroy();
Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->price, false, false, ['image' => "", 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->price, false, false, ['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
}
public function initELVPayment($user)
@ -28,17 +24,16 @@ class PaymentHelper
$shopping_user = $this->makeShoppingUser($user);
$shopping_order = $this->makeShoppingOrder($user, $shopping_user);
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance('shopping')->totalWithShipping(2, '.', '') * 100;
$payment_method = 'elv';
$ret['elv']['mandate_identification'] = isset($user->account->payment_data['mandate_identification']) ? $user->account->payment_data['mandate_identification'] : "";
$ret['elv']['creditor_identifier'] = isset($user->account->payment_data['creditor_identifier']) ? $user->account->payment_data['creditor_identifier'] : "";
$ret['elv']['iban'] = isset($user->account->payment_data['iban']) ? $user->account->payment_data['iban'] : "";
$ret['elv']['bic'] = isset($user->account->payment_data['bic']) ? $user->account->payment_data['bic'] : "";
$ret['elv']['bankaccountholder'] = isset($user->account->payment_data['bankaccountholder']) ? $user->account->payment_data['bankaccountholder'] : "";
$ret['elv']['mandate_identification'] = isset($user->account->payment_data['mandate_identification']) ? $user->account->payment_data['mandate_identification'] : '';
$ret['elv']['creditor_identifier'] = isset($user->account->payment_data['creditor_identifier']) ? $user->account->payment_data['creditor_identifier'] : '';
$ret['elv']['iban'] = isset($user->account->payment_data['iban']) ? $user->account->payment_data['iban'] : '';
$ret['elv']['bic'] = isset($user->account->payment_data['bic']) ? $user->account->payment_data['bic'] : '';
$ret['elv']['bankaccountholder'] = isset($user->account->payment_data['bankaccountholder']) ? $user->account->payment_data['bankaccountholder'] : '';
$reference = $pay->setPrePayment($payment_method, $amount, 'EUR', $ret);
$pay->setPersonalData();
@ -71,12 +66,12 @@ class PaymentHelper
if ($response['status'] === 'APPROVED') {
$payT = PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'authorization',
'request' => 'authorization',
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
'transmitted_data' => $response,
'mode' => $shopping_payment->mode
'mode' => $shopping_payment->mode,
]);
UserHistory::create(['user_id' => $user->id, 'shopping_order_id' => $shopping_order->id, 'action' => 'abo_open_payment', 'referenz' => $payT->id, 'identifier' => $user->payment_account, 'status' => 5]);
}
@ -84,7 +79,7 @@ class PaymentHelper
public function makeShoppingUser($user, $is_from = 'membership', $is_for = 'me')
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->auth_user_id = $user->id;
$shopping_user->mode = 'prev';
$shopping_user->language = $user->getLocale();
@ -99,6 +94,7 @@ class PaymentHelper
$shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email;
$shopping_user->language = $user->getLocale();
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->accepted_data_checkbox = 1;
@ -118,6 +114,7 @@ class PaymentHelper
$shopping_user->shipping_phone = $user->account->shipping_phone;
$shopping_user->shipping_postnumber = $user->account->shipping_postnumber;
$shopping_user->save();
return $shopping_user;
}
@ -147,12 +144,12 @@ class PaymentHelper
$shopping_order = ShoppingOrder::create($data);
$items = Yard::instance('shopping')->getContentByOrder();
foreach ($items as $item) {
if (!ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
if (! ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
$price_net = Yard::instance('shopping')->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
@ -163,12 +160,13 @@ class PaymentHelper
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
'slug' => $item->options->slug,
];
$shopping_order_item = ShoppingOrderItem::create($data);
}
}
$shopping_order->makeTaxSplit();
return $shopping_order;
}
}

View file

@ -2,7 +2,6 @@
namespace App\Services;
use App\Http\Controllers\Api\KasController;
use App\Models\ShoppingUser;
use App\Models\ShoppingUserMemberLog;
@ -12,8 +11,6 @@ use App\User;
class UserUtil
{
public static function setShoppingUserToNewMember($pre_member_id, $new_member_id)
{
$ShoppingUsers = ShoppingUser::where('member_id', $pre_member_id)->get();
@ -21,7 +18,7 @@ class UserUtil
ShoppingUserMemberLog::create([
'pre_member_id' => $shopping_user->member_id,
'shopping_user_id' => $shopping_user->id,
'new_member_id' => $new_member_id
'new_member_id' => $new_member_id,
]);
$shopping_user->member_id = $new_member_id;
$shopping_user->save();
@ -30,8 +27,8 @@ class UserUtil
public static function setNewSponsorToChilds($inactive_sponsor_id, $new_sponsor_id)
{
//alle User die diesen inaktivien Sponsor haben
$child_users = User::where('m_sponsor', $inactive_sponsor_id)->get(); //auch deaktiverte
// alle User die diesen inaktivien Sponsor haben
$child_users = User::where('m_sponsor', $inactive_sponsor_id)->get(); // auch deaktiverte
foreach ($child_users as $child_user) {
UserCleanUpLog::create([
'inactive_sponsor_id' => $inactive_sponsor_id,
@ -45,12 +42,12 @@ class UserUtil
public static function resetChildsToSponsor($re_sponsor_id)
{
//alle alten Childs vom re_sponsor_id / User wieder herstellen
// alle alten Childs vom re_sponsor_id / User wieder herstellen
$UserCleanUpUsers = UserCleanUpLog::where('inactive_sponsor_id', $re_sponsor_id)->get();
foreach ($UserCleanUpUsers as $UserCleanUpUser) {
$child_user = User::find($UserCleanUpUser->child_user_id);
if ($child_user) {
//delete Logs from user child where is newer then this
// delete Logs from user child where is newer then this
$deleteUserCleanUpLogs = UserCleanUpLog::where('child_user_id', $UserCleanUpUser->child_user_id)->where('created_at', '>', $UserCleanUpUser->created_at)->get();
foreach ($deleteUserCleanUpLogs as $deleteUserCleanUpLog) {
$deleteUserCleanUpLog->delete();
@ -58,11 +55,11 @@ class UserUtil
if ($child_user->m_sponsor) { // child is active
$child_user->m_sponsor = $re_sponsor_id;
}
if ($child_user->pre_sponsor) { //child is inactive
if ($child_user->pre_sponsor) { // child is inactive
$child_user->pre_sponsor = $re_sponsor_id;
}
$child_user->save();
//delete this log
// delete this log
$UserCleanUpUser->delete();
}
}
@ -72,10 +69,22 @@ class UserUtil
{
$user = User::find($user_id);
if ($user) {
if (! $user) {
\Log::channel('cleanup')->error('setUserToClient: User not found, user_id: '.$user_id);
return false;
}
if (! $user->account) {
\Log::channel('cleanup')->error('setUserToClient: User has no account data, user_id: '.$user_id);
return false;
}
try {
$data = [
'member_id' => $sponsor_id,
'language' => $user->lang ? $user->lang : 'de',
'language' => $user->lang ?? 'de',
'billing_salutation' => $user->account->salutation,
'billing_company' => $user->account->company,
'billing_firstname' => $user->account->first_name,
@ -87,6 +96,7 @@ class UserUtil
'billing_country_id' => $user->account->country_id,
'billing_phone' => $user->account->getPhoneNumber(),
'billing_email' => $user->email,
'language' => $user->account->getLocale(),
'same_as_billing' => $user->account->same_as_billing,
'shipping_salutation' => $user->account->shipping_salutation,
'shipping_company' => $user->account->shipping_company,
@ -100,11 +110,17 @@ class UserUtil
'shipping_phone' => $user->account->getShippingPhoneFull(),
'shipping_postnumber' => $user->account->shipping_postnumber,
];
ShoppingUser::create($data);
return true;
} catch (\Exception $e) {
\Log::channel('cleanup')->error('setUserToClient failed for user_id: '.$user_id.' | Error: '.$e->getMessage());
return false;
}
}
/*
find next activ sponsor on user id
first $sponsor_id can user_id, looks has m_sponsor or pre_sponsor.
@ -113,27 +129,28 @@ class UserUtil
{
$user = User::withTrashed()->find($sponsor_id);
if (!$user) { //kein User unter der ID - to root
if (! $user) { // kein User unter der ID - to root
return User::find(6);
}
//user ist aktiv
// user ist aktiv
if ($user->isActiveAccount()) {
return $user;
}
if ($user->m_sponsor) { //hat der User einen m_sponsor
if ($user->m_sponsor) { // hat der User einen m_sponsor
return self::findNextActiveSponsor($user->m_sponsor);
}
if ($user->pre_sponsor) { //hat der User einen pre_sponsor - schon inaktiv
if ($user->pre_sponsor) { // hat der User einen pre_sponsor - schon inaktiv
return self::findNextActiveSponsor($user->pre_sponsor);
}
//dump('not sponsor');
// dump('not sponsor');
return $user;
}
public static function deactiveUser($user)
{
$user->pre_sponsor = $user->m_sponsor; //den sponsor speichern für wiederherstellung
$user->pre_sponsor = $user->m_sponsor; // den sponsor speichern für wiederherstellung
$user->m_sponsor = null;
$user->active = false;
$user->save();
@ -143,7 +160,7 @@ class UserUtil
{
if ($user->pre_sponsor) {
$pre_sponsor = self::findNextActiveSponsor($user->pre_sponsor);
$user->m_sponsor = $pre_sponsor->id; //den sponsor wiederherstellen
$user->m_sponsor = $pre_sponsor->id; // den sponsor wiederherstellen
$user->pre_sponsor = null;
}
$user->active = true;
@ -152,14 +169,14 @@ class UserUtil
public static function deleteUser(User $user, $complete = false)
{
//shop wird gelöscht
// shop wird gelöscht
if ($user->shop) {
// $subdomain_name = $user->shop->slug . '.mivita.care';
$user->shop->name = "delete" . $user->shop->id;
$user->shop->slug = "delete" . $user->shop->id;
$user->shop->name = 'delete'.$user->shop->id;
$user->shop->slug = 'delete'.$user->shop->id;
$user->shop->save();
$user->shop->delete();
//isset KAS - delete Subdomain
// isset KAS - delete Subdomain
/*if (!Util::isTestSystem()) {
$kas = new KasController();
$pra = array(
@ -169,12 +186,12 @@ class UserUtil
}*/
}
//user soll nicht komplett gelöscht werden
$user->email = "delete-" . $user->email;
//password wird gelöscht
$user->password = "delete" . time();
// user soll nicht komplett gelöscht werden
$user->email = 'delete-'.$user->email;
// password wird gelöscht
$user->password = 'delete'.time();
$user->confirmed = 0;
$user->confirmation_code = "delete" . time();
$user->confirmation_code = 'delete'.time();
$user->confirmation_date = null;
$user->confirmation_code_to = null;
$user->confirmation_code_remider = 2;
@ -185,9 +202,9 @@ class UserUtil
$user->admin = 0;
$user->deleted_at = now();
$user->pre_deleted_at = now();
//user soll komplett gelöscht werden
// user soll komplett gelöscht werden
if ($complete) {
$user->email = "delete-" . time() . "-" . rand(1000, 9999);
$user->email = 'delete-'.time().'-'.rand(1000, 9999);
if ($user->account) {
$user->account->delete();
}
@ -198,14 +215,16 @@ class UserUtil
return true;
}
public static function checkEmailExists($user)
{
$email = str_replace("delete-", "", $user->email);
$email = str_replace('delete-', '', $user->email);
$user = User::where('email', $email)->first();
if ($user) {
return 'Der Account kann nicht wieder hergestellt werden, da die E-Mail-Adresse <b>' . $email . '</b> bereits in Verwendung ist.';
return 'Der Account kann nicht wieder hergestellt werden, da die E-Mail-Adresse <b>'.$email.'</b> bereits in Verwendung ist.';
}
return null;
}
@ -213,11 +232,11 @@ class UserUtil
{
if ($user->pre_sponsor) {
$pre_sponsor = self::findNextActiveSponsor($user->pre_sponsor);
$user->m_sponsor = $pre_sponsor->id; //den sponsor wiederherstellen
$user->m_sponsor = $pre_sponsor->id; // den sponsor wiederherstellen
$user->pre_sponsor = null;
}
$user->email = str_replace("delete-", "", $user->email);
$user->email = str_replace('delete-', '', $user->email);
$user->confirmed = 1;
$user->confirmation_date = now();
$user->confirmation_code = null;
@ -242,13 +261,13 @@ class UserUtil
}
}
public static function reactiveUserResetChilds($user_id, $info = '')
{
$user = User::find($user_id);
if (!$user) {
\Log::channel('cleanup')->error('reactiveUserResetChilds find no user by user_id:' . $user_id);
if (! $user) {
\Log::channel('cleanup')->error('reactiveUserResetChilds find no user by user_id:'.$user_id);
return 0;
}
$data = [
@ -258,7 +277,7 @@ class UserUtil
'm_first_name' => $user->account ? $user->account->m_first_name : '',
'm_last_name' => $user->account ? $user->account->m_last_name : '',
];
\Log::channel('cleanup')->info('reactiveUserResetChilds ' . $info . ' : ' . json_encode($data));
\Log::channel('cleanup')->info('reactiveUserResetChilds '.$info.' : '.json_encode($data));
self::reactiveUser($user);
self::resetChildsToSponsor($user->id);
@ -268,8 +287,9 @@ class UserUtil
{
$user = User::find($user_id);
if (!$user) {
\Log::channel('cleanup')->error('deactiveUserNewSponsorChilds find no user by user_id:' . $user_id);
if (! $user) {
\Log::channel('cleanup')->error('deactiveUserNewSponsorChilds find no user by user_id:'.$user_id);
return 0;
}
$data = [
@ -284,9 +304,9 @@ class UserUtil
if ($active_sponsor) {
self::setNewSponsorToChilds($user->id, $active_sponsor->id);
} else {
\Log::channel('cleanup')->error('cleanUpInActiveUser find no active_sponsor by inactive_user:' . $user->id);
\Log::channel('cleanup')->error('cleanUpInActiveUser find no active_sponsor by inactive_user:'.$user->id);
}
\Log::channel('cleanup')->info('deactiveUserNewSponsorChilds ' . $info . ' : ' . json_encode($data));
\Log::channel('cleanup')->info('deactiveUserNewSponsorChilds '.$info.' : '.json_encode($data));
self::deactiveUser($user);
}
}

View file

@ -257,7 +257,7 @@ class Yard extends Cart
if (! $shipping_price) {
return;
}
if ($this->weight() == 0) {
if ($this->allItemsFreeShippingConsultant() || $this->weight() == 0) {
$shipping_price->price = 0;
$shipping_price->price_comp = 0;
} else {
@ -416,6 +416,18 @@ class Yard extends Cart
return $total;
}
public function allItemsFreeShippingConsultant()
{
$content = $this->getContent();
if ($content->isEmpty()) {
return false;
}
return $content->every(function (CartItem $cartItem) {
return (bool) $cartItem->options->free_shipping_consultant;
});
}
public function points()
{
$content = $this->getContent();
@ -510,7 +522,7 @@ class Yard extends Cart
}
$price = $product->price;
if ($set_price === 'with') {
$cartItem = $this->getCartItem($product->id, $product->getLang('name'), 1, $price, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
$cartItem = $this->getCartItem($product->id, $product->getLang('name'), 1, $price, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
$price = $product->getPriceWith(false, true, $this->getUserCountry());
}
if ($set_price === 'withTaxFree') {