diff --git a/dev/app-bak/Console/Commands/BusinessClearData.php b/dev/app-bak/Console/Commands/BusinessClearData.php
deleted file mode 100644
index a8213512..00000000
--- a/dev/app-bak/Console/Commands/BusinessClearData.php
+++ /dev/null
@@ -1,136 +0,0 @@
-argument('month');
- $year = (int) $this->argument('year');
-
- // Validierung
- if ($month < 1 || $month > 12) {
- $this->error('Invalid month. Must be between 1 and 12.');
- return 1;
- }
-
- $currentYear = (int) date('Y');
- if ($year < 2020 || $year > $currentYear + 1) {
- $this->error('Invalid year. Must be between 2020 and ' . ($currentYear + 1));
- return 1;
- }
-
- $this->info("Preparing to clear business data for month: {$month} | year: {$year}");
-
- // Finde bestehende Struktur
- $existingStructure = UserBusinessStructure::where('year', $year)
- ->where('month', $month)
- ->first();
-
- if (!$existingStructure) {
- $this->info('No stored business structure found for the specified month/year');
- return 0;
- }
-
- $structureId = $existingStructure->id;
- $userBusinessCount = UserBusiness::where('b_structure_id', $structureId)->count();
- $userCount = is_array($existingStructure->users) ? count($existingStructure->users) : 0;
-
- $this->info("Found structure ID: {$structureId}");
- $this->info("- UserBusiness records: {$userBusinessCount}");
- $this->info("- Users in structure: {$userCount}");
- $this->info("- Completed: " . ($existingStructure->completed ? 'Yes' : 'No'));
-
- // Bestätigung (außer bei --force)
- if (!$this->option('force')) {
- if (!$this->confirm('Are you sure you want to delete this business structure data?')) {
- $this->info('Operation cancelled by user');
- return 0;
- }
- }
-
- $startTime = microtime(true);
-
- // Lösche UserBusiness Einträge
- if ($userBusinessCount > 0) {
- $this->info("Deleting {$userBusinessCount} UserBusiness records...");
- UserBusiness::where('b_structure_id', $structureId)->delete();
- $this->info('✓ UserBusiness records deleted');
- }
-
- // Lösche UserBusinessStructure
- $this->info('Deleting UserBusinessStructure...');
- $existingStructure->delete();
- $this->info('✓ UserBusinessStructure deleted');
-
- // Garbage Collection
- gc_collect_cycles();
-
- $endTime = microtime(true);
- $duration = round(($endTime - $startTime) * 1000, 2);
-
- $this->info("✅ Successfully cleared all business data in {$duration}ms");
- $this->logMemoryUsage();
-
- return 0;
- } catch (\Exception $e) {
- $this->error('Error clearing business data: ' . $e->getMessage());
- $this->error('Stack trace: ' . $e->getTraceAsString());
- return 1;
- }
- }
-
- /**
- * Loggt aktuelle Memory-Nutzung
- */
- private function logMemoryUsage(): void
- {
- $currentMemory = memory_get_usage();
- $peakMemory = memory_get_peak_usage();
-
- $currentFormatted = $this->formatBytes($currentMemory);
- $peakFormatted = $this->formatBytes($peakMemory);
-
- $this->info("Memory - Current: {$currentFormatted} | Peak: {$peakFormatted}");
- }
-
- /**
- * Formatiert Bytes in lesbare Einheiten
- */
- private function formatBytes(int $bytes, int $precision = 2): string
- {
- $units = array('B', 'KB', 'MB', 'GB', 'TB');
-
- for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
- $bytes /= 1024;
- }
-
- return round($bytes, $precision) . ' ' . $units[$i];
- }
-}
diff --git a/dev/app-bak/Console/Commands/BusinessLevelReports.php b/dev/app-bak/Console/Commands/BusinessLevelReports.php
deleted file mode 100644
index 5e116d5e..00000000
--- a/dev/app-bak/Console/Commands/BusinessLevelReports.php
+++ /dev/null
@@ -1,149 +0,0 @@
-levelReportService = $levelReportService;
- }
-
- /**
- * Execute the console command.
- *
- * @return int
- */
- public function handle()
- {
- try {
- $this->info('Generiere Level-Aufstieg-Report...');
-
- // Filter Parameter
- $filters = [
- 'month' => $this->option('month'),
- 'year' => $this->option('year'),
- 'user_id' => $this->option('user-id'),
- 'only_not_updated' => $this->option('not-updated')
- ];
-
- $exportCsv = $this->option('csv');
-
- // Lade Level-Aufstiege über Service
- $levelPromotions = $this->levelReportService->getLevelPromotions($filters);
-
- if ($levelPromotions->isEmpty()) {
- $this->info('Keine Level-Aufstiege gefunden.');
- return 0;
- }
-
- if ($exportCsv) {
- $filepath = $this->levelReportService->exportToCsv($levelPromotions);
- $this->info('');
- $this->info('CSV-Export erstellt: ' . $filepath);
- $this->info('Anzahl Datensätze: ' . $levelPromotions->count());
- } else {
- $this->displayReport($levelPromotions);
- }
-
- $this->info('Report erfolgreich generiert.');
- return 0;
- } catch (\Exception $e) {
- $this->error('Fehler beim Generieren des Reports: ' . $e->getMessage());
- return 1;
- }
- }
-
- private function displayReport($promotions)
- {
- $statistics = $this->levelReportService->getStatistics($promotions);
-
- $this->info('');
- $this->info('=== LEVEL-AUFSTIEG REPORT ===');
- $this->info('');
-
- if ($promotions->isEmpty()) {
- $this->info('Keine Level-Aufstiege gefunden.');
- return;
- }
-
- $headers = [
- 'Datum',
- 'User ID',
- 'Name',
- 'E-Mail',
- 'Von Level',
- 'Zu Level',
- 'Aktueller Level',
- 'Margin',
- 'KP Req',
- 'PP Req',
- 'Growth Bonus',
- 'User PP',
- 'User KP',
- 'Level Update',
- 'Aktiv'
- ];
-
- $rows = [];
- foreach ($promotions->toArray() as $promotion) {
- $rows[] = [
- $promotion['date'],
- $promotion['user_id'],
- $promotion['first_name'] . ' ' . $promotion['last_name'],
- $promotion['email'],
- $promotion['from_level_name'] . ' (ID:' . $promotion['from_level_id'] . ')',
- $promotion['to_level_name'] . ' (ID:' . $promotion['to_level_id'] . ')',
- $promotion['current_user_level_name'] . ' (ID:' . ($promotion['current_user_level_id'] ?? 'N/A') . ')',
- $promotion['to_level_margin'] . '%',
- number_format($promotion['to_level_qual_kp'], 0, ',', '.'),
- number_format($promotion['to_level_qual_pp'], 0, ',', '.'),
- $promotion['to_level_growth_bonus'] . '%',
- number_format($promotion['total_pp'], 0, ',', '.'),
- number_format($promotion['sales_volume_points_sum'], 0, ',', '.'),
- $promotion['level_updated'],
- $promotion['active_account'],
- ];
- }
-
- $this->table($headers, $rows);
-
- // Zusammenfassung
- $this->info('');
- $this->info('=== ZUSAMMENFASSUNG ===');
- $this->info('Anzahl Level-Aufstiege: ' . $statistics['total_count']);
-
- $this->info('');
- $this->info('Aufstiege nach Ziel-Level:');
- foreach ($statistics['level_stats'] as $level => $count) {
- $this->info(" - {$level}: {$count}");
- }
-
- $this->info('');
- $this->info('Aufstiege nach Zeitraum:');
- foreach ($statistics['period_stats'] as $period => $count) {
- $this->info(" - {$period}: {$count}");
- }
- }
-
-}
diff --git a/dev/app-bak/Console/Commands/BusinessStore.php b/dev/app-bak/Console/Commands/BusinessStore.php
deleted file mode 100644
index 2440a0eb..00000000
--- a/dev/app-bak/Console/Commands/BusinessStore.php
+++ /dev/null
@@ -1,191 +0,0 @@
-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);
- return 0;
- }
-
- $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->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
- $this->executeWithErrorHandling('Business Structure Storage', function () {
- $this->storeBusinessStructureUsersDetailMonth();
- });
-
- $this->executeWithErrorHandling('Commission Calculation', function () {
- $this->userBusinessCommissionsToCredit();
- });
-
- // Auskommentierte Prozesse bleiben inaktiv
- // $this->userCreatePaymentCreditsPDF();
- // $this->userLevelUpdate();
- // $this->storeBusinessStructureUsersDetailPeriod(1, 6);
-
- $this->logExecutionTime('COMMAND COMPLETED SUCCESSFULLY');
- $this->logMemoryUsage('Command End');
- \Log::channel('cron')->info('COMMAND COMPLETED SUCCESSFULLY');
-
- return 0;
- } catch (\Exception $e) {
- $this->error('Command failed with error: ' . $e->getMessage());
- $this->error('Stack trace: ' . $e->getTraceAsString());
- $this->logExecutionTime('COMMAND FAILED');
- return 1;
- }
- }
-
- private function storeBusinessStructureUsersDetailMonth()
- {
-
- $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);
- }
-
- private function userBusinessCommissionsToCredit()
- {
-
- $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->logExecutionTime('END Command userBusinessCommissionsToCredit:');
- }
-
- private function userCreatePaymentCreditsPDF()
- {
-
- $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->logExecutionTime('END Command userCreatePaymentCreditsPDF:');
- }
-
- private function userLevelUpdate()
- {
-
- $this->info('userLevelUpdate month: ' . $this->month . ' year:' . $this->year);
-
- $userLevelUpdate = new UserLevelUpdate($this->month, $this->year);
- $levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
-
- 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->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);
- $businessUsersStore = new BusinessUsersStore($i, $this->year);
- $businessUsersStore->storeUserBusinessStructure();
- $businessUsersStore->storeBusinessUsersDetail();
- $bool = $businessUsersStore->storeBusinessCompleted();
-
- $this->logExecutionTime('Period BusinessStore: ' . $bool);
- }
- }
-
- private function logExecutionTime($message)
- {
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
- }
-}
diff --git a/dev/app-bak/Console/Commands/BusinessStoreOptimized.php b/dev/app-bak/Console/Commands/BusinessStoreOptimized.php
deleted file mode 100644
index 64dc7caa..00000000
--- a/dev/app-bak/Console/Commands/BusinessStoreOptimized.php
+++ /dev/null
@@ -1,368 +0,0 @@
-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;
- }
-
- $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->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
- if ($this->option('clear')) {
- $this->executeWithErrorHandling('Clear Stored Data', function () {
- $this->clearStoredData();
- });
- }
-
- // Prozesse ausführen mit optimierter Fehlerbehandlung
- $this->executeWithErrorHandling('Business Structure Storage', function () {
- \Log::channel('cron')->info('RUN Command BusinessStoreOptimized Business Structure Storage');
- $this->storeBusinessStructureUsersDetailMonth();
- });
-
- $this->executeWithErrorHandling('Commission Calculation', function () {
- \Log::channel('cron')->info('RUN Command BusinessStoreOptimized Commission Calculation');
- $this->userBusinessCommissionsToCredit();
- });
-
- // Auskommentierte Prozesse bleiben inaktiv
- // $this->userCreatePaymentCreditsPDF();
- // $this->userLevelUpdate();
- // $this->storeBusinessStructureUsersDetailPeriod(1, 6);
-
- $this->logExecutionTime('COMMAND COMPLETED SUCCESSFULLY');
- $this->logMemoryUsage('Command End');
- \Log::channel('cron')->info('COMMAND COMPLETED SUCCESSFULLY');
-
- return 0;
- } catch (\Exception $e) {
- $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);
-
- try {
- $businessUsersStore = new BusinessUsersStoreOptimized($this->month, $this->year);
- $businessUsersStore->storeUserBusinessStructure();
- $businessUsersStore->storeBusinessUsersDetail();
- $bool = $businessUsersStore->storeBusinessCompleted();
-
- $this->logExecutionTime('END Command storeBusinessStructureUsersDetailMonth: ' . $bool);
- } catch (\Exception $e) {
- $this->error('Error in storeBusinessStructureUsersDetailMonth: ' . $e->getMessage());
- throw $e;
- }
- }
-
- private function userBusinessCommissionsToCredit()
- {
- $this->info('userBusinessCommissionsToCredit month: ' . $this->month . ' year:' . $this->year);
-
- try {
- $userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
- $userBusinesses = $userPaymentCredits->getUserBusinessByMonthYear();
-
- $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);
- $processedCount++;
-
- // Memory-Check alle 100 User
- if ($processedCount % 100 === 0) {
- $this->logMemoryUsage("After processing {$processedCount} users");
- }
- }
-
- $this->info("Processed {$processedCount} user businesses total");
- $this->logExecutionTime('END Command userBusinessCommissionsToCredit:');
- } catch (\Exception $e) {
- $this->error('Error in userBusinessCommissionsToCredit: ' . $e->getMessage());
- throw $e;
- }
- }
-
- private function userCreatePaymentCreditsPDF()
- {
- $this->info('userCreatePaymentCreditsPDF month: ' . $this->month . ' year:' . $this->year);
-
- try {
- $userPaymentCredits = new UserPaymentCredits($this->month, $this->year);
- $creditItemUsers = $userPaymentCredits->getUserCreditItemUsersByMonthYear();
-
- $processedCount = 0;
- foreach ($creditItemUsers as $creditItemUser) {
- $bool = $userPaymentCredits->makeCreditPaymentPDF($creditItemUser->user_id, $this->sendCreditMail);
- $this->info('creditsPDF: ' . $bool . ' user_id: ' . $creditItemUser->user_id);
- $processedCount++;
-
- // Memory-Check alle 50 PDFs
- if ($processedCount % 50 === 0) {
- $this->logMemoryUsage("After processing {$processedCount} PDFs");
- }
- }
-
- $this->info("Created {$processedCount} PDF files total");
- $this->logExecutionTime('END Command userCreatePaymentCreditsPDF:');
- } catch (\Exception $e) {
- $this->error('Error in userCreatePaymentCreditsPDF: ' . $e->getMessage());
- throw $e;
- }
- }
-
- private function userLevelUpdate()
- {
- $this->info('userLevelUpdate month: ' . $this->month . ' year:' . $this->year);
-
- try {
- $userLevelUpdate = new UserLevelUpdate($this->month, $this->year);
- $levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
-
- $updatedCount = 0;
- 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);
- $updatedCount++;
- }
- }
-
- $this->info("Updated {$updatedCount} user levels total");
- $this->logExecutionTime('END Command userLevelUpdate:');
- } catch (\Exception $e) {
- $this->error('Error in userLevelUpdate: ' . $e->getMessage());
- throw $e;
- }
- }
-
- private function storeBusinessStructureUsersDetailPeriod($from, $to)
- {
- try {
- for ($i = $from; $i <= $to; $i++) {
- $this->info('Store Business Structure Users Detail month: ' . $i . ' year:' . $this->year);
- $this->logMemoryUsage("Before month {$i}");
-
- $businessUsersStore = new BusinessUsersStoreOptimized($i, $this->year);
- $businessUsersStore->storeUserBusinessStructure();
- $businessUsersStore->storeBusinessUsersDetail();
- $bool = $businessUsersStore->storeBusinessCompleted();
-
- $this->logExecutionTime('Period BusinessStore: ' . $bool);
- $this->logMemoryUsage("After month {$i}");
- }
- } catch (\Exception $e) {
- $this->error('Error in storeBusinessStructureUsersDetailPeriod: ' . $e->getMessage());
- throw $e;
- }
- }
-
- /**
- * Löscht gespeicherte Business Structure Daten für den angegebenen Monat/Jahr
- */
- private function clearStoredData()
- {
- try {
- $this->info("Clearing stored business data for month: {$this->month} | year: {$this->year}");
-
- // Finde bestehende UserBusinessStructure
- $existingStructure = UserBusinessStructure::where('year', $this->year)
- ->where('month', $this->month)
- ->first();
-
- if (!$existingStructure) {
- $this->info('No stored business structure found to clear');
- return;
- }
-
- $structureId = $existingStructure->id;
- $this->info("Found existing structure with ID: {$structureId}");
-
- // Lösche zugehörige UserBusiness Einträge
- $deletedUserBusinesses = UserBusiness::where('b_structure_id', $structureId)->count();
- if ($deletedUserBusinesses > 0) {
- UserBusiness::where('b_structure_id', $structureId)->delete();
- $this->info("Deleted {$deletedUserBusinesses} UserBusiness records");
- }
-
- // Lösche die UserBusinessStructure
- $existingStructure->delete();
- $this->info("Deleted UserBusinessStructure with ID: {$structureId}");
-
- // Garbage Collection nach dem Löschen
- gc_collect_cycles();
-
- $this->info('Successfully cleared all stored business data');
- $this->logMemoryUsage('After clearing data');
- } catch (\Exception $e) {
- $this->error('Error clearing stored data: ' . $e->getMessage());
- throw $e;
- }
- }
-
- private function logExecutionTime($message)
- {
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
- }
-
- /**
- * Führt eine Funktion mit Fehlerbehandlung aus
- */
- private function executeWithErrorHandling(string $processName, callable $callback): void
- {
- try {
- $startTime = microtime(true);
- $this->info("Starting: {$processName}");
- $this->logMemoryUsage("Before {$processName}");
-
- $callback();
-
- $endTime = microtime(true);
- $duration = round(($endTime - $startTime) * 1000, 2);
- $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());
- throw $e;
- }
- }
-
- /**
- * Loggt aktuelle Memory-Nutzung
- */
- private function logMemoryUsage(string $checkpoint): void
- {
- $currentMemory = memory_get_usage();
- $peakMemory = memory_get_peak_usage();
- $memoryLimit = $this->parseMemoryLimit(ini_get('memory_limit'));
-
- $currentFormatted = $this->formatBytes($currentMemory);
- $peakFormatted = $this->formatBytes($peakMemory);
- $limitFormatted = $this->formatBytes($memoryLimit);
- $usagePercent = round(($currentMemory / $memoryLimit) * 100, 2);
-
- $this->info("[{$checkpoint}] Memory: {$currentFormatted} / {$limitFormatted} ({$usagePercent}%) | Peak: {$peakFormatted}");
-
- if ($usagePercent > 80) {
- $this->warn("High memory usage detected at {$checkpoint}: {$usagePercent}%");
- }
- }
-
- /**
- * Konvertiert Memory-Limit String zu Bytes
- */
- private function parseMemoryLimit(string $limit): int
- {
- $limit = trim($limit);
- $last = strtolower($limit[strlen($limit) - 1]);
- $number = (int) $limit;
-
- switch ($last) {
- case 'g':
- $number *= 1024;
- case 'm':
- $number *= 1024;
- case 'k':
- $number *= 1024;
- }
-
- return $number;
- }
-
- /**
- * Formatiert Bytes in lesbare Einheiten
- */
- private function formatBytes(int $bytes, int $precision = 2): string
- {
- $units = array('B', 'KB', 'MB', 'GB', 'TB');
-
- for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
- $bytes /= 1024;
- }
-
- return round($bytes, $precision) . ' ' . $units[$i];
- }
-}
diff --git a/dev/app-bak/Console/Commands/BusinessTestAccount.php b/dev/app-bak/Console/Commands/BusinessTestAccount.php
deleted file mode 100644
index 0abb7021..00000000
--- a/dev/app-bak/Console/Commands/BusinessTestAccount.php
+++ /dev/null
@@ -1,161 +0,0 @@
-argument('user_id');
- $month = (int) $this->argument('month');
- $year = (int) $this->argument('year');
-
- $this->info("Testing account data for User ID: {$userId}, Month: {$month}, Year: {$year}");
- $this->line('');
-
- // Lade User mit Account
- $user = User::with('account', 'user_level')->find($userId);
-
- if (!$user) {
- $this->error("User {$userId} not found");
- return 1;
- }
-
- $this->info("User found: {$user->email}");
- $this->info("Account ID: " . ($user->account_id ?? 'NULL'));
-
- if ($user->account) {
- $this->info("Account loaded: YES");
- $this->info("Account m_account: " . ($user->account->m_account ?? 'NULL'));
- $this->info("Account first_name: " . ($user->account->first_name ?? 'NULL'));
- $this->info("Account last_name: " . ($user->account->last_name ?? 'NULL'));
- $this->info("Account birthday: " . ($user->account->birthday ?? 'NULL'));
- $this->info("Account phone: " . ($user->account->getPhoneNumber() ?? 'NULL'));
- } else {
- $this->warn("Account loaded: NO");
- }
-
- $this->line('');
- $this->info('Testing BusinessUserItemOptimized...');
-
- // Erstelle Date Object
- $date = new stdClass();
- $date->month = $month;
- $date->year = $year;
- $date->start_date = "{$year}-{$month}-01 00:00:00";
- $date->end_date = date('Y-m-t 23:59:59', strtotime("{$year}-{$month}-01"));
-
- // Teste BusinessUserItemOptimized
- $businessUserItem = new BusinessUserItemOptimized($date);
- $businessUserItem->makeUserFromModel($user, true);
-
- $bUser = $businessUserItem->getBUser();
-
- $this->line('');
- $this->info('Results from BusinessUserItemOptimized:');
- $this->info("m_account: " . ($bUser->m_account ?? 'NULL'));
- $this->info("first_name: " . ($bUser->first_name ?? 'NULL'));
- $this->info("last_name: " . ($bUser->last_name ?? 'NULL'));
- $this->info("user_birthday: " . ($bUser->user_birthday ?? 'NULL'));
- $this->info("user_phone: " . ($bUser->user_phone ?? 'NULL'));
- $this->info("email: " . ($bUser->email ?? 'NULL'));
-
- $this->line('');
- $this->info('Sales Volume Fields:');
- $this->info("sales_volume_KP_points: " . ($bUser->sales_volume_KP_points ?? 'NULL'));
- $this->info("sales_volume_TP_points: " . ($bUser->sales_volume_TP_points ?? 'NULL'));
- $this->info("sales_volume_points_shop: " . ($bUser->sales_volume_points_shop ?? 'NULL'));
- $this->info("sales_volume_points_KP_sum: " . ($bUser->sales_volume_points_KP_sum ?? 'NULL'));
- $this->info("sales_volume_points_TP_sum: " . ($bUser->sales_volume_points_TP_sum ?? 'NULL'));
- $this->info("sales_volume_total: " . ($bUser->sales_volume_total ?? 'NULL'));
- $this->info("sales_volume_total_shop: " . ($bUser->sales_volume_total_shop ?? 'NULL'));
- $this->info("sales_volume_total_sum: " . ($bUser->sales_volume_total_sum ?? 'NULL'));
-
- $this->line('');
- $this->info('Commission Fields:');
- $this->info("payline_points: " . ($bUser->payline_points ?? 'NULL'));
- $this->info("commission_pp_total: " . ($bUser->commission_pp_total ?? 'NULL'));
- $this->info("commission_shop_sales: " . ($bUser->commission_shop_sales ?? 'NULL'));
- $this->info("commission_growth_total: " . ($bUser->commission_growth_total ?? 'NULL'));
-
- // Test UserSalesVolume directly
- $this->line('');
- $this->info('Testing UserSalesVolume data directly:');
- $userSalesVolume = $user->getUserSalesVolume($month, $year, 'first');
- if ($userSalesVolume) {
- $this->info("UserSalesVolume found: ID {$userSalesVolume->id}");
- $this->info("month_KP_points: " . ($userSalesVolume->month_KP_points ?? 'NULL'));
- $this->info("month_TP_points: " . ($userSalesVolume->month_TP_points ?? 'NULL'));
- $this->info("month_shop_points: " . ($userSalesVolume->month_shop_points ?? 'NULL'));
- $this->info("month_total_net: " . ($userSalesVolume->month_total_net ?? 'NULL'));
- $this->info("month_shop_total_net: " . ($userSalesVolume->month_shop_total_net ?? 'NULL'));
- } else {
- $this->warn("No UserSalesVolume found for month {$month}/{$year}");
-
- // Check if any UserSalesVolume exists for this user
- $anyVolume = \App\Models\UserSalesVolume::where('user_id', $userId)->orderBy('year', 'desc')->orderBy('month', 'desc')->first();
- if ($anyVolume) {
- $this->info("Latest UserSalesVolume found: {$anyVolume->month}/{$anyVolume->year}");
- } else {
- $this->warn("No UserSalesVolume records found for this user at all");
- }
- }
-
- $this->line('');
-
- // Prüfe ob UserBusiness bereits gespeichert ist
- $existingUserBusiness = UserBusiness::where('user_id', $userId)
- ->where('month', $month)
- ->where('year', $year)
- ->first();
-
- if ($existingUserBusiness) {
- $this->info('Existing UserBusiness found:');
- $this->info("m_account: " . ($existingUserBusiness->m_account ?? 'NULL'));
- $this->info("first_name: " . ($existingUserBusiness->first_name ?? 'NULL'));
- $this->info("last_name: " . ($existingUserBusiness->last_name ?? 'NULL'));
- $this->info("user_birthday: " . ($existingUserBusiness->user_birthday ?? 'NULL'));
- $this->info("user_phone: " . ($existingUserBusiness->user_phone ?? 'NULL'));
- $this->info("email: " . ($existingUserBusiness->email ?? 'NULL'));
- } else {
- $this->info('No existing UserBusiness found for this period');
- }
-
- $this->line('');
- $this->info('✅ Test completed successfully');
-
- return 0;
- } catch (\Exception $e) {
- $this->error('Test failed with error: ' . $e->getMessage());
- $this->error('Stack trace: ' . $e->getTraceAsString());
- return 1;
- }
- }
-}
diff --git a/dev/app-bak/Console/Commands/CheckPaymentsAccount.php b/dev/app-bak/Console/Commands/CheckPaymentsAccount.php
deleted file mode 100644
index ebe38672..00000000
--- a/dev/app-bak/Console/Commands/CheckPaymentsAccount.php
+++ /dev/null
@@ -1,213 +0,0 @@
-info('COMMAND [payments:check-accounts] started.');
- $this->info('COMMAND [payments:check-accounts] started.');
-
- // Die Logik wurde 1:1 aus der checkPaymentsAccounts-Methode übernommen
- $renewalDate = Carbon::now()->modify('+' . (config('mivita.remind_first_days') + 1) . ' days');
- Log::channel('cron')->info('Erneuerungsdatum für Zahlungen: ' . $renewalDate->format('Y-m-d H:i:s'));
-
- $users = User::where('payment_account', '!=', NULL)
- ->where('active', '=', 1)
- ->where('blocked', '!=', 1)
- ->where('payment_account', '<', $renewalDate)
- ->get();
-
- Log::channel('cron')->info('Found ' . $users->count() . ' users for payment reminders.');
- $this->info('Found ' . $users->count() . ' users for payment reminders.');
-
- foreach ($users as $user) {
- Log::channel('cron')->info('Prüfe Zahlungserinnerungen für Benutzer: ' . $user->email);
- $this->checkReminderPayments($user);
- }
-
- Log::channel('cron')->info('COMMAND [payments:check-accounts] finished.');
- $this->info('COMMAND [payments:check-accounts] finished.');
- return 0; // Success
- }
-
- /**
- * Überprüft und sendet Zahlungserinnerungen basierend auf Benutzerkontostand
- *
- * RULES:
- * > 21 remind_first_days = 31 reminder_first
- * > 21 remind_first_days + sepa = 32 reminder_first_sepa
- * > 14 remind_sec_days = 33 reminder_sec
- * > 2 remind_last_days = 34 reminder_last
- * > 0 deaktiv = 35 reminder_deaktiv
- * > 0 deaktiv + sepa = 36 reminder_deaktiv_sepa
- * == 7 abo_booking_days + sepa + cron = 37 reminder_collect_sepa
- *
- * @param User $user Benutzer
- * @return void
- */
-
- private function checkReminderPayments(User $user)
- {
- //35 reminder_deaktiv, 36 reminder_deaktiv_sepa
- if (!$user->isActiveAccount()) {
- Log::channel('cron')->info('Inaktives Konto für Benutzer: ' . $user->email);
- $this->checkIsReminderSend($user, 35);
- return;
- }
-
- //34 reminder_last
- if ($user->daysActiveAccount() <= config('mivita.remind_last_days')) {
- Log::channel('cron')->info('Letzte Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
- $this->checkIsReminderSend($user, 34);
- return;
- }
-
- //33 reminder_sec
- if ($user->daysActiveAccount() <= config('mivita.remind_sec_days')) {
- Log::channel('cron')->info('Zweite Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
- $this->checkIsReminderSend($user, 33);
- return;
- }
-
- //31 reminder_first
- if ($user->daysActiveAccount() > config('mivita.remind_sec_days')) {
- Log::channel('cron')->info('Erste Erinnerung für Benutzer: ' . $user->email . ' (Tage aktiv: ' . $user->daysActiveAccount() . ')');
- $this->checkIsReminderSend($user, 31);
- return;
- }
- }
-
- /**
- * Überprüft, ob eine Erinnerung bereits gesendet wurde
- *
- * @param User $user Benutzer
- * @param int $status Status-Code der Erinnerung
- * @return bool
- */
- private function checkIsReminderSend(User $user, $status)
- {
- $isSend = UserHistory::whereUserId($user->id)
- ->whereAction('reminder_payments')
- ->whereIdentifier($user->payment_account)
- ->whereStatus($status)
- ->latest()
- ->first();
-
- if ($isSend) {
- Log::channel('cron')->info('Erinnerung bereits gesendet für Benutzer: ' . $user->email . ' (Status: ' . $status . ')');
- return true;
- }
-
- Log::channel('cron')->info('Sende neue Erinnerung für Benutzer: ' . $user->email . ' (Status: ' . $status . ')');
- $referenz = $this->sendReminderMail($user, $status);
-
- UserHistory::create([
- 'user_id' => $user->id,
- 'action' => 'reminder_payments',
- 'referenz' => $referenz,
- 'identifier' => $user->payment_account,
- 'status' => $status
- ]);
-
- return false;
- }
-
- /**
- * Sendet eine Erinnerungs-E-Mail an den Benutzer
- *
- * @param User $user Benutzer
- * @param int $status Status-Code der Erinnerung
- * @return int
- */
- private function sendReminderMail(User $user, $status)
- {
- $days = abs($user->daysActiveAccount());
- $pay_date = Carbon::parse($user->payment_account)->modify('- ' . config('mivita.abo_booking_days') . ' days')->format('d.m.Y');
- $datetime = $user->getPaymentAccountDateFormat();
- $price = "";
-
- if ($user->payment_order_id && isset($user->payment_order_product->price)) {
- $price = 'von ' . $user->payment_order_product->getFormattedPrice() . ' EUR';
- }
-
- $message = __('reminder.copy_first_' . $status, ['days' => $days, 'datetime' => $datetime, 'price' => $price, 'pay_date' => $pay_date]);
- $message_last = __('reminder.copy_last_' . $status, ['days' => $days, 'datetime' => $datetime, 'price' => $price, 'pay_date' => $pay_date]);
- $button = __('reminder.button_' . $status);
-
- $message = preg_replace("/[\n\r]/", "", $message);
- $message_last = preg_replace("/[\n\r]/", "", $message_last);
-
- $data = [
- 'subject' => __('reminder.subject') . " | ID: " . $status,
- 'message' => $message,
- 'message_last' => $message_last,
- 'url' => config('app.url') . '/user/membership',
- 'button' => $button,
- ];
-
- $sender = User::find(1);
- $customer_mail = UserMessage::create(['user_id' => $user->id, 'send_user_id' => $sender->id, 'email' => $user->email, 'subject' => $data['subject'], 'message' => $data['message'] . " " . $data['message_last']]);
-
- try {
- if (!Util::isTestSystem()) {
- if ($status >= 34) {
- Log::channel('cron')->info('Sende kritische Erinnerung mit BCC an: ' . $user->email);
- Mail::to($user->email)
- ->locale($user->getLocale())
- ->bcc(config('app.default_mail'))
- ->send(new MailCustomMessage($user, $data, $sender, false));
- } else {
- Log::channel('cron')->info('Sende normale Erinnerung an: ' . $user->email);
- Mail::to($user->email)
- ->locale($user->getLocale())
- ->send(new MailCustomMessage($user, $data, $sender, false));
- }
- } else {
- Log::channel('cron')->info('Testsystem: E-Mail-Versand simuliert für: ' . $user->email);
- }
- } catch (\Exception $e) {
- Log::channel('cron')->error('Mail-Fehler für Benutzer ' . $user->email . ': ' . $e->getMessage());
- $customer_mail->fail = true;
- $customer_mail->error = $e->getMessage();
- $customer_mail->save();
- return 0;
- }
-
- $customer_mail->send = true;
- $customer_mail->sent_at = now();
- $customer_mail->save();
-
- Log::channel('cron')->info('Erinnerungsmail erfolgreich gesendet an: ' . $user->email);
- return 1;
- }
-}
diff --git a/dev/app-bak/Console/Commands/SubDomains.php b/dev/app-bak/Console/Commands/SubDomains.php
deleted file mode 100644
index 9687fe3e..00000000
--- a/dev/app-bak/Console/Commands/SubDomains.php
+++ /dev/null
@@ -1,664 +0,0 @@
-timeStart = microtime(true);
-
- $userId = $this->argument('user_id');
- $force = $this->option('force');
- $startId = $this->option('start');
- $createMissing = $this->option('create-missing');
- $debug = $this->option('debug');
-
- if ($debug) {
- $this->warn("DEBUG-MODUS (DRY-RUN): Es werden keine tatsächlichen Änderungen vorgenommen!");
- }
-
- $this->info("Starte Subdomain-Verwaltung" . ($force ? " (erzwungener Modus)" : ""));
-
- try {
- if ($userId) {
- $this->info("Verarbeite einzelnen Benutzer mit ID: {$userId}");
- $result = $this->syncSingleUser($userId, $force, $createMissing, $debug);
-
- if ($result) {
- $this->info("Benutzer {$userId} erfolgreich synchronisiert" . ($debug ? " (simuliert)" : ""));
- } else {
- $this->warn("Benutzer {$userId} konnte nicht vollständig synchronisiert werden" . ($debug ? " (simuliert)" : ""));
- }
- } else {
- $this->info("Verarbeite alle Benutzer ab ID: {$startId}");
- $result = $this->syncAllUsers($force, $startId, $createMissing, $debug);
-
- // Zusammenfassung der Ergebnisse
- $this->displaySummary($result, $debug);
- }
-
- $this->logExecutionTime("Subdomain-Verwaltung abgeschlossen" . ($debug ? " (DEBUG-MODUS)" : ""));
- return 0;
- } catch (Exception $e) {
- $this->error("Ein Fehler ist aufgetreten: " . $e->getMessage());
- Log::error("Shopping User Sync Fehler: ", [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- 'user_id' => $userId,
- 'force' => $force,
- 'start_id' => $startId,
- 'debug' => $debug
- ]);
- return 1;
- }
- }
-
-
- /**
- * Zeigt eine Zusammenfassung der Synchronisationsergebnisse an
- *
- * @param array $result Ergebnisdaten der Synchronisation
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return void
- */
- private function displaySummary($result, $debug = false)
- {
- $this->line("");
- $this->info("=== Zusammenfassung " . ($debug ? "(DEBUG-MODUS)" : "") . " ===");
- $this->info("Verarbeitete Shops: " . count($result['shops']));
- $this->info("Aktualisierte PHP-Versionen: " . $result['updatedCount'] . ($debug ? " (simuliert)" : ""));
- $this->info("Aktivierte SSL-Zertifikate: " . $result['sslEnabledCount'] . ($debug ? " (simuliert)" : ""));
- $this->info("Aktualisierte SSL-Konfigurationen: " . $result['sslConfiguredCount'] . ($debug ? " (simuliert)" : ""));
-
- if (!empty($result['createdSubdomains'])) {
- $this->info("Neu erstellte Subdomains: " . count($result['createdSubdomains']) . ($debug ? " (simuliert)" : ""));
- }
-
- if (!empty($result['missingSubdomains'])) {
- $this->warn("Fehlende Subdomains: " . count($result['missingSubdomains']));
- }
-
- if (!empty($result['unusedSubdomains'])) {
- $this->warn("Ungenutzte Subdomains: " . count($result['unusedSubdomains']));
- }
-
- if (!empty($result['doubleDomains'])) {
- $this->warn("Benutzer mit mehreren Shops: " . count($result['doubleDomains']));
- }
- }
-
- /**
- * Synchronisiert einen einzelnen Benutzer und seine Shops
- *
- * @param int $userId Benutzer-ID
- * @param bool $force Erzwingt die Aktualisierung aller Subdomains
- * @param bool $createMissing Erstellt fehlende Subdomains
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function syncSingleUser($userId, $force = false, $createMissing = false, $debug = false)
- {
- $this->info("Synchronisiere Benutzer mit ID: {$userId}");
-
- // Benutzer-Shops abrufen
- $userShops = UserShop::where('user_id', $userId)->get();
-
- if ($userShops->isEmpty()) {
- $this->warn("Keine Shops für Benutzer {$userId} gefunden");
- return false;
- }
-
- $this->info("Gefundene Shops für Benutzer {$userId}: " . $userShops->count());
-
- // Subdomains abrufen und filtern
- $subdomains = $this->getFilteredSubdomains();
- $success = true;
-
- // Benutzer-Shops durchlaufen und mit Subdomains abgleichen
- foreach ($userShops as $userShop) {
- $fullDomainName = $userShop->slug . '.' . $this->domain;
- $this->info("Verarbeite Shop: {$fullDomainName}");
-
- // Prüfen, ob Subdomain existiert
- if (array_key_exists($fullDomainName, $subdomains)) {
- $success = $this->processExistingSubdomain($userShop, $subdomains[$fullDomainName], $force, $debug) && $success;
- } else {
- // Subdomain fehlt
- $this->warn("Shop {$userShop->slug}: Keine Subdomain gefunden");
-
- // Optional: Neue Subdomain erstellen
- if ($createMissing) {
- $this->info("Erstelle fehlende Subdomain für Shop {$userShop->slug}" . ($debug ? " (simuliert)" : ""));
- $success = $this->createSubdomain($userShop->slug, $debug) && $success;
- } else {
- $success = false;
- }
- }
- }
-
- return $success;
- }
-
- /**
- * Verarbeitet eine existierende Subdomain und aktualisiert sie bei Bedarf
- *
- * @param UserShop $userShop Shop-Objekt
- * @param array $subdomainInfo Subdomain-Informationen
- * @param bool $force Erzwingt die Aktualisierung
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function processExistingSubdomain($userShop, $subdomainInfo, $force, $debug = false)
- {
- $success = true;
- $hasSSL = ($subdomainInfo['ssl_certificate_sni'] === 'Y' ||
- $subdomainInfo['ssl_proxy'] === 'Y');
- $sslActive = ($subdomainInfo['ssl_certificate_sni_is_active'] ?? 'N') === 'Y';
- $phpVersion = $subdomainInfo['php_version'];
-
- $this->info("Shop {$userShop->slug}: PHP-Version: {$phpVersion}, SSL: " .
- ($hasSSL ? "Aktiviert" : "Nicht aktiviert") .
- ($hasSSL ? ", SSL aktiv: " . ($sslActive ? "Ja" : "Nein") : ""));
-
- // Prüfen, ob PHP-Version aktualisiert werden muss
- $requiredPhpVersion = config('app.php_version');
- if ($force || $phpVersion !== $requiredPhpVersion) {
- $this->info("Shop {$userShop->slug}: PHP-Version aktualisieren von {$phpVersion} auf {$requiredPhpVersion}" . ($debug ? " (simuliert)" : ""));
-
- if (!$debug && !$this->updateSubdomainParams($userShop->slug, $requiredPhpVersion)) {
- $this->error("PHP-Version für {$userShop->slug}.{$this->domain} konnte nicht aktualisiert werden");
- $success = false;
- }
- }
-
- // Prüfen, ob SSL aktiviert werden muss
- if ($force || !$hasSSL) {
- $this->info("Shop {$userShop->slug}: SSL aktivieren" . ($debug ? " (simuliert)" : ""));
-
- if (!$debug && !$this->enableSSL($userShop->slug)) {
- $this->error("SSL für {$userShop->slug}.{$this->domain} konnte nicht aktiviert werden");
- $success = false;
- }
- }
- // Prüfen, ob SSL-Konfiguration aktualisiert werden muss
- else if ($force || ($hasSSL && !$sslActive)) {
- $this->info("Shop {$userShop->slug}: SSL-Konfiguration aktualisieren" . ($debug ? " (simuliert)" : ""));
-
- if (!$debug && !$this->updateSSL($userShop->slug . '.' . $this->domain)) {
- $this->error("SSL-Konfiguration für {$userShop->slug}.{$this->domain} konnte nicht aktualisiert werden");
- $success = false;
- }
- }
-
- return $success;
- }
-
- /**
- * Synchronisiert alle Benutzer-Shops
- *
- * @param bool $force Erzwingt die Aktualisierung aller Subdomains
- * @param int $startId Beginnt die Synchronisation ab dieser ID
- * @param bool $createMissing Erstellt fehlende Subdomains
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return array Ergebnisdaten der Synchronisation
- */
- private function syncAllUsers($force, $startId, $createMissing = false, $debug = false)
- {
- $this->info("Starte Synchronisation aller Benutzer-Shops ab ID: {$startId}");
-
- // Benutzer-Shops abrufen
- $userShopsQuery = UserShop::query();
-
- if ($startId > 1) {
- $userShopsQuery->where('id', '>=', $startId);
- }
-
- $userShops = $userShopsQuery->limit(1000)->get();
- $this->info("Gefundene Benutzer-Shops: " . $userShops->count());
-
- // Subdomains abrufen und filtern
- $subdomains = $this->getFilteredSubdomains();
- $this->info("Gefilterte Subdomains: " . count($subdomains));
-
- // Ergebnis-Arrays initialisieren
- $doubleDomains = [];
- $missingSubdomains = [];
- $outdatedPhpVersions = [];
- $missingSSL = [];
- $sslConfigurationNeeded = [];
- $createdSubdomains = [];
- $updatedCount = 0;
- $sslEnabledCount = 0;
- $sslConfiguredCount = 0;
-
- // Benutzer-Shops durchlaufen und mit Subdomains abgleichen
- foreach ($userShops as $userShop) {
- $fullDomainName = $userShop->slug . '.' . $this->domain;
-
- // Status der Subdomain setzen
- $userShop->hasSubdomain = false;
- $userShop->hasSSL = false;
- $userShop->sslActive = false;
- $userShop->PHPversion = "";
-
- // Prüfen, ob Subdomain existiert
- if (array_key_exists($fullDomainName, $subdomains)) {
- $userShop->hasSubdomain = true;
- $userShop->hasSSL = ($subdomains[$fullDomainName]['ssl_certificate_sni'] === 'Y' ||
- $subdomains[$fullDomainName]['ssl_proxy'] === 'Y');
- $userShop->sslActive = ($subdomains[$fullDomainName]['ssl_certificate_sni_is_active'] ?? 'N') === 'Y';
- $userShop->PHPversion = $subdomains[$fullDomainName]['php_version'];
-
- // Prüfen, ob PHP-Version aktualisiert werden muss
- $requiredPhpVersion = config('app.php_version');
- if ($force || $userShop->PHPversion !== $requiredPhpVersion) {
- $this->info("Shop {$userShop->slug}: PHP-Version aktualisieren von {$userShop->PHPversion} auf {$requiredPhpVersion}" . ($debug ? " (simuliert)" : ""));
- $outdatedPhpVersions[] = $userShop->slug;
-
- if (!$debug && $this->updateSubdomainParams($userShop->slug, $requiredPhpVersion)) {
- $updatedCount++;
- } else if ($debug) {
- // Im Debug-Modus zählen wir trotzdem, als ob es erfolgreich wäre
- $updatedCount++;
- }
- }else{
- $this->info("Shop {$userShop->slug}: PHP-Version ist aktuell: {$userShop->PHPversion}");
- }
-
- // Prüfen, ob SSL aktiviert werden muss
- /* if ($force || !$userShop->hasSSL) {
- $this->info("Shop {$userShop->slug}: SSL aktivieren" . ($debug ? " (simuliert)" : ""));
- $missingSSL[] = $userShop->slug;
-
- if (!$debug && $this->enableSSL($userShop->slug)) {
- $sslEnabledCount++;
- } else if ($debug) {
- // Im Debug-Modus zählen wir trotzdem, als ob es erfolgreich wäre
- $sslEnabledCount++;
- }
- }
- // Prüfen, ob SSL-Konfiguration aktualisiert werden muss
- else if ($force || ($userShop->hasSSL && !$userShop->sslActive)) {
- $this->info("Shop {$userShop->slug}: SSL-Konfiguration aktualisieren" . ($debug ? " (simuliert)" : ""));
- $sslConfigurationNeeded[] = $userShop->slug;
-
- if (!$debug && $this->updateSSL($fullDomainName)) {
- $sslConfiguredCount++;
- } else if ($debug) {
- // Im Debug-Modus zählen wir trotzdem, als ob es erfolgreich wäre
- $sslConfiguredCount++;
- }
- }*/
-
- // Subdomain aus der Liste entfernen, um später ungenutzte zu identifizieren
- unset($subdomains[$fullDomainName]);
- } else {
- // Subdomain fehlt
- $missingSubdomains[] = $userShop->slug;
- $this->warn("Shop {$userShop->slug}: Keine Subdomain gefunden");
-
- // Optional: Neue Subdomain erstellen
- if ($createMissing) {
- $this->info("Erstelle fehlende Subdomain für Shop {$userShop->slug}" . ($debug ? " (simuliert)" : ""));
- if (!$debug && $this->createSubdomain($userShop->slug)) {
- $createdSubdomains[] = $userShop->slug;
- } else if ($debug) {
- // Im Debug-Modus zählen wir trotzdem, als ob es erfolgreich wäre
- $createdSubdomains[] = $userShop->slug;
- }
- }
- }
-
- // Doppelte Domains pro Benutzer erfassen
- $doubleDomains[$userShop->user_id][$userShop->id] = $fullDomainName;
- }
-
- // Bereinigen der doppelten Domains (nur Benutzer mit mehreren Shops behalten)
- foreach ($doubleDomains as $userId => $domains) {
- if (count($domains) === 1) {
- unset($doubleDomains[$userId]);
- }
- }
-
- $this->logExecutionTime("Synchronisation abgeschlossen" . ($debug ? " (DEBUG-MODUS)" : ""));
-
- // Ergebnisdaten zurückgeben
- return [
- 'shops' => $userShops,
- 'unusedSubdomains' => $subdomains,
- 'doubleDomains' => $doubleDomains,
- 'missingSubdomains' => $missingSubdomains,
- 'outdatedPhpVersions' => $outdatedPhpVersions,
- 'missingSSL' => $missingSSL,
- 'sslConfigurationNeeded' => $sslConfigurationNeeded,
- 'createdSubdomains' => $createdSubdomains,
- 'updatedCount' => $updatedCount,
- 'sslEnabledCount' => $sslEnabledCount,
- 'sslConfiguredCount' => $sslConfiguredCount
- ];
- }
-
- /**
- * Ruft alle Subdomains ab und filtert sie
- *
- * @return array Gefilterte Subdomains
- */
- private function getFilteredSubdomains()
- {
- $kas = new KasController();
- $subdomains = [];
-
- // Alle Subdomains abrufen
- $this->info("Rufe Subdomains von KAS ab...");
- $getSubdomains = $kas->action('get_subdomains');
-
- // Subdomains filtern und in ein leicht zugängliches Array umwandeln
- foreach ($getSubdomains as $subdomain) {
- if (!isset($subdomain['subdomain_name'])) {
- continue;
- }
-
- // Spezielle Subdomains überspringen
- $skip = false;
- foreach ($this->skipPrefixes as $prefix) {
- if (strpos($subdomain['subdomain_name'], $prefix) !== false) {
- $skip = true;
- break;
- }
- }
-
- if ($skip) {
- continue;
- }
-
- // Subdomain-Informationen speichern
- $subdomains[$subdomain['subdomain_name']] = [
- 'ssl_certificate_sni' => $subdomain['ssl_certificate_sni'] ?? 'N',
- 'php_version' => $subdomain['php_version'] ?? '',
- 'ssl_proxy' => $subdomain['ssl_proxy'] ?? 'N',
- 'ssl_certificate_sni_is_active' => $subdomain['ssl_certificate_sni_is_active'] ?? 'N',
- ];
- }
-
- return $subdomains;
- }
-
- /**
- * Ändert Parameter einer Subdomain, insbesondere die PHP-Version
- *
- * @param string $subdomain Name der Subdomain ohne Domain
- * @param string $phpVersion Neue PHP-Version (z.B. '8.2')
- * @param array $additionalParams Weitere zu ändernde Parameter
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function updateSubdomainParams($subdomain, $phpVersion, $additionalParams = [], $debug = false)
- {
- $this->info("Aktualisiere Parameter für: {$subdomain}.{$this->domain}" . ($debug ? " (simuliert)" : ""));
-
- if ($debug) {
- $this->line(" - PHP-Version: {$phpVersion}");
- if (!empty($additionalParams)) {
- $this->line(" - Zusätzliche Parameter: " . json_encode($additionalParams));
- }
- return true;
- }
-
- try {
- $kas = new KasController();
-
- // Standardparameter
- $params = [
- 'subdomain_name' => $subdomain . '.' . $this->domain, // Vollständigen Domainnamen verwenden
- 'php_version' => $phpVersion
- ];
-
- // Oder alternativ, falls die API die Subdomain und Domain getrennt erwartet:
- // $params = [
- // 'subdomain_name' => $subdomain,
- // 'domain_name' => $this->domain,
- // 'php_version' => $phpVersion
- // ];
-
- // Zusätzliche Parameter hinzufügen
- $params = array_merge($params, $additionalParams);
-
- // Subdomain aktualisieren
- $result = $kas->action('update_subdomain', $params);
- $this->info("Parameter: ".json_encode($params));
-
- if ($result) {
- $this->info("Parameter für {$subdomain}.{$this->domain} erfolgreich aktualisiert " . json_encode($result));
- return true;
- } else {
- $this->error("Fehler beim Aktualisieren der Parameter für {$subdomain}.{$this->domain}: " . json_encode($result));
- return false;
- }
- } catch (Exception $e) {
- $this->error("Fehler beim Aktualisieren der Parameter für {$subdomain}.{$this->domain}: " . $e->getMessage());
- Log::error("Subdomain Parameter Update Fehler", [
- 'subdomain' => $subdomain,
- 'domain' => $this->domain,
- 'php_version' => $phpVersion,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
-
- /**
- * Aktualisiert die SSL-Konfiguration einer Subdomain mit erweiterten Parametern
- *
- * @param string $subdomainName Vollständiger Domainname (z.B. 'shop.mivita.care')
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function updateSSL($subdomainName, $debug = false)
- {
- $this->info("Aktualisiere SSL-Konfiguration für: {$subdomainName}" . ($debug ? " (simuliert)" : ""));
-
- if ($debug) {
- $this->line(" - SSL-Parameter werden aktualisiert");
- return true;
- }
-
- try {
- $kas = new KasController();
- $ssl = KasSLLController::getApiSSLParameter();
-
- $params = array_merge(['hostname' => $subdomainName], $ssl);
- $result = $kas->action('update_ssl', $params);
-
- if ($result === "TRUE" || $result === true) {
- $this->info("SSL-Konfiguration für {$subdomainName} erfolgreich aktualisiert");
- return true;
- } else {
- $this->warn("SSL-Konfiguration für {$subdomainName} nicht vollständig aktualisiert: " . json_encode($result));
- return false;
- }
- } catch (Exception $e) {
- $this->error("Fehler bei der SSL-Konfiguration für {$subdomainName}: " . $e->getMessage());
- Log::error("SSL Update Fehler", [
- 'subdomain' => $subdomainName,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
-
- /**
- * Aktiviert SSL für eine Subdomain mit vollständiger Konfiguration
- *
- * @param string $subdomain Name der Subdomain ohne Domain
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function enableSSL($subdomain, $debug = false)
- {
- $fullDomainName = $subdomain . '.' . $this->domain;
- $this->info("Aktiviere SSL für: {$fullDomainName}" . ($debug ? " (simuliert)" : ""));
-
- if ($debug) {
- $this->line(" - SSL-Proxy wird aktiviert");
- $this->line(" - HTTP zu HTTPS Weiterleitung wird eingerichtet");
- $this->line(" - SSL-Konfiguration wird aktualisiert");
- return true;
- }
-
- // Schritt 1: Subdomain-Parameter aktualisieren (ssl_proxy aktivieren)
- $subdomainResult = $this->updateSubdomainParams($subdomain, config('app.php_version'), [
- 'ssl_proxy' => 'Y',
- 'redirect_status' => 301 // Weiterleitung von HTTP auf HTTPS
- ]);
-
- if (!$subdomainResult) {
- $this->error("SSL-Aktivierung für {$fullDomainName} fehlgeschlagen: Subdomain-Parameter konnten nicht aktualisiert werden");
- return false;
- }
-
- // Schritt 2: SSL-Konfiguration aktualisieren
- $sslResult = $this->updateSSL($fullDomainName);
-
- if (!$sslResult) {
- $this->warn("SSL-Aktivierung für {$fullDomainName} teilweise erfolgreich: SSL-Konfiguration konnte nicht aktualisiert werden");
- return false;
- }
-
- $this->info("SSL für {$fullDomainName} vollständig aktiviert");
- return true;
- }
-
- /**
- * Erstellt eine neue Subdomain für einen Shop
- *
- * @param string $slug Shop-Slug
- * @param bool $debug Debug-Modus (Dry-Run)
- * @return bool Erfolg der Operation
- */
- private function createSubdomain($slug, $debug = false)
- {
- $fullDomainName = $slug . '.' . $this->domain;
- $this->info("Erstelle neue Subdomain: {$fullDomainName}" . ($debug ? " (simuliert)" : ""));
-
- if ($debug) {
- $this->line(" - Pfad: /mein.mivita.care/public/");
- $this->line(" - PHP-Version: " . config('app.php_version'));
- $this->line(" - SSL wird direkt aktiviert");
- return true;
- }
-
- try {
- $kas = new KasController();
-
- // Parameter für die neue Subdomain
- $params = [
- 'subdomain_name' => $slug,
- 'domain_name' => $this->domain,
- 'subdomain_path' => '/mein.mivita.care/public/',
- 'php_version' => config('app.php_version'),
- ];
-
- // Subdomain erstellen
- $result = $kas->action('add_subdomain', $params);
-
- if ($result === $fullDomainName) {
- $this->info("Subdomain {$fullDomainName} erfolgreich erstellt");
-
- // SSL direkt aktivieren
- $this->enableSSL($slug);
-
- return true;
- } else {
- $this->error("Fehler beim Erstellen der Subdomain {$fullDomainName}: " . json_encode($result));
- return false;
- }
- } catch (Exception $e) {
- $this->error("Fehler beim Erstellen der Subdomain {$fullDomainName}: " . $e->getMessage());
- Log::error("Subdomain Erstellung Fehler", [
- 'slug' => $slug,
- 'domain' => $this->domain,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
-
- /**
- * Protokolliert die Ausführungszeit einer Operation
- *
- * @param string $message Nachricht für die Protokollierung
- * @return void
- */
- private function logExecutionTime($message)
- {
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info($message. ' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");
- }
-}
diff --git a/dev/app-bak/Console/Commands/SyncShoppingUserData.php b/dev/app-bak/Console/Commands/SyncShoppingUserData.php
deleted file mode 100644
index 32563762..00000000
--- a/dev/app-bak/Console/Commands/SyncShoppingUserData.php
+++ /dev/null
@@ -1,129 +0,0 @@
-argument('user_id');
- $force = $this->option('force');
- $startId = $this->option('start');
-
- try {
- if ($userId) {
- $this->syncSingleUser($userId);
- } else {
- $this->syncAllUsers($force, $startId);
- }
- } catch (Exception $e) {
- $this->error("Ein Fehler ist aufgetreten: " . $e->getMessage());
- Log::error("Shopping User Sync Fehler: ", [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return 1;
- }
-
- return 0;
- }
-
- private function syncAllUsers($force, $startId)
- {
- $this->info("Starte Synchronisierung für alle User ab ID: {$startId}...");
- $count = 0;
- $errors = [];
-
- // Aktiviere SQL Query Logging für Debugging
- DB::enableQueryLog();
-
- User::where('id', '>=', $startId)
- ->orderBy('id')
- ->chunk(10, function($users) use (&$count, &$errors, $force) {
- foreach($users as $user) {
- try {
- $this->info("\nVerarbeite User ID: {$user->id} ({$user->email})");
-
- $this->syncUser($user);
- $count++;
-
- $this->info("✓ User ID {$user->id} erfolgreich synchronisiert");
-
- } catch (Exception $e) {
- $errorMessage = "Fehler bei User ID {$user->id} ({$user->email}): " . $e->getMessage();
- $errors[] = $errorMessage;
- $this->error($errorMessage);
-
- // Log die letzten SQL Queries
- Log::error("Letzte SQL Queries:", [
- 'queries' => DB::getQueryLog()
- ]);
-
- if (!$force) {
- throw $e;
- }
- }
- }
- });
-
- $this->newLine();
- $this->info("Synchronisierung abgeschlossen!");
- $this->info("Gesamt synchronisierte User: {$count}");
-
- if (count($errors) > 0) {
- $this->warn("Es gab " . count($errors) . " Fehler während der Synchronisierung:");
- foreach($errors as $error) {
- $this->warn("- " . $error);
- }
- }
- }
-
- private function syncUser(User $user)
- {
- try {
- $this->output->write(" Setze Faker Mail... ");
- ShoppingUserService::setFakerMail($user);
- $this->info("✓");
-
- $this->output->write(" Synchronisiere Numbers... ");
- ShoppingUserService::syncNumbersByEmail($user);
- $this->info("✓");
-
- $this->output->write(" Synchronisiere Orders... ");
- ShoppingUserService::syncOrdersByEmail($user);
- $this->info("✓");
-
- } catch (Exception $e) {
- throw new Exception($e->getMessage() . "\n" . $e->getTraceAsString());
- }
- }
-
- private function syncSingleUser($userId)
- {
- $user = User::find($userId);
- if (!$user) {
- throw new Exception("User ID {$userId} nicht gefunden");
- }
-
- $this->info("Starte Synchronisierung für User ID {$userId}...");
-
- try {
- $this->syncUser($user);
- $this->info("✓ Synchronisierung erfolgreich abgeschlossen");
- } catch (Exception $e) {
- throw new Exception("Fehler bei User ID {$userId}: " . $e->getMessage());
- }
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Console/Commands/UserCleanUp.php b/dev/app-bak/Console/Commands/UserCleanUp.php
deleted file mode 100644
index 19f9c0a4..00000000
--- a/dev/app-bak/Console/Commands/UserCleanUp.php
+++ /dev/null
@@ -1,161 +0,0 @@
-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.
- $this->cleanUpInActiveUser();
-
- return 0;
-
- \Log::channel('cleanup')->info('COMMAND [user:cleanup] finished.');
- //return 0;
- }
-
- //gibt es gelöschte Berater mit Kunden und childs???
-
- private function deleteInavtiveUsers()
- {
-
- $this->info('START Command deleteInavtiveUsers');
- $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
- UserUtil::setNewSponsorToChilds($delete_user->id, $active_sponsor->id);
- 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);
- 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;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info('END Command deleteInavtiveUsers: ' . $count . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
- }
-
- private function cleanUpInActiveUser()
- {
-
- $this->info('START Command cleanUpInActiveUser');
- $count = 0;
-
- //clean up user where inactive since 2 weeks
- $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++;
-
- \Log::channel('cleanup')->info('inactive_user: ' . json_encode($data));
- UserUtil::deactiveUser($inactive_user);
- }
-
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info('END Command cleanUpInActiveUser: ' . $count . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
- }
-}
diff --git a/dev/app-bak/Console/Commands/UserMakeAboOrder.php b/dev/app-bak/Console/Commands/UserMakeAboOrder.php
deleted file mode 100644
index 48d4d7ac..00000000
--- a/dev/app-bak/Console/Commands/UserMakeAboOrder.php
+++ /dev/null
@@ -1,292 +0,0 @@
-timeStart = microtime(true);
- \Log::channel('cron')->info('UserMakeAboOrder: Befehl gestartet');
- $this->info('RUN Command user:make_abo_order');
-
- try {
- $this->checkAbosToOrder();
- $executionTime = $this->getExecutionTime();
- \Log::channel('cron')->info("UserMakeAboOrder: Befehl erfolgreich abgeschlossen in {$executionTime}");
- $this->info("Befehl erfolgreich abgeschlossen in {$executionTime}");
-
- return 0;
- } catch (\Exception $e) {
- \Log::channel('cron')->error('UserMakeAboOrder: Fehler beim Ausführen des Befehls', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- $this->error('Fehler beim Ausführen des Befehls: ' . $e->getMessage());
- return 1;
- }
- }
-
- /**
- * Prüft alle Abos, die heute fällig sind und erstellt Bestellungen
- *
- * @return void
- */
- private function checkAbosToOrder()
- {
- $dateNow = Carbon::now()->format('Y-m-d');
-
- \Log::channel('abo_order')->info('UserMakeAboOrder: Suche nach fälligen Abos für Datum', ['date' => $dateNow]);
-
- $userAbos = UserAbo::where('next_date', '=', $dateNow)
- ->where('active', true)
- ->get();
-
- $count = $userAbos->count();
- \Log::channel('abo_order')->info("UserMakeAboOrder: {$count} fällige Abos gefunden");
- $this->info("Gefundene fällige Abos: {$count}");
-
- foreach ($userAbos as $userAbo) {
- \Log::channel('abo_order')->info('UserMakeAboOrder: Verarbeite Abo', [
- 'abo_id' => $userAbo->id,
- 'payone_userid' => $userAbo->payone_userid
- ]);
-
- $this->info("Verarbeite Abo: {$userAbo->id} (PayoneUserid: {$userAbo->payone_userid})");
-
- try {
- $shoppingOrder = $this->makeOrder($userAbo);
-
- if ($shoppingOrder) {
- \Log::channel('abo_order')->info('UserMakeAboOrder: Bestellung erstellt', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id
- ]);
- $this->info("Bestellung erstellt: {$shoppingOrder->id}");
- } else {
- \Log::channel('abo_order')->warning('UserMakeAboOrder: Keine Bestellung erstellt für Abo', ['abo_id' => $userAbo->id]);
- $this->warn("Keine Bestellung erstellt für Abo: {$userAbo->id}");
- }
- } catch (\Exception $e) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Fehler bei der Verarbeitung des Abos', [
- 'abo_id' => $userAbo->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- $this->error("Fehler bei Abo {$userAbo->id}: " . $e->getMessage());
- }
- }
- }
-
- /**
- * Erstellt eine Bestellung für ein Abo
- *
- * @param UserAbo $userAbo
- * @return mixed
- */
- private function makeOrder($userAbo)
- {
- \Log::channel('abo_order')->info('UserMakeAboOrder: Starte Bestellungserstellung', ['abo_id' => $userAbo->id]);
- $this->info('Starte Bestellungserstellung für Abo: ' . $userAbo->id);
-
- $shoppingOrder = null;
- $userOrder = new UserMakeOrder($userAbo);
-
- try {
- if (!$userOrder->createShoppingUser()) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Konnte Shopping-User nicht erstellen', ['abo_id' => $userAbo->id]);
- $this->error("Konnte Shopping-User für Abo {$userAbo->id} nicht erstellen");
- return null;
- }
-
- $shoppingOrder = $userOrder->makeShoppingOrder();
- if (!$shoppingOrder) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Konnte Bestellung nicht erstellen', ['abo_id' => $userAbo->id]);
- $this->error("Konnte Bestellung für Abo {$userAbo->id} nicht erstellen");
- return null;
- }
-
- \Log::channel('abo_order')->info('UserMakeAboOrder: Bestellung erstellt, starte Zahlungsvorgang', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id
- ]);
-
- $response = $userOrder->makePayment();
- $this->info('makePayment response: ' . json_encode($response));
-
- if (!isset($response['status'])) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Ungültige Zahlungsantwort', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id,
- 'response' => $response
- ]);
- $this->error("Ungültige Zahlungsantwort für Abo {$userAbo->id}");
- return $shoppingOrder;
- }
-
- if ($response['status'] === 'APPROVED') {
- \Log::channel('abo_order')->info('UserMakeAboOrder: Zahlung erfolgreich', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id,
- 'response' => $response
- ]);
- $this->info("Zahlung erfolgreich für Abo {$userAbo->id}");
- $this->updateAbo($userAbo, $shoppingOrder, 1);
- } elseif ($response['status'] === 'ERROR') {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Zahlungsfehler', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id,
- 'error' => $response
- ]);
- $this->error("Zahlungsfehler für Abo {$userAbo->id}");
-
- MyLog::writeLog(
- 'userabo',
- 'error',
- 'Error:3002 App\Console\Commands\UserMakeAboOrder::makeOrder / makePayment Error response',
- $response
- );
-
- $this->updateAbo($userAbo, $shoppingOrder, 3);
-
- $shoppingPayment = $userOrder->getShoppingPayment();
- $data = [
- 'mode' => $shoppingPayment->mode,
- 'txaction' => 'error',
- 'send_link' => false,
- 'payment_error' => $response,
- ];
-
- Payment::paymentStatusSendMail($shoppingOrder, $shoppingPayment, $data);
- } else {
- \Log::channel('abo_order')->warning('UserMakeAboOrder: Unbekannter Zahlungsstatus', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id,
- 'status' => $response['status']
- ]);
- $this->warn("Unbekannter Zahlungsstatus für Abo {$userAbo->id}: {$response['status']}");
- }
- } catch (\Exception $e) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Ausnahme bei der Bestellungserstellung', [
- 'abo_id' => $userAbo->id,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- $this->error("Ausnahme bei Abo {$userAbo->id}: " . $e->getMessage());
- }
-
- return $shoppingOrder;
- }
-
- /**
- * Aktualisiert das Abo nach einer Bestellung
- *
- * @param UserAbo $userAbo
- * @param mixed $shoppingOrder
- * @param int $status
- * @return void
- */
- private function updateAbo($userAbo, $shoppingOrder, $status = 1)
- {
- \Log::channel('abo_order')->info('UserMakeAboOrder: Aktualisiere Abo', [
- 'abo_id' => $userAbo->id,
- 'order_id' => $shoppingOrder->id,
- 'status' => $status
- ]);
-
- $this->info("Aktualisiere Abo: {$userAbo->id} mit Status {$status}");
-
- $updateData = [
- 'next_date' => AboHelper::setNextDate(now(), $userAbo->abo_interval),
- 'last_date' => now(),
- ];
-
- if ($status !== 1) {
- $updateData['status'] = $status;
- }
-
- try {
- $userAbo->update($updateData);
-
- UserAboOrder::create([
- 'user_abo_id' => $userAbo->id,
- 'shopping_order_id' => $shoppingOrder->id,
- 'status' => $status,
- ]);
-
- \Log::channel('abo_order')->info('UserMakeAboOrder: Abo erfolgreich aktualisiert', [
- 'abo_id' => $userAbo->id,
- 'next_date' => $updateData['next_date']
- ]);
- } catch (\Exception $e) {
- \Log::channel('abo_order')->error('UserMakeAboOrder: Fehler beim Aktualisieren des Abos', [
- 'abo_id' => $userAbo->id,
- 'error' => $e->getMessage()
- ]);
- $this->error("Fehler beim Aktualisieren des Abos {$userAbo->id}: " . $e->getMessage());
- }
- }
-
- /**
- * Berechnet die Ausführungszeit
- *
- * @return string
- */
- private function getExecutionTime()
- {
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- return $sec . ' Sekunden und ' . round($micro * 1000, 2) . ' ms';
- }
-}
diff --git a/dev/app-bak/Console/Commands/UserRestore.php b/dev/app-bak/Console/Commands/UserRestore.php
deleted file mode 100644
index ae0001a2..00000000
--- a/dev/app-bak/Console/Commands/UserRestore.php
+++ /dev/null
@@ -1,112 +0,0 @@
-info('RUN Command user:restore');
-
- $this->timeStart = microtime(true);
-
- $this->restoreInavtiveUsers();
- return 0;
-
- //\Log::info('Cron is running');
- //return 0;
- }
-
- //gibt es gelöschte Berater mit Kunden und childs???
-
- private function restoreInavtiveUsers(){
-
- $this->info('START Command restoreInavtiveUsers');
- $count = 0;
-
- $this->user_id = $this->argument('user_id');
-
- if(!$this->user_id){
- $this->info('NO user_id as argument');
- return;
- }
-
- $this->info('RUN Command restoreInavtiveUsers on user_id: '.$this->user_id);
-
- $user = User::find($this->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));
-
- UserUtil::reactiveUser($user);
- //childs wieder herstellen
- UserUtil::resetChildsToSponsor($user->id);
-
-
- $diff = microtime(true) - $this->timeStart;
- $sec = intval($diff);
- $micro = $diff - $sec;
-
- $this->info('END Command deleteInavtiveUsers: '.$count. ' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");
-
- }
-}
-
-
-//497
-
-//489 -> de
-
-//478 new
\ No newline at end of file
diff --git a/dev/app-bak/Console/Kernel.php b/dev/app-bak/Console/Kernel.php
deleted file mode 100755
index c236e2e7..00000000
--- a/dev/app-bak/Console/Kernel.php
+++ /dev/null
@@ -1,56 +0,0 @@
-command('payments:check-accounts')->dailyAt('02:00');
- // Jobs 2, 3, 4: Die Befehle aus deinem alten Shell-Skript.
- // Werden nacheinander täglich zu unterschiedlichen Zeiten ausgeführt,
- // um die Serverlast zu verteilen.
- $schedule->command('store-optimized 0 0')->dailyAt('03:00');
-
- $schedule->command('user:cleanup')->dailyAt('03:30');
- $schedule->command('user:make_abo_order')->dailyAt('04:00');
- }
-
- /**
- * Register the commands for the application.
- *
- * @return void
- */
- protected function commands()
- {
- $this->load(__DIR__ . '/Commands');
-
- require base_path('routes/console.php');
- }
-}
diff --git a/dev/app-bak/Cron/BusinessUsersStore.php b/dev/app-bak/Cron/BusinessUsersStore.php
deleted file mode 100644
index d30e3523..00000000
--- a/dev/app-bak/Cron/BusinessUsersStore.php
+++ /dev/null
@@ -1,164 +0,0 @@
-month = $month;
- $this->year = $year;
- }
-
-
- public function getStoreUserBusinessStructure()
- {
- return UserBusinessStructure::where('year', $this->year)->where('month', $this->month)->first();
- }
-
- public function storeUserBusinessStructure()
- {
- if ($this->user_business_structure = $this->getStoreUserBusinessStructure()) {
- return $this->user_business_structure;
- }
- $treeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'admin');
- //only load, when no structur is save
- $treeCalcBot->initStructureAdmin(false);
- $this->storeStructure($treeCalcBot);
- }
-
- public function storeBusinessUsersDetail()
- {
- if (!$this->user_business_structure) {
- $this->user_business_structure = $this->getStoreUserBusinessStructure();
- if (!$this->user_business_structure) {
- abort(403, 'not found UserBusinessStructure');
- }
- }
- foreach ($this->user_business_structure->users as $user_id => $completed) {
- if ($completed === 0) {
- $user = User::find($user_id);
- if ($user) {
- $TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'admin');
- $TreeCalcBot->initBusinesslUserDetail($user);
- if (!$TreeCalcBot->business_user) {
- abort(403, 'not found TreeCalcBot->business_user');
- }
- $this->storeBusinesslUser($TreeCalcBot->business_user);
- $users = $this->user_business_structure->users;
- $users[$user_id] = 1;
- $this->user_business_structure->users = $users;
- $this->user_business_structure->save();
- }
- }
- }
- }
-
-
- public function storeBusinesslUser($business_user)
- {
- $b_user = $business_user->getBUser();
- $b_user->user_items = $this->storeUserItems($business_user->businessUserItems, 1);
- $b_user->b_structure_id = $this->user_business_structure->id;
- $b_user->save();
- }
-
-
- public function storeBusinessCompleted()
- {
- if (!$this->user_business_structure) {
- $this->user_business_structure = $this->getStoreUserBusinessStructure();
- }
- foreach ($this->user_business_structure->users as $user_id => $completed) {
- if ($completed === 0) {
- return false;
- }
- $this->user_business_structure->completed = 1;
- $this->user_business_structure->save();
- }
- return true;
- }
-
-
- private function storeUserItems($userItems, $line)
- {
- $ret = [];
- foreach ($userItems as $userItem) {
- $temp = null;
- if (count($userItem->businessUserItems) > 0) {
- $temp = $this->storeUserItems($userItem->businessUserItems, $line + 1);
- }
- $obj = new stdClass();
- $obj->user_id = $userItem->user_id;
- $obj->line = $line;
- $obj->points = $userItem->sales_volume_points_sum;
- $obj->parents = $temp;
- $ret[] = $obj;
- }
- return $ret;
- }
-
-
- private function storeStructure($treeCalcBot)
- {
- /*if($this->user_business_structure = $this->getStoreUserBusinessStructure()){
- return $this->user_business_structure;
- }*/
-
- $structure = [];
- foreach ($treeCalcBot->business_users as $business_user) {
- $structure[] = $this->storeStructureItem($business_user, 0);
- }
-
- $parentless = [];
- if ($treeCalcBot->parentless) {
- foreach ($treeCalcBot->parentless as $pless) {
- $parentless[] = $this->storeStructureItem($pless, 0);
- }
- }
- $fill = [
- 'month' => $this->month,
- 'year' => $this->year,
- 'structure' => $structure,
- 'parentless' => $parentless,
- 'users' => $this->users_structure,
- 'completed' => false,
- 'status' => 0
- ];
- $this->user_business_structure = UserBusinessStructure::create($fill);
- return $this->user_business_structure;
- }
-
-
-
- private function storeStructureItem($item, $deep)
- {
- $temp = null;
- if ($item->businessUserItems) {
- foreach ($item->businessUserItems as $parent) {
- $temp[] = $this->storeStructureItem($parent, $deep + 1);
- }
- }
- $this->users_structure[$item->user_id] = 0;
- $obj = new stdClass();
- $obj->user_id = $item->user_id;
- //$obj->name = $item->first_name .' '. $item->last_name ;
- $obj->email = $item->email;
- $obj->deep = $deep;
- //$obj->points = $item->sales_volume_points_sum;
- $obj->parents = $temp;
- return $obj;
- }
-}
diff --git a/dev/app-bak/Cron/BusinessUsersStoreOptimized.php b/dev/app-bak/Cron/BusinessUsersStoreOptimized.php
deleted file mode 100644
index 18483d1d..00000000
--- a/dev/app-bak/Cron/BusinessUsersStoreOptimized.php
+++ /dev/null
@@ -1,263 +0,0 @@
-month = $month;
- $this->year = $year;
- $this->logger = $logger ?? app(LoggerInterface::class);
- }
-
- public function getStoreUserBusinessStructure()
- {
- return UserBusinessStructure::where('year', $this->year)
- ->where('month', $this->month)
- ->first();
- }
-
- public function storeUserBusinessStructure()
- {
- if ($this->user_business_structure = $this->getStoreUserBusinessStructure()) {
- $this->logger->info("Found existing business structure for {$this->month}/{$this->year}");
- return $this->user_business_structure;
- }
-
- try {
- $this->logger->info("Creating new business structure for {$this->month}/{$this->year}");
- $startTime = microtime(true);
-
- // Verwende TreeCalcBotOptimized mit Live-Berechnung für aktuelle Daten
- $treeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'admin', true);
- $treeCalcBot->initStructureAdmin(false, true); // forceLiveCalculation = true
-
- $this->storeStructure($treeCalcBot);
-
- $endTime = microtime(true);
- $duration = round(($endTime - $startTime) * 1000, 2);
- $this->logger->info("Business structure created in {$duration}ms with " . count($this->users_structure) . " users");
- } catch (\Exception $e) {
- $this->logger->error("Error creating business structure: " . $e->getMessage());
- throw $e;
- }
- }
-
- public function storeBusinessUsersDetail()
- {
- if (!$this->user_business_structure) {
- $this->user_business_structure = $this->getStoreUserBusinessStructure();
- if (!$this->user_business_structure) {
- throw new \Exception('UserBusinessStructure not found');
- }
- }
-
- $totalUsers = count($this->user_business_structure->users);
- $processedUsers = 0;
-
- $this->logger->info("Processing {$totalUsers} business user details");
-
- foreach ($this->user_business_structure->users as $user_id => $completed) {
- if ($completed === 0) {
- try {
- $user = User::find($user_id);
- if ($user) {
- $this->processBusinessUser($user, $user_id);
- $processedUsers++;
-
- // Log progress every 50 users
- if ($processedUsers % 50 === 0) {
- $this->logger->info("Processed {$processedUsers}/{$totalUsers} business users");
- }
- } else {
- $this->logger->warning("User {$user_id} not found, skipping");
- $this->markUserCompleted($user_id);
- }
- } catch (\Exception $e) {
- $this->logger->error("Error processing user {$user_id}: " . $e->getMessage());
- // Mark as completed to avoid infinite retry loops
- $this->markUserCompleted($user_id);
- }
- }
- }
-
- $this->logger->info("Completed processing {$processedUsers} business user details");
- }
-
- private function processBusinessUser(User $user, int $user_id): void
- {
- try {
- $startTime = microtime(true);
-
- // Verwende TreeCalcBotOptimized für detaillierte Benutzerberechnung
- $TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'admin', true);
- $TreeCalcBot->initBusinesslUserDetail($user, true); // forceLiveCalculation = true
-
- if (!$TreeCalcBot->business_user) {
- throw new \Exception("business_user not found for user {$user_id}");
- }
-
- $this->storeBusinesslUser($TreeCalcBot->business_user);
- $this->markUserCompleted($user_id);
-
- $endTime = microtime(true);
- $duration = round(($endTime - $startTime) * 1000, 2);
- $this->logger->debug("Processed user {$user_id} in {$duration}ms");
- } catch (\Exception $e) {
- $this->logger->error("Error in processBusinessUser for {$user_id}: " . $e->getMessage());
- throw $e;
- }
- }
-
- private function markUserCompleted(int $user_id): void
- {
- $users = $this->user_business_structure->users;
- $users[$user_id] = 1;
- $this->user_business_structure->users = $users;
- $this->user_business_structure->save();
- }
-
- public function storeBusinesslUser($business_user)
- {
- try {
- $b_user = $business_user->getBUser();
- $b_user->user_items = $this->storeUserItems($business_user->businessUserItems, 1);
- $b_user->b_structure_id = $this->user_business_structure->id;
- $b_user->save();
- } catch (\Exception $e) {
- $this->logger->error("Error storing business user: " . $e->getMessage());
- throw $e;
- }
- }
-
- public function storeBusinessCompleted()
- {
- if (!$this->user_business_structure) {
- $this->user_business_structure = $this->getStoreUserBusinessStructure();
- }
-
- $incompleteCount = 0;
- foreach ($this->user_business_structure->users as $user_id => $completed) {
- if ($completed === 0) {
- $incompleteCount++;
- }
- }
-
- if ($incompleteCount === 0) {
- $this->user_business_structure->completed = 1;
- $this->user_business_structure->save();
- $this->logger->info("Business structure marked as completed");
- return true;
- }
-
- $this->logger->info("{$incompleteCount} users still incomplete");
- return false;
- }
-
- private function storeUserItems($userItems, $line)
- {
- $ret = [];
-
- try {
- foreach ($userItems as $userItem) {
- $temp = null;
- if (count($userItem->businessUserItems) > 0) {
- $temp = $this->storeUserItems($userItem->businessUserItems, $line + 1);
- }
-
- $obj = new stdClass();
- $obj->user_id = $userItem->user_id;
- $obj->line = $line;
- $obj->points = $userItem->sales_volume_points_sum ?? 0;
- $obj->parents = $temp;
- $ret[] = $obj;
- }
- } catch (\Exception $e) {
- $this->logger->error("Error storing user items at line {$line}: " . $e->getMessage());
- throw $e;
- }
-
- return $ret;
- }
-
- private function storeStructure($treeCalcBot)
- {
- try {
- $structure = [];
- $businessUsers = $treeCalcBot->business_users;
-
- if (!is_array($businessUsers)) {
- throw new \Exception("business_users is not an array");
- }
-
- foreach ($businessUsers as $business_user) {
- $structure[] = $this->storeStructureItem($business_user, 0);
- }
-
- $parentless = [];
- $parentlessUsers = $treeCalcBot->parentless;
-
- if ($parentlessUsers && is_array($parentlessUsers)) {
- foreach ($parentlessUsers as $pless) {
- $parentless[] = $this->storeStructureItem($pless, 0);
- }
- }
-
- $fill = [
- 'month' => $this->month,
- 'year' => $this->year,
- 'structure' => $structure,
- 'parentless' => $parentless,
- 'users' => $this->users_structure,
- 'completed' => false,
- 'status' => 0
- ];
-
- $this->user_business_structure = UserBusinessStructure::create($fill);
- $this->logger->info("Stored structure with " . count($structure) . " root users and " . count($parentless) . " parentless users");
-
- return $this->user_business_structure;
- } catch (\Exception $e) {
- $this->logger->error("Error storing structure: " . $e->getMessage());
- throw $e;
- }
- }
-
- private function storeStructureItem($item, $deep)
- {
- try {
- $temp = null;
- if (isset($item->businessUserItems) && is_array($item->businessUserItems)) {
- foreach ($item->businessUserItems as $parent) {
- $temp[] = $this->storeStructureItem($parent, $deep + 1);
- }
- }
-
- $this->users_structure[$item->user_id] = 0;
-
- $obj = new stdClass();
- $obj->user_id = $item->user_id;
- $obj->email = $item->email ?? 'unknown';
- $obj->deep = $deep;
- $obj->parents = $temp;
-
- return $obj;
- } catch (\Exception $e) {
- $this->logger->error("Error storing structure item for user {$item->user_id}: " . $e->getMessage());
- throw $e;
- }
- }
-}
diff --git a/dev/app-bak/Cron/UserLevelUpdate.php b/dev/app-bak/Cron/UserLevelUpdate.php
deleted file mode 100644
index c56e54f3..00000000
--- a/dev/app-bak/Cron/UserLevelUpdate.php
+++ /dev/null
@@ -1,68 +0,0 @@
-month = $month;
- $this->year = $year;
- }
-
-
- public function getUserBusinessByMonthYear(){
- return UserBusiness::select('user_businesses.*')
- ->where('user_businesses.month', '=', $this->month)
- ->where('user_businesses.year', '=', $this->year)
- ->where('user_businesses.next_qual_user_level', '!=', NULL)
- ->get();
- }
-
- public function makeUserLevelUpdate(UserBusiness $userBusiness, $send_update_mail){
- $ret = false;
- $nextQualUserLevel = $userBusiness->next_qual_user_level;
- if(!isset($nextQualUserLevel['hasUpdated']) && $userBusiness->user){
- $userBusiness->user->m_level = $nextQualUserLevel['id'];
- $userBusiness->user->save();
- $nextQualUserLevel['hasUpdated'] = 1;
- $userBusiness->next_qual_user_level = $nextQualUserLevel;
- $userBusiness->save();
- $ret = $nextQualUserLevel['id'].' '.$nextQualUserLevel['name'];
- if($send_update_mail){
- self::sendUpdateMail($userBusiness->user, $userBusiness->total_qual_pp, $nextQualUserLevel['name']);
- }
-
- }
- return $ret;
- }
-
-
- private function sendUpdateMail(User $user, $tp, $to){
- $bcc = [];
- $email = $user->email;
- if(!$email){
- if($user->mode === 'test'){
- }else{
- $email = config('app.checkout_mail');
- }
- }
- if($user->mode === 'test'){
- $bcc[] = config('app.checkout_test_mail');
- }else{
- $bcc[] = config('app.checkout_mail');
- }
- Mail::to($email)->bcc($bcc)->locale($user->getLocale())->send(new MailUserLevelUpdate($tp, $to));
- }
-}
diff --git a/dev/app-bak/Cron/UserMakeOrder.php b/dev/app-bak/Cron/UserMakeOrder.php
deleted file mode 100644
index d17a1d5f..00000000
--- a/dev/app-bak/Cron/UserMakeOrder.php
+++ /dev/null
@@ -1,203 +0,0 @@
-userAbo = $userAbo;
- Log::info('UserMakeOrder initialisiert für UserAbo ID: ' . $userAbo->id);
- }
-
-
- public function checkProducts()
- {
- Log::info('Überprüfe Produkte für UserAbo ID: ' . $this->userAbo->id);
- $ret = [];
-
- if (!$this->userAbo->items || $this->userAbo->items->isEmpty()) {
- Log::warning('Keine Artikel für UserAbo ID: ' . $this->userAbo->id . ' gefunden');
- return $ret;
- }
- //preise prüfen, ob sie sich geändert haben?
- foreach($this->userAbo->items as $item){
- $ret[] = [
- 'product_id' => $item->product_id,
- 'comp' => $item->comp,
- 'qty' => $item->qty,
- 'price' => $item->price,
- 'price_net' => $item->price_net,
- 'tax_rate' => $item->tax_rate,
- 'tax' => $item->tax,
- 'price_vk_net' => $item->price_vk_net,
- 'discount' => $item->discount,
- 'points' => $item->points,
- ];
- }
-
- Log::info('Produkte überprüft: ' . count($ret) . ' Artikel gefunden');
- return $ret;
- }
-
- public function makePayment()
- {
- Log::info('Starte Zahlungsvorgang für UserAbo ID: ' . $this->userAbo->id);
-
- try {
- $this->pay = new PayoneController();
- $this->pay->init($this->shopping_user, $this->shopping_order);
- $amount = $this->shopping_order->subtotal_ws * 100;
- $this->pay->setAboPayment($this->userAbo, $amount, 'EUR');
- $this->pay->setPersonalData();
- $response = $this->pay->ResponseData(true);
-
- Log::info('Zahlungsvorgang abgeschlossen für UserAbo ID: ' . $this->userAbo->id . ', Status: ' . ($response->status ?? 'unbekannt'));
- return $response;
- } catch (\Exception $e) {
- Log::error('Fehler bei Zahlungsvorgang für UserAbo ID: ' . $this->userAbo->id . ': ' . $e->getMessage());
- throw $e;
- }
- }
-
- public function getShoppingPayment()
- {
- Log::info('Rufe Zahlungsinformationen ab für UserAbo ID: ' . $this->userAbo->id);
-
- if($this->pay){
- $payment = $this->pay->getShoppingPayment();
- Log::info('Zahlungsinformationen abgerufen: ' . ($payment ? 'erfolgreich' : 'nicht verfügbar'));
- return $payment;
- }
-
- Log::warning('Keine Zahlungsinformationen verfügbar für UserAbo ID: ' . $this->userAbo->id);
- return false;
- }
-
- public function createShoppingUser()
- {
- Log::info('Erstelle Shopping-User für UserAbo ID: ' . $this->userAbo->id);
- //hier muss der letzte shopping_user verwendet werden
- try {
- $this->shopping_user = AboOrderCart::makeCustomerDetail($this->userAbo);
- $this->shopping_user->created_at = now();
- $this->shopping_user->updated_at = now();
- $this->shopping_user->save();
-
- Log::info('Shopping-User erstellt für UserAbo ID: ' . $this->userAbo->id . ', Neue User-ID: ' . $this->shopping_user->id);
- return $this->shopping_user;
- } catch (\Exception $e) {
- Log::error('Fehler beim Erstellen des Shopping-Users für UserAbo ID: ' . $this->userAbo->id . ': ' . $e->getMessage());
- throw $e;
- }
-
-
- Log::warning('Kein Shopping-User verfügbar für UserAbo ID: ' . $this->userAbo->id);
- return false;
- }
-
- public function makeShoppingOrder()
- {
- Log::info('Erstelle Bestellung für UserAbo ID: ' . $this->userAbo->id);
-
- try {
- if (!$this->shopping_user) {
- Log::error('Kein Shopping-User verfügbar für Bestellerstellung, UserAbo ID: ' . $this->userAbo->id);
- return false;
- }
-
- AboOrderCart::initYard($this->userAbo, $this->shopping_user);
- //hier wird die Bestellung erstellt inkl aktueller Preise
- AboOrderCart::makeOrderYard($this->userAbo);
-
- $yard = Yard::instance('shopping');
-
- if (!$this->userAbo->shopping_user || !$this->userAbo->shopping_user->shopping_order || !$this->userAbo->shopping_user->shopping_order->user_shop) {
- Log::error('Fehlende Beziehungsdaten für Bestellerstellung, UserAbo ID: ' . $this->userAbo->id);
- return false;
- }
-
- $this->shopping_order = ShoppingOrder::create([
- 'shopping_user_id' => $this->shopping_user->id,
- 'auth_user_id' => $this->shopping_user->auth_user_id,
- 'country_id' => $yard->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'user_shop_id' => $this->userAbo->shopping_user->shopping_order->user_shop->id,
- 'payment_for' => $this->shopping_user->getOrderPaymentFor(),
- 'total' => $yard->total(2, '.', ''),
- 'subtotal' => $yard->subtotal(2, '.', ''),
- 'shipping' => $yard->shipping(2, '.', ','),
- 'shipping_net' => $yard->shippingNet(2, '.', ''),
- 'subtotal_ws' => $yard->subtotalWithShipping(2, '.', ''),
- 'tax' => $yard->taxWithShipping(2, '.', ''),
- 'total_shipping' => $yard->totalWithShipping(2, '.', ''),
- 'points' => $yard->points(),
- 'weight' => $yard->weight(),
- 'is_abo' => 1,
- 'abo_interval' => 0,
- 'txaction' => 'prev',
- 'mode' => $this->userAbo->shopping_user->shopping_order->mode,
- ]);
-
- Log::info('Bestellung erstellt für UserAbo ID: ' . $this->userAbo->id . ', Bestellnummer: ' . $this->shopping_order->id);
-
- $items = $yard->getContentByOrder();
- $itemCount = 0;
-
- foreach ($items as $item) {
- if (!ShoppingOrderItem::where('shopping_order_id', $this->shopping_order->id)->where('row_id', $item->rowId)->count()){
- $price_net = $yard->rowPriceNet($item, 2, '.', '');
- $tax = $item->price - $price_net;
- $data = [
- 'shopping_order_id' => $this->shopping_order->id,
- 'row_id' => $item->rowId,
- 'product_id' => $item->id,
- 'comp' => $item->options->comp,
- 'qty' => $item->qty,
- 'price' => $item->price,
- 'price_net' => $price_net,
- 'tax_rate' => $item->taxRate,
- 'tax' => $tax,
- 'price_vk_net' => $this->shopping_order->getPriceVkNetBy($item->id),
- 'discount' => $item->options->no_commission ? 0 : $this->shopping_order->getUserDiscount(),
- 'points' => $item->options->points,
- 'slug' => $item->options->slug
- ];
- ShoppingOrderItem::create($data);
- $itemCount++;
- }
- }
-
- Log::info('Bestellpositionen hinzugefügt für UserAbo ID: ' . $this->userAbo->id . ', Anzahl: ' . $itemCount);
-
- $this->shopping_order->makeTaxSplit();
- Log::info('Steueraufteilung für Bestellung abgeschlossen, UserAbo ID: ' . $this->userAbo->id);
-
- return $this->shopping_order;
- } catch (\Exception $e) {
- Log::error('Fehler bei Bestellerstellung für UserAbo ID: ' . $this->userAbo->id . ': ' . $e->getMessage());
- throw $e;
- }
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Cron/UserPaymentCredits.php b/dev/app-bak/Cron/UserPaymentCredits.php
deleted file mode 100644
index 24d12fb8..00000000
--- a/dev/app-bak/Cron/UserPaymentCredits.php
+++ /dev/null
@@ -1,106 +0,0 @@
-month = $month;
- $this->year = $year;
- }
-
-
- public function getUserBusinessByMonthYear(){
- return UserBusiness::select('user_businesses.*')
- ->where('user_businesses.month', '=', $this->month)
- ->where('user_businesses.year', '=', $this->year)
- ->where(function($q) {
- return $q->where('user_businesses.commission_pp_total', '>', 0)
- ->orWhere('user_businesses.commission_shop_sales', '>', 0);
- })
- ->get();
- }
-
- public function addUserCreditItem($userBusiness)
- {
- //HTMLHelper::getMonth($userBusiness->month)
-
- $date = $userBusiness->month.'#'.$userBusiness->year;
-
- if($userBusiness->commission_shop_sales > 0){
- if($this->hasNotUserCreditItem($userBusiness, 1)){
- UserCreditItem::create([
- 'user_id' => $userBusiness->user_id,
- 'user_business_id' => $userBusiness->id,
- 'credit' => $userBusiness->commission_shop_sales,
- 'message' => 'payment.commission_shop#'.$date,
- 'from_month' => $userBusiness->month,
- 'from_year' => $userBusiness->year,
- 'status' => 1,
- ]);
- }
- }
- if($userBusiness->commission_pp_total > 0){
- if($this->hasNotUserCreditItem($userBusiness, 2)){
- UserCreditItem::create([
- 'user_id' => $userBusiness->user_id,
- 'user_business_id' => $userBusiness->id,
- 'credit' => $userBusiness->commission_pp_total,
- 'message' => 'payment.commission_payline#'.$date,
- 'from_month' => $userBusiness->month,
- 'from_year' => $userBusiness->year,
- 'status' => 2,
- ]);
- }
- }
- if($userBusiness->commission_growth_total > 0){
- if($this->hasNotUserCreditItem($userBusiness, 5)){
- UserCreditItem::create([
- 'user_id' => $userBusiness->user_id,
- 'user_business_id' => $userBusiness->id,
- 'credit' => $userBusiness->commission_growth_total,
- 'message' => 'payment.commission_growth_bonus#'.$date,
- 'from_month' => $userBusiness->month,
- 'from_year' => $userBusiness->year,
- 'status' => 5,
- ]);
- }
- }
- return $userBusiness;
-
- }
-
- public function getUserCreditItemUsersByMonthYear(){
- return UserCreditItem::select('user_credit_items.*')
- ->where('paid', '=', false)
- ->groupBy('user_id')
- ->get();
- }
-
- public function makeCreditPaymentPDF($user_id, $credit_send_mail)
- {
- //$user_id = 2;
- $user = User::findOrFail($user_id);
- $data = [];
- if($credit_send_mail){
- $data['credit_send_mail'] = false;
- }
- $credit_repo = new CreditRepository($user);
- return $credit_repo->create($data);
- }
-
- private function hasNotUserCreditItem($userBusiness, $status){
- return (UserCreditItem::where('user_business_id', $userBusiness->id)
- ->where('user_id', $userBusiness->user_id)->where('status', $status)->count() > 0) ? false : true;
- }
-}
diff --git a/dev/app-bak/Domain/DomainContext.php b/dev/app-bak/Domain/DomainContext.php
deleted file mode 100644
index ae3bccc0..00000000
--- a/dev/app-bak/Domain/DomainContext.php
+++ /dev/null
@@ -1,69 +0,0 @@
-type === 'unknown';
- }
-
- /**
- * Prüft, ob es sich um eine User-Shop-Domain handelt.
- */
- public function isUserShop(): bool
- {
- return $this->type === 'user-shop';
- }
-
- /**
- * Gibt den Slug des User-Shops zurück.
- */
- public function getUserShopSlug(): ?string
- {
- return $this->userShop?->slug;
- }
-
-
-}
diff --git a/dev/app-bak/Exceptions/Handler.php b/dev/app-bak/Exceptions/Handler.php
deleted file mode 100755
index b00396b3..00000000
--- a/dev/app-bak/Exceptions/Handler.php
+++ /dev/null
@@ -1,122 +0,0 @@
-shouldReport($exception)) {
- $this->sendEmail($exception);
- }
- parent::report($exception);
- }
-
- /**
- * Render an exception into an HTTP response.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Throwable $exception
- * @return \Symfony\Component\HttpFoundation\Response
- *
- * @throws \Throwable
- */
- public function render($request, Throwable $exception)
- {
- return parent::render($request, $exception);
- }
-
- /**
- * Convert an authentication exception into a response.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Illuminate\Auth\AuthenticationException $exception
- * @return \Symfony\Component\HttpFoundation\Response
- */
- protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
- {
- if ($request->expectsJson()) {
- return response()->json(['message' => $exception->getMessage()], 401);
- }
-
- try {
- // Versuche domain-spezifische Login-Route
- $context = app(\App\Domain\DomainContext::class);
- $loginRoute = match($context->type) {
- 'portal' => 'portal.login.form',
- 'crm' => 'login', // CRM hat eine eigene login route
- default => 'login'
- };
-
- return redirect()->guest(route($loginRoute));
- } catch (\Exception $e) {
- // Fallback: Weiterleitung zur Hauptdomain
- return redirect()->guest('https://' . config('app.domain') . config('app.tld_care') . '/login');
- }
- }
-
- public function sendEmail(Throwable $exception)
- {
- try {
- $e = FlattenException::create($exception);
- $handler = new HtmlErrorRenderer(true); // boolean, true raises debug flag...
- $css = $handler->getStylesheet();
- $content = $handler->getBody($e);
- //Mail::to(config('app.exception_mail'))->send(new MailContact($contact));
- // Verwende normale Mail-Klasse statt Facade, um Probleme bei der Initialisierung zu vermeiden
- $to = config('app.exception_mail');
- $subject = 'mivita Exception: ' . \Request::fullUrl();
-
- if ($to) {
- \Mail::send('emails.exception', compact('css', 'content'), function ($message) use ($to, $subject) {
- $message
- ->to($to)
- ->subject($subject)
- ;
- });
- }
- } catch (Throwable $ex) {
- // Einfache Fehlerprotokollierung ohne Facade
- file_put_contents(
- storage_path('logs/laravel-' . date('Y-m-d') . '.log'),
- '[' . date('Y-m-d H:i:s') . '] exception-handler-error: ' . $ex->getMessage() . "\n",
- FILE_APPEND
- );
- }
- }
-}
diff --git a/dev/app-bak/Exports/UserTeamExport.php b/dev/app-bak/Exports/UserTeamExport.php
deleted file mode 100644
index 0767de01..00000000
--- a/dev/app-bak/Exports/UserTeamExport.php
+++ /dev/null
@@ -1,33 +0,0 @@
-collection = $data;
- $this->headings = $header;
- }
-
- public function collection()
- {
- return collect($this->collection);
- }
-
- public function headings(): array
- {
- return [$this->headings];
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Exports/xExport.php b/dev/app-bak/Exports/xExport.php
deleted file mode 100644
index 2494092b..00000000
--- a/dev/app-bak/Exports/xExport.php
+++ /dev/null
@@ -1,33 +0,0 @@
-collection = $data;
- $this->headings = $header;
- }
-
- public function collection()
- {
- return collect($this->collection);
- }
-
- public function headings(): array
- {
- return [$this->headings];
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Admin/AboController.php b/dev/app-bak/Http/Controllers/Admin/AboController.php
deleted file mode 100644
index 00863fdc..00000000
--- a/dev/app-bak/Http/Controllers/Admin/AboController.php
+++ /dev/null
@@ -1,151 +0,0 @@
-middleware('admin');
- $this->aboRepository = $aboRepository;
- }
-
- public function index()
- {
- if (Request::get('reset') === 'filter') {
- 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_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_members' => $filter_members,
- ];
- return view('admin.abo.index', $data);
- }
-
-
- public function detail($id)
- {
- $data = Request::all();
- $user_abo = UserAbo::findOrFail($id);
-
- //init Yard
- AboOrderCart::initYard($user_abo);
- $customer_detail = AboOrderCart::getCustomerDetail();
- AboOrderCart::makeOrderYard($user_abo);
-
- $comp_products = [];
- if ($user_abo->is_for === 'me') {
- $comp_products = Shop::getCompProducts('abo-me');
- }
-
- $data = [
- 'user_abo' => $user_abo,
- 'isAdmin' => true,
- 'customer_detail' => $customer_detail,
- 'view' => $user_abo->is_for,
- 'comp_products' => $comp_products,
- ];
- return view('admin.abo.detail', $data);
- }
-
-
- public function update($id)
- {
- $data = Request::all();
- 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('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') != "") {
- $query->where('user_id', '=', Request::get('filter_member_id'));
- }
-
- set_user_attr('filter_status', 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 '';
- })
- ->addColumn('start_date', function (UserAbo $user_abo) {
- return $user_abo->start_date;
- })
- ->addColumn('next_date', function (UserAbo $user_abo) {
- return $user_abo->next_date;
- })
- ->addColumn('abo_interval', function (UserAbo $user_abo) {
- return \App\Services\HTMLHelper::getAboStrLang($user_abo->abo_interval);
- })
- ->addColumn('status', function (UserAbo $user_abo) {
- return $user_abo->getStatusFormated();
- })
- ->addColumn('active', function (UserAbo $user_abo) {
- return get_active_badge($user_abo->active);
- })
-
- ->addColumn('is_for', function (UserAbo $user_abo) {
- return $user_abo->getIsForFormated();
- })
- ->addColumn('count', function (UserAbo $user_abo) {
- return $user_abo->getCountOrders();
- })
- ->addColumn('amount', function (UserAbo $user_abo) {
- 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 '' . $user_abo->shopping_user->member->getFullName() . '';
- }
- })
- ->addColumn('payone_userid', function (UserAbo $user_abo) {
- return $user_abo->payone_userid;
- })
-
- ->orderColumn('id', 'id $1')
- ->orderColumn('start_date', 'start_date $1')
- ->orderColumn('next_date', 'next_date $1')
- ->orderColumn('abo_interval', 'abo_interval $1')
- ->orderColumn('status', 'status $1')
- ->orderColumn('active', 'active $1')
- ->orderColumn('is_for', 'is_for $1')
- ->orderColumn('count', 'count $1')
- ->orderColumn('amount', 'amount $1')
- ->orderColumn('payone_userid', 'payone_userid $1')
- ->rawColumns(['id', 'status', 'active', 'is_for', 'member'])
- ->make(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Admin/DownloadController.php b/dev/app-bak/Http/Controllers/Admin/DownloadController.php
deleted file mode 100644
index 0eeb6586..00000000
--- a/dev/app-bak/Http/Controllers/Admin/DownloadController.php
+++ /dev/null
@@ -1,188 +0,0 @@
-middleware('admin');
- $this->tagRepository = $tagRepository;
- $this->fileRepository = $fileRepository;
- }
-
- 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){
- $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'){
- $this->fileRepository->makeThumb($id);
- \Session()->flash('alert-success', 'Vorschaubild erstellt!');
- return back();
- }
- if($do === 'delete'){
- $this->fileRepository->deleteFile($id);
- \Session()->flash('alert-success', 'Datei gelöscht!');
- return redirect(route('admin_downloadcenter_files'));
- }
- if($do === 'delete_thumb'){
- $this->fileRepository->deleteThumb($id);
- \Session()->flash('alert-success', 'Vorschaubild gelöscht!');
- return back();
- }
- if($do === 'deactivate'){
- $file = DcFile::findOrFail($id);
- $file->active = false;
- $file->save();
- \Session()->flash('alert-success', 'Datei nicht anzeigen!');
- return back();
- }
-
- 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'){
- $file = DcFile::findOrFail($id);
- $this->fileRepository->tagsUpdate($id, Request::get('nestable_check'));
- \Session()->flash('alert-success', 'Tags aktualisiert!');
- return back();
- }
-
- }
-
- public function upload(){
- return view('admin.downloadcenter.file_upload');
- }
-
- public function uploadFile(){
- $data = Request::all();
- $file = $this->fileRepository->uploadFile($data);
-
- return Response::json([
- 'error' => false,
- 'filename' => $file->filename,
- 'filedata' => '',
- 'code' => 200
- ], 200);
-
- //return response()->json(['success'=>basename($file)]);
- }
-
- 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){
- \Session()->flash('alert-success', 'gespeichert!');
- }
- return view('admin.downloadcenter.tags', $data);
- }
-
- 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){
- $this->tagRepository->deleteItem($obj, $id);
- return redirect(route('admin_downloadcenter_tags'));
- }
-
- public function datatable(){
-
- $query = DcFile::with('tags')->select('dc_files.*');
- return \DataTables::eloquent($query)
- ->addColumn('id', function (DcFile $file) {
- return '';
- })
- ->addColumn('image', function (DcFile $file) {
- return ($file->hasThumb() && $file->hasBig()) ?
- '' :
- ' Vorschaubild
erstellen ';
- })
- ->addColumn('name', function (DcFile $file) {
- //Storage::disk('local')->url($file->filename) }}
- return ''.$file->original_name.'';
- // return ''.$file->original_name.'';
- })
- ->addColumn('category', function (DcFile $file) {
- //return $file->category ? $file->category->name : '';
- })
- ->addColumn('tags', function (DcFile $file) {
- //return $file->hasTags() ? '('.$file->fileTag()->count().')' : 'X';
- return $file->tags->implode('name', '
');
- })
- ->addColumn('size', function (DcFile $file) {
- return Util::formatBytes($file->size);
- })
- ->addColumn('active', function (DcFile $file) {
- return get_active_badge($file->active);
- //return $file->active ? ' aktiv' : ' inaktiv';
- })
- ->addColumn('created_at', function (DcFile $file) {
- return $file->created_at->format('d.m.Y H:i');
- })
- ->addColumn('updated_at', function (DcFile $file) {
- return $file->updated_at->format('d.m.Y');
- })
- ->addColumn('action', function (DcFile $file) {
- return '';
- })
- ->filterColumn('name', function($query, $keyword) {
- if($keyword != ""){
- $query->where('original_name', 'LIKE', '%'.$keyword.'%');
- }
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('name', 'original_name $1')
- ->orderColumn('original_name', 'original_name $1')
- ->orderColumn('category', 'category $1')
- ->orderColumn('size', 'size $1')
- ->orderColumn('active', 'active $1')
- ->orderColumn('created_at', 'created_at $1')
- ->rawColumns(['id', 'image', 'name', 'active', 'tags', 'action'])
- ->make(true);
- }
-
-}
diff --git a/dev/app-bak/Http/Controllers/Admin/PaymentSalesController.php b/dev/app-bak/Http/Controllers/Admin/PaymentSalesController.php
deleted file mode 100644
index 528e24d5..00000000
--- a/dev/app-bak/Http/Controllers/Admin/PaymentSalesController.php
+++ /dev/null
@@ -1,467 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- ];
- return view('admin.payment.salesvolume', $data);
- }
-
-
- public function download(){
-
- /*
- EXCEL EXPORT function */
-
- /*
- if(Request::get('action') === "exportfull_paid"){
- return $this->exportFullList(1);
- }
- if(Request::get('action') === "exportfull_unpaid"){
- return $this->exportFullList(0);
- }
- */
- if(Request::get('action') === "exportfull_paid_invoice"){
- return $this->exportFullListInvoice();
- }
- if(Request::get('action') === "export"){
- return $this->exportKompaktListInvoice();
- }
- }
-
-
- private function setFilterVars(){
-
- if(!session('payment_sales_vol_filter_month')){
- session(['payment_sales_vol_filter_month' => intval(date('m'))]);
- }
- if(!session('payment_sales_vol_filter_year')){
- session(['payment_sales_vol_filter_year' => intval(date('Y'))]);
- }
-
- if(Request::get('payment_sales_vol_filter_month')){
- session(['payment_sales_vol_filter_month' => Request::get('payment_sales_vol_filter_month')]);
- }
- if(Request::get('payment_sales_vol_filter_year')){
- session(['payment_sales_vol_filter_year' => Request::get('payment_sales_vol_filter_year')]);
- }
- }
-
- private function exportKompaktListInvoice(){
- $objects = $this->initKompaktList();
- $columns = [];
- $filename = "mivita-absatzmengen-kompakt".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
- $headers = array(
- '#',
- 'Produkt',
- 'Artikelnummer',
- 'Menge',
-
- );
- if($objects){
- foreach ($objects as $key => $obj){
- $columns[] = array(
- 'id' => $key,
- 'name' => $obj['name'],
- 'number' => $obj['number'],
- 'value' => $obj['value'],
- );
- }
- }
- return Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
- }
-
-
- private function exportFullListInvoice(){
-
- $this->setFilterVars();
-
- $UserInvoices = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
- ->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
- ->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
- ->get();
-
- $headers = array('Rechnungsnummer','Datum', 'EMail', 'Zahlung', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Summe', 'Kompensation');
- $columns = [];
- $hasSOID = [];
- $total_value = [];
-
- foreach($UserInvoices as $UserInvoice){
- if($UserInvoice->shopping_order){
- $ShoppingOrder = $UserInvoice->shopping_order;
- $object = [];
- $object['Rechnungsnummer'] = $UserInvoice->full_number;
- $object['Datum'] = $UserInvoice->date;
- $object['EMail'] = $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->billing_email : 'n/a';
- $object['Zahlung'] = $ShoppingOrder->getPaymentForType();
-
- if($ShoppingOrder->payment_for === 5){ //homeparty
- if($ShoppingOrder->homeparty){
- foreach($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item){
- $total_value[$homeparty_item->product_id] = isset($total_value[$homeparty_item->product_id]) ? $total_value[$homeparty_item->product_id] + $homeparty_item->qty : $homeparty_item->qty;
- $object['ProduktNummer'] = $homeparty_item->product ? $homeparty_item->product->number : "n/a";
- $object['ProduktName'] = $homeparty_item->product ? $homeparty_item->product->name : "n/a";
- $object['Anzahl'] = $homeparty_item->qty;
- $object['Summe'] = $total_value[$homeparty_item->product_id];
- $object['Kompensation'] = '';
- $columns[] = $object;
- }
- }
-
- }elseif($ShoppingOrder->payment_for === 8){ //collective_invoice
- if($ShoppingOrder->shopping_collect_order){
- foreach($ShoppingOrder->shopping_collect_order->shop_items as $shop_item){
- $total_value[$shop_item['pid']] = isset($total_value[$shop_item['pid']]) ? $total_value[$shop_item['pid']] + $shop_item['qty'] : $shop_item['qty'];
- $object['ProduktNummer'] = $shop_item['number'];
- $object['ProduktName'] = $shop_item['name'];
- $object['Anzahl'] = $shop_item['qty'];
- $object['Summe'] = $total_value[$shop_item['pid']];
- $object['Kompensation'] = '';
- $columns[] = $object;
- }
-
- }
- }else{
- if($ShoppingOrder->shopping_order_items){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- $total_value[$shopping_order_item->product_id] = isset($total_value[$shopping_order_item->product_id]) ? $total_value[$shopping_order_item->product_id] + $shopping_order_item->qty : $shopping_order_item->qty;
- $object['ProduktNummer'] = $shopping_order_item->product ? $shopping_order_item->product->number : "n/a";
- $object['ProduktName'] = $shopping_order_item->product ? $shopping_order_item->product->name : "n/a";
- $object['Anzahl'] = $shopping_order_item->qty;
- $object['Summe'] = $total_value[$shopping_order_item->product_id];
- $object['Kompensation'] = ($shopping_order_item->comp ? $shopping_order_item->comp : '');
-
- $columns[] = $object;
- }
- }
- }
- $hasSOID[] = $ShoppingOrder->id;
-
- }
- }
-
- $filename = "mivita-absatzmengen-voll-".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
- return Excel::download(new xExport($columns, $headers), $filename.'.xls');
-
- }
-
-
-
- private function initKompaktList()
- {
- $this->setFilterVars();
-
- $UserInvoices = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
- ->where('user_invoices.month', '=', session('payment_sales_vol_filter_month'))
- ->where('user_invoices.year', '=', session('payment_sales_vol_filter_year'))
- ->get();
-
- $objects = [];
-
- foreach($UserInvoices as $UserInvoice){
- if($UserInvoice->shopping_order){
- $ShoppingOrder = $UserInvoice->shopping_order;
-
- if($ShoppingOrder->payment_for === 5){ //homeparty
- if($ShoppingOrder->homeparty){
- foreach($ShoppingOrder->homeparty->homeparty_order_items as $homeparty_item){
- if(isset($objects[$homeparty_item->product_id])){
- $value = intval($objects[$homeparty_item->product_id]['value'] + $homeparty_item->qty);
- $objects[$homeparty_item->product_id]['value'] = $value;
- }else{
- $objects[$homeparty_item->product_id] = [
- 'name' => $homeparty_item->product ? $homeparty_item->product->name : "n/a ".$homeparty_item->product_id,
- 'number' => $homeparty_item->product ? $homeparty_item->product->number : "n/a ".$homeparty_item->product_id,
- 'value' => $homeparty_item->qty
- ];
- }
- }
- }
-
- }elseif($ShoppingOrder->payment_for === 8){ //collective_invoice
- if($ShoppingOrder->shopping_collect_order){
- foreach($ShoppingOrder->shopping_collect_order->shop_items as $shop_item){
-
- if(isset($objects[$shop_item['pid']])){
- $value = intval($objects[$shop_item['pid']]['value'] + $shop_item['qty']);
- $objects[$shop_item['pid']]['value'] = $value;
- }else{
- $objects[$shop_item['pid']] = [
- 'name' => $shop_item['name'],
- 'number' => $shop_item['number'],
- 'value' => $shop_item['qty']
- ];
- }
- }
- }
- }else{
- if($ShoppingOrder->shopping_order_items){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- if(isset($objects[$shopping_order_item->product_id])){
- $value = intval($objects[$shopping_order_item->product_id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product_id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product_id] = [
- 'name' => $shopping_order_item->product ? $shopping_order_item->product->name : "n/a ".$shopping_order_item->product_id,
- 'number' => $shopping_order_item->product ? $shopping_order_item->product->number : "n/a ".$shopping_order_item->product_id,
- 'value' => $shopping_order_item->qty
- ];
- }
- }
- }
- }
- $hasSOID[] = $ShoppingOrder->id;
-
- }
- }
-
- return $objects;
-
- }
-
- public function datatable(){
-
-
- /*$collect = collect([
- ['id' => 1, 'name' => 'John', 'number'=>92012, 'value'=>123],
- ['id' => 2, 'name' => 'Jane', 'number'=>92012, 'value'=>123],
- ['id' => 3, 'name' => 'James', 'number'=>92012, 'value'=>123],
- ]);*/
- $objects = $this->initKompaktList();
- $collection = collect();
- if($objects){
- foreach($objects as $key => $obj){
- $collection->push([
- 'id' => $key,
- 'name' => $obj['name'],
- 'number' => $obj['number'],
- 'value' => $obj['value'],
- ]);
- }
- }
-
- return \DataTables::of($collection)->toJson();
- }
-
- /*
- //Auswertung nach ShoppingOrder
- //nach Datum created_at wann die Bestellung erstellt wurde
- //Ist nicht das Datum der Rechnung, da hier teilweise die Sammelrechnungen oder Zahlungen erst in nächsten Monat erfolgen
-
-
- public function exportFullList($paid = 1){
-
-
- $date_start = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d H:i:s');
- $ShoppingOrders = ShoppingOrder::where('paid', $paid)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $txActions = ['prev' => 'keine Zahlung', 'appointed' => 'offen', 'failed' => 'abbruch', 'paid' => 'bezahlt'];
- $headers = array('ID', 'Zahlung', 'Datum', 'EMail', 'ProduktID', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Notiz', 'Gesamt');
- $objects = [];
- $columns = [];
- $hasSOID = [];
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- $value = "";
- if($shopping_order_item->product){
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- $value = $shopping_order_item->qty;
-
- }
-
- }
- $object = [];
- if(in_array($ShoppingOrder->id, $hasSOID)){
- $object['ID'] = '';
- $object['EMail'] = '';
- $object['Zahlung'] = '';
- $object['Datum'] = '';
- }else{
- $object['ID'] = $ShoppingOrder->id;
- $object['EMail'] = $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->billing_email : 'n/a';
- $object['Zahlung'] = isset($txActions[$ShoppingOrder->txaction]) ? $txActions[$ShoppingOrder->txaction] : $ShoppingOrder->txaction;
- $object['Datum'] = $ShoppingOrder->created_at->format('d.m.Y');
- }
- $object['ProduktID'] = $shopping_order_item->product_id;
- $object['ProduktNummer'] = $shopping_order_item->product ? $shopping_order_item->product->number : "n/a";
- $object['ProduktName'] = $shopping_order_item->product ? $shopping_order_item->product->name : "n/a";
- $object['Anzahl'] = $shopping_order_item->qty;
- $object['Notiz'] = ($shopping_order_item->comp ? 'Compensation '.$shopping_order_item->comp : '') . ($shopping_order_item->shopping_collect_order_id ? 'Sammelbestellung '.$shopping_order_item->shopping_collect_order_id : '');
- $object['Gesamt'] = $value;
- $columns[] = $object;
-
- $hasSOID[] = $ShoppingOrder->id;
- }
- }
- if($paid){
- $filename = "mivita-absatzmengen-full-paid-".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
- }else{
- $filename = "mivita-absatzmengen-full-unpaid-".session('payment_sales_vol_filter_month').'_'.session('payment_sales_vol_filter_year')."-export";
- }
-
- return Excel::download(new xExport($columns, $headers), $filename.'.xls');
-
- //CSV EXPORT function
- $headers = array(
- "Content-type" => "text/csv",
- "Content-Disposition" => "attachment; filename=$fileName",
- "Pragma" => "no-cache",
- "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
- "Expires" => "0"
- );
-
- $header = array('ID', 'Zahlung', 'Datum', 'EMail', 'ProduktID', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Notiz', 'Gesamt');
-
- $callback = function() use($columns, $header) {
-
- $file = fopen('php://output', 'w');
- fputcsv($file, $header);
- $row = [];
-
- foreach ($columns as $row) {
- fputcsv($file, $row);
-
- }
-
- fclose($file);
- };
-
- return response()->stream($callback, 200, $headers);
-
-
-
- }
- */
-
- /*
- //alte Funktion auswerung nach ShoppingOrder
- private function testCheckFunction(){
- //$date_start = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->format('Y-m-d');
- //$date_end = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d');
-
- $date_start = Carbon::parse('01.01.2024')->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.01.2024')->endOfMonth()->format('Y-m-d H:i:s');
- dump($date_start);
- dump($date_end);
-
- $ShoppingOrders = ShoppingOrder::where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $objects = [];
- $counter = 0;
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
-
- if($shopping_order_item->product){
- if($shopping_order_item->product->id === 122){
- //dump($shopping_order_item->qty);
- //$counter += $shopping_order_item->qty;
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- }
- }
- }
-
- }
- }
-
- $ShoppingOrderItems = ShoppingOrderItem::whereProductId(122)->whereBetween('created_at', [$date_start, $date_end])->get();
- $counter = 0;
- foreach($ShoppingOrderItems as $ShoppingOrderItem){
- $counter += $ShoppingOrderItem->qty;
- dump($ShoppingOrderItem->id);
- }
- // dump($objects);
- dump($counter);
- dd("OKAY");
- }*/
-
- /*
- // alte Funktion auswerung nach ShoppingOrder
- private function initSearch($returnColl = true)
- {
- $this->setFilterVars();
-
- $date_start = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.'.session('payment_sales_vol_filter_month').'.'.session('payment_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d H:i:s');
- $ShoppingOrders = ShoppingOrder::where('paid', 1)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $objects = [];
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- if($shopping_order_item->product){
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- }
- }
- }
- }
-
- if($returnColl){
- $collection = collect();
-
- foreach($objects as $key => $obj){
- $collection->push([
- 'id' => $key,
- 'name' => $obj['name'],
- 'number' => $obj['number'],
- 'value' => $obj['value'],
- ]);
- }
- return $collection;
- }
- return $objects;
- }
- */
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Admin/ProductsSalesController.php b/dev/app-bak/Http/Controllers/Admin/ProductsSalesController.php
deleted file mode 100644
index 3f7c724b..00000000
--- a/dev/app-bak/Http/Controllers/Admin/ProductsSalesController.php
+++ /dev/null
@@ -1,342 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- ];
- return view('admin.payment.salesvolume', $data);
- }
-
-
-
- public function download(){
-
- /*
- EXCEL EXPORT function */
-
- if(Request::get('action') === "exportfull_paid"){
- return $this->exportFullList(1);
- }
- if(Request::get('action') === "exportfull_unpaid"){
- return $this->exportFullList(0);
- }
-
- if(Request::get('action') === "exportfull_paid_invoice"){
- return $this->exportFullListInvoice();
- }
-
-
-
- if(Request::get('action') === "export"){
- $objects = $this->initSearch(false);
- $columns = [];
- $filename = "mivita-absatzmengen-".session('product_sales_vol_filter_month').'_'.session('product_sales_vol_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 Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
- }
- }
-
-
- private function setFilterVars(){
-
- if(!session('product_sales_vol_filter_month')){
- session(['product_sales_vol_filter_month' => intval(date('m'))]);
- }
- if(!session('product_sales_vol_filter_year')){
- session(['product_sales_vol_filter_year' => intval(date('Y'))]);
- }
-
- if(Request::get('product_sales_vol_filter_month')){
- session(['product_sales_vol_filter_month' => Request::get('product_sales_vol_filter_month')]);
- }
- if(Request::get('product_sales_vol_filter_year')){
- session(['product_sales_vol_filter_year' => Request::get('product_sales_vol_filter_year')]);
- }
- }
-
- public function exportFullList($paid = 1){
-
- $date_start = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d H:i:s');
- $ShoppingOrders = ShoppingOrder::where('paid', $paid)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $txActions = ['prev' => 'keine Zahlung', 'appointed' => 'offen', 'failed' => 'abbruch', 'paid' => 'bezahlt'];
- $headers = array('ID', 'Zahlung', 'Datum', 'EMail', 'ProduktID', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Notiz', 'Gesamt');
- $objects = [];
- $columns = [];
- $hasSOID = [];
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- $value = "";
- if($shopping_order_item->product){
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- $value = $shopping_order_item->qty;
-
- }
-
- }
- $object = [];
- if(in_array($ShoppingOrder->id, $hasSOID)){
- $object['ID'] = '';
- $object['EMail'] = '';
- $object['Zahlung'] = '';
- $object['Datum'] = '';
- }else{
- $object['ID'] = $ShoppingOrder->id;
- $object['EMail'] = $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->billing_email : 'n/a';
- $object['Zahlung'] = isset($txActions[$ShoppingOrder->txaction]) ? $txActions[$ShoppingOrder->txaction] : $ShoppingOrder->txaction;
- $object['Datum'] = $ShoppingOrder->created_at->format('d.m.Y');
- }
- $object['ProduktID'] = $shopping_order_item->product_id;
- $object['ProduktNummer'] = $shopping_order_item->product ? $shopping_order_item->product->number : "n/a";
- $object['ProduktName'] = $shopping_order_item->product ? $shopping_order_item->product->name : "n/a";
- $object['Anzahl'] = $shopping_order_item->qty;
- $object['Notiz'] = ($shopping_order_item->comp ? 'Compensation '.$shopping_order_item->comp : '') . ($shopping_order_item->shopping_collect_order_id ? 'Sammelbestellung '.$shopping_order_item->shopping_collect_order_id : '');
- $object['Gesamt'] = $value;
- $columns[] = $object;
-
- $hasSOID[] = $ShoppingOrder->id;
- }
- }
- if($paid){
- $filename = "mivita-absatzmengen-full-paid-".session('product_sales_vol_filter_month').'_'.session('product_sales_vol_filter_year')."-export";
- }else{
- $filename = "mivita-absatzmengen-full-unpaid-".session('product_sales_vol_filter_month').'_'.session('product_sales_vol_filter_year')."-export";
- }
-
- return Excel::download(new xExport($columns, $headers), $filename.'.xls');
-
- /* CSV EXPORT function
- $headers = array(
- "Content-type" => "text/csv",
- "Content-Disposition" => "attachment; filename=$fileName",
- "Pragma" => "no-cache",
- "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
- "Expires" => "0"
- );
-
- $header = array('ID', 'Zahlung', 'Datum', 'EMail', 'ProduktID', 'ProduktNummer', 'ProduktName', 'Anzahl', 'Notiz', 'Gesamt');
-
- $callback = function() use($columns, $header) {
-
- $file = fopen('php://output', 'w');
- fputcsv($file, $header);
- $row = [];
-
- foreach ($columns as $row) {
- fputcsv($file, $row);
-
- }
-
- fclose($file);
- };
-
- return response()->stream($callback, 200, $headers);
-
- */
-
- }
-
- private function initSearch($returnColl = true)
- {
- $this->setFilterVars();
-
- $date_start = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d H:i:s');
- $ShoppingOrders = ShoppingOrder::where('paid', 1)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $objects = [];
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
- if($shopping_order_item->product){
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- }
- }
- }
- }
-
- if($returnColl){
- $collection = collect();
-
- foreach($objects as $key => $obj){
- $collection->push([
- 'id' => $key,
- 'name' => $obj['name'],
- 'number' => $obj['number'],
- 'value' => $obj['value'],
- ]);
- }
- return $collection;
- }
- return $objects;
- }
-
-
- public function datatable(){
-
- $collection = $this->initSearch(true);
-
- $collect = collect([
- ['id' => 1, 'name' => 'John', 'number'=>92012, 'value'=>123],
- ['id' => 2, 'name' => 'Jane', 'number'=>92012, 'value'=>123],
- ['id' => 3, 'name' => 'James', 'number'=>92012, 'value'=>123],
- ]);
-
- return \DataTables::of($collection)->toJson();
-
-
-
- }
-
- /*private function export_vp(){
-
- $query = User::with('account')->select('users.*')->where('users.deleted_at', '=', null)->where('users.admin', "<", 4)->get();
- $fileName = "GS-VP-export-".date("d-m-Y").".csv";
- $headers = array(
- "Content-type" => "text/csv",
- "Content-Disposition" => "attachment; filename=$fileName",
- "Pragma" => "no-cache",
- "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
- "Expires" => "0"
- );
-
- $columns = array('ID', 'Email', 'Firma', 'Anrede', 'Vorname', 'Nachname', 'Mitglied', 'Bis');
-
- $callback = function() use($query, $columns) {
-
- $file = fopen('php://output', 'w');
- fputcsv($file, $columns);
- $row = [];
-
- foreach ($query as $val) {
- $row['ID'] = $val->id;
- $row['Email'] = $val->email;
- $row['Firma'] = $val->account->company;
- $row['Anrede'] = $val->account->salutation == 'mr' ? 'Herr' : 'Frau' ;
- $row['Vorname'] = $val->account->first_name;
- $row['Nachname'] = $val->account->last_name;
- $row['Mitglied'] = $val->payment_account ? ($val->isActiveAccount() ? 'JA' : 'Abgelaufen') : "Nein";
- $row['Bis'] = $val->payment_account ? $val->getPaymentAccountDateFormat(false) : "-";
- fputcsv($file, $row);
-
- }
-
- fclose($file);
- };
-
- return response()->stream($callback, 200, $headers);
-
- //dd("ok");
- }*/
-
- /*private function testCheckFunction(){
-
- //$date_start = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->format('Y-m-d');
- //$date_end = Carbon::parse('01.'.session('product_sales_vol_filter_month').'.'.session('product_sales_vol_filter_year'))->endOfMonth()->format('Y-m-d');
-
- $date_start = Carbon::parse('01.01.2024')->format('Y-m-d H:i:s');
- $date_end = Carbon::parse('01.01.2024')->endOfMonth()->format('Y-m-d H:i:s');
- dump($date_start);
- dump($date_end);
-
- $ShoppingOrders = ShoppingOrder::where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
-
- $objects = [];
- $counter = 0;
- foreach($ShoppingOrders as $ShoppingOrder){
- foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
-
- if($shopping_order_item->product){
- if($shopping_order_item->product->id === 122){
- //dump($shopping_order_item->qty);
- //$counter += $shopping_order_item->qty;
- if(isset($objects[$shopping_order_item->product->id])){
- $value = intval($objects[$shopping_order_item->product->id]['value'] + $shopping_order_item->qty);
- $objects[$shopping_order_item->product->id]['value'] = $value;
- }else{
- $objects[$shopping_order_item->product->id] = [
- 'name' => $shopping_order_item->product->name,
- 'number' => $shopping_order_item->product->number,
- 'value' => $shopping_order_item->qty
- ];
- }
- }
- }
-
- }
- }
-
- $ShoppingOrderItems = ShoppingOrderItem::whereProductId(122)->whereBetween('created_at', [$date_start, $date_end])->get();
- $counter = 0;
- foreach($ShoppingOrderItems as $ShoppingOrderItem){
- $counter += $ShoppingOrderItem->qty;
- dump($ShoppingOrderItem->id);
- }
- // dump($objects);
- dump($counter);
- dd("OKAY");
- }*/
-
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/AdminUserController.php b/dev/app-bak/Http/Controllers/AdminUserController.php
deleted file mode 100755
index 82c14eed..00000000
--- a/dev/app-bak/Http/Controllers/AdminUserController.php
+++ /dev/null
@@ -1,320 +0,0 @@
-middleware('superadmin');
- $this->userRepo = $userRepo;
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function index()
- {
- $data = [
- //'values' => User::where('admin', 0)->get(),
- 'values' => User::where('confirmation_code_remider', '!=', 2)->get(),
- ];
- return view('admin.user.index', $data);
- }
-
- public function edit($user_id)
- {
- $user = User::findOrFail($user_id);
- if (!$user->account) {
- $user->account = new UserAccount();
- }
-
- $data = [
- 'user' => $user,
- ];
- return view('admin.user.edit', $data);
- }
-
- /**
- * @param Request $request
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function store(Request $request)
- {
- $data = Request::all();
- $user = User::findOrFail($data['id']);
-
- /* if(isset($data['user-delete'])){
- if(isset($data['realy_delete_user'])){
- return redirect(route('admin_user_delete', [$user->id]));
- }
- }*/
- if (isset($data['save-admin'])) {
- $user->admin = $data['admin'];
- SysLog::action('save-admin', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user admin value: ' . HTMLHelper::getLabel($user->admin))
- ->save();
- }
-
- if (isset($data['save-confirmed'])) {
- $data['confirmed'] = isset($data['confirmed']) ? true : false;
- $user->confirmed = $data['confirmed'];
- if ($data['confirmed']) {
- if (!isset($data['confirmation_date']) || $data['confirmation_date'] == "") {
- $user->confirmation_date = now();
- } else {
- $user->confirmation_date = \Carbon::parse(str_replace("- ", "", $data['confirmation_date']));
- }
- } else {
- $user->confirmation_date = null;
- }
- SysLog::action('save-confirmed', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user confirmed value: ' . $user->confirmed . " to date: " . $data['confirmation_date'])
- ->save();
- }
-
- if (isset($data['save-active'])) {
- $data['active'] = isset($data['active']) ? true : false;
- $user->active = $data['active'];
- if ($data['active'] === true && $user->wizard < 20) {
- $user->wizard = 20;
- }
- if ($data['active']) {
- if (!isset($data['active_date']) || $data['active_date'] == "") {
- $user->active_date = now();
- } else {
- $user->active_date = \Carbon::parse(str_replace("- ", "", $data['active_date']));
- }
- } else {
- $user->active_date = null;
- }
- SysLog::action('save-active', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user active value: ' . $user->active . " to date: " . $data['active_date'])
- ->save();
- }
-
- if (isset($data['save-account'])) {
- $old = $user->getPaymentAccountDateFormat(true);
- if (!isset($data['payment_account']) || $data['payment_account'] == "") {
- $user->payment_account = null;
- } else {
- $user->wizard = 100;
- $payment_account = \Carbon::parse(str_replace("- ", "", $data['payment_account']));
- $user->payment_account = $payment_account;
- if ($payment_account > Carbon::now()) {
- if ($user->active === 0) {
- $user->active = true;
- UserUtil::reactiveUserResetChilds($user->id, 'on save-account AdminUserController');
- }
- } else {
- if ($user->active === 1) {
- $user->active = false;
- UserUtil::deactiveUserNewSponsorChilds($user->id, 'on save-account AdminUserController');
- }
- }
- }
- //th.schifferegger@gmail.com
- SysLog::action('save-account', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user payment_account from date: ' . $old . " to date: " . $data['payment_account'])
- ->save();
- }
-
- if (isset($data['save-shop'])) {
- $old = $user->getPaymentShopDateFormat(true);
- if (!isset($data['payment_shop']) || $data['payment_shop'] == "") {
- $user->payment_shop = null;
- } else {
- $user->wizard = 100;
- $user->payment_shop = \Carbon::parse(str_replace("- ", "", $data['payment_shop']));
- }
- SysLog::action('save-shop', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user payment_shop from date: ' . $old . " to date: " . $data['payment_shop'])
- ->save();
- }
-
- if (isset($data['save-test_mode'])) {
- $user->test_mode = isset($data['test_mode']) ? true : false;
- SysLog::action('save-test_mode', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user test_mode value: ' . $user->test_mode)
- ->save();
- }
-
- if (isset($data['save-payment_methods'])) {
- $user->payment_methods = isset($data['payment_methods']) ? array_map('intval', $data['payment_methods']) : null;
- SysLog::action('save-payment_methods', 'admin_user', 3)
- ->setUserId(Auth::user()->id)
- ->setModel($user->id, User::class)
- ->setMessage('Set user payment_methods value: ' . $user->getPaymentMethodsShort())
- ->save();
- }
-
- $user->save();
-
- \Session()->flash('alert-save', true);
- return redirect('/admin/users');
- }
-
- public function deleteUser()
- {
- $data = Request::all();
- $user = User::withTrashed()->findOrFail($data['id']);
- if (isset($data['realy_delete_user'])) {
- $this->userRepo->deleteUser($user);
- \Session()->flash('alert-success', __('msg.contact_delete'));
- }
- if (isset($data['realy_delete_user_complete'])) {
- // $this->userRepo->deleteUserComplete($user);
- $this->userRepo->deleteUser($user, true);
- \Session()->flash('alert-success', __('msg.contact_delete'));
- }
- return redirect('/admin/users');
- }
-
-
- public function userLoginAs($userId)
- {
- if (Auth::user()->isSuperAdmin()) {
- $user = User::find($userId);
- Auth::login($user);
- return redirect('/home');
- }
- }
-
- public function getUsers()
- {
- $query = User::withTrashed()
- ->where(function ($q) {
- $q->where('pre_deleted_at', '!=', null)
- ->orWhere(function ($query) {
- $query->whereNull('deleted_at')
- ->whereNull('pre_deleted_at');
- });
- })
- ->with('account')
- ->select('users.*')
- ->where('users.admin', "<", 5);
-
- return \DataTables::eloquent($query)
- ->addColumn('first_name', function (User $user) {
- return $user->account ? $user->account->first_name : '';
- })
- ->addColumn('email', function (User $user) {
- if ($user->pre_deleted_at) {
- return '' . $user->email . '';
- }
- return $user->email;
- })
- ->addColumn('last_name', function (User $user) {
- return $user->account ? $user->account->last_name : '';
- })
- ->addColumn('id', function (User $user) {
- return '';
- })
- ->addColumn('admin', function (User $user) {
- return '' . HTMLHelper::getRoleLabel($user->admin) . '';
- })
- ->addColumn('confirmed', function (User $user) {
- $date = $user->getConfirmationDateFormat();
- $link = '';
- return $user->confirmed ? $link . ' ' . $date . '' : $link . '';
- })
- ->addColumn('active', function (User $user) {
- $date = $user->getActiveDateFormat();
- $link = '';
- return $user->active ? $link . ' ' . $date . '' : $link . '';
- })
- ->addColumn('account', function (User $user) {
- $date = $user->getPaymentAccountDateFormat();
- $link = '';
- if ($user->payment_account) {
- if ($user->isActiveAccount()) {
- return $link . ' ' . $date . '';
- }
- return $link . ' ' . $date . '';
- }
- return $link . '';
- })
- ->addColumn('shop', function (User $user) {
- $date = $user->getPaymentShopDateFormat();
- $link = '';
- if ($user->payment_shop) {
- if ($user->isActiveShop()) {
- return $link . ' ' . $date . '';
- }
- return $link . ' ' . $date . '';
- }
- return $link . '';
- })
- ->addColumn('shop_domain', function (User $user) {
- return $user->shop ? '' . $user->shop->getSubdomain(false) . '' : '';
- })
- ->addColumn('since', function (User $user) {
- if ($user->shop) {
- if ($user->shop->active) {
- return $user->shop->getActiveDateFormatSmall();
- }
- return $user->shop->getActiveDateFormatSmall();
- }
- return "-";
- })
- ->addColumn('country', function (User $user) {
- return ($user->account && $user->account->country) ? $user->account->country->de : '';
- })
- ->addColumn('my_payment_methods', function (User $user) {
- $payment_methods = json_encode($user->payment_methods);
- $link = '';
- if (!$user->payment_methods) {
- return $link . '';
- }
- return $link . ' ' . $user->getPaymentMethodsShort() . '';
- })
- ->addColumn('action_login', function (User $user) {
- return '';
- })
- ->addColumn('action_delete', function (User $user) {
- return '';
- })
- ->addColumn('test_mode', function (User $user) {
- $link = '';
- return $user->test_mode ? $link . '' : $link . '';
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('email', 'email $1')
- ->orderColumn('confirmed', 'confirmed $1')
- ->orderColumn('active', 'active $1')
- ->orderColumn('shop', 'shop $1')
- ->orderColumn('admin', 'active $1')
- ->rawColumns(['id', 'email', 'admin', 'confirmed', 'active', 'account', 'shop', 'shop_domain', 'my_payment_methods', 'test_mode', 'action_login', 'action_delete'])
- ->make(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Api/AuthController.php b/dev/app-bak/Http/Controllers/Api/AuthController.php
deleted file mode 100755
index 611cb488..00000000
--- a/dev/app-bak/Http/Controllers/Api/AuthController.php
+++ /dev/null
@@ -1,112 +0,0 @@
-validate([
- 'email' => 'required|string|email',
- 'password' => 'required|string',
- 'remember_me' => 'boolean'
- ]);
- $credentials = request(['email', 'password']);
-
- if (!Auth::attempt($credentials))
- return response()->json([
- 'message' => 'Unauthorized'
- ], 401);
- $user = $request->user();
-
- $tokenResult = $user->createToken('Personal Access Token');
- $token = $tokenResult->token;
-
- if ($request->remember_me){
- $token->expires_at = Carbon::now()->addWeeks(1);
- }else{
- $token->expires_at = Carbon::now()->addDays(1);
- }
-
- \DB::table('oauth_access_tokens')
- ->whereDate('expires_at', '<', now()->addWeeks(1))
- ->delete();
-
- \DB::table('oauth_refresh_tokens')
- ->whereDate('expires_at', '<', now()->addWeeks(1))
- ->delete();
-
-
- $token->save();
- return response()->json([
- 'access_token' => $tokenResult->accessToken,
- 'token_type' => 'Bearer',
- 'expires_at' => Carbon::parse(
- $tokenResult->token->expires_at
- )->toDateTimeString()
- ]);
- }
-
-
- public function checked(Request $request)
- {
- return response()->json([
- 'message' => 'login'
- ]);
- }
-
- public function logout(Request $request)
- {
- $request->user()->token()->revoke();
- return response()->json([
- 'message' => 'Successfully logged out'
- ]);
- }
-
- /**
- * Get the authenticated User
- *
- * @return [json] user object
- */
- /* public function user(Request $request)
- {
- return response()->json($request->user());
- }
- */
-
- /*public function signup(Request $request)
- {
- $request->validate([
- 'name' => 'required|string',
- 'email' => 'required|string|email|unique:users',
- 'password' => 'required|string|confirmed'
- ]);
- $user = new User([
- 'name' => $request->name,
- 'email' => $request->email,
- 'password' => Hash::make($request->password),
- ]);
- $user->save();
- return response()->json([
- 'message' => 'Successfully created user!'
- ], 201);
- }*/
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Api/GoogleMerchantController.php b/dev/app-bak/Http/Controllers/Api/GoogleMerchantController.php
deleted file mode 100644
index e131e575..00000000
--- a/dev/app-bak/Http/Controllers/Api/GoogleMerchantController.php
+++ /dev/null
@@ -1,61 +0,0 @@
-whereJsonContains('show_on', '1')->orderBy('pos', 'DESC')->get();
-
- // Create feed object
- $feed = LaravelGoogleShoppingFeed::init(
- 'mivita shop',
- 'Bio Aloe Vera & Naturkosmetik',
- 'https://mivita.shop'
- );
-
- // Put products to the feed
- foreach ($products as $product) {
- $feed->addItem([
- 'id' => $product->id,
- 'title' => $product->name,
- 'description' => $product->copy,
- 'link' => $product->getProductUrl(),
- 'g:image_link' => $product->getImageUrl(),
- 'g:availability' => 'in stock',
- 'g:price' => "{$product->price} EUR",
- 'g:brand' => 'MIVITA',
- 'g:gtin' => $product->ean,
- 'g:condition' => 'new',
- 'g:custom_label_0' => $product->weight,
- 'g:custom_label_1' => $product->contents_total,
- 'g:custom_label_2' => $product->getUnitType(),
- 'g:custom_label_3' => $product->contents_str,
- 'g:custom_label_4' => $product->ingredients,
- 'g:unit_pricing_measure' => $product->getBasePriceFormattedFullWith(false, false, null)
- ]);
- }
- return $feed->generate();
- // Get the feed XML
- //$feedXml = $feed->toString();
- //return response($feedXml)->header('Content-Type', 'application/xml');
- }
-
- // http://api.mivita.test/google/merchant/feed
-
-}
diff --git a/dev/app-bak/Http/Controllers/Api/KasController.php b/dev/app-bak/Http/Controllers/Api/KasController.php
deleted file mode 100755
index 1a94b8b6..00000000
--- a/dev/app-bak/Http/Controllers/Api/KasController.php
+++ /dev/null
@@ -1,116 +0,0 @@
- Sekunden ab, bei Y verlängert sich die Session mit jeder Benutzung
- private $CredentialToken = false;
- private $kas_flood_delay = 2;
-
- /**
- * Create a new controller instance.
- *
- * @return void
- */
- public function __construct()
- {
- $this->login();
- }
-
-
- public function action($func, $para = array()){
-
- $this->checkSession($func);
- try
- {
- $Params = array(); // Parameter für die API-Funktion
- $SoapRequest = new SoapClient('https://kasapi.kasserver.com/soap/wsdl/KasApi.wsdl', [
- 'cache_wsdl' => WSDL_CACHE_NONE,
- 'exceptions' => false
- ]);
- $req = $SoapRequest->KasApi(json_encode(array(
- 'KasUser' => $this->kas_user, // KAS-User
- 'KasAuthType' => 'session', // Auth per Sessiontoken
- 'KasAuthData' => $this->CredentialToken, // Auth-Token
- 'KasRequestType' => $func, // API-Funktion
- 'KasRequestParams' => $para // Parameter an die API-Funktion
- )));
- Session::put('flood_protection.'.$func, time() + $this->kas_flood_delay + 0.2);
-
- if(is_array($req) && isset($req['Response']['ReturnString']) && $req['Response']['ReturnString'] == "TRUE"){
- return $req['Response']['ReturnInfo'];
- }
- return $req;
- }
-
- // Fehler abfangen und ausgeben
- catch (\SoapFault $fault)
- {
- trigger_error(" Fehlernummer: {$fault->faultcode},
- Fehlermeldung: {$fault->faultstring},
- Verursacher: {$fault->faultactor},
- Details: {$fault->detail}", E_USER_ERROR);
- }
- }
-
-
- private function login(){
-
- $this->checkSession('auth');
- try
- {
-
- $SoapLogon = new SoapClient('https://kasapi.kasserver.com/soap/wsdl/KasAuth.wsdl', [
- 'cache_wsdl' => WSDL_CACHE_NONE,
- 'exceptions' => false
- ]);
- $this->CredentialToken = $SoapLogon->KasAuth(json_encode(array(
- 'KasUser' => $this->kas_user,
- 'KasAuthType' => 'plain',
- 'KasPassword' => $this->kas_pass,
- 'SessionLifeTime' => $this->session_lifetime,
- 'SessionUpdateLifeTime' => $this->session_update_lifetime
- )));
- Session::put('flood_protection.auth', time() + $this->kas_flood_delay + 0.2);
-
- }
-
- // Fehler abfangen und ausgeben
- catch (\SoapFault $fault)
- {
- trigger_error("Fehlernummer: {$fault->faultcode},
- Fehlermeldung: {$fault->faultstring},
- Verursacher: {$fault->faultactor},
- Details: {$fault->detail}", E_USER_ERROR);
- }
-
- }
-
- private function checkSession($func)
- {
- $name = 'flood_protection.'.$func;
-
- if(Session::exists($name)){
- $time_to_wait = (float)Session::get($name) - time();
- Session::forget($name);
- }else {
- $time_to_wait = 0;
- }
- if ( $time_to_wait >= 0 ) {
- usleep( intval( $time_to_wait*1000000 ) );
- }
-
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Api/PayoneController.php b/dev/app-bak/Http/Controllers/Api/PayoneController.php
deleted file mode 100755
index 4eca92de..00000000
--- a/dev/app-bak/Http/Controllers/Api/PayoneController.php
+++ /dev/null
@@ -1,187 +0,0 @@
- '698fb2555f8b2efc74f60b2121421f45',
- 'txaction' => 'paid',
- 'clearingtype' => 'wlt',
- 'userid' => '158723953',
- 'txid' => '321623031',
- 'price' => '89.00',
- 'param' => '1', //$this->shopping_order->id,
- 'reference' => '15c83aee2766c3',
- ];
-
- */
-
- 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");
- exit;
- }
-
- if($data['key'] != config('payone.defaults.key')) {
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2002 App\Http\Controllers\Api\PayoneController::paymentStatus Key error',
- $data
- );
- print("TSOK");
- exit;
- }
-
- $shopping_order = ShoppingOrder::find($data['param']);
- if(!$shopping_order){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2003 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingOrder not found:',
- $data
- );
- print("TSOK");
- exit;
- }
-
- $shopping_payment = ShoppingPayment::where('reference', $data['reference'])->first();
- if(!$shopping_payment){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2004 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment not found',
- $data
- );
- print("TSOK");
- exit;
- }
-
- if($shopping_payment->shopping_order_id != $shopping_order->id){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2005 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment no realation ShoppingOrder',
- $data
- );
- print("TSOK");
- exit;
- }
-
- $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;
- $data['price-amount'] = $price;
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2006 App\Http\Controllers\Api\PayoneController::paymentStatus Price error',
- $data
- );
- print("TSOK");
- exit;
- }
-
- /* TODO -- need this? */
- if($shopping_payment->txaction == $data['txaction']){
-
- if($data['txaction'] === 'paid' && $shopping_order->txaction === 'paid'){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2007 App\Http\Controllers\Api\PayoneController::paymentStatus same txaction - was already paid',
- $data
- );
- //was already paid
- print("TSOK");
- exit;
- }else{
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:2007 App\Http\Controllers\Api\PayoneController::paymentStatus same txaction - show',
- $data
- );
- }
- }
-
- //create transaction
- PaymentTransaction::create([
- 'shopping_payment_id' => $shopping_payment->id,
- 'request' => 'transaction',
- 'txid' => $data['txid'],
- 'userid' => $data['userid'],
- 'status' => 'PAYONE',
- 'key' => $data['key'],
- 'txaction' => $data['txaction'],
- 'transmitted_data' => Util::utf8ize($data),
- 'mode' => $data['mode'],
- ]);
-
- $shopping_order->txaction = $data['txaction'];
- $shopping_order->save();
- $shopping_payment->txaction = $data['txaction'];
- $shopping_payment->save();
-
- $send_link = false;
- $send_mail = true;
- if($data['txaction'] === 'failed'){
- $shopping_order->setUserHistoryValue(['status' => 6]);
- Util::setInstanceStatusByPayment($shopping_payment, 5);
- }
- if($data['txaction'] === 'appointed'){
- $shopping_order->setUserHistoryValue(['status' => 7]);
- ShoppingUserService::snycOrdersByShoppingOrder($shopping_order);
- Util::setInstanceStatusByPayment($shopping_payment, 4);
- }
-
- if($data['txaction'] === 'paid'){
- if(!$shopping_order->paid){
- $send_link = Payment::paymentStatusPaidAction($shopping_order, true, $shopping_payment);
- }else{
- $send_mail = false;
- }
- }
- $data['send_link'] = $send_link;
- if($send_mail){
- Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
- }
- print("TSOK");
- exit;
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Api/ShoppingUserController.php b/dev/app-bak/Http/Controllers/Api/ShoppingUserController.php
deleted file mode 100755
index f40d7d3c..00000000
--- a/dev/app-bak/Http/Controllers/Api/ShoppingUserController.php
+++ /dev/null
@@ -1,718 +0,0 @@
-validate([
- 'wp_order_numbers' => 'required',
- ]);
-
- if(!is_array($request->wp_order_numbers)){
- $wp_order_numbers = json_decode($request->wp_order_numbers);
-
- }else{
- $wp_order_numbers = $request->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()
- ], 400);
- }
-
- $status = [];
- 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,
- 'user' => $shopping_user ? true : false,
- 'order' => ($shopping_user && $shopping_user->shopping_order) ? true : false,
- 'status' => $shopping_user ? $shopping_user->getAPIShippedType() : false,
- ];
- }
-
- return response()->json([
- 'success' => true,
- 'data' => $status,
- 'time' => Carbon::now()->toDateTimeString()
- ], 200);
-
- }
-
- /**
- * @param Request $request
- * wp_order_number [1234]
- * @return \Illuminate\Http\JsonResponse
- */
- public function cancel(Request $request)
- {
- $request->validate([
- 'wp_order_number' => 'required|int',
- ]);
- $shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
- if (!$shopping_user) {
- return response()->json([
- 'success' => false,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
- 'order' => false,
- 'status' => false,
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
- if(!$shopping_user->shopping_order){
- return response()->json([
- 'success' => false,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' has no order',
- 'order' => false,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
- 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',
- 'order' => true,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
-
- $shopping_user->shopping_order->shipped = 10;
- $shopping_user->shopping_order->save();
-
- return response()->json([
- 'success' => true,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' is cancel',
- 'order' => true,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 200);
-
- }
-
-
- /**
- * @param Request $request
- * wp_order_number [1234]
- * @return \Illuminate\Http\JsonResponse
- */
- public function open(Request $request)
- {
- $request->validate([
- 'wp_order_number' => 'required|int',
- ]);
- $shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
- if (!$shopping_user) {
- return response()->json([
- 'success' => false,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
- 'order' => false,
- 'status' => false,
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
- if(!$shopping_user->shopping_order){
- return response()->json([
- 'success' => false,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' has no order',
- 'order' => false,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
- 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',
- 'order' => true,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
-
- $shopping_user->shopping_order->shipped = 0;
- $shopping_user->shopping_order->save();
-
- return response()->json([
- 'success' => true,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' is open',
- 'order' => true,
- 'status' => $shopping_user->getAPIShippedType(),
- 'time' => Carbon::now()->toDateTimeString()
- ], 200);
-
- }
-
-
- /**
- * @param Request $request
- * wp_order_numbers [1234, 1234]
- * @return \Illuminate\Http\JsonResponse
- */
- public function show(Request $request)
- {
- //$this->member_id = auth()->user()->m_sponsor;
- $request->validate([
- 'wp_order_numbers' => 'required',
- ]);
-
- if(!is_array($request->wp_order_numbers)){
- $wp_order_numbers = json_decode($request->wp_order_numbers);
-
- }else{
- $wp_order_numbers = $request->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()
- ], 400);
- }
- $data = [];
-
- 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) {
- $user = $this->prepareForShow($shopping_user);
- $order = $this->prepareForShowOrder($shopping_user->shopping_order);
- }
- $data[] = [
- 'wp_order_number' => $wp_order_number,
- 'user' => $user,
- '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()
- ], 200);
-
- }
-
- /**
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse
- */
- public function store(Request $request)
- {
- $request->validate([
- 'billing_email' => 'required|string|email',
- 'billing_firstname' => 'required|string',
- 'billing_lastname' => 'required|string',
- 'billing_address' => 'required|string',
- 'billing_zipcode' => 'required|string',
- 'billing_city' => 'required|string',
- 'billing_country_code' => 'required|string',
- 'wp_order_number' => 'required|int|unique:shopping_users,wp_order_number',
- 'wp_order_date' => 'required|date',
- ]);
-
- $this->member_id = auth()->user()->m_sponsor;
-
- $data = $this->prepareForStore($request->all());
- $data['member_id'] = $this->member_id ;
- $data['number'] = ShoppingUser::max('number') + 1;
- $data['mode'] = $request->mode ? $request->mode : 'live';
- $data['is_from'] = 'extern';
- $data['is_for'] = 'ot-member';
-
- $shopping_user = ShoppingUser::create($data);
-
- //Kundenhoheit prüfen
- $priority = CustomerPriority::checkOne($shopping_user, true, false, true);
- \App\Services\Shop::newUserOrder($shopping_user->number);
- //exists //like //update
- $user = $this->prepareForShow($shopping_user);
- return response()->json([
- 'success' => true,
- 'data' => [
- 'wp_order_number' => $shopping_user->wp_order_number,
- 'user' => $user,
- 'customer_priority' => $priority,
- 'customer_number' => $shopping_user->number,
- 'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
- ],
- 'time' => Carbon::now()->toDateTimeString()
- ], 200);
-
- }
-
- /**
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse
- */
- public function update(Request $request)
- {
- $request->validate([
- 'wp_order_number' => 'required|int',
- ]);
- $shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
- if (!$shopping_user) {
- return response()->json([
- 'success' => false,
- '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
- $priority = CustomerPriority::checkChangeOne($shopping_user, $data, true);
- $updated = $shopping_user->fill($data)->save();
- \App\Services\Shop::newUserOrder($shopping_user->number);
-
- if ($updated){
- $user = $this->prepareForShow($shopping_user);
- $order = $this->prepareForShowOrder($shopping_user->shopping_order);
- return response()->json([
- 'success' => true,
- 'data' => [
- 'wp_order_number' => $shopping_user->wp_order_number,
- 'user' => $user,
- '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()
- ], 200);
- }
- return response()->json([
- 'success' => false,
- 'message' => 'Entry could not be updated'
- ], 500);
- }
-
- public function order(Request $request)
- {
- $request->validate([
- 'wp_order_number' => 'required|int',
- 'wp_order' => 'required',
- ]);
-
-
- $shopping_user = ShoppingUser::where('wp_order_number', '=', $request->wp_order_number)->first();
- if (!$shopping_user) {
- return response()->json([
- 'success' => false,
- 'message' => 'Entry with wp_order_number ' . $request->wp_order_number . ' not found',
- 'time' => Carbon::now()->toDateTimeString()
- ], 400);
- }
-
- 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()
- ], 400);
- }
- if(!is_array($request->wp_order)){
- $wp_order = json_decode($request->wp_order);
-
- }else{
- $wp_order = $request->wp_order;
- }
-
- $wp_invoice_path = isset($request->wp_invoice_path) ? $request->wp_invoice_path : null;
- $wp_advertising = isset($request->wp_advertising) ? $request->wp_advertising : '';
- $wp_incentives = isset($request->wp_incentives) ? $request->wp_incentives : '';
-
- $api_notice = [
- 'wp_advertising' => $wp_advertising,
- 'wp_incentives' => $wp_incentives,
- ];
-
- $wp_order = $this->prepareOrder($wp_order, $shopping_user, $wp_invoice_path, $api_notice);
-
- if ($wp_order){
- $user = $this->prepareForShow($shopping_user);
- $order = $this->prepareForShowOrder($shopping_user->shopping_order);
- return response()->json([
- 'success' => true,
- 'data' => [
- 'wp_order_number' => $shopping_user->wp_order_number,
- 'wp_invoice_path' => $wp_invoice_path,
- 'wp_advertising' => $wp_advertising,
- 'wp_incentives' => $wp_incentives,
- 'wp_order' => $wp_order,
- 'user' => $user,
- 'order' => $order,
- 'customer_number' => $shopping_user->number,
- 'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
- 'status' => $shopping_user->getAPIShippedType(),
- ],
- 'time' => Carbon::now()->toDateTimeString()
- ], 200);
- }
- return response()->json([
- 'success' => false,
- '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);
- }
-
- 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',
-
- //$salutation = array('mr' => 1, 'ms' => 2);
- $ret = [];
- foreach ($shopping_user_data as $key=>$value){
-
- 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'){
- $ret['shipping_country_code'] = $shopping_user->shipping_country_id ? $shopping_user->shipping_country->code : null;
- }
- if($key === 'billing_salutation'){
- $ret['billing_salutation'] = $shopping_user->billing_salutation === 'ms' ? 2 : 1;
- }
- if($key === 'shipping_salutation'){
- $ret['shipping_salutation'] = $shopping_user->shipping_salutation === 'ms' ? 2 : 1;
- }
-
- if(in_array($key, $needs)){
- $ret[$key] = $value;
- }
- }
- return $ret;
- }
-
- private function prepareForShowOrder($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),
- 'weight' => $shopping_order->weight,
- ];
- $ret['items'] = [];
- 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),
- ];
- }
- return $ret;
- }
-
- private function prepareForUpdate($data){
-
- //$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';
- }
-
- $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',
- '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']);
- }
- if($key === 'shipping_country_code' && isset($data['shipping_country_code']) ) {
- $ret['shipping_country_id'] = Country::getCountryIdByCodeOrOne($data['shipping_country_code']);
- }
- if($key === 'billing_phone') {
- $ret['billing_phone'] = strlen($data['billing_phone']) <= 3 ? '' : $data['billing_phone'];
- }
- if($key === 'shipping_phone') {
- $ret['shipping_phone'] = strlen($data['shipping_phone']) <= 3 ? '' : $data['shipping_phone'];
- }
- if(in_array($key, $needs)){
- $ret[$key] = $value;
- }
- }
- return $ret;
- }
-
- private function prepareForStore($data){
-
- //$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';
- }
- $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',
- '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',
- 'wp_order_number', 'wp_order_date'];
-
- foreach ($needs as $need){
-
- $ret[$need] = isset($data[$need]) ? $data[$need] : null;
- if ($need === 'billing_country_id') {
- $ret['billing_country_id'] = isset($data['billing_country_code']) ? Country::getCountryIdByCodeOrOne($data['billing_country_code']) : 1;
- }
- if ($need === 'shipping_country_id') {
- $ret['shipping_country_id'] = isset($data['shipping_country_code']) ? Country::getCountryIdByCodeOrOne($data['shipping_country_code']) : $ret['billing_country_id'];
- }
- if ($need === 'billing_phone' && $ret[$need] !== null) {
- $ret['billing_phone'] = strlen($data['billing_phone']) <= 3 ? '' : $data['billing_phone'];
- }
- if ($need === 'shipping_phone' && $ret[$need] !== null) {
- $ret['shipping_phone'] = strlen($data['shipping_phone']) <= 3 ? '' : $data['shipping_phone'];
- }
- if ($need === 'wp_order_date') {
- $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['has_buyed'] = true;
- $ret['subscribed'] = false;
- return $ret;
- }
-
- private function prepareOrder($wp_shopping_order, $shopping_user, $wp_invoice_path, $api_notice){
- Yard::instance('shopping')->destroy();
- $ret = [];
-
- if(is_array($wp_shopping_order)){
- foreach ($wp_shopping_order as $order) {
- //$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";
- } else {
-
- $product = Product::whereWpNumber($order->article)->first();
- if (!$product) {
- $error[] = "article not found";
- } else {
- if ($order->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]);
- Yard::setTax($cartItem->rowId, $product->getTaxWith());
- }
- }
- $order->message = $error;
- $ret[] = $order;
- }
-
- $ShippingCountry = ShippingCountry::whereCountryId($shopping_user->shipping_country_id)->first();
- if($ShippingCountry){
- Yard::instance('shopping')->setShippingCountryWithPrice($ShippingCountry->id);
- }
- $shopping_order = $this->makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice);
- $this->orderStatusSendMail($shopping_order);
-
- $shopping_user->shopping_order = $shopping_order;
- Yard::instance('shopping')->destroy();
- }
- return $ret;
- }
-
- 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,
- 'country_id' => Yard::instance('shopping')->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'user_shop_id' => auth()->user()->user_sponsor->shop->id,
- 'payment_for' => 7,
- 'member_id' => $shopping_user->member_id,
- 'total' => Yard::instance('shopping')->total(2, '.', ''),
- 'subtotal' => Yard::instance('shopping')->subtotal(2, '.', ''),
- 'shipping' => Yard::instance('shopping')->shipping(2, '.', ','),
- 'shipping_net' => Yard::instance('shopping')->shippingNet(2, '.', ''),
- 'subtotal_ws' => Yard::instance('shopping')->subtotalWithShipping(2, '.', ''),
- 'tax' => Yard::instance('shopping')->taxWithShipping(2, '.', ''),
- 'total_shipping' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
- 'points' => Yard::instance('shopping')->points(),
- 'weight' => Yard::instance('shopping')->weight(),
- 'paid' => true,
- 'txaction' => 'extern',
- 'wp_invoice_path' => $wp_invoice_path,
- 'api_notice' => $api_notice,
- 'api_status' => 0,
- 'mode' => $shopping_user->mode,
- ];
- $shopping_order = $shopping_user->shopping_order;
- if($shopping_order){
- $shopping_order->fill($data);
- $shopping_order->save();
- }else{
- $shopping_order= ShoppingOrder::create($data);
- }
- $items = Yard::instance('shopping')->content();
-
-
- $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,
- 'product_id' => $item->id,
- 'qty' => $item->qty,
- 'price' => $item->price,
- 'price_net' => $price_net,
- 'tax_rate' => $item->taxRate,
- 'tax' => $tax,
- '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,
- ])->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()){
- $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,
- 'product_id' => $item->id,
- 'qty' => $item->qty,
- 'price' => $item->price,
- 'price_net' => $price_net,
- 'tax_rate' => $item->taxRate,
- 'tax' => $tax,
- '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
- ]);
- }
-
- }
- $shopping_order->makeTaxSplit();
- return $shopping_order;
- }
-
-
- public function orderStatusSendMail(ShoppingOrder $shopping_order){
-
- $bcc = [];
- $user_mail = $shopping_order->shopping_user->member->email;
- if($shopping_order->mode === 'dev'){
- $bcc[] = config('app.checkout_test_mail');
- }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));
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/AttributeController.php b/dev/app-bak/Http/Controllers/AttributeController.php
deleted file mode 100755
index 64797b47..00000000
--- a/dev/app-bak/Http/Controllers/AttributeController.php
+++ /dev/null
@@ -1,86 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $data = [
- 'values' => Attribute::all(),
- 'trans' => array_keys(config('localization.supportedLocales')),
- ];
- return view('admin.attribute.index', $data);
- }
-
- public function store()
- {
-
- $data = Request::all();
- if($data['id'] == "new"){
- $model = Attribute::create([
- 'parent_id' => null,
- 'name' => $data['name'],
- 'pos' => $data['pos'],
- 'active' => isset($data['active']) ? true : false,
- ]);
- }else{
- $model = Attribute::find($data['id']);
- $model->parent_id = null;
- $model->name = $data['name'];
- $model->pos = $data['pos'];
- $model->active = isset($data['active']) ? true : false;
- $model->save();
- }
-
- if(!empty($data['trans'])){
- $trans = [];
- foreach ($data['trans'] as $lang => $value){
- if($value && $value != null){
- $trans[$lang] = $value;
- }
- }
- if(count($trans)){
- $model->trans_name = $trans;
- $model->save();
- }
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_product_attributes'));
-
-
- }
-
-
- public function delete($id){
-
- if(ProductAttribute::where('attribute_id', $id)->count()){
- \Session()->flash('alert-error', 'Eintrag wird als Produktattribute verwendet');
- return redirect(route('admin_product_attributes'));
- }
- /* if(Attribute::where('parent_id', $id)->count()){
- \Session()->flash('alert-error', 'Eintrag wird als Main Attribute verwendet');
- return redirect(route('admin_industry_sectors'));
- }
- */
- $model = Attribute::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_attributes'));
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Auth/ForgotPasswordController.php b/dev/app-bak/Http/Controllers/Auth/ForgotPasswordController.php
deleted file mode 100755
index 6a247fef..00000000
--- a/dev/app-bak/Http/Controllers/Auth/ForgotPasswordController.php
+++ /dev/null
@@ -1,32 +0,0 @@
-middleware('guest');
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Auth/LoginController.php b/dev/app-bak/Http/Controllers/Auth/LoginController.php
deleted file mode 100755
index c71b8e71..00000000
--- a/dev/app-bak/Http/Controllers/Auth/LoginController.php
+++ /dev/null
@@ -1,105 +0,0 @@
-middleware('guest')->except('logout');
- }
-
- public function showLoginForm()
- {
- //login als Kunde, dann zum Login wechseln
- if(Auth::guard('customers')->check()){
- return redirect()->route('change_login');
- }
-
- return view('auth.login');
- }
-
- public function showChangeLogin(){
- if(Auth::guard('customers')->check()){
- return view('auth.change');
- }
- if(Auth::guard('user')->check()){
- return redirect(route('home'));
-
- }
- return redirect(route('login'));
-
- }
-
- public function confirmChangeLogin(Request $request)
- {
- //$url = Util::getMyMivitaShopUrl();
- $user_shop_domain = session('user_shop_domain');
- $locale = session('locale');
- Auth::guard('customers')->logout();
- $request->session()->invalidate();
- $request->session()->regenerateToken();
- session(['user_shop_domain' => $user_shop_domain]);
- session(['locale' => $locale]);
- return redirect()->route('login');
- }
-
- protected function authenticated(Request $request, $user)
- {
- $user->last_login = date('Y-m-d H:i:s');
- $user->save();
- }
-
- protected function handleUserWasAuthenticated(Request $request, $throttles)
- {
-
-
- }
-
-
- //*
- //
- /* protected function validateLogin(Request $request)
- {
- $this->validate($request, [
- $this->username() => 'required|exists:users,' . $this->username() . ',active,1',
- 'password' => 'required',
- ], [
- $this->username() . '.exists' => trans('validation.usernotactive'),
- ]);
-
- }
- */
-}
diff --git a/dev/app-bak/Http/Controllers/Auth/RegisterController.php b/dev/app-bak/Http/Controllers/Auth/RegisterController.php
deleted file mode 100755
index bb28d068..00000000
--- a/dev/app-bak/Http/Controllers/Auth/RegisterController.php
+++ /dev/null
@@ -1,80 +0,0 @@
-middleware('guest');
- }
-
- public function showRegistrationForm()
- {
- //register off! - to login
- return redirect('login');
-
- }
-
- /**
- * Get a validator for an incoming registration request.
- *
- * @param array $data
- * @return \Illuminate\Contracts\Validation\Validator
- */
- protected function validator(array $data)
- {
- return Validator::make($data, [
- 'name' => 'required|string|max:255',
- 'email' => 'required|string|email|max:255|unique:users',
- 'password' => 'required|string|min:6|confirmed',
- ]);
- }
-
- /**
- * Create a new user instance after a valid registration.
- *
- * @param array $data
- * @return \App\User
- */
- protected function create(array $data)
- {
- return User::create([
- 'name' => $data['name'],
- 'email' => $data['email'],
- 'password' => Hash::make($data['password']),
- ]);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Auth/ResetPasswordController.php b/dev/app-bak/Http/Controllers/Auth/ResetPasswordController.php
deleted file mode 100755
index cf726eec..00000000
--- a/dev/app-bak/Http/Controllers/Auth/ResetPasswordController.php
+++ /dev/null
@@ -1,39 +0,0 @@
-middleware('guest');
- }
-}
diff --git a/dev/app-bak/Http/Controllers/BusinessCommissionController.php b/dev/app-bak/Http/Controllers/BusinessCommissionController.php
deleted file mode 100644
index f0fa1d2d..00000000
--- a/dev/app-bak/Http/Controllers/BusinessCommissionController.php
+++ /dev/null
@@ -1,169 +0,0 @@
- 'nur Provisionen', 2 => 'alle'];
-
-
- public function __construct()
- {
- $this->middleware('admin');
- }
-
- public function index()
- {
-
- $filter_members = UserBusiness::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();
-
-
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- 'filter_members' => $filter_members,
- 'filter_show' => $this->filter_show,
-
- ];
- return view('admin.business.commissions', $data);
- }
-
- public function store(){
- $data = Request::all();
-
- dd($data);
-
- return redirect(route('admin_business_commissions'));
- }
-
-
- private function setFilterVars(){
-
- if(!session('commissions_filter_month')){
- session(['commissions_filter_month' => intval(date('m'))]);
- }
- if(!session('commissions_filter_year')){
- session(['commissions_filter_year' => intval(date('Y'))]);
- }
- if(!session('commissions_filter_show')){
- session(['commissions_filter_show' => 1]);
- }
-
- session(['commissions_filter_member_id' => Request::get('commissions_filter_member_id')]);
-
- if(Request::get('commissions_filter_month')){
- session(['commissions_filter_month' => Request::get('commissions_filter_month')]);
- }
- if(Request::get('commissions_filter_year')){
- session(['commissions_filter_year' => Request::get('commissions_filter_year')]);
- }
- if(Request::get('commissions_filter_show')){
- session(['commissions_filter_show' => Request::get('commissions_filter_show')]);
- }
- }
-
- private function initSearch()
- {
- $this->setFilterVars();
-
- $query = UserBusiness::select('user_businesses.*')
- ->where('user_businesses.month', '=', Request::get('commissions_filter_month'))
- ->where('user_businesses.year', '=', Request::get('commissions_filter_year'));
-
- if(intval(Request::get('commissions_filter_show')) === 1){
- $query->where(function($q) {
- return $q->where('user_businesses.commission_pp_total', '>', 0)
- ->orWhere('user_businesses.commission_shop_sales', '>', 0);
- });
- }
-
- if(Request::get('commissions_filter_member_id')){
- $query->where('user_businesses.user_id', '=', Request::get('commissions_filter_member_id'));
- }
-
- return $query;
- }
-
- public function datatable(){
-
- $query = $this->initSearch();
- return \DataTables::eloquent($query)
- /* ->addColumn('id', function (UserSalesVolume $UserSalesVolume) {
- return '';
- })*/
-
-
- ->addColumn('commission_total', function (UserBusiness $UserBusiness) {
- $commission_total = $UserBusiness->commission_pp_total + $UserBusiness->commission_shop_sales;
- return $commission_total > 0 ?
- ''.formatNumber($commission_total).' €'
- : $commission_total.' €';
- })
- ->addColumn('commission_pp_total', function (UserBusiness $UserBusiness) {
- return $UserBusiness->commission_pp_total > 0 ?
- ''.formatNumber($UserBusiness->commission_pp_total).' €'
- : $UserBusiness->commission_pp_total.' €';
- })
- ->addColumn('commission_shop_sales', function (UserBusiness $UserBusiness) {
- return $UserBusiness->commission_shop_sales > 0 ?
- ''.formatNumber($UserBusiness->commission_shop_sales).' €'
- : $UserBusiness->commission_shop_sales.' €';
- })
- ->addColumn('active_account', function (UserBusiness $userBusiness) {
- return get_active_badge($userBusiness->active_account);
- })
- ->addColumn('payment_account_date', function (UserBusiness $userBusiness) {
- return $userBusiness->active_date ? formatDate($userBusiness->active_date) : "-";
- })
-
- /* ->filterColumn('m_account', function($query, $keyword) {
- if($keyword != ""){
- $query->whereRaw("m_account LIKE ?", '%'.$keyword.'%');
- }
- })
- ->filterColumn('first_name', function($query, $keyword) {
- if($keyword != ""){
- $query->whereRaw("first_name LIKE ?", '%'.$keyword.'%');
- }
- })
- ->filterColumn('last_name', function($query, $keyword) {
- if($keyword != ""){
- $query->whereRaw("last_name LIKE ?", '%'.$keyword.'%');
- }
- })
- ->filterColumn('email', function($query, $keyword) {
- if($keyword != ""){
- $query->whereRaw("email LIKE ?", '%'.$keyword.'%');
- }
- })*/
-
- ->orderColumn('id', 'id $1')
- ->orderColumn('commission_pp_total', 'commission_pp_total $1')
- ->orderColumn('commission_shop_sales', 'commission_shop_sales $1')
- ->orderColumn('email', 'users.email $1')
- ->orderColumn('m_account', 'm_account $1')
- ->orderColumn('first_name', 'first_name $1')
- ->orderColumn('last_name', 'last_name $1')
- ->rawColumns(['id', 'commission_total', 'commission_pp_total', 'commission_shop_sales', 'active_account'])
- ->make(true);
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/BusinessController.php b/dev/app-bak/Http/Controllers/BusinessController.php
deleted file mode 100644
index aaf66507..00000000
--- a/dev/app-bak/Http/Controllers/BusinessController.php
+++ /dev/null
@@ -1,397 +0,0 @@
- 'aktiv', 2 => 'nicht aktiv', 3 => 'alle'];
- private $month;
- private $year;
-
- public function __construct()
- {
- $this->middleware('admin');
- }
-
- public function show()
- {
- abort(403, 'This page is removed');
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- 'filter_active' => $this->filter_active,
- ];
- return view('admin.business.show', $data);
- }
-
- public function structure()
- {
- //abort(403, 'This page is removed');
- $this->setFilterVars();
- $this->month = session('business_user_filter_month');
- $this->year = session('business_user_filter_year');
-
- $TreeCalcBot = new TreeCalcBot($this->month, $this->year, 'admin');
- $TreeCalcBot->initStructureAdmin();
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- 'TreeCalcBot' => $TreeCalcBot,
- ];
- return view('admin.business.structure', $data);
- }
-
- public function userDetail($user_id)
- {
- abort(403, 'This page is removed');
- $user = User::findOrFail($user_id);
- $this->setFilterVars();
-
- $data = [];
- $data['month'] = session('business_user_filter_month');
- $data['year'] = session('business_user_filter_year');
- $TreeCalcBot = new TreeCalcBot($data['month'], $data['year'], 'admin');
- $TreeCalcBot->initBusinesslUserDetail($user);
- if (!$TreeCalcBot->business_user) {
- abort(403, 'no user found');
- }
- return view('admin.business.user_detail', compact('TreeCalcBot', 'user', 'data'));
- }
-
- public function userStore($user_id)
- {
- dd('function on: App\Console\Commands\BusinessStore');
- /*$data = Request::all();
- $user = User::findOrFail($data['user_id']);
- $TreeCalcBot = new TreeCalcBot($data['month'], $data['year'], 'admin');
- $TreeCalcBot->initBusinesslUserDetail($user);
- if(!$TreeCalcBot->business_user){
- abort(403, 'no user found');
- }
- //$TreeCalcBot->storeBusinesslUser();*/
-
- //return back();
- }
-
- private function setFilterVars()
- {
-
- if (!session('business_user_filter_month')) {
- session(['business_user_filter_month' => intval(date('m'))]);
- }
- if (!session('business_user_filter_year')) {
- session(['business_user_filter_year' => intval(date('Y'))]);
- }
- if (!session('business_user_filter_active')) {
- session(['business_user_filter_active' => 1]);
- }
- if (!session('business_user_filter_depiction')) {
- session(['business_user_filter_depiction' => 'active']);
- }
-
- if (Request::get('business_user_filter_depiction')) {
- session(['business_user_filter_depiction' => Request::get('business_user_filter_depiction')]);
- }
- if (Request::get('business_user_filter_name')) {
- session(['business_user_filter_name' => Request::get('business_user_filter_name')]);
- } else {
- session(['business_user_filter_name' => '']);
- }
- if (Request::get('business_user_filter_active')) {
- session(['business_user_filter_active' => Request::get('business_user_filter_active')]);
- }
- if (Request::get('business_user_filter_month')) {
- session(['business_user_filter_month' => Request::get('business_user_filter_month')]);
- }
- if (Request::get('business_user_filter_year')) {
- session(['business_user_filter_year' => Request::get('business_user_filter_year')]);
- }
- }
-
-
- public function userDatatable()
- {
- $this->month = Request::get('business_user_filter_month');
- $this->year = Request::get('business_user_filter_year');
-
- //only the currently month get from Users -> older month from UserBusiness
- return $this->userCurrentlyDatatable();
- if (TreeCalcBot::isFromStored($this->month, $this->year)) {
- return $this->userStoredDatatable();
- } else {
- return $this->userCurrentlyDatatable();
- }
- }
-
- private function initStoredSearch($archive = false, $request = true)
- {
- $this->setFilterVars();
-
- $query = UserBusiness::select('user_businesses.*')->where('month', $this->month)->where('year', $this->year);
- if (Request::get('business_user_filter_active')) {
- if (Request::get('business_user_filter_active') == 1) {
- $query->where('user_businesses.active_account', 1);
- }
- if (Request::get('business_user_filter_active') == 2) {
- $query->where('user_businesses.active_account', 0);
- }
- if (Request::get('business_user_filter_active') == 3) {
- //both -> payment_account only not null
- }
- }
- return $query;
- }
-
- private function userStoredDatatable()
- {
- $query = $this->initStoredSearch();
- return \DataTables::eloquent($query)
- ->addColumn('id', function (UserBusiness $userBusiness) {
- return '' .
- (config('app.debug') === true ? '' : '');
- })
- ->addColumn('m_account', function (UserBusiness $userBusiness) {
- return $userBusiness->m_account;
- })
- ->addColumn('user_level', function (UserBusiness $userBusiness) {
- return $userBusiness->user_level_name;
- })
- ->addColumn('is_qual_kp', function (UserBusiness $userBusiness) {
- if ($userBusiness->m_level_id) {
- $isQualKP = ($userBusiness->sales_volume_points_sum >= $userBusiness->qual_kp) ? true : false;
- return ' KU ' . $userBusiness->qual_kp . '';
- }
- return '-';
- })
- ->addColumn('sales_volume_KP_points', function (UserBusiness $userBusiness) {
- return '
"; print_r($out);
-
- exit;
-
- /*return response()->view('cron.result', [
- 'result' => $result,
- 'output' => $out
- ]);*/
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/CustomerController.php b/dev/app-bak/Http/Controllers/CustomerController.php
deleted file mode 100755
index 9b1d3a38..00000000
--- a/dev/app-bak/Http/Controllers/CustomerController.php
+++ /dev/null
@@ -1,210 +0,0 @@
-middleware('admin');
- $this->customerRepository = $customerRepository;
-
- }
-
- public function index()
- {
- if(Request::get('reset') === 'filter'){
- set_user_attr('filter_member_id', null);
- set_user_attr('filter_customer_member', null);
- return redirect(route('admin_customers'));
- }
- $filter_members = ShoppingUser::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();
- $data = [
- 'filter_members' => $filter_members,
- ];
- return view('admin.customer.index', $data);
- }
-
-
- public function detail($id)
- {
- $shopping_user = ShoppingUser::findOrFail($id);
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => true,
- 'isView' => 'customer',
- ];
- return view('admin.customer.detail', $data);
- }
-
- public function edit($id)
- {
- if($id === "new"){
- $shopping_user = new ShoppingUser();
- $shopping_user->id = "new";
- }else{
- $shopping_user = ShoppingUser::findOrFail($id);
- }
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => true,
- 'isView' => 'customer',
-
- ];
- return view('admin.customer.edit', $data);
- }
-
- public function store($id)
- {
- $data = Request::all();
-
- if ($data['action'] === 'shopping-user-change-member') {
- if (!isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
- $data = [
- 'change_member_error' => "Das Passwort ist falsch.",
- 'shopping_user' => ShoppingUser::find($id),
- 'isAdmin' => true,
- 'isView' => 'customer',
- ];
- return view('admin.customer.detail', $data);
- }
- //change
- $shopping_user = ShoppingUser::findOrFail($data['id']);
- CustomerPriority::newMemberForCustomer($shopping_user, $data['change_member_id'], $data['customer_set_member_for']);
- \Session()->flash('alert-save', true);
- return redirect(route('admin_customer_detail', [$shopping_user->id]));
- }
- if($data['action'] === 'shopping-user-store') {
- $rules = array(
- 'billing_salutation' => 'required',
- 'billing_firstname'=>'required',
- 'billing_lastname'=>'required',
- 'billing_email'=>'required|email',
- 'billing_address'=>'required',
- 'billing_zipcode'=>'required',
- 'billing_city' => 'required',
- 'billing_country_id' => 'required'
- );
-
- if(!Request::get('same_as_billing')){
- $rules = array_merge($rules, [
- 'shipping_firstname'=>'required',
- 'shipping_lastname'=>'required',
- 'shipping_address'=>'required',
- 'shipping_zipcode'=>'required',
- 'shipping_city' => 'required',
- 'shipping_salutation' => 'required',
- 'shipping_country_id' => 'required'
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- $shopping_user = ShoppingUser::findOrFail($id);
-
- $data['language'] = isset($data['language']) ? $data['language'] : \App::getLocale();
- $data['has_buyed'] = isset($data['has_buyed']) ? true : false;
- $data['subscribed'] = isset($data['subscribed']) ? true : false;
- //subscribed can only true when has_buyed ist active
- $data['subscribed'] = $data['has_buyed'] ? $data['subscribed'] : false;
-
- /* if($shopping_user->auth_user_id > 0){
- $data['has_buyed'] = true;
- $data['subscribed'] = false;
- }*/
- $data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
- $data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];
- CustomerPriority::checkChangeOne($shopping_user, $data, true);
- $shopping_user->fill($data);
- $shopping_user->save();
- \App\Services\Shop::newUserOrder($shopping_user->number);
-
- \Session()->flash('alert-save', true);
- }
- return redirect(route('admin_customer_detail', [$shopping_user->id]));
-
- }
-
- public function getCustomers()
- {
- $query = ShoppingUser::select('shopping_users.*')->where('auth_user_id', '=', NULL);
-
- set_user_attr('filter_member_id', Request::get('filter_member_id'));
- if(Request::get('filter_member_id') != ""){
- $query->where('member_id', '=', Request::get('filter_member_id'));
- }
- /* set_user_attr('filter_customer_member', Request::get('filter_customer_member'));
- if(Request::get('filter_customer_member') != ""){
- if(Request::get('filter_customer_member') === 'customers'){
- $query->where('auth_user_id', '=', NULL);
- }
- if(Request::get('filter_customer_member') === 'members'){
- $query->where('auth_user_id', '!=', NULL);
- }
- }*/
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingUser $ShoppingUser) {
- return '';
- })
- ->addColumn('billing_email', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->faker_mail ? "-" : $ShoppingUser->billing_email;
- })
- ->addColumn('billing_salutation', function (ShoppingUser $ShoppingUser) {
- return HTMLHelper::getSalutationLang($ShoppingUser->billing_salutation);
- })
- ->addColumn('billing_country_id', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->billing_country ? $ShoppingUser->billing_country->getLocated() : '';
- })
- ->addColumn('isMember', function (ShoppingUser $ShoppingUser) {
- return get_active_badge($ShoppingUser->auth_user_id).($ShoppingUser->mode==='dev' ? ' dev' : '');
- })
- ->addColumn('member_id', function (ShoppingUser $ShoppingUser) {
- if($ShoppingUser->is_like){
- return '';
- }
- if($ShoppingUser->member){
- return ''.$ShoppingUser->member->getFullName().'';
- }
-
- return '';
- })
- ->addColumn('created_at', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->created_at->format('d.m.Y');
- })
- ->addColumn('subscribed', function (ShoppingUser $ShoppingUser) {
- return get_active_badge($ShoppingUser->subscribed);
- })
- ->filterColumn('billing_email', function($query, $keyword) {
- if($keyword != ""){
- $query->where('billing_email', 'LIKE', '%'.$keyword.'%');
- }
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('billing_country_id', 'billing_country_id $1')
- ->orderColumn('billing_salutation', 'billing_salutation $1')
- ->orderColumn('billing_email', 'billing_email $1')
- ->orderColumn('created_at', 'created_at $1')
- ->orderColumn('isMember', 'auth_user_id $1')
- ->orderColumn('member_id', 'member_id $1')
- ->orderColumn('subscribed', 'subscribed $1')
- ->rawColumns(['id', 'subscribed', 'isMember', 'member_id'])
- ->make(true);
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/DataTableController.php b/dev/app-bak/Http/Controllers/DataTableController.php
deleted file mode 100644
index f29f38d1..00000000
--- a/dev/app-bak/Http/Controllers/DataTableController.php
+++ /dev/null
@@ -1,16 +0,0 @@
-middleware('auth');
- $this->middleware('admin')->except(['show', 'track']);
- }
-
- /**
- * Test the DHL API login credentials and return a JSON response.
- *
- * @return \Illuminate\Http\JsonResponse
- */
- public function testLogin()
- {
- try {
- // 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'],
- $dhlConfig['api_key'],
- $dhlConfig['username'],
- $dhlConfig['password']
- );
-
- // Test the connection
- $connectionTest = $dhlClient->testConnection();
-
- if ($connectionTest) {
- $result = [
- 'success' => true,
- 'message' => 'DHL API Verbindung erfolgreich getestet!',
- 'details' => [
- 'base_url' => $dhlConfig['base_url'],
- 'using_admin_config' => !empty($dhlConfig['api_key'])
- ]
- ];
- } else {
- $result = [
- 'success' => false,
- 'message' => 'DHL API Verbindung fehlgeschlagen. Prüfen Sie Ihre Zugangsdaten.'
- ];
- }
-
- return response()->json($result);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Test login failed', [
- 'error' => $e->getMessage()
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'DHL API Test fehlgeschlagen: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Display the DHL Cockpit (main overview)
- *
- * @param Request $request
- * @return View
- */
- public function index(Request $request): View
- {
- // Statistics for dashboard widgets
- $stats = [
- 'total_shipments' => DhlShipment::count(),
- 'pending_shipments' => DhlShipment::where('status', 'pending')->count(),
- 'shipped_today' => DhlShipment::whereDate('created_at', today())->count(),
- 'returns_count' => DhlShipment::where('type', 'return')->count(),
- ];
-
- return view('admin.dhl.cockpit', compact('stats'));
- }
-
- /**
- * Provides data for the DHL Cockpit DataTable.
- *
- * @param Request $request
- * @return \Illuminate\Http\JsonResponse
- */
- public function datatable(Request $request): JsonResponse
- {
- $query = DhlShipment::with(['shoppingOrder.shopping_user'])
- ->select('dhl_package_shipments.*') // Explicitly select to avoid conflicts
- ->orderBy('created_at', 'desc');
-
- // Apply filters from the request
- if ($request->filled('type')) {
- $query->where('type', $request->get('type'));
- }
- if ($request->filled('status')) {
- $query->where('status', $request->get('status'));
- }
- if ($request->filled('date_from')) {
- $query->whereDate('created_at', '>=', $request->get('date_from'));
- }
- if ($request->filled('date_to')) {
- $query->whereDate('created_at', '<=', $request->get('date_to'));
- }
- if ($request->filled('search')) {
- $search = $request->get('search');
- $query->where(function ($q) use ($search) {
- $q->where('dhl_shipment_no', 'LIKE', "%{$search}%")
- ->orWhere('id', 'LIKE', "%{$search}%")
- ->orWhereHas('shoppingOrder', function ($orderQuery) use ($search) {
- $orderQuery->where('id', $search);
- });
- });
- }
-
- return DataTables::eloquent($query)
- ->addColumn('checkbox', function ($shipment) {
- return '';
- })
- ->editColumn('id', function ($shipment) {
- return '#' . $shipment->id . '';
- })
- ->addColumn('type', function ($shipment) {
- if ($shipment->type == 'outbound') {
- return ' Ausgehend';
- } else {
- return ' Retoure';
- }
- })
- ->addColumn('order', function ($shipment) {
- if ($shipment->order_id) {
- return '#' . $shipment->order_id . '';
- }
- return 'N/A';
- })
- ->addColumn('customer', function ($shipment) {
- if ($shipment->shoppingOrder && $shipment->shoppingOrder->shopping_user) {
- return e($shipment->shoppingOrder->shopping_user->billing_firstname) . ' ' . e($shipment->shoppingOrder->shopping_user->billing_lastname) .
- '
' . e($shipment->shoppingOrder->shopping_user->billing_email) . '';
- }
- return 'Unbekannt';
- })
- ->editColumn('dhl_shipment_no', function ($shipment) {
- return $shipment->dhl_shipment_no ? '' . e($shipment->dhl_shipment_no) . '' : '-';
- })
- ->addColumn('status', function ($shipment) {
- $statusMap = [
- 'pending' => ['class' => 'warning', 'text' => 'Wartend'],
- 'created' => ['class' => 'success', 'text' => 'Erstellt'],
- 'shipped' => ['class' => 'primary', 'text' => 'Versendet'],
- 'delivered' => ['class' => 'info', 'text' => 'Zugestellt'],
- 'cancelled' => ['class' => 'secondary', 'text' => 'Storniert'],
- 'failed' => ['class' => 'danger', 'text' => 'Fehler'],
- ];
- $statusInfo = $statusMap[$shipment->status] ?? ['class' => 'light', 'text' => e($shipment->status)];
- return '' . $statusInfo['text'] . '';
- })
- ->addColumn('tracking_status', function ($shipment) {
- if ($shipment->tracking_status) {
- return '' . e($shipment->tracking_status) . '' .
- ($shipment->last_tracked_at ? '
' . $shipment->last_tracked_at->format('d.m.Y H:i') . '' : '');
- }
- return '-';
- })
- ->editColumn('weight_kg', function ($shipment) {
- 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 = '';
- $buttons .= '';
- if ($shipment->label_path) {
- $buttons .= '';
- }
- if ($shipment->canCancel()) {
- $buttons .= '';
- }
- if ($shipment->type == 'outbound' && !$shipment->returns()->count()) {
- $buttons .= '';
- }
- $buttons .= '';
- return $buttons;
- })
- ->rawColumns(['checkbox', 'id', 'type', 'order', 'customer', 'dhl_shipment_no', 'status', 'tracking_status', 'actions'])
- ->make(true);
- }
-
- /**
- * Show the form for creating a new shipment
- *
- * @param ShoppingOrder $order
- * @return View
- */
- public function create(ShoppingOrder $order): View|\Illuminate\Http\RedirectResponse
- {
- // Check if order already has a shipment
- $existingShipment = DhlShipment::where('shopping_order_id', $order->id)
- ->where('type', 'outbound')
- ->first();
-
- if ($existingShipment) {
- return redirect()->route('admin.dhl.show', $existingShipment)
- ->with('warning', 'Für diese Bestellung existiert bereits eine Sendung.');
- }
-
- return view('admin.dhl.create', compact('order'));
- }
-
- /**
- * Store a new shipment (async via queue)
- *
- * @param Request $request
- * @return JsonResponse
- */
- public function store(Request $request): JsonResponse
- {
- try {
- // Use DhlModalService for validation
- $dhlModalService = new DhlModalService();
- $validationResult = $dhlModalService->validateShipmentData($request->all());
-
- if (!$validationResult['valid']) {
- return response()->json([
- 'success' => false,
- 'message' => 'Validierungsfehler: ' . implode(', ', $validationResult['errors'])
- ], 422);
- }
-
- // Basic Laravel validation as fallback
- $request->validate([
- 'order_id' => 'required|exists:shopping_orders,id',
- 'weight' => 'required|numeric|min:0.1|max:31.5',
- 'product_code' => 'sometimes|string',
- 'priority' => 'sometimes|string|in:normal,high',
- 'auto_track' => 'sometimes|boolean',
- // Shipping address validation
- 'shipping_firstname' => 'required|string|max:50',
- 'shipping_lastname' => 'required|string|max:50',
- 'shipping_company' => 'nullable|string|max:100',
- 'shipping_address' => 'required|string|max:100',
- 'shipping_houseNumber' => 'required|string|max:50',
- 'shipping_zipcode' => 'required|string|max:10',
- 'shipping_city' => 'required|string|max:50',
- 'shipping_country_id' => 'required|exists:countries,id',
- 'shipping_phone' => 'nullable|string|max:20',
- ]);
-
- $order = ShoppingOrder::findOrFail($request->order_id);
-
- // Check if shipment already exists
- /* $existingShipment = DhlShipment::where('shopping_order_id', $order->id)
- ->where('type', 'outbound')
- ->first();
-
- if ($existingShipment) {
- return response()->json([
- 'success' => false,
- 'message' => 'Für diese Bestellung existiert bereits eine Sendung.'
- ], 422);
- }
- */
-
- // Use service to prepare address data
- $shippingAddress = $dhlModalService->prepareAddressForApi($request->all());
-
- // Prepare options for shipment creation
- $options = [
- 'product_code' => $request->get('product_code', 'V01PAK'),
- 'priority' => $request->get('priority', 'normal'),
- 'auto_track' => $request->get('auto_track', true),
- 'shipping_address' => $shippingAddress,
- 'services' => $request->get('services', []),
- 'dimensions' => $request->only(['length', 'width', 'height'])
- ];
-
- // Use DhlShipmentService (handles queue/sync automatically based on config)
- $dhlShipmentService = new DhlShipmentService();
- $result = $dhlShipmentService->createShipment($order, (float) $request->weight, $options);
-
- Log::info('[DHL Controller] Shipment creation processed', [
- 'order_id' => $order->id,
- 'weight' => $request->weight,
- 'queued' => $result['queued'] ?? false,
- 'success' => $result['success'] ?? false,
- ]);
-
- return response()->json($result);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Failed to dispatch shipment creation', [
- 'error' => $e->getMessage(),
- 'order_id' => $request->order_id ?? 'unknown',
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler beim Erstellen der Sendung: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Display the specified shipment
- *
- * @param DhlShipment $shipment
- * @return View
- */
- public function show(DhlShipment $shipment): View
- {
- $shipment->load(['shoppingOrder.shopping_user', 'relatedShipment']);
-
- return view('admin.dhl.show', compact('shipment'));
- }
-
- /**
- * Cancel the specified shipment
- *
- * @param Request $request
- * @param DhlShipment $shipment
- * @return JsonResponse
- */
- public function cancel(Request $request, DhlShipment $shipment): JsonResponse
- {
- try {
- // Validate cancellation is possible
- if (!$shipment->canCancel()) {
- return response()->json([
- 'success' => false,
- 'message' => 'Diese Sendung kann nicht mehr storniert werden.'
- ], 422);
- }
-
- // Dispatch cancellation job
- $options = [
- 'priority' => $request->get('priority', 'normal')
- ];
-
- CancelShipmentJob::dispatch($shipment, $options);
-
- Log::info('[DHL Controller] Shipment cancellation job dispatched', [
- 'shipment_id' => $shipment->id,
- 'shipment_number' => $shipment->shipment_number,
- ]);
-
- return response()->json([
- 'success' => true,
- 'message' => 'Sendung wird storniert...'
- ]);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Failed to dispatch shipment cancellation', [
- 'error' => $e->getMessage(),
- 'shipment_id' => $shipment->id,
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler beim Stornieren der Sendung: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Create return label for the specified shipment
- *
- * @param Request $request
- * @param DhlShipment $shipment
- * @return JsonResponse
- */
- public function createReturnLabel(Request $request, DhlShipment $shipment): JsonResponse
- {
- try {
- // Validate return label creation is possible
- if ($shipment->type !== 'outbound') {
- return response()->json([
- 'success' => false,
- 'message' => 'Retourenlabels können nur für ausgehende Sendungen erstellt werden.'
- ], 422);
- }
-
- // Check if return label already exists
- $existingReturn = DhlShipment::where('related_shipment_id', $shipment->id)
- ->where('type', 'return')
- ->first();
-
- if ($existingReturn) {
- return response()->json([
- 'success' => false,
- 'message' => 'Für diese Sendung existiert bereits ein Retourenlabel.'
- ], 422);
- }
-
- // Dispatch return label creation job
- $options = [
- 'auto_track' => $request->get('auto_track', false),
- 'priority' => $request->get('priority', 'normal')
- ];
-
- CreateReturnLabelJob::dispatch($shipment, $options);
-
- Log::info('[DHL Controller] Return label creation job dispatched', [
- 'original_shipment_id' => $shipment->id,
- 'shipment_number' => $shipment->shipment_number,
- ]);
-
- return response()->json([
- 'success' => true,
- 'message' => 'Retourenlabel wird erstellt...'
- ]);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Failed to dispatch return label creation', [
- 'error' => $e->getMessage(),
- 'shipment_id' => $shipment->id,
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler beim Erstellen des Retourenlabels: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Update tracking status for the specified shipment
- *
- * @param DhlShipment $shipment
- * @return JsonResponse
- */
- public function updateTracking(DhlShipment $shipment): JsonResponse
- {
- try {
- if (!$shipment->tracking_number) {
- return response()->json([
- 'success' => false,
- 'message' => 'Keine Tracking-Nummer verfügbar.'
- ], 422);
- }
-
- // Dispatch tracking update job
- TrackShipmentJob::dispatch($shipment, ['auto_retrack' => false]);
-
- Log::info('[DHL Controller] Tracking update job dispatched', [
- 'shipment_id' => $shipment->id,
- 'tracking_number' => $shipment->tracking_number,
- ]);
-
- return response()->json([
- 'success' => true,
- 'message' => 'Tracking-Informationen werden aktualisiert...'
- ]);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Failed to dispatch tracking update', [
- 'error' => $e->getMessage(),
- 'shipment_id' => $shipment->id,
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler beim Aktualisieren der Tracking-Informationen: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Download shipping label
- *
- * @param DhlShipment $shipment
- * @return Response
- */
- public function downloadLabel(DhlShipment $shipment): Response
- {
- try {
- if (!$shipment->label_path || !Storage::exists($shipment->label_path)) {
- abort(404, 'Versandlabel nicht gefunden.');
- }
-
- $labelContent = Storage::get($shipment->label_path);
- $filename = sprintf(
- 'dhl-label-%s-%s.pdf',
- $shipment->type,
- $shipment->shipment_number ?: $shipment->id
- );
-
- return response($labelContent, 200)
- ->header('Content-Type', 'application/pdf')
- ->header('Content-Disposition', "attachment; filename=\"{$filename}\"");
- } catch (Exception $e) {
- Log::error('[DHL Controller] Failed to download label', [
- 'error' => $e->getMessage(),
- 'shipment_id' => $shipment->id,
- 'label_path' => $shipment->label_path,
- ]);
-
- abort(500, 'Fehler beim Download des Versandlabels.');
- }
- }
-
- /**
- * Batch operations (multiple shipments)
- *
- * @param Request $request
- * @return JsonResponse
- */
- public function batchAction(Request $request): JsonResponse
- {
- try {
- $request->validate([
- 'action' => 'required|in:cancel,download_labels,update_tracking',
- 'shipment_ids' => 'required|array|min:1',
- 'shipment_ids.*' => 'exists:dhl_package_shipments,id',
- ]);
-
- $shipmentIds = $request->shipment_ids;
- $action = $request->action;
- $processed = 0;
- $errors = [];
-
- foreach ($shipmentIds as $shipmentId) {
- try {
- $shipment = DhlShipment::findOrFail($shipmentId);
-
- switch ($action) {
- case 'cancel':
- if ($shipment->canCancel()) {
- CancelShipmentJob::dispatch($shipment);
- $processed++;
- } else {
- $errors[] = "Sendung {$shipment->shipment_number} kann nicht storniert werden.";
- }
- break;
-
- case 'update_tracking':
- if ($shipment->tracking_number) {
- TrackShipmentJob::dispatch($shipment, ['auto_retrack' => false]);
- $processed++;
- } else {
- $errors[] = "Sendung {$shipment->shipment_number} hat keine Tracking-Nummer.";
- }
- break;
-
- case 'download_labels':
- // This would require ZIP creation - implement if needed
- $errors[] = "Stapel-Download noch nicht implementiert.";
- break;
- }
- } catch (Exception $e) {
- $errors[] = "Fehler bei Sendung {$shipmentId}: " . $e->getMessage();
- }
- }
-
- Log::info('[DHL Controller] Batch action executed', [
- 'action' => $action,
- 'processed' => $processed,
- 'errors_count' => count($errors),
- ]);
-
- return response()->json([
- 'success' => $processed > 0,
- 'message' => sprintf('%d Sendungen verarbeitet.', $processed),
- 'processed' => $processed,
- 'errors' => $errors,
- ]);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Batch action failed', [
- 'error' => $e->getMessage(),
- 'action' => $request->action ?? 'unknown',
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler bei der Stapelverarbeitung: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Public tracking page (for customers)
- *
- * @param Request $request
- * @return View|JsonResponse
- */
- public function track(Request $request): View|JsonResponse
- {
- if ($request->expectsJson()) {
- $request->validate([
- 'tracking_number' => 'required|string|min:10',
- ]);
-
- try {
- $shipment = DhlShipment::where('tracking_number', $request->tracking_number)->first();
-
- if (!$shipment) {
- return response()->json([
- 'success' => false,
- 'message' => 'Sendung nicht gefunden.'
- ], 404);
- }
-
- // Dispatch tracking update
- TrackShipmentJob::dispatch($shipment, ['auto_retrack' => false]);
-
- return response()->json([
- 'success' => true,
- 'data' => [
- 'tracking_number' => $shipment->tracking_number,
- 'status' => $shipment->status,
- 'tracking_status' => $shipment->tracking_status,
- 'last_tracked_at' => $shipment->last_tracked_at?->format('d.m.Y H:i'),
- ]
- ]);
- } catch (Exception $e) {
- Log::error('[DHL Controller] Public tracking failed', [
- 'error' => $e->getMessage(),
- 'tracking_number' => $request->tracking_number ?? 'unknown',
- ]);
-
- return response()->json([
- 'success' => false,
- 'message' => 'Fehler beim Abrufen der Tracking-Informationen.'
- ], 500);
- }
- }
-
- return view('public.tracking');
- }
-}
diff --git a/dev/app-bak/Http/Controllers/FileController.php b/dev/app-bak/Http/Controllers/FileController.php
deleted file mode 100644
index 23b934fa..00000000
--- a/dev/app-bak/Http/Controllers/FileController.php
+++ /dev/null
@@ -1,178 +0,0 @@
-auth_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) {
- return true;
- }
- abort(404);
- }
-
- private function isPermissionAuth()
- {
- if (Auth::check()) {
- return true;
- }
- abort(403, "Nicht autorisiert");
- }
-
- public function show($id = null, $from = null, $do = 'file')
- {
-
- $path = "";
- $filename = "";
- $disk = "public";
-
- /*if($disk === 'user'){
- $file = \App\Models\File::findOrFail($id);
- $this->isPermission($file->user_id);
- $path = Storage::disk($disk)->path($file->dir.$file->filename);
- if (file_exists($path)) {
- return Response::file($path);
- }
- }*/
- if ($from === 'invoice') {
- $shopping_order = \App\Models\ShoppingOrder::findOrFail($id);
- 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();
- }
- }
-
- if ($from === 'delivery') {
- $shopping_order = \App\Models\ShoppingOrder::findOrFail($id);
- 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();
- }
- }
-
- 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();
- }
-
- if ($from === 'credit_detail') {
- $user_credit = \App\Models\UserCredit::findOrFail($id);
- $this->isPermissionUserCredit($user_credit);
-
- return $this->create_credit_detail($user_credit, $do);
-
-
- /*
- $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);
- $filename = $dc_file->filename;
- $disk = 'public';
- $path = $dc_file->getFile();
- }
- if ($from === 'dc_thumb') {
- // $this->isPermissionAuth();
- $dc_file = \App\Models\DcFile::findOrFail($id);
- $filename = $dc_file->filename;
- $disk = 'public';
- $path = $dc_file->getThumb();
- }
-
- if ($from === 'dc_big') {
- // $this->isPermissionAuth();
- $dc_file = \App\Models\DcFile::findOrFail($id);
- $filename = $dc_file->filename;
- $disk = 'public';
- $path = $dc_file->getBig();
- }
-
-
-
- if (!Storage::disk($disk)->exists($path)) {
- return Response::make('Datei nicht gefunden.', 404);
- }
-
- if ($do === 'download') {
- return Storage::disk($disk)->download($path, $filename);
- }
-
- $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);
- }
-
- if ($do === 'file') {
- return Response::make($file, 200)
- ->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);
- }
- if ($do === 'pdf') {
- $path = storage_path() . '/app/public/' . $path;
-
- $headers = array(
- 'Content-Type:' . $mime,
- // 'Content-Length: ' . $file->size
- // 'Content-Disposition: ' . $stream . '; filename=' . $file->original_name
- );
-
- return Response::download($path, $filename, $headers);
- }
- }
- }
-
- private function create_credit_detail(UserCredit $user_credit, $do)
- {
-
- $credit_repo = new CreditRepository($user_credit->user);
- return $credit_repo->create_report($user_credit, $do);
- //\Session()->flash('alert-success', "Gutschrift erstellt");
-
- }
-}
diff --git a/dev/app-bak/Http/Controllers/HomeController.php b/dev/app-bak/Http/Controllers/HomeController.php
deleted file mode 100755
index ad3fe274..00000000
--- a/dev/app-bak/Http/Controllers/HomeController.php
+++ /dev/null
@@ -1,274 +0,0 @@
- Auth::user(),
- 'now' => Carbon::now(),
- ];
- return view('home', $data);
- }
-
-
- public function loadingModal()
- {
-
- $data = Request::get('data');
- $target = Request::get('target');
- $response = "";
- if ($data === "data_protection") {
- $data = [
- 'modal' => true,
- 'user_shop' => true,
- 'isMivitaShop' => false,
- ];
- $response = view('legal.data_protect_de', $data)->render();
- }
- if ($data === "imprint") {
- $data = [
- 'modal' => true,
- 'user_shop' => Util::getUserShop(),
- ];
- $response = view('legal.imprint_de', $data)->render();
- }
- 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") {
- $data = [
- 'modal' => true,
- 'user_shop' => Util::getUserShop(),
- ];
- $response = view('legal.agb_de', $data)->render();
- }
- if (Request::ajax()) {
- return response()->json(['response' => $response, 'target' => $target]);
- }
- abort(404);
- }
-
- /* public function checkLogin($identify, $token)
- {
- if($identify){
- //user find by $identify
- $user = User::where('identify', '=', $identify)->first();
- if(!$user){
- return abort(404);
- }
- //user - check für from $sf_guard_user - old system
- $sf_guard_user = SfGuardUser::where('identify', '=', $identify)->first();
- if(!$sf_guard_user){
- return abort(404);
- }
- if($user->id != $sf_guard_user->user_id){
- return abort(404);
-
- }
- if($sf_guard_user->token != $token){
- return abort(404);
- }
- $time = Carbon::parse($sf_guard_user->token_at);
- $now = Carbon::now();
- $duration = $time->diffInSeconds($now);
-
- if($duration > 3){
- return abort(404);
- }
- $sf_guard_user->token = null;
- $sf_guard_user->token_at = null;
- $sf_guard_user->save();
- if(!Auth::check()){
- $user->last_login = now();
- $user->save();
- Auth::login($user);
- }
- if(Auth::check()){
- return redirect('/templates');
- }
- }
- return abort(404);
- }
- */
- public function zahlungsarten()
- {
- return view('web.templates.zahlungsarten', [
- 'user_shop' => Util::getUserShop(),
- 'isMivitaShop' => Util::isMivitaShop(),
- 'yard_instance' => 'webshop',
- ]);
- }
-
- public function versandkosten()
- {
- return view('web.templates.versandkosten', [
- 'user_shop' => Util::getUserShop(),
- 'isMivitaShop' => Util::isMivitaShop(),
- 'yard_instance' => 'webshop',
- ]);
- }
-
- public function legalDataProtected()
- {
- $data = [
- 'modal' => false,
- 'user_shop' => Util::getUserShop(),
- 'isMivitaShop' => Util::isMivitaShop(),
- 'yard_instance' => 'webshop',
- ];
- return view('legal.data_protected', $data);
- }
-
- public function legalAGB()
- {
- $data = [
- 'modal' => false,
- 'user_shop' => Util::getUserShop(),
- 'yard_instance' => 'webshop',
- 'yard_instance' => 'webshop',
-
- ];
- return view('legal.agb', $data);
- }
-
- public function legalImprint()
- {
-
- $data = [
- 'modal' => false,
- 'user_shop' => Util::getUserShop(),
- 'yard_instance' => 'webshop',
- ];
- return view('legal.imprint', $data);
- }
-
- public function verify($confirmation_code)
- {
- if (! $confirmation_code) {
- return redirect('/status/error');
- }
-
- $user = User::whereConfirmationCode($confirmation_code)->first();
- if (! $user) {
- return redirect('/status/not/found');
- }
- $user_auto_login = false;
- if ($user->confirmed === 0) {
- $user->confirmed = 1;
- $user->confirmation_date = now();
- $user_auto_login = true;
- //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;
- $user->save();
-
- //Login!
- if ($user_auto_login) {
- Auth::login($user);
- }
- $url = Util::getMyMivitaUrl();
- return redirect($url);
- }
-
- public function statusRegister()
- {
- 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
- */
- public function checkMail()
- {
-
- $data = Request::all();
- if ($data['user_id'] === "new") {
- if (User::where('email', $data['email'])->count()) {
- return json_encode(false);
- }
- } else {
- if (User::where('email', $data['email'])->where('id', '!=', $data['user_id'])->count()) {
- return json_encode(false);
- }
- }
- return json_encode(true);
- }
-
- public function blocked()
- {
- return view('status.user_blocked');
- }
-
- 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
- if ($user && ($user->wizard == 13 || $user->wizard == 20)) {
- $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(route('/'));
- }
- }
- }
-}
diff --git a/dev/app-bak/Http/Controllers/ImportProductController.php b/dev/app-bak/Http/Controllers/ImportProductController.php
deleted file mode 100755
index 20948b99..00000000
--- a/dev/app-bak/Http/Controllers/ImportProductController.php
+++ /dev/null
@@ -1,108 +0,0 @@
-middleware('admin');
- $this->productRepo = $productRepo;
-
- }
-
- public function import(){
-
- dd('nicht aktiv, wenn muss geprüft werden, ob die funktion IMAGE existieren');
- $path = app_path().'/../_static/products/';
-
- include($path.'_all_products.php');
-
- $slugs = array();
-
- foreach ($get_products as $c_id => $values){
-
- foreach ($values as $val){
- if(in_array($val['slug'], $slugs)){
- continue;
- }
- $slugs[] = $val['slug'];
-
- include($path.$val['slug'].'.php');
-
- $data = [
- 'id' => 'new',
- 'name' => $val['name'],
- 'title' => '',
- 'copy' => $copy,
- 'price' => $price,
- 'price_ek' => 0,
- 'tax' => 19,
- 'price_old' => null,
- 'contents' => $content,
- 'number' => $item_no,
- 'icons' => $icons,
- 'description' => $description,
- 'usage' => $usage,
- 'ingredients' => $ingredients,
- 'pos' => null,
- 'amount' => 0,
- 'active' => 1,
- 'categories' => array($c_id),
- ];
-
-
- $product = $this->productRepo->update($data);
- //images
- foreach($images as $image){
- $i_path = storage_path().'/'.'app'.'/products/' .$val['slug'].'/'.$image['image'];
- $mine = \File::mimeType($i_path);
- $ext = \File::extension($i_path);
- $size = \File::size($i_path);
- $original_name = $image['image'];
-
- $name = \App\Services\Slim::sanitizeFileName($image['image']);
- $name = uniqid() . '_' . $name;
-
- $img = Image::make($i_path);
- $img->resize(600, 800, function ($c) {
- // $c->aspectRatio();
- $c->upsize();
- });
- //
- \Storage::put('/public/images/product/'.$product->id.'/'.$name, (string) $img->encode());
-
-
- ProductImage::create([
- 'product_id' => $product->id,
- 'filename' => $name,
- 'original_name' => $original_name,
- 'ext' => $ext,
- 'mine' => $mine,
- 'size' => $size
- ]);
- }
- }
-
- }
-
-
- die("okay");
- //array('slug' => 'aloe-vera-gel99', 'name' => 'Aloe Vera Gel 99%', 'first' => 'aloe-vera-gel99-1.jpg', 'hover' => 'aloe-vera-gel99-2.jpg'),
-
- }
-
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/IngredientController.php b/dev/app-bak/Http/Controllers/IngredientController.php
deleted file mode 100755
index bd4ad8f6..00000000
--- a/dev/app-bak/Http/Controllers/IngredientController.php
+++ /dev/null
@@ -1,78 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $data = [
- 'values' => Ingredient::all(),
- ];
- return view('admin.ingredient.index', $data);
- }
-
- public function edit($id)
- {
- if($id === "new"){
- $model = new Ingredient();
- $model->active = true;
- }else{
- $model = Ingredient::findOrFail($id);
- }
- $data = [
- 'model' => $model,
- //'trans' => array_keys(config('localization.supportedLocales')),
-
- ];
- return view('admin.ingredient.edit', $data);
- }
-
- public function store()
- {
-
- $data = Request::all();
- $data['active'] = isset($data['active']) ? true : false;
- if($data['id'] === "new"){
- $model = Ingredient::create($data);
- }else{
- $model = Ingredient::find($data['id']);
- $model->fill($data)->save();
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_product_ingredients'));
-
-
- }
-
- public function delete($id){
-
- if(ProductIngredient::where('ingredient_id', $id)->count()) {
- \Session()->flash('alert-error', 'Eintrag wird als Produkt-Inhaltsstoff verwendet');
- return redirect(route('admin_product_ingredients'));
- }
- $model = Ingredient::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_ingredients'));
- }
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/LeadController.php b/dev/app-bak/Http/Controllers/LeadController.php
deleted file mode 100755
index 5fbb6d40..00000000
--- a/dev/app-bak/Http/Controllers/LeadController.php
+++ /dev/null
@@ -1,520 +0,0 @@
-middleware('admin');
- $this->userRepo = $userRepo;
-
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- 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();
-
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- 'filter_sponsor' => $filter_sponsor,
- ];
-
- return view('admin.lead.index', $data);
- }
-
-
- private function setFilterVars(){
-
- /*if(!session('leads_filter_month')){
- session(['leads_filter_month' => intval(date('m'))]);
- }
- if(!session('leads_filter_year')){
- session(['leads_filter_year' => intval(date('Y'))]);
- }*/
-
- session(['leads_filter_sponsor_id' => Request::get('leads_filter_sponsor_id')]);
-
- /* if(Request::get('leads_filter_month')){
- session(['leads_filter_month' => Request::get('leads_filter_month')]);
- }
- if(Request::get('leads_filter_year')){
- session(['leads_filter_year' => Request::get('leads_filter_year')]);
- }*/
- }
-
-
-
- /**
- * @param $id
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function edit($id)
- {
- 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";
- }else{
- $user = User::withTrashed()->findOrFail($id);
- if(!$user->account){
- $user->account = new UserAccount();
- }
- }
- $data = [
- 'show' => Request::get('show'),
- 'user' => $user,
- 'can_change_mail' => true,
- '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)
- {
- $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.";
- }else{
- $m_data_load = true;
- }
-
- 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";
- }else{
- $user = User::withTrashed()->findOrFail($id);
- if(!$user->account){
- $user->account = new UserAccount();
- }
- }
- $next_account_id = UserAccount::withTrashed()->max('m_account') +1;
- if($user->account->m_account === null){
- $user->account->m_account = $next_account_id;
- }
-
- $data = [
- 'show' => 'check_lead',
- 'user' => $user,
- 'm_data_load' => $m_data_load,
- 'm_data_error' => $m_data_error,
- 'can_change_mail' => true,
- '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)
- {
-
- $data = Request::all();
- $show = Request::get('show');
- 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'])){
- $user = User::findOrFail($data['user_id']);
- return $this->userRepo->reverse_charge_delete($data, $user, route('admin_lead_edit', [$user->id]));
- }
-
-
- /*
- if(isset($data['reverse_charge_validate']) && isset($data['user_id'])){
- $user = User::findOrFail($data['user_id']);
- $user->wizard = 1;
- $user->save();
- $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;
- $user->save();
- $userRepo = new UserRepository($user);
- return $userRepo->reverse_charge_delete($data, $user);
- }*/
-
- if ($data['user_id'] === "new" || $data['user_id'] == 0) {
- $rules = array(
- 'salutation' => 'required',
- 'first_name'=>'required',
- 'last_name'=>'required',
- 'email' => 'required|string|email|max:255|unique:users',
- 'email-confirm' => 'required|same:email',
- );
- }else{
- $rules = array(
- 'salutation' => 'required',
- 'first_name'=>'required',
- 'last_name'=>'required',
- 'address'=>'required',
- 'zipcode'=>'required',
- 'city' => 'required',
- 'email' => 'required|string|email|max:255|exists:users,email',
- 'email-confirm' => 'required|same:email',
- 'bank_owner' => 'required',
- 'bank_iban' => 'required',
- 'bank_bic' => 'required',
- );
- 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'
-
- ]);
- }
- }
-
- 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';
- }
-
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
-
- 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());
- }
-
- 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();
- }
- }
-
- $this->userRepo->update($data);
-
- 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";
- $t_user = User::find($data['m_sponsor']);
- $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)
- ->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->save();
- }
-
- if(isset($data['contact_verify'])){
-
- $user = $this->userRepo->getModel();
-
- $confirmation_code = UserService::createConfirmationCode();
-
- $user->lang = $user->getLandByCountry();
- $user->confirmation_code = $confirmation_code;
- //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);
- }
- //user released when register is complete
- public function released($action, $id){
-
- $user = User::findOrFail($id);
-
- if($action === 'completed'){
- $validator = Validator::make(Request::all(), []);
- if(!$user->m_sponsor){
- $validator->errors()->add('m_sponsor', __('Berater hat keinen Sponsor.'));
- }
- if(!$user->account->m_first_name){
- $validator->errors()->add('m_first_name', __('Berater hat keinen Vornamen.'));
- }
- if(!$user->account->m_last_name){
- $validator->errors()->add('m_last_name', __('Berater hat keinen Nachnamen.'));
- }
- 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
- $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->createContractPDF();
-
- //set wizard tp payments
- $user->wizard = 20;
- $user->active = 1;
- $user->active_date = now();
- $user->confirmation_code = null;
- $user->confirmation_code_to = null;
- $user->confirmation_code_remider = 0;
- $user->save();
-
- //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!");
- }
-
- if($action === 'incomplete'){
-
-
- //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'));
- $user->confirmation_code_remider = 0;
- $user->wizard = 1;
- $user->release_account = null;
- $user->save();
-
- $input = Request::all();
- $data = [
- 'subject' => $input['account_incomplete_subject'],
- 'message' => $input['account_incomplete_message'],
- 'confirmation_code' => $confirmation_code,
- ];
- try {
- Mail::to($user->email)->locale($user->getLocale())->send(new MailCustomMessage($user, $data, \Auth::user(), true));
- }
- catch(\Exception $e){
- dump($e->getMessage());
- dd("error");
- }
- UserHistory::create(['user_id' => $user->id, 'action'=>'released_incomplete', 'status'=>0]);
- \Session()->flash('alert-success', "E-Mail an Berater gesendet.");
-
- }
- return redirect(route('admin_lead_edit', [$user->id]));
- }
-
-
- //send new verfified mail to user
- public function newMailVerified($id){
-
- $user = User::findOrFail($id);
-
- $confirmation_code = UserService::createConfirmationCode();
- $user->confirmation_code = $confirmation_code;
- $user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
- $user->confirmation_code_remider = 0;
- $user->save();
-
- try {
- Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyAccount($confirmation_code, $user));
- }
- catch(\Exception $e){
- dump($e->getMessage());
- dd("error");
- }
- UserHistory::create(['user_id' => $user->id, 'action'=>'new_mail_verified', 'status'=>0]);
-
- \Session()->flash('alert-success', "E-Mail erneut gesendet");
- return redirect(route('admin_lead_edit', [$user->id]));
-
- }
-
-
- public function deleteFile($user_id, $file_id, $relation){
-
- if($relation === 'upload'){
- $user = User::findOrFail($user_id);
- $file = $user->files()->findOrFail($file_id);
- if($file->identifier === 'business_license'){
- $user->account->setNotice('business_license', '');
- }
- //remove file
- \Storage::disk('user')->delete($file->dir.$file->filename);
- $file->delete();
- \Session()->flash('alert-success', __('msg.file_deleted'));
- }
- return back();
- }
-
- private function initSearch()
- {
- $this->setFilterVars();
-
- //$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);
- 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 : '';
- })
- ->addColumn('last_name', function (User $user) {
- return $user->account ? $user->account->last_name : '';
- })
- ->addColumn('user_level', function (User $user) {
- return $user->user_level ? ''.$user->user_level->name.'' : '';
- })
- ->addColumn('user_sponsor', function (User $user) {
- return $user->user_sponsor ?
- ''.$user->user_sponsor->account->first_name." ".$user->user_sponsor->account->last_name.'' : "-";
- })
- ->addColumn('id', function (User $user) {
- return '';
- })
- ->addColumn('confirmed', function (User $user) {
- return $user->confirmed ? '' : '';
- })
- ->addColumn('active', function (User $user) {
- return $user->active ? ' ' : '';
- })
- ->addColumn('agreement', function (User $user) {
- return $user->agreement ? ' ' : '';
- })
-
- ->addColumn('useractive', function (User $user) {
- $date = $user->getActiveDateFormat();
- $link = '';
- return $user->active ? $link.' '.$date.'' : $link.'';
- })
- ->addColumn('payaccount', function (User $user) {
- $date = $user->getPaymentAccountDateFormat();
- $link = '';
- if($user->payment_account){
- if($user->isActiveAccount()){
- return $link.' '.$date.'';
- }
- return $link.' '.$date.'';
- }
- return $link.'';
- })
- ->addColumn('payshop', function (User $user) {
- $date = $user->getPaymentShopDateFormat();
- $link = '';
- if($user->payment_shop){
- if($user->isActiveShop()){
- return $link.' '.$date.'';
- }
- return $link.' '.$date.'';
- }
- return $link.'';
- })
-
-
- ->addColumn('payment_account', function (User $user) {
- return $user->payment_account ? ' ' : '';
- })
- ->addColumn('payment_account_date', function (User $user) {
- return $user->payment_account ? $user->getPaymentAccountDateFormat(false) : "-";
- })
- ->addColumn('payment_shop', function (User $user) {
- return $user->payment_shop ? ' ' : '';
- })
-
- ->addColumn('payment_shop_date', function (User $user) {
- return $user->payment_shop ? $user->getPaymentShopDateFormat(false) : "-";
- })
- ->addColumn('shop_domain', function (User $user) {
- return $user->shop ? ' '.$user->shop->getSubdomain(false).'' : '';
-
- })
- ->addColumn('turnover', function (User $user) {
- return "-";
- })
- ->addColumn('sales_total', function (User $user) {
- return "-";
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('confirmed', 'confirmed $1')
- ->orderColumn('active', 'active $1')
- ->orderColumn('agreement', 'agreement $1')
- ->orderColumn('payment_account', 'payment_account $1')
- ->orderColumn('payment_shop', 'payment_shop $1')
- ->rawColumns(['id', 'user_level', 'user_sponsor', 'confirmed', 'useractive', 'payaccount', 'payshop', 'agreement', 'active', 'payment_account', 'payment_shop', 'shop_domain'])
- ->make(true);
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/LevelReportsController.php b/dev/app-bak/Http/Controllers/LevelReportsController.php
deleted file mode 100644
index a0b3e1a5..00000000
--- a/dev/app-bak/Http/Controllers/LevelReportsController.php
+++ /dev/null
@@ -1,88 +0,0 @@
-levelReportService = $levelReportService;
- }
-
- /**
- * Zeige Level-Aufstieg Reports
- */
- public function index(Request $request)
- {
- // Filter aus Request extrahieren
- $filters = [
- 'month' => $request->get('month'),
- 'year' => $request->get('year'),
- 'user_id' => $request->get('user_id'),
- 'only_not_updated' => $request->boolean('not_updated')
- ];
-
- // Lade Level-Aufstiege
- $promotions = $this->levelReportService->getLevelPromotions($filters);
- $statistics = $this->levelReportService->getStatistics($promotions);
-
- // Verfügbare Jahre für Filter
- $availableYears = range(date('Y'), date('Y') - 5);
- $availableMonths = [
- 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'
- ];
-
- return view('admin.level-reports.index', compact(
- 'promotions',
- 'statistics',
- 'filters',
- 'availableYears',
- 'availableMonths'
- ));
- }
-
- /**
- * CSV Export
- */
- public function export(Request $request)
- {
- // Filter aus Request extrahieren
- $filters = [
- 'month' => $request->get('month'),
- 'year' => $request->get('year'),
- 'user_id' => $request->get('user_id'),
- 'only_not_updated' => $request->boolean('not_updated')
- ];
-
- // Lade Level-Aufstiege
- $promotions = $this->levelReportService->getLevelPromotions($filters);
-
- if ($promotions->isEmpty()) {
- return redirect()->back()->with('error', 'Keine Daten für Export gefunden.');
- }
-
- // Erstelle CSV
- $filename = 'level_promotions_' . date('Y-m-d_H-i-s') . '.csv';
- $filepath = $this->levelReportService->exportToCsv($promotions, $filename);
-
- // Download CSV
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/ModalController.php b/dev/app-bak/Http/Controllers/ModalController.php
deleted file mode 100644
index d6386076..00000000
--- a/dev/app-bak/Http/Controllers/ModalController.php
+++ /dev/null
@@ -1,264 +0,0 @@
-middleware('auth');
- }
-
- public function load(){
- $data = Request::all();
- $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();
- }
- 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();
- }
- if($data['action'] === 'shopping-user-is-like-member'){
- $current = ShoppingUser::find($data['id']); //current user form order
- $possibles = [];
- if($current->is_like){
- $likes = $current->getNotice('like');
- foreach ($likes as $like_id=>$number){
- $possibles[] = ShoppingUser::find($like_id);
- }
- }
- $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();
- }
- 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();
- }
-
- 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();
- }
-
- 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){
- abort(404);
- }
- $isAdmin = false ;
- $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){
- abort(404);
- }
- $isAdmin = false ;
- $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();
- }
-
- if($data['action'] === 'user-order-my-delivery-add'){
- $user = \Auth::user();
- /* $product = Product::find($data['id']); //current user form order
- $ret = view("admin.modal.show_product", compact('product', 'data'))->render(); */
- }
- if($data['action'] === 'homeparty-add-product') {
- $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();
- }
-
- 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();
- }
- if($data['action'] === 'user-level-add'){
- $value = new UserLevel();
- $route = route('admin_level_store', ['new']);
- $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');
- }else{
- $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();
- }
-
- 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();
- }
- $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();
- }
- 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();
- }
- if($data['action'] === 'add-user-credit'){
- $value = [];
- $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();
- }
- if($data['action'] === 'abo_update_settings'){
- $user_abo = UserAbo::find($data['id']);
- if($data['view'] === 'admin'){
- $route = route('admin_abos_update', [$user_abo->id]);
- }else{
- $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'] === 'abo-add-product') {
- $user_abo = UserAbo::find($data['id']);
- $ret = view("user.abo.modal_abo_show_products", compact( 'data', 'user_abo'))->render();
- }
-
- if($data['action'] === 'create-dhl-shipment') {
- $id = $data['id'] ?? null;
- $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){
- 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){
- 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
- * @return string Rendered view
- */
- private function handleDhlShipmentModal($id, array $data): string
- {
- try {
- $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
- ]);
-
- 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()
- ]);
-
- // Return error view or fallback
- $errorData = [
- 'id' => $id,
- 'data' => $data,
- 'order' => null,
- 'orderWeight' => 1.0,
- 'shippingAddress' => null,
- 'availableCountries' => \App\Models\Country::where('active', 1)->get(),
- 'productCodes' => [
- 'V01PAK' => 'DHL Paket (National)',
- 'V53WPAK' => 'DHL Paket International',
- 'V54EPAK' => 'DHL Express'
- ],
- 'errors' => ['Fehler beim Laden der Daten: ' . $e->getMessage()],
- 'warnings' => []
- ];
-
- return view("admin.dhl.modal_create_shipment", $errorData)->render();
- }
- }
-
-}
-
-
-
-/* */
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Pay/PayoneController.php b/dev/app-bak/Http/Controllers/Pay/PayoneController.php
deleted file mode 100644
index 4636059a..00000000
--- a/dev/app-bak/Http/Controllers/Pay/PayoneController.php
+++ /dev/null
@@ -1,607 +0,0 @@
- 'PayPal',
- 'cc' => 'CreditCard',
- 'sb#GPY' => 'giropay',
- 'sb#PNT' => 'Sofort',
- 'wlt#PDT' => 'paydirekt',
- 'fnc' => 'Rechnungskauf',
- 'pref' => 'Vorauskasse',
- ];*/
-
-
-namespace App\Http\Controllers\Pay;
-
-use App\Http\Controllers\Controller;
-use App\Models\PaymentTransaction;
-use App\Models\ShoppingPayment;
-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;
-
- public function __construct() {
-
- $this->default = \Config::get('payone.defaults');
- }
-
- public function init($shopping_user, $shopping_order){
- $this->shopping_user = $shopping_user;
- $this->shopping_order = $shopping_order;
- $this->default['mode'] = $this->shopping_order->mode;
- }
-
- public function getShoppingPayment(){
- return $this->shopping_payment;
- }
- public function setAboPayment($user_abo, $amount, $currency){
- $this->reference = substr(uniqid('m', false), 0, 16);
-
- $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'] : '',
- 'userid' => $user_abo->payone_userid,
- 'onlinebanktransfertype' => '',
- "request" => "authorization",
- ];
-
-
- $this->aboInitPayment = [
- 'recurrence'=>'recurring',
- 'customer_is_present'=>'no',
- 'request' => 'authorization',
- '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,
- ];
-
- $this->shopping_payment = ShoppingPayment::create([
- 'shopping_order_id' => $this->shopping_order->id,
- 'clearingtype' => $this->method["clearingtype"],
- 'wallettype' => $this->method["wallettype"],
- 'onlinebanktransfertype' => $this->method["onlinebanktransfertype"],
- 'carddata' => $user_abo->carddata,
- 'reference' => $this->reference,
- 'amount' => $amount,
- 'currency' => $currency,
- 'is_abo' => $this->shopping_order->is_abo,
- 'abo_interval' => 0,
- 'mode' => $this->shopping_order->mode,
- ]);
- }
- //make Payone payment
- public function setPrePayment($payment_method, $amount, $currency, $ret = []){
-
- $this->reference = substr(uniqid('m', false), 0, 16);
- $this->setMethod($payment_method, $ret);
-
- $this->urls = [
- 'successurl' => route('checkout.transaction_status', ['success', $this->reference]),
- 'errorurl' => route('checkout.transaction_status', ['error', $this->reference]),
- 'backurl' => route('checkout.transaction_status', ['cancel', $this->reference]),
- ];
-
- $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,
- ];
- //init Abo
- if($this->shopping_order->is_abo){
- if($this->method["clearingtype"] === "cc"){
- $this->aboInitPayment = [
- 'recurrence'=>'recurring',
- 'customer_is_present'=>'yes',
- 'request' => 'authorization',
- 'amount' => $amount,
- ];
- $this->method['request'] = 'authorization';
-
- }
-
- if($this->method["clearingtype"] === "wlt"){
- //payment for Abo PayPal
- $this->aboInitPayment = [
- 'recurrence'=>'recurring',
- 'customer_is_present'=>'yes',
- 'request' => 'authorization',
- 'amount' => $amount,
- 'add_paydata[redirection_mode]' => 'DIRECT_TO_MERCHANT',
- ];
- $this->setDeliverylData($this->shopping_user);
- $this->method['request'] = 'authorization';
- }
-
- }
-
- $this->shopping_payment = ShoppingPayment::create([
- 'shopping_order_id' => $this->shopping_order->id,
- 'clearingtype' => $this->method["clearingtype"],
- 'wallettype' => $this->method["wallettype"],
- 'onlinebanktransfertype' => $this->method["onlinebanktransfertype"],
- 'carddata' => isset($ret['cc']) ? $ret['cc'] : null,
- 'reference' => $this->reference,
- 'amount' => $amount,
- 'currency' => $currency,
- 'is_abo' => $this->shopping_order->is_abo,
- 'abo_interval' => $this->shopping_order->abo_interval,
- 'identifier' => Util::getUserShopIdentifier(),
- 'mode' => $this->shopping_order->mode,
- ]);
-
- $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,
- // "language" => ($this->shopping_user->billing_country) ? strtoupper($this->shopping_user->billing_country->code) : "DE", // mandatory
- "language" => "DE",
- ];
-
- /**
- * Paydirekt requires both, personal data and shipping data
- */
- /* $this->deliveryData = array(
- "shipping_firstname" => "Paul",
- "shipping_lastname" => "Neverpayer",
- "shipping_street" => "Hamburger Allee 26-28",
- "shipping_zip" => "60486",
- "shipping_city" => "Frankfurt am Main",
- "shipping_country" => "DE"
- );*/
-
- }
-
- private function setMethod($payment_method, $ret = []){
-
- if($payment_method){
- if(strpos($payment_method, '#')){
- $payment_method = explode('#', $payment_method);
- //wallet Paypal
- if($payment_method[0] === 'wlt'){
- $this->method = [
- "clearingtype" => "wlt",
- "wallettype" => $payment_method[1],
- 'onlinebanktransfertype' => "",
- "request" => "authorization"
- ];
-
-
- }
- //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",
- ];
- }
-
- //Rechnungskauf
- if($payment_method[0] === 'fnc'){
- //MIVITA
- if(isset($payment_method[1]) && $payment_method[1] === 'MIV'){
- $this->method = [
- "clearingtype" => "fnc",
- "wallettype" => "",
- 'onlinebanktransfertype' => "MIV",
- "request" => "authorization",
- ];
- }
- //PAYONE
- /* $this->method = [
- "clearingtype" => "fnc",
- "wallettype" => "",
- 'onlinebanktransfertype' => "",
- "financingtype" => "PYV",
- "request" => "genericpayment",
- "add_paydata[action]" => "pre_check",
- "add_paydata[payment_type]" => "Payolution-Invoicing",
- ];*/
- }
-
- }
- //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'],
- // "bankcountry" => "DE",
- ];
- }
-
- //vorkasse
- if($payment_method === 'vor'){
- $this->method = [
- "clearingtype" => "vor",
- "wallettype" => "",
- 'onlinebanktransfertype' => "",
- "request" => "authorization",
- ];
- }
-
- //CreditCard
- if($payment_method === 'cc'){
- //need the $cc_ret
- $this->method = [
- "clearingtype" => "cc",
- "wallettype" => "",
- 'onlinebanktransfertype' => "",
- "request" => "authorization",
- "pseudocardpan" => $ret['cc']['pseudocardpan'],
- //"xid" => "3-D Secure transaction ID"
- ];
- }
- }
- }
-
- public function onlyPaymentResponse(){
- $request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
- $response = Payone::sendRequest($request);
- return $response;
- }
-
- public function ResponseData($is_abo = false){
-
- $request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
- //dd($request);
- //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'],
- 'txid' => 0,
- 'userid' => 0,
- 'status' => 'FNCMIV',
- 'transmitted_data' => $request,
- 'txaction' => 'invoice_open',
- 'mode' => $this->shopping_payment->mode,
- ]);
- Util::setUserHistoryValue(['status'=>5]);
- if($is_abo){
- return $this->reference;
- }
- return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
- exit;
- }
-
- $response = Payone::sendRequest($request);
- /*
- * status APPROVED / REDIRECT / ERROR / PENDING
- */
- if($response['status'] === 'ERROR'){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'PayPal Preauthorization Fehler: ' . $response['errormessage'],
- $response
- );
- PaymentTransaction::create([
- 'shopping_payment_id' => $this->shopping_payment->id,
- 'request' => $this->method['request'],
- 'errorcode' => $response['errorcode'],
- 'errormessage' => $response['errormessage'],
- 'customermessage' => $response['customermessage'],
- 'status' => $response['status'],
- 'mode' => $this->shopping_payment->mode,
- ]);
- Util::setUserHistoryValue(['status'=>3]);
- if($is_abo){
- return $response;
- }
- \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,
- 'request' => $this->method['request'],
- 'txid' => $response['txid'],
- 'userid' => $response['userid'],
- 'status' => $response['status'],
- 'mode' => $this->shopping_payment->mode,
-
- ]);
- Util::setUserHistoryValue(['status'=>4]);
- if($is_abo){
- return $response;
- }
- return redirect()->away($response["redirecturl"]);
- exit;
-
- }
-
- if($response['status'] === 'APPROVED'){
- // header("Location: " . $response["redirecturl"]); // or other redirect method
- $payt = PaymentTransaction::create([
- 'shopping_payment_id' => $this->shopping_payment->id,
- 'request' => $this->method['request'],
- 'txid' => $response['txid'],
- 'userid' => $response['userid'],
- 'status' => $response['status'],
- 'transmitted_data' => $response,
- 'mode' => $this->shopping_payment->mode,
-
- ]);
- Util::setUserHistoryValue(['status'=>5]);
- if($is_abo){
- return $response;
- }
-
- 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
- return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
- exit;
- }
-
- 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)
- }
-
-
- if($response['status'] === 'PENDING'){
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:1000 Status PENDING App\Http\Controllers\Pay\PayoneController::ResponseData response status PENDING',
- $response
- );
- die();
- //txid
- //Payment process ID (PAYONE)
- //userid
- //Debtor ID (PAYONE)
- }
- MyLog::writeLog(
- 'payone',
- 'error',
- 'Error:1001 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Http\Controllers\Pay\PayoneController::ResponseData error no response status',
- $response
- );
- 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 = array_merge($this->default, $this->prepayment);
- return Payone::sendRequest($request);
- }
-
- public function checkBankAccount($data, $amount, $currency, $shopping_user)
- {
- $this->shopping_user = $shopping_user;
- $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'],
-
- // "language" => 'de',
- ];
-
- $request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->urls);
- return Payone::sendRequest($request);
- }
-
- public function setDeliverylData($shopping_user){
- if($shopping_user->same_as_billing == true){
- $this->deliveryData = [
- 'shipping_firstname' => $shopping_user->billing_firstname,
- 'shipping_lastname' => $shopping_user->billing_lastname,
- 'shipping_zip' => $shopping_user->billing_zipcode,
- 'shipping_city' => $shopping_user->billing_city,
- 'shipping_country' => $shopping_user->billing_country->code,
- 'shipping_street' => $shopping_user->billing_address,
- ];
- }else{
- $this->deliveryData = [
- 'shipping_firstname' => $shopping_user->shipping_firstname,
- 'shipping_lastname' => $shopping_user->shipping_lastname,
- 'shipping_zip' => $shopping_user->shipping_zipcode,
- 'shipping_city' => $shopping_user->shipping_city,
- 'shipping_country' => $shopping_user->shipping_country->code,
- 'shipping_street' => $shopping_user->shipping_address,
- ];
- }
- }
-
- /* public function getPDFFile($mandateId)
- {
-
- $params['file_reference'] = $mandateId;//"XX-T0000000";
- $params['file_type'] = 'SEPA_MANDATE';
- $params['file_format'] = 'PDF';
- $request = array_merge($this->default, $params);
-
- return Payone::sendRequest($request);
- }
- */
-
-
-
-
- /* public function checkStatus(){
- // again, the default values will be needed
- $capture = array(
- "request" => "capture",
- "txid" => "your_txid",
- "sequencenumber" => "previous_sequencenumber_plus_one", // get this from the last received transactionsstatus
- "amount" => "your_amount", // you can either capture the full amount of the tx, or less
- "currency" => "EUR"
- );
- $request = array_merge($this->default, $capture);
- $response = Payone::sendRequest($request);
-
- } */
-
-
- //set for clearingtype
- //debit payment
- /*
- *
- *
- * $params['bankaccountholder'] = $paymentData['mopt_payone__debit_bankaccountholder'];
- $params['iban'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_iban']);
- $params['bic'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bic']);
-
- * $params['bankcountry'] = $paymentData['mopt_payone__debit_bankcountry'];
- $params['bankaccount'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bankaccount']);
- $params['bankcode'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bankcode']);
-
-
- if (Shopware()->Session()->moptMandateData) {
- $params['mandate_identification'] = Shopware()->Session()->moptMandateData['mopt_payone__mandateIdentification'];
- }
- *
- * ["clearing_bankaccount"]=> string(10) "2599100003"
- ["clearing_bankcode"]=> string(8) "12345678"
- ["clearing_bankcountry"]=> string(2) "DE"
- ["clearing_bankname"]=> string(8) "Testbank"
- ["clearing_bankaccountholder"]=> string(11) "Test Nutzer"
- ["clearing_bankcity"]=> string(4) "Kiel"
- ["clearing_bankiban"]=> string(22) "DE00123456782599100003"
- ["clearing_bankbic"]=> string(8) "TESTTEST" }
- */
- /*
- * PNT Sofortbanking (DE, AT, CH, NL)
- GPY giropay (DE)
- EPS eps – online transfer (AT)
- PFF PostFinance E-Finance (CH)
- PFC PostFinance Card (CH)
- IDL iDEAL (NL)
- P24 Przelewy24 (PL)
- BCT Bancontact*/
- /*
- * iban
- * bic
- * bankcountry*/
-
- /* * Card type
- V Visa
- M MasterCard
- A American Express
- D Diners / Discover
- J JCB
- O Maestro International
-
-
-
-
-
-
-
-*/
-
-
-
-}
-
-
-
-
diff --git a/dev/app-bak/Http/Controllers/PaymentCreditController.php b/dev/app-bak/Http/Controllers/PaymentCreditController.php
deleted file mode 100644
index 8294188d..00000000
--- a/dev/app-bak/Http/Controllers/PaymentCreditController.php
+++ /dev/null
@@ -1,262 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- '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'])) {
- \Session()->flash('alert-error', 'Vertriebspartner nicht gefunden');
- return back();
- }
- if (!isset($data['credit'])) {
- \Session()->flash('alert-error', 'Bitte Betrag eingeben');
- return back();
- }
- 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");
- }
-
- return redirect(route('admin_payments_credit'));
- }
-
- public function create()
- {
- $data = Request::all();
- if (isset($data['action'])) {
- if ($data['action'] === 'create_credit') {
- 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");
- 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");
- return back();
- }
- }
- }
-
- private function setFilterVars()
- {
- if (!session('credit_filter_month')) {
- session(['credit_filter_month' => intval(date('m'))]);
- }
- if (!session('credit_filter_year')) {
- session(['credit_filter_year' => intval(date('Y'))]);
- }
- if (Request::get('credit_filter_name')) {
- session(['credit_filter_name' => Request::get('credit_filter_name')]);
- } else {
- session(['credit_filter_name' => '']);
- }
- if (Request::get('credit_filter_month')) {
- session(['credit_filter_month' => Request::get('credit_filter_month')]);
- }
- if (Request::get('credit_filter_year')) {
- session(['credit_filter_year' => Request::get('credit_filter_year')]);
- }
- }
-
- private function makeUserCreditItems()
- {
- $ret = [];
- $UserCreditItems = UserCreditItem::wherePaid(false)->get();
- foreach ($UserCreditItems as $userCreditItem) {
- if (isset($ret[$userCreditItem->user_id])) {
- $ret[$userCreditItem->user_id]['sum'] += $userCreditItem->credit;
- $ret[$userCreditItem->user_id]['entries'][$userCreditItem->id] = $userCreditItem;
- } else {
- 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] = [
- 'user_id' => $userCreditItem->user_id,
- 'm_account' => $user ? $user->account->m_account : "gelöscht",
- 'first_name' => $user ? $user->account->first_name : "gelöscht",
- 'last_name' => $user ? $user->account->last_name : "gelöscht",
- 'email' => $user ? $user->email : "gelöscht",
- 'sum' => $userCreditItem->credit,
- 'entries' => [$userCreditItem->id => $userCreditItem],
- ];
- */
- } else {
- $ret[$userCreditItem->user_id] = [
- 'user_id' => $userCreditItem->user_id,
- 'm_account' => $userCreditItem->user->account->m_account,
- 'first_name' => $userCreditItem->user->account->first_name,
- 'last_name' => $userCreditItem->user->account->last_name,
- 'email' => $userCreditItem->user->email,
- 'sum' => $userCreditItem->credit,
- 'entries' => [$userCreditItem->id => $userCreditItem],
- ];
- }
- }
- }
- return $ret;
- }
-
- public function delete($id, $del)
- {
-
- if ($del === 'user_credit_item') {
- $UserCreditItem = UserCreditItem::findOrFail($id);
- if ($deleteTime = $UserCreditItem->deleteTime()) {
- $UserCreditItem->delete();
- \Session()->flash('alert-success', "Guthaben ist gelöscht");
- } else {
- \Session()->flash('alert-error', "Guthaben kann nicht gelöscht werden");
- }
- }
- return redirect(route('admin_payments_credit'));
- }
-
- private function initSearch($archive = false, $request = true)
- {
-
- $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');
- $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;
- }
-
- public function datatable()
- {
-
- $query = $this->initSearch();
-
- return \DataTables::eloquent($query)
-
- ->addColumn('user.account.first_name', function (UserCredit $UserCredit) {
- 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";
- })
- ->addColumn('user.email', function (UserCredit $UserCredit) {
- return isset($UserCredit->user) ? $UserCredit->user->email : "gelöscht";
- })
- ->addColumn('view', function (UserCredit $UserCredit) {
- $ret = "";
- if ($UserCredit->isCredit()) {
- $ret .= ' ';
- $ret .= '
';
-
- $ret .= ' ';
- $ret .= ' ';
- } else {
- $ret = "-";
- }
- return $ret;
- })
-
- ->addColumn('total', function (UserCredit $UserCredit) {
- 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') . "
";
- }
- }
- return $ret;
- })
- ->addColumn('status', function (UserCredit $UserCredit) {
- return '
- ' . $UserCredit->getStatusType() . '
- ';
- })
- ->filterColumn('user.account.first_name', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('user.account', function ($query) use ($keyword) {
- return $query->where('first_name', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->filterColumn('user.account.last_name', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('user.account', function ($query) use ($keyword) {
- return $query->where('last_name', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->filterColumn('user.email', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('user', function ($query) use ($keyword) {
- return $query->where('email', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('status', 'status $1')
- ->orderColumn('total', 'total $1')
- ->rawColumns(['total', 'credits', 'status', 'view'])
- ->make(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/PaymentInvoiceController.php b/dev/app-bak/Http/Controllers/PaymentInvoiceController.php
deleted file mode 100644
index f4fffe89..00000000
--- a/dev/app-bak/Http/Controllers/PaymentInvoiceController.php
+++ /dev/null
@@ -1,117 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- ];
- return view('admin.payment.invoice', $data);
- }
-
- private function setFilterVars()
- {
-
- if (!session('invoice_filter_month')) {
- session(['invoice_filter_month' => intval(date('m'))]);
- }
- if (!session('invoice_filter_year')) {
- session(['invoice_filter_year' => intval(date('Y'))]);
- }
- if (Request::get('invoice_filter_name')) {
- session(['invoice_filter_name' => Request::get('invoice_filter_name')]);
- } else {
- session(['invoice_filter_name' => '']);
- }
- if (Request::get('invoice_filter_month')) {
- session(['invoice_filter_month' => Request::get('invoice_filter_month')]);
- }
- if (Request::get('invoice_filter_year')) {
- session(['invoice_filter_year' => Request::get('invoice_filter_year')]);
- }
- }
-
- private function initSearch($archive = false, $request = true)
- {
- $this->setFilterVars();
-
- $query = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
- ->where('user_invoices.month', '=', Request::get('invoice_filter_month'))
- ->where('user_invoices.year', '=', Request::get('invoice_filter_year'));
-
- if (Request::get('invoice_filter_name')) {
- $query->whereHas('shopping_order.shopping_user', function ($query) {
- return $query->where('billing_firstname', 'LIKE', '%' . Request::get('invoice_filter_name') . '%')->orWhere('billing_lastname', 'LIKE', '%' . Request::get('invoice_filter_name') . '%')->orWhere('billing_email', 'LIKE', '%' . Request::get('invoice_filter_name') . '%');
- })->get();
- }
- return $query;
- }
-
- public function datatable()
- {
-
- $query = $this->initSearch();
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (UserInvoice $UserInvoice) {
- if ($UserInvoice->shopping_order->auth_user_id) {
- return '';
- }
- return '';
- })
- ->addColumn('total_shipping', function (UserInvoice $UserInvoice) {
- return '' . $UserInvoice->shopping_order->getFormattedTotalShipping() . " €";
- })
- ->addColumn('created_at', function (UserInvoice $UserInvoice) {
- return $UserInvoice->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (UserInvoice $UserInvoice) {
- if ($UserInvoice->shopping_order) {
- return Payment::getShoppingOrderBadge($UserInvoice->shopping_order);
- }
- return "-";
- })
- ->addColumn('status', function (UserInvoice $UserInvoice) {
- return '
- ' . $UserInvoice->getStatusType() . '
- ';
- })
- ->addColumn('invoice', function (UserInvoice $UserInvoice) {
- $ret = "";
- $ret .= ' ';
- $ret .= '';
- return $ret;
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('invoice_number', 'invoice_number $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('shipped', 'shipped $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
- ->orderColumn('created_at', 'created_at $1')
- ->orderColumn('status', 'status $1')
-
- ->rawColumns(['id', 'shipping_order', 'txaction', 'total_shipping', 'status', 'txaction', 'invoice'])
- ->make(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/PaymentMethodController.php b/dev/app-bak/Http/Controllers/PaymentMethodController.php
deleted file mode 100755
index b0c0d9a5..00000000
--- a/dev/app-bak/Http/Controllers/PaymentMethodController.php
+++ /dev/null
@@ -1,89 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $data = [
- 'values' => PaymentMethod::all(),
- 'trans' => array_keys(config('localization.supportedLocales')),
- ];
- return view('admin.payment_method.index', $data);
- }
-
- public function store()
- {
-
- $data = Request::all();
- if($data['id'] === "new"){
- $model = PaymentMethod::create([
- 'name' => $data['name'],
- 'short' => $data['short'],
- 'pos' => $data['pos'],
- 'show_on' => isset($data['show_on']) ? $data['show_on'] : null,
- 'is_abo' => isset($data['is_abo']) ? $data['is_abo'] : false,
- 'default' => isset($data['default']) ? true : false,
- 'active' => isset($data['active']) ? true : false,
- ]);
- }else{
- $model = PaymentMethod::find($data['id']);
- $model->name = $data['name'];
- $model->short = $data['short'];
- $model->pos = $data['pos'];
- $model->is_abo = isset($data['is_abo']) ? true : false;
- $model->show_on = isset($data['show_on']) ? $data['show_on'] : null;
- $model->default = isset($data['default']) ? true : false;
- $model->active = isset($data['active']) ? true : false;
- $model->save();
- }
-
- /* if(!empty($data['trans'])){
- $trans = [];
- foreach ($data['trans'] as $lang => $value){
- if($value && $value != null){
- $trans[$lang] = $value;
- }
- }
- if(count($trans)){
- $model->trans_name = $trans;
- $model->save();
- }
- }*/
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_payment_methods'));
-
-
- }
-
-
- /*public function delete($id){
-
- if(ProductAttribute::where('attribute_id', $id)->count()){
- \Session()->flash('alert-error', 'Eintrag wird als Produktattribute verwendet');
- return redirect(route('admin_product_attributes'));
- }
-
- $model = Attribute::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_attributes'));
- }
- */
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/PaymentPointsController.php b/dev/app-bak/Http/Controllers/PaymentPointsController.php
deleted file mode 100644
index 5a3d76b5..00000000
--- a/dev/app-bak/Http/Controllers/PaymentPointsController.php
+++ /dev/null
@@ -1,125 +0,0 @@
-middleware('auth');
- }
-
- public function index()
- {
- dd("function?");
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(),
- ];
- return view('admin.payment.invoice', $data);
- }
-
- private function setFilterVars()
- {
-
- if (!session('invoice_filter_month')) {
- session(['invoice_filter_month' => intval(date('m'))]);
- }
- if (!session('invoice_filter_year')) {
- session(['invoice_filter_year' => intval(date('Y'))]);
- }
- if (Request::get('invoice_filter_name')) {
- session(['invoice_filter_name' => Request::get('invoice_filter_name')]);
- } else {
- session(['invoice_filter_name' => '']);
- }
- if (Request::get('invoice_filter_month')) {
- session(['invoice_filter_month' => Request::get('invoice_filter_month')]);
- }
- if (Request::get('invoice_filter_year')) {
- session(['invoice_filter_year' => Request::get('invoice_filter_year')]);
- }
- }
-
- private function initSearch($archive = false, $request = true)
- {
- $this->setFilterVars();
-
- $query = UserInvoice::with('shopping_order')->with('shopping_order.shopping_user')->select('user_invoices.*')
- ->where('user_invoices.month', '=', Request::get('invoice_filter_month'))
- ->where('user_invoices.year', '=', Request::get('invoice_filter_year'));
-
- if (Request::get('invoice_filter_name')) {
- $query->where('shopping_order.shopping_user.billing_firstname', 'LIKE', '%' . Request::get('invoice_filter_name') . '%');
- $query->where('shopping_order.shopping_user.billing_lastname', 'LIKE', '%' . Request::get('invoice_filter_name') . '%');
- $query->where('shopping_order.shopping_user.billing_email', 'LIKE', '%' . Request::get('invoice_filter_name') . '%');
- }
-
- //->orderBy('created_at', 'DESC');
- /* $query = FlexHour::leftJoin("flex_hour_items", function($join) {
- $join->on("flex_hour_items.flex_hour_id","=","flex_hours.id");
- $join->where("flex_hour_items.date","=", FlexHourItemBot::$date);
- })*/
- return $query;
- }
-
- public function datatable()
- {
-
- $query = $this->initSearch();
- return \DataTables::eloquent($query)
- ->addColumn('id', function (UserInvoice $UserInvoice) {
- if ($UserInvoice->shopping_order->auth_user_id) {
- return '';
- }
- return '';
- })
- ->addColumn('total_shipping', function (UserInvoice $UserInvoice) {
- return '' . $UserInvoice->shopping_order->getFormattedTotalShipping() . " €";
- })
- ->addColumn('created_at', function (UserInvoice $UserInvoice) {
- return $UserInvoice->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (UserInvoice $UserInvoice) {
- if ($UserInvoice->shopping_order) {
- return Payment::getShoppingOrderBadge($UserInvoice->shopping_order);
- }
- return "-";
- })
- ->addColumn('status', function (UserInvoice $UserInvoice) {
- return '
- ' . $UserInvoice->getStatusType() . '
- ';
- })
- ->addColumn('invoice', function (UserInvoice $UserInvoice) {
- $ret = "";
- $ret .= ' ';
- $ret .= '';
-
- return $ret;
- })
-
- ->orderColumn('id', 'id $1')
- ->orderColumn('invoice_number', 'invoice_number $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('shipped', 'shipped $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
- ->rawColumns(['id', 'shipping_order', 'txaction', 'total_shipping', 'status', 'txaction', 'invoice'])
- ->make(true);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/PaymentTaxAdvisorController.php b/dev/app-bak/Http/Controllers/PaymentTaxAdvisorController.php
deleted file mode 100644
index 9afcada9..00000000
--- a/dev/app-bak/Http/Controllers/PaymentTaxAdvisorController.php
+++ /dev/null
@@ -1,246 +0,0 @@
- 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 $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()
- {
- $this->middleware('admin');
- }
-
- public function index()
- {
-
- $this->setFilterVars();
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2023),
- ];
- return view('admin.payment.taxadvisor', $data);
- }
-
-
- public function createZip($filesToZip)
- {
- $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));
- }
-
- $zip->close();
- return response()->download($path.$zipFileName)->deleteFileAfterSend(true);
- } else {
- return "Failed to create the zip file.";
- }
- }
-
-
- public function download(){
-
-
- $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;
- }
- }
-
- return $this->createZip($files);
-
- dd("asd");
-
-
-
- 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 Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
- }
- }
-
-
- private function setFilterVars(){
-
- if(!session('payment_taxadvisor_filter_month')){
- session(['payment_taxadvisor_filter_month' => intval(date('m'))]);
- }
- 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_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 ''.$UserInvoice->shopping_order->getFormattedTotalShipping()." €";
- })
- ->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 .= ' ';
- $ret .= '';
- 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);
-
-
-
- }
-
-
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Portal/AboController.php b/dev/app-bak/Http/Controllers/Portal/AboController.php
deleted file mode 100644
index 4bf0f27a..00000000
--- a/dev/app-bak/Http/Controllers/Portal/AboController.php
+++ /dev/null
@@ -1,311 +0,0 @@
-middleware('auth:customers');
- $this->yard = Yard::instance($this->instance);
- }
-
-
- public function myAbo()
- {
- $user = Auth::guard('customers')->user();
-
- if (!$user->shopping_user_id) {
- return view('portal.abo.my_abo_create', [
- 'user' => $user,
- 'no_shopping_user' => true,
- 'step' => 0,
- ]);
- }
-
- $shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
- $user_abo = UserAbo::where('email', $shopping_user->billing_email)
- ->where('status', '>', 1)
- ->first();
-
- return $user_abo
- ? view('portal.abo.my_abo', ['user_abo' => $user_abo])
- : view('portal.abo.my_abo_create', [
- 'shopping_user' => $shopping_user,
- 'step' => 0,
- ]);
- }
-
- public function myAboCreate($step)
- {
- $user = Auth::guard('customers')->user();
-
- 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'])){
- return redirect($data['checkout_url']);
- }
- return view('portal.abo.my_abo_create', $data);
- }
-
- private function prepareAboCreateData($shopping_user, $step)
- {
- $data = [
- 'shopping_user' => $shopping_user,
- 'basis_products' => Product::where('active', true)
- ->whereJsonContains('show_on', ['12'])
- ->orderBy('pos', 'ASC')
- ->get(),
- 'upgrade_products' => Product::where('active', true)
- ->whereJsonContains('show_on', ['13'])
- ->orderBy('pos', 'ASC')
- ->get(),
- 'step' => 0,
- ];
- if(Request::get('action') == 'back') {
- $step = $step - 2;
- }
-
- switch ($step) {
- case 0:
- $data['step'] = 0;
- break;
- case 1:
- $this->initYard($shopping_user);
- $data['step'] = 1;
- break;
- case 2:
- UserService::setInstance($this->instance);
- UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
- $data['step'] = 2;
- break;
- case 3:
- UserService::setInstance($this->instance);
- UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
- if(Request::get('action') == 'next'){
- if (!$this->checkBasisProduct()) {
- $data['error'] = __('abo.abo_error_basis_product');
- $data['step'] = 2;
- } else {
- $data['step'] = 3;
- }
- }else{
- $data['step'] = 3;
- }
- break;
- case 4:
- UserService::setInstance($this->instance);
- UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
- $this->upgradeProductToCart();
- $data['step'] = 4;
- break;
- case 5:
- //chekout verarbeiten
- UserService::setInstance($this->instance);
- UserService::initCustomerYard($shopping_user, 'abo-ot-customer');
- if(Request::get('action') == 'checkout'){
- //checkout verarbeiten
- if (!$this->preCheckCheckout()) {
- $data['error'] = __('abo.abo_error_basis_product');
- $data['step'] = 4;
- } else {
- $data['checkout_url'] = $this->processCheckout();
- }
- }
- $data['step'] = 4;
- break;
- default:
- abort(404, 'Page not found.');
- }
-
- return $data;
- }
-
- private function initYard($shopping_user)
- {
- $delivery_country = $shopping_user->getDeliveryCountry(true);
-
- if (!$delivery_country) {
- abort(404, 'No delivery country found, please edit your personal data.');
- }
-
- \Session::put('user_init_country', strtolower($delivery_country->code));
- \Session::forget('user_init_country_options');
- \Session::put('locale', strtolower(\App::getLocale()));
-
- Shop::initUserShopLang($delivery_country, $this->instance);
- }
-
- private function preCheckCheckout(){
- $result = false;
- //alle inhlate des warenkorb
- $cartItems = $this->yard->content();
- 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'])) {
- return false;
- }
-
- foreach ($data['base_product_qty'] as $product_id => $quantity) {
- $product = Product::find($product_id);
-
- if (!$product || intval($quantity) <= 0) {
- continue;
- }
- $result = true;
- $this->addProductToCart($product, $quantity);
-
- }
-
- return $result;
- }
-
- private function upgradeProductToCart(){
- $data = Request::all();
- $result = false;
-
- if (!isset($data['upgrade_product_qty'])) {
- return false;
- }
-
- foreach ($data['upgrade_product_qty'] as $product_id => $quantity) {
- $product = Product::find($product_id);
-
- if (!$product) {
- continue;
- }
-
- $result = true;
- $this->addProductToCart($product, $quantity);
- }
-
- return $result;
- }
-
- private function addProductToCart($product, $quantity)
- {
- // Suche nach dem Produkt im Warenkorb
- $cartItems = $this->yard->search(function($item) use ($product) {
- return $item->id === $product->id;
- });
-
- // Wenn die Menge 0 ist, entferne das Produkt
- if ($quantity <= 0) {
- foreach ($cartItems as $item) {
- $this->yard->remove($item->rowId);
- }
- return;
- }
-
- $image = $product->images->first()->slug ?? '';
- $price = $product->getPriceWith(
- $this->yard->getUserTaxFree(),
- false,
- $this->yard->getUserCountry()
- );
-
- // Wenn das Produkt bereits im Warenkorb ist, aktualisiere die Menge
- if ($cartItems->count() > 0) {
- $cartItem = $cartItems->first();
- $this->yard->update($cartItem->rowId, $quantity);
- } else {
- // Wenn das Produkt noch nicht im Warenkorb ist, füge es hinzu
- $cartItem = $this->yard->add(
- $product->id,
- $product->getLang('name'),
- $quantity,
- $price,
- 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
- ]
- );
- }
-
- // $this->setProductTax($cartItem, $product);
- $this->yard->reCalculateShippingPrice();
- }
-
-
- private function processCheckout(){
- $user_shop = Util::getUserShop();
- if(!$user_shop){
- $user_shop = Util::getDefaultUserShop();
- }
- do {
- $identifier = Util::getToken();
- } while( ShoppingInstance::where('identifier', $identifier)->count() );
-
- $data = [];
- $data['is_from'] = 'shopping';
- $data['user_price_infos'] = $this->yard->getUserPriceInfos();
-
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => $user_shop->id,
- 'payment' => 1, //Customer Shop Payment
- 'subdomain' => url('/'),
- 'country_id' => $this->yard->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'shopping_data' => $data,
- 'back' => url()->previous(),
-
- ]);
-
- $this->yard->store($identifier);
- //add to DB
- $path = route('checkout.checkout_card', ['identifier'=>$identifier]);
- if(strpos($path, 'https') === false){
- $path = str_replace('http', 'https', $path);
- }
- return $path;
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Portal/Auth/LoginController.php b/dev/app-bak/Http/Controllers/Portal/Auth/LoginController.php
deleted file mode 100755
index 7403bc13..00000000
--- a/dev/app-bak/Http/Controllers/Portal/Auth/LoginController.php
+++ /dev/null
@@ -1,203 +0,0 @@
-check()) {
- return redirect()->route('portal.change_login');
- }
- //wenn als Kunde eingeloggt, dann direkt zum Dashboard
- if (Auth::guard('customers')->check()) {
- return redirect()->route('portal.dashboard');
- }
- return view('portal.auth.login'); // Erstelle diese View
- }
-
- // Sendet das OTP
- public function sendOtp(Request $request)
- {
- $request->validate(['email' => 'required|email']);
- $email = $request->input('email');
-
- // 1. Prüfen, ob die E-Mail im System bekannt ist über Kunden-Tabelle)
- $customer = Customer::firstOrCreate(['email' => $email]); // Erstellt Kunden, wenn nicht vorhanden
- if ($customer && $customer->language) {
- \App::setLocale($customer->language);
- }
-
- // if (!$customerExists && !$orderExists) { // Oder nur eine Prüfung, je nach Logik
- if (!$customer) { // Prüfung anhand des Customer-Models
- throw ValidationException::withMessages([
- 'email' => __('auth.failed_customer'), // Generische Fehlermeldung
- ]);
- }
- // 2. Alten Token löschen (optional, aber empfohlen)
- DB::table('otp_tokens')->where('email', $email)->delete();
-
- // 3. OTP generieren (z.B. 6-stellige Zahl)
- $otp = random_int(100000, 999999);
- $expiresAt = Carbon::now()->addMinutes(10); // Gültigkeit z.B. 10 Minuten
-
- // 4. OTP (gehasht!) speichern
- DB::table('otp_tokens')->insert([
- 'email' => $email,
- 'token' => Hash::make((string)$otp), // WICHTIG: Token hashen!
- 'expires_at' => $expiresAt,
- 'created_at' => Carbon::now(),
- ]);
-
- // 5. OTP per E-Mail senden (Notification oder Mailable verwenden)
- try {
- Mail::to($email)->locale(\App::getLocale())->send(new MailOTPCustomer($otp, $email));
- } catch (\Exception $e) {
- // Logge den Fehler
- \Log::error('OTP Send Error: ' . $e->getMessage());
- // Gib eine Fehlermeldung zurück, ohne Details preiszugeben
- return back()->withErrors(['email' => 'Konnte E-Mail nicht senden. Bitte versuchen Sie es später erneut.'])->withInput();
- }
-
-
- // 6. Zum OTP-Eingabeformular weiterleiten (E-Mail in Session speichern oder als Parameter übergeben)
- session(['otp_email' => $email]); // Explizit in Session speichern
- return redirect()->route('portal.login.otp.form', ['email' => $email]); // E-Mail auch als Parameter übergeben
- }
-
- // Zeigt das Formular zur Eingabe des OTP an
- public function showOtpForm(Request $request, $email = null, $otp = null)
- {
- //wenn als Berater eingeloggt, dann zum Login wechseln
- if (Auth::guard('user')->check()) {
- return redirect()->route('portal.change_login');
- }
- //wenn als Kunde eingeloggt, dann zum Dashboard wechseln
- if (Auth::guard('customers')->check()) {
- return redirect()->route('portal.dashboard');
- }
- // E-Mail aus der Session holen (oder als Request-Parameter erwarten)
- if ($email) {
- $email = $email;
- } else {
- $email = session('otp_email', $request->query('email'));
- }
- if (!$email) {
- return redirect()->route('portal.login.form')->withErrors(['message' => 'Sitzung abgelaufen oder E-Mail fehlt.']);
- }
-
- // CSRF-Token regenerieren für neue Session
- $request->session()->regenerateToken();
-
- // Übergebe sowohl 'email' als auch 'otp' an die View
- return view('portal.auth.verify-otp', ['email' => $email, 'otp_value' => $otp]); // Variable umbenannt zu otp_value für Klarheit
- }
-
- // Validiert das OTP und loggt den Kunden ein
- public function verifyOtpAndLogin(Request $request)
- {
- $request->validate([
- 'email' => 'required|email',
- 'otp' => 'required|numeric|digits:6', // An die Länge deines OTPs anpassen
- ]);
-
- $email = $request->input('email');
- $otpInput = $request->input('otp');
-
- // 1. Gespeicherten OTP-Eintrag finden
- $otpRecord = DB::table('otp_tokens')->where('email', $email)->first();
-
- // 2. Prüfen ob Eintrag existiert, nicht abgelaufen ist und das OTP (Hash) übereinstimmt
- if (!$otpRecord || Carbon::now()->gt($otpRecord->expires_at) || !Hash::check($otpInput, $otpRecord->token)) {
- // Ungültiges oder abgelaufenes OTP
- DB::table('otp_tokens')->where('email', $email)->delete(); // Ungültigen Token löschen
- return back()->withErrors(['otp' => 'Ungültiges oder abgelaufenes Einmalpasswort.'])->withInput(['email' => $email]);
- }
- // 3. Kunden-Objekt finden (basierend auf dem Provider-Model)
- $customer = Customer::where('email', $email)->first(); // Oder User::where('email', $email)->where('role','customer')->first();
-
- if (!$customer) {
- // Sollte eigentlich nicht passieren, wenn sendOtp korrekt funktioniert hat
- DB::table('otp_tokens')->where('email', $email)->delete();
- return back()->withErrors(['otp' => __('auth.failed')])->withInput(['email' => $email]);
- }
- // 4. Kunden einloggen über den 'customers'-Guard
- Auth::guard('customers')->login($customer); // Loggt den gefundenen Kunden ein
-
- // 5. Explizite Session-Speicherung
- $request->session()->save();
-
- // 6. OTP-Eintrag löschen
- DB::table('otp_tokens')->where('email', $email)->delete();
-
- // 7. Session Token regenerieren (statt komplette Session)
- $request->session()->regenerate();
-
- // 8. customer DB aktualisieren
- $shopping_user = ShoppingUser::where('billing_email', $email)->latest()->first();
- if ($shopping_user) {
- $data = [
- 'name' => $shopping_user->billing_firstname . ' ' . $shopping_user->billing_lastname,
- 'shopping_user_id' => $shopping_user->id,
- 'member_id' => $shopping_user->member_id,
- 'number' => $shopping_user->number,
- 'language' => session('locale') ?? 'de',
- ];
- $customer->update($data);
- } else {
- $data = [
- 'name' => __('portal.guest'),
- 'shopping_user_id' => null,
- 'member_id' => null,
- 'number' => null,
- 'language' => session('locale') ?? 'de',
- ];
- $customer->update($data);
- }
-
-
- // 10. Zum Kunden-Dashboard weiterleiten
- return redirect()->intended(route('portal.dashboard')); // intended() leitet zur ursprünglich angefragten Seite weiter
- }
-
- // Logout für Kunden
- public function logout(Request $request)
- {
- $url = Util::getMyMivitaShopUrl();
- Auth::guard('customers')->logout();
- $request->session()->invalidate();
- $request->session()->regenerateToken();
- return redirect($url);
- }
-
- // Logout für Berater
- public function logoutChange(Request $request)
- {
- //$url = Util::getMyMivitaShopUrl();
- $user_shop_domain = session('user_shop_domain');
- $locale = session('locale');
- Auth::guard('user')->logout();
- $request->session()->invalidate();
- $request->session()->regenerateToken();
- session(['user_shop_domain' => $user_shop_domain]);
- session(['locale' => $locale]);
- return redirect()->route('portal.login.form');
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Portal/CustomerController.php b/dev/app-bak/Http/Controllers/Portal/CustomerController.php
deleted file mode 100644
index da5b9a79..00000000
--- a/dev/app-bak/Http/Controllers/Portal/CustomerController.php
+++ /dev/null
@@ -1,99 +0,0 @@
-middleware('auth:customers');
- }
-
-
- public function myDataEdit()
- {
- $user = Auth::guard('customers')->user();
- if($user->shopping_user_id){
- $shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
- }else{
- $shopping_user = new ShoppingUser();
- }
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => false,
- 'isView' => 'customer',
- ];
- return view('portal.customer.edit', $data);
-
- }
-
- 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(
- 'billing_salutation' => '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')){
- $rules = array_merge($rules, [
- 'shipping_firstname'=>'required',
- 'shipping_lastname'=>'required',
- 'shipping_address'=>'required',
- 'shipping_zipcode'=>'required',
- 'shipping_city' => 'required',
- 'shipping_salutation' => 'required',
- 'shipping_country_id' => 'required'
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
- }
- $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){
- $shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
- $shopping_user->fill($data);
- $shopping_user->save();
- }else{
- $data['billing_email'] = $user->email;
- $shopping_user = ShoppingUser::create($data);
- $user->shopping_user_id = $shopping_user->id;
- $user->save();
- //kundenhoheit
- CustomerPriority::checkOne(ShoppingUser::find($shopping_user->id), true);
-
-
- }
-
-
- \Session()->flash('alert-save', true);
-
- return redirect(route('portal.my_data.edit'));
- }
-
-}
diff --git a/dev/app-bak/Http/Controllers/Portal/InController.php b/dev/app-bak/Http/Controllers/Portal/InController.php
deleted file mode 100755
index 6093ef16..00000000
--- a/dev/app-bak/Http/Controllers/Portal/InController.php
+++ /dev/null
@@ -1,132 +0,0 @@
-check()){
- return redirect(route('portal.change_login'));
- }
- if(!Auth::guard('customers')->check()){ // if () {
- return redirect(route('portal.login.form'));
- }
- return redirect(route('portal.dashboard'));
-
- }
-
- public function changeLogin(){
- if(Auth::guard('customers')->check()){
- return redirect(route('portal.dashboard'));
- }
- if(Auth::guard('user')->check()){
- return view('portal.auth.change');
-
- }
- return redirect(route('portal.login.form'));
-
- }
-
- public function dashboard()
- {
- if(!Auth::guard('customers')->check()){
- return redirect(route('portal.login.form'));
- }
- $data = [
- 'user' => Auth::guard('customers')->user(),
- 'now' => Carbon::now(),
- ];
- return view('portal.dashboard', $data);
- }
-
- public function loadingModal(){
-
- $data = Request::all();
-
- $response = "";
- $status = false;
- if(isset($data['action'])){
- 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();
- return response()->json(['response' => $data, 'html'=>$ret, 'status'=>$status]);
- }
- }
-
- $data = Request::get('data');
- $target = Request::get('target');
- if($data === "data_protection"){
- $data = [
- 'modal' => true,
- 'user_shop' => true,
- 'isMivitaShop' => false,
- ];
- $response = view('legal.data_protect_de', $data)->render();
- }
- if($data === "imprint"){
- $data = [
- 'modal' => true,
- 'user_shop' => Util::getUserShop(),
- ];
- $response = view('legal.imprint_de', $data)->render();
- }
- 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"){
- $data = [
- 'modal' => true,
- 'user_shop' => Util::getUserShop(),
- ];
- $response = view('legal.agb_de', $data)->render();
- }
- if(Request::ajax()) {
- return response()->json(['response' => $response, 'target'=>$target]);
- }
- abort(404);
- }
-
-
-
- /* public function goToShop(){
-
- if(!Auth::guard('customers')->check()){
- return redirect(config('app.protocol') . config('app.domain') . config('app.tld_shop'));
- }
- $customer = Auth::guard('customers')->user();
- //subdmain for member
- $member = User::where('email', $customer->email)->first();
- if($member){
- return redirect(config('app.protocol') . $member->subdomain . config('app.tld_care'));
- }
- // $customer->member_id
-
- // return redirect(config('app.protocol') . config('app.domain') . config('app.tld_shop'));
- }*/
-}
diff --git a/dev/app-bak/Http/Controllers/Portal/OrderController.php b/dev/app-bak/Http/Controllers/Portal/OrderController.php
deleted file mode 100644
index aeab71f6..00000000
--- a/dev/app-bak/Http/Controllers/Portal/OrderController.php
+++ /dev/null
@@ -1,116 +0,0 @@
-middleware('auth:customers');
- }
-
-
- 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);
-
- }
-
- public function myOrderShow($id)
- {
- $user = Auth::guard('customers')->user();
- $shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
- $shopping_order = ShoppingOrder::findOrFail($id);
- if($shopping_order->shopping_user_id != $user->shopping_user_id){
- abort(403, 'Unauthorized action.');
- }
- return view('portal.order.my_order_show', [
- 'shopping_order' => $shopping_order,
- 'shopping_user' => $shopping_user,
- ]);
- }
-
- public function myOrderCreate($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.');
- }
- $shopping_user = ShoppingUser::findOrFail($user->shopping_user_id);
- $delivery_country = $shopping_user->getDeliveryCountry(true);
-
- \Session::put('user_init_country', strtolower($delivery_country->code));
- \Session::forget('user_init_country_options');
- \Session::put('locale', strtolower(\App::getLocale()));
-
- 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);
- }
- }
- $url = Util::getMyMivitaShopUrl("/user/card/show");
- return redirect($url);
- }
-
-
- private function addToCard($id, $quantity = 1)
- {
- $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);
- }
- }
-
-
-
-}
diff --git a/dev/app-bak/Http/Controllers/ProductController.php b/dev/app-bak/Http/Controllers/ProductController.php
deleted file mode 100755
index 8a009c98..00000000
--- a/dev/app-bak/Http/Controllers/ProductController.php
+++ /dev/null
@@ -1,233 +0,0 @@
-middleware('admin');
- $this->productRepo = $productRepo;
-
- }
-
- public function index()
- {
- if(Request::get('show_active_products')){
- set_user_attr('show_active_products', Request::get('show_active_products'));
- }
- if(get_user_attr('show_active_products') === "true"){
- $values = Product::where('active', true)->orderBy('pos', 'DESC')->orderBy('id', 'DESC')->get();
- }else{
- $values = Product::orderBy('pos', 'DESC')->orderBy('id', 'DESC')->get();
-
- }
- $data = [
- 'values' => $values
- ];
- return view('admin.product.index', $data);
- }
-
- public function edit($id)
- {
- if($id === "new"){
- $model = new Product();
- $model->active = true;
- }else{
- $model = Product::findOrFail($id);
- }
- $country_for_prices = Country::where('own_eur', '=', true)->orWhere('currency', '=', true)->get();
- $data = [
- 'product' => $model,
- 'country_for_prices' => $country_for_prices,
- ];
- return view('admin.product.edit', $data);
- }
-
- public function store()
- {
- $data = Request::all();
- $rules = array(
- 'name' => 'required',
- );
- /*if(isset($data['number']) && $data['number'] != ""){
- $rules['number'] = 'int';
- }*/
- if(isset($data['wp_number'])){
- if($data['id'] !== "new"){
- $model = Product::findOrFail($data['id']);
- $rules['wp_number'] = 'unique:products,wp_number,'.$model->id;
- }else{
- $rules['wp_number'] = 'unique:products,wp_number';
-
- }
- }
- $validator = Validator::make(Request::all(), $rules);
-
- if($data['id'] === "new"){
- $model = new Product();
- }else{
- $model = Product::findOrFail($data['id']);
- }
- $country_for_prices = Country::where('own_eur', '=', true)->orWhere('currency', '=', true)->get();
-
- $data = [
- 'product' => $model,
- 'country_for_prices' => $country_for_prices,
-
- ];
-
- if ($validator->fails()) {
-
- return view('admin.product.edit', $data)->withErrors($validator);
-
- } else {
- $product = $this->productRepo->update(Request::all());
- \Session()->flash('alert-save', true);
- return redirect(route('admin_product_edit', [$product->id]));
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_product_show'));
-
-
- }
-
- public function copy($id){
- $model = Product::findOrFail($id);
-
- $product = $this->productRepo->copy($model);
-
-
-
- \Session()->flash('alert-success', 'Eintrag kopiert');
- return redirect(route('admin_product_show'));
- }
-
- public function delete($id, $do = 'product', $did = null){
- if($do === 'product'){
- $model = Product::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_show'));
- }
-
- if($do === 'ingredient'){
- $model = Product::findOrFail($id);
- $ProductIngredient = ProductIngredient::where('ingredient_id', $did)->where('product_id', $model->id)->first();
- if($ProductIngredient){
- $ProductIngredient->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_edit', [$model->id]));
- }
-
- }
-
- }
-
-
- // Upload FILE -----------------------------------------------------------------------------------------------------------------------
-
- public function imageUpload(){
-
- $product_id = Request::get('product_id');
- $product = Product::findOrFail($product_id);
-
- try {
- $image = \App\Services\Slim::getImages('images')[0];
-
- if ( isset($image['output']['data']) )
- {
-
- // Base64 of the image
- $data = $image['output']['data'];
- $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');
-
- if (!isset($file_ex[$image['output']['type']])) {
- \Session()->flash('alert-danger', 'File is not jpg or png!');
- return redirect(route('admin_product_edit', [$product->id]));
- }
-
- $ext = $file_ex[$image['output']['type']];
- // Original file name
- $name = $image['output']['name'];
- $name = \App\Services\Slim::sanitizeFileName($name);
- $name = uniqid() . '_' . $name;
-
- $data = \Storage::disk('public')->put(
- 'images/product/'.$product->id.'/'.$name,
- $data
- );
-
- ProductImage::create([
- 'product_id' => $product->id,
- 'filename' => $name,
- 'original_name' => $image['output']['name'],
- 'ext' => $ext,
- 'mine' => $image['output']['type'],
- 'size' => $image['input']['size']
- ]);
-
-
- \Session()->flash('alert-success', __('msg.file_uploaded'));
- return redirect(route('admin_product_edit', [$product->id]));
- }
- \Session()->flash('alert-danger', __('msg.file_empty'));
- return redirect(route('admin_product_edit', [$product->id]));
-
- }
- catch ( \Exception $e) {
- \Session()->flash('alert-danger', "Fehler".$e);
- return redirect(route('admin_product_edit', [$product->id]));
- }
- }
-
- public function imageDelete($image_id, $product_id){
-
- $product = Product::findOrFail($product_id);
- $product_image = ProductImage::findOrFail($image_id);
-
- if($product_image->product_id == $product->id){
- $file = 'images/product/'.$product->id.'/'.$product_image->filename;
- \Storage::disk('public')->delete($file);
-
- $product_image->delete();
-
- \Session()->flash('alert-success', __('msg.file_deleted'));
- return redirect(route('admin_product_edit', [$product->id]));
-
- }
- \Session()->flash('alert-danger', __('msg.file_not_found'));
- return redirect(route('admin_product_edit', [$product->id]));
-
- }
-
- public function imageAttribute($product_id, $attr, $val = false){
-
- if(is_numeric($val) && $val < 0){
- $val = 0;
- }
-
- $product_image = ProductImage::findOrFail($product_id);
-
- $product_image->{$attr} = $val;
- $product_image->save();
-
- \Session()->flash('alert-success', "Wert gespeichert");
- return redirect()->back();
-
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/RevenueReportController.php b/dev/app-bak/Http/Controllers/RevenueReportController.php
deleted file mode 100644
index 1422eab3..00000000
--- a/dev/app-bak/Http/Controllers/RevenueReportController.php
+++ /dev/null
@@ -1,343 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
- $this->setFilterVars();
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- 'revenue_summary' => $this->getRevenueSummary(),
- 'credit_summary' => $this->getCreditSummary()
- ];
-
- return view('admin.revenue.index', $data);
- }
-
- public function export()
- {
- $this->setFilterVars();
-
- $filter_year = session('revenue_filter_year');
-
- // Get data like in the HTML view
- $revenue_summary = $this->getRevenueSummary();
- $credit_summary = $this->getCreditSummary();
-
- $filename = "umsatz-gutschrift-bericht-{$filter_year}";
-
- $columns = [];
-
- // Umsätze Section Header
- $columns[] = ['Typ' => 'UMSÄTZE', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
-
- // Yearly Revenue Summary
- if(isset($revenue_summary['yearly']) && $revenue_summary['yearly']->count() > 0) {
- foreach($revenue_summary['yearly'] as $item) {
- $columns[] = [
- 'Typ' => $item->period_label,
- 'Netto' => number_format($item->total_net, 2, ',', '.'),
- 'Steuer' => number_format($item->total_tax, 2, ',', '.'),
- 'Brutto' => number_format($item->total_gross, 2, ',', '.')
- ];
- }
- } else {
- $columns[] = [
- 'Typ' => "Jahr {$filter_year}",
- 'Netto' => '0,00',
- 'Steuer' => '0,00',
- 'Brutto' => '0,00'
- ];
- }
-
- // Empty row
- $columns[] = ['Typ' => '', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
-
- // Monthly Revenue Breakdown
- $columns[] = ['Typ' => 'MONATLICHE AUFSCHLÜSSELUNG UMSÄTZE', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
- if(isset($revenue_summary['monthly']) && $revenue_summary['monthly']->count() > 0) {
- foreach($revenue_summary['monthly'] as $item) {
- $columns[] = [
- 'Typ' => $item->period_label,
- 'Netto' => number_format($item->total_net, 2, ',', '.'),
- 'Steuer' => number_format($item->total_tax, 2, ',', '.'),
- 'Brutto' => number_format($item->total_gross, 2, ',', '.')
- ];
- }
- } else {
- $columns[] = [
- 'Typ' => 'Keine monatlichen Umsätze gefunden',
- 'Netto' => '',
- 'Steuer' => '',
- 'Brutto' => ''
- ];
- }
-
- // Two empty rows for separation
- $columns[] = ['Typ' => '', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
- $columns[] = ['Typ' => '', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
-
- // Gutschriften Section Header
- $columns[] = ['Typ' => 'GUTSCHRIFTEN', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
-
- // Yearly Credit Summary
- if(isset($credit_summary['yearly']) && $credit_summary['yearly']->count() > 0) {
- foreach($credit_summary['yearly'] as $item) {
- $columns[] = [
- 'Typ' => $item->period_label,
- 'Netto' => number_format($item->total_net, 2, ',', '.'),
- 'Steuer' => number_format($item->total_tax, 2, ',', '.'),
- 'Brutto' => number_format($item->total_gross, 2, ',', '.')
- ];
- }
- } else {
- $columns[] = [
- 'Typ' => "Jahr {$filter_year}",
- 'Netto' => '0,00',
- 'Steuer' => '0,00',
- 'Brutto' => '0,00'
- ];
- }
-
- // Empty row
- $columns[] = ['Typ' => '', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
-
- // Monthly Credit Breakdown
- $columns[] = ['Typ' => 'MONATLICHE AUFSCHLÜSSELUNG GUTSCHRIFTEN', 'Netto' => '', 'Steuer' => '', 'Brutto' => ''];
- if(isset($credit_summary['monthly']) && $credit_summary['monthly']->count() > 0) {
- foreach($credit_summary['monthly'] as $item) {
- $columns[] = [
- 'Typ' => $item->period_label,
- 'Netto' => number_format($item->total_net, 2, ',', '.'),
- 'Steuer' => number_format($item->total_tax, 2, ',', '.'),
- 'Brutto' => number_format($item->total_gross, 2, ',', '.')
- ];
- }
- } else {
- $columns[] = [
- 'Typ' => 'Keine monatlichen Gutschriften gefunden',
- 'Netto' => '',
- 'Steuer' => '',
- 'Brutto' => ''
- ];
- }
-
- $headers = ['Zeitraum', 'Netto (€)', 'Steuer (€)', 'Brutto (€)'];
-
- return Excel::download(new UserTeamExport($columns, $headers), $filename . '.xlsx');
- }
-
- private function setFilterVars()
- {
- if (!session('revenue_filter_month')) {
- session(['revenue_filter_month' => intval(date('m'))]);
- }
- if (!session('revenue_filter_year')) {
- session(['revenue_filter_year' => intval(date('Y'))]);
- }
- if(!session('revenue_filter_type')){
- session(['revenue_filter_type' => 'year']);
- }
- if (Request::get('revenue_filter_month')) {
- session(['revenue_filter_month' => Request::get('revenue_filter_month')]);
- }
- if (Request::get('revenue_filter_year')) {
- session(['revenue_filter_year' => Request::get('revenue_filter_year')]);
- }
- if (Request::get('revenue_filter_type')) {
- session(['revenue_filter_type' => Request::get('revenue_filter_type')]);
- }
- }
-
- private function getRevenueSummary()
- {
- $year = session('revenue_filter_year');
-
- return [
- 'yearly' => $this->getRevenueByYear($year),
- 'monthly' => $this->getRevenueByMonthsInYear($year)
- ];
- }
-
- private function getCreditSummary()
- {
- $year = session('revenue_filter_year');
-
- return [
- 'yearly' => $this->getCreditByYear($year),
- 'monthly' => $this->getCreditByMonthsInYear($year)
- ];
- }
-
- private function getRevenueByYear($year)
- {
- return UserInvoice::join('shopping_orders', 'user_invoices.shopping_order_id', '=', 'shopping_orders.id')
- ->selectRaw("
- {$year} as year,
- CONCAT('Jahr ', {$year}) as period_label,
- SUM(shopping_orders.subtotal_ws) as total_net,
- SUM(shopping_orders.tax) as total_tax,
- SUM(shopping_orders.total_shipping) as total_gross
- ")
- ->where('user_invoices.year', $year)
- ->where('user_invoices.cancellation', false)
- ->groupBy(DB::raw('1'))
- ->get();
- }
-
- private function getRevenueByMonth($year, $month)
- {
- return UserInvoice::join('shopping_orders', 'user_invoices.shopping_order_id', '=', 'shopping_orders.id')
- ->selectRaw("
- {$year} as year,
- {$month} as month,
- CONCAT(CASE {$month}
- WHEN 1 THEN 'Januar'
- WHEN 2 THEN 'Februar'
- WHEN 3 THEN 'März'
- WHEN 4 THEN 'April'
- WHEN 5 THEN 'Mai'
- WHEN 6 THEN 'Juni'
- WHEN 7 THEN 'Juli'
- WHEN 8 THEN 'August'
- WHEN 9 THEN 'September'
- WHEN 10 THEN 'Oktober'
- WHEN 11 THEN 'November'
- WHEN 12 THEN 'Dezember'
- END, ' ', {$year}) as period_label,
- SUM(shopping_orders.subtotal_ws) as total_net,
- SUM(shopping_orders.tax) as total_tax,
- SUM(shopping_orders.total_shipping) as total_gross
- ")
- ->where('user_invoices.year', $year)
- ->where('user_invoices.month', $month)
- ->where('user_invoices.cancellation', false)
- ->groupBy(DB::raw('1'))
- ->get();
- }
-
- private function getRevenueByMonthsInYear($year)
- {
- return UserInvoice::join('shopping_orders', 'user_invoices.shopping_order_id', '=', 'shopping_orders.id')
- ->selectRaw("
- user_invoices.year,
- user_invoices.month,
- CONCAT(CASE user_invoices.month
- WHEN 1 THEN 'Januar'
- WHEN 2 THEN 'Februar'
- WHEN 3 THEN 'März'
- WHEN 4 THEN 'April'
- WHEN 5 THEN 'Mai'
- WHEN 6 THEN 'Juni'
- WHEN 7 THEN 'Juli'
- WHEN 8 THEN 'August'
- WHEN 9 THEN 'September'
- WHEN 10 THEN 'Oktober'
- WHEN 11 THEN 'November'
- WHEN 12 THEN 'Dezember'
- END, ' ', user_invoices.year) as period_label,
- SUM(shopping_orders.subtotal_ws) as total_net,
- SUM(shopping_orders.tax) as total_tax,
- SUM(shopping_orders.total_shipping) as total_gross
- ")
- ->where('user_invoices.year', $year)
- ->where('user_invoices.cancellation', false)
- ->groupBy('user_invoices.year', 'user_invoices.month')
- ->orderBy('user_invoices.month')
- ->get();
- }
-
- private function getCreditByYear($year)
- {
- return UserCredit::selectRaw("
- {$year} as year,
- CONCAT('Jahr ', {$year}) as period_label,
- SUM(net) as total_net,
- SUM(tax) as total_tax,
- SUM(total) as total_gross
- ")
- ->where('year', $year)
- ->where('cancellation', false)
- ->groupBy(DB::raw('1'))
- ->get();
- }
-
- private function getCreditByMonth($year, $month)
- {
- return UserCredit::selectRaw("
- {$year} as year,
- {$month} as month,
- CONCAT(CASE {$month}
- WHEN 1 THEN 'Januar'
- WHEN 2 THEN 'Februar'
- WHEN 3 THEN 'März'
- WHEN 4 THEN 'April'
- WHEN 5 THEN 'Mai'
- WHEN 6 THEN 'Juni'
- WHEN 7 THEN 'Juli'
- WHEN 8 THEN 'August'
- WHEN 9 THEN 'September'
- WHEN 10 THEN 'Oktober'
- WHEN 11 THEN 'November'
- WHEN 12 THEN 'Dezember'
- END, ' ', {$year}) as period_label,
- SUM(net) as total_net,
- SUM(tax) as total_tax,
- SUM(total) as total_gross
- ")
- ->where('year', $year)
- ->where('month', $month)
- ->where('cancellation', false)
- ->groupBy(DB::raw('1'))
- ->get();
- }
-
- private function getCreditByMonthsInYear($year)
- {
- return UserCredit::selectRaw("
- year,
- month,
- CONCAT(CASE month
- WHEN 1 THEN 'Januar'
- WHEN 2 THEN 'Februar'
- WHEN 3 THEN 'März'
- WHEN 4 THEN 'April'
- WHEN 5 THEN 'Mai'
- WHEN 6 THEN 'Juni'
- WHEN 7 THEN 'Juli'
- WHEN 8 THEN 'August'
- WHEN 9 THEN 'September'
- WHEN 10 THEN 'Oktober'
- WHEN 11 THEN 'November'
- WHEN 12 THEN 'Dezember'
- END, ' ', year) as period_label,
- SUM(net) as total_net,
- SUM(tax) as total_tax,
- SUM(total) as total_gross
- ")
- ->where('year', $year)
- ->where('cancellation', false)
- ->groupBy('year', 'month')
- ->orderBy('month')
- ->get();
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/SalesController.php b/dev/app-bak/Http/Controllers/SalesController.php
deleted file mode 100755
index f58c6671..00000000
--- a/dev/app-bak/Http/Controllers/SalesController.php
+++ /dev/null
@@ -1,392 +0,0 @@
-middleware('admin');
- }
-
- public function users(){
-
- if(Request::get('reset') === 'filter'){
- return redirect(route('admin_sales_users'));
- }
- $data = [
-
- ];
- return view('admin.sales.users', $data);
- }
-
- public function usersDetail($id)
- {
- $ShoppingOrder = ShoppingOrder::find($id);
- if( $ShoppingOrder->payment_for === 6 || $ShoppingOrder->payment_for === 7){
- return redirect(route('admin_sales_customers_detail', [$ShoppingOrder->id]));
- abort(403, 'Kundenbestellung');
- }
- /*if($ShoppingOrder->shipped === 0){
- $ShoppingOrder->shipped = 1;
- $ShoppingOrder->save();
- }*/
-
- $data = [
- 'shopping_order' => $ShoppingOrder,
- 'isAdmin' => true,
- 'isView' => 'sales_user',
- ];
- return view('admin.sales.user_detail', $data);
- }
-
- public function usersStore($id)
- {
- die("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);
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getShoppingOrderBadge($ShoppingOrder);
- })
- ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getFormattedTotalShipping()." €";
- })
- ->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
- })
- ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
- if($ShoppingOrder->payment_for === 8){
- return '';
- }
- return ''.$ShoppingOrder->getShippedType().'';
- })
- ->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getPaymentForBadge($ShoppingOrder);
- })
- ->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->isInvoice() ? '
- ' : '-';
- })
- ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->getLastShoppingPayment('reference');
- })
- ->addColumn('orders', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->orders : '';
- })
- ->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->user_shop ? ''.$ShoppingOrder->user_shop->getSubdomain(false).'' : '';
- })
- ->addColumn('auth_user_shop', function (ShoppingOrder $ShoppingOrder) {
- $auth_user_shop = UserShop::whereUserId($ShoppingOrder->auth_user_id)->first();
- return $auth_user_shop ? ''.$auth_user_shop->getSubdomain(false).'' : '-';
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('user_shop_id', 'user_shop_id $1')
- ->orderColumn('shipped', 'shipped $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
- ->orderColumn('payment_for', 'payment_for $1')
-
- ->rawColumns(['id', 'txaction', 'user_shop_id', 'auth_user_shop', 'payment_for', 'total_shipping', 'invoice', 'shipped'])
- ->make(true);
- }
-
- public function customers()
- {
- if(Request::get('reset') === 'filter'){
- 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')
- ->join('user_shops', 'shopping_orders.user_shop_id', '=', 'user_shops.id')
- ->orderBy('user_shops.slug')
- ->distinct()
- ->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();
-
-
-
- $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){
- 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();
- }
- */
- $data = [
- 'shopping_order' => $ShoppingOrder,
- 'isAdmin' => true,
- 'isView' => 'sales_customer',
- ];
- return view('admin.sales.customer_detail', $data);
- }
-
- public function customersStore($id)
- {
- $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.";
- }else{
- //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')){
- \Session()->flash('alert-error', 'Das Passwort ist falsch.');
- return redirect($data['back']);
- }else{
- 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
- 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')){
- \Session()->flash('alert-error', 'Das Passwort ist falsch.');
- return back();
- }else{
- 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]));
- }
- }
- $data = [
- 'change_member_error' => $change_member_error,
- 'shopping_order' => ShoppingOrder::find($id),
- '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);
- set_user_attr('filter_user_shop_id', 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') === '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') != ""){
- $query->where('member_id', '=', Request::get('filter_member_id'));
- }
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getShoppingOrderBadge($ShoppingOrder);
- })
- ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getFormattedTotalShipping()." €";
- })
- ->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 ' '.$shopping_oder_id.'';
- }
- }
- return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
- })
- ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getShippedType().'';
- })
- ->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 ' ';
- }
- return $ShoppingOrder->isInvoice() ? '
- ' : '-';
- })
- ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->getLastShoppingPayment('reference');
- })
- ->addColumn('member_id', function (ShoppingOrder $ShoppingOrder) {
- if($ShoppingOrder->member_id && $ShoppingOrder->member) {
- return $ShoppingOrder->member ? '' . $ShoppingOrder->member->getFullName() . '' : 'gelöscht';
- }
- if($ShoppingOrder->shopping_user && $ShoppingOrder->shopping_user->is_like){
- return '';
- }
- return '';
- })
- ->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->user_shop ? ''.$ShoppingOrder->user_shop->getSubdomain(false).'' : '';
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('user_shop_id', 'user_shop_id $1')
- ->orderColumn('member_id', 'member_id $1')
- ->orderColumn('shipped', 'shipped $1')
- ->orderColumn('payment_for', 'payment_for $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
- ->rawColumns(['id', 'member_id', 'txaction', 'user_shop_id', 'payment_for', 'payment', 'total_shipping', 'invoice', 'shipped'])
- ->make(true);
- }
-
- public function store(){
- $data = Request::all();
- if(!isset($data['id'])){
- abort(404);
- }
- if(isset($data['action'])){
- if($data['action'] === 'store_shipped' && isset($data['shipped'])){
- $shopping_order = ShoppingOrder::findOrFail($data['id']);
- $shopping_order->shipped = $data['shipped'];
- $shopping_order->save();
- }
-
- if($data['action'] === 'store_txaction' && isset($data['txaction']) && isset($data['payment_id'])){
- $shopping_order = ShoppingOrder::findOrFail($data['id']);
- $shopping_payment = ShoppingPayment::findOrFail($data['payment_id']);
-
- PaymentTransaction::create([
- 'shopping_payment_id' => $shopping_payment->id,
- 'request' => 'transaction',
- 'txid' => 0,
- 'userid' => 0,
- 'status' => 'FNCMIV',
- 'transmitted_data' => NULL,
- 'txaction' => $data['txaction'],
- 'mode' => $shopping_payment->mode,
- ]);
-
- $shopping_order->txaction = $data['txaction'];
- $shopping_order->paid = true;
- $shopping_order->save();
- $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);
- }
-
- }
- if(isset($data['back'])){
- return redirect($data['back']);
- }
- }
-
- /*
- Manuelle Rechnung erstellen.*/
- public function invoice(){
- $data = Request::all();
- if(!isset($data['id'])){
- abort(404);
- }
- if(isset($data['action'])){
- if($data['action'] === 'create_invoice'){
- $shopping_order = ShoppingOrder::findOrFail($data['id']);
-
- $invoice_repo = new InvoiceRepository($shopping_order);
- if($shopping_order->isInvoice()){
- $invoice_repo->update($data);
- }else{
- $invoice_repo->createAndSalesVolume($data);
- }
-
- 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]));
- }
- }
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/SettingController.php b/dev/app-bak/Http/Controllers/SettingController.php
deleted file mode 100644
index ea090072..00000000
--- a/dev/app-bak/Http/Controllers/SettingController.php
+++ /dev/null
@@ -1,118 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
-
- $data = [
- 'values' => [],
- ];
- return view('admin.settings.index', $data);
- }
-
-
- public function store()
- {
- $data = Request::all();
- if (isset($data['action'])) {
- if (isset($data['settings'])) {
- foreach ($data['settings'] as $key => $value) {
- $value['val'] = isset($value['val']) ? $value['val'] : false;
- Setting::setContentBySlug($key, $value['val'], $value['type']);
- }
- }
-
- // DHL-spezifische Behandlung
- if ($data['action'] === 'save_dhl') {
- $this->updateDhlConfigCache();
- \Session()->flash('alert-save-dhl', 'DHL Konfiguration erfolgreich gespeichert!');
- } else {
- \Session()->flash('alert-save', '1');
- }
- }
-
- return redirect(route('admin_settings'));
- }
-
- /**
- * Get DHL configuration merged from database settings and .env values
- * Database settings override .env values
- */
- public function getDhlConfig()
- {
- return [
- // API Settings
- 'base_url' => Setting::getContentBySlug('dhl_base_url') ?: config('dhl.base_url'),
- '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'),
-
- // 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'),
-
- // 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'),
- ],
-
- // 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'),
- 'default' => config('dhl.account_numbers.default'),
- ],
-
- // Static config values (webhook, profile, legacy)
- 'profile' => config('dhl.profile'),
- 'webhook' => config('dhl.webhook'),
- 'legacy' => config('dhl.legacy'),
- ];
- }
-
- /**
- * Update DHL configuration cache after saving settings
- */
- private function updateDhlConfigCache()
- {
- // Clear config cache to force reload from database
- \Artisan::call('config:clear');
-
- // Optional: Test DHL connection with new settings
- try {
- $dhlManager = app('Acme\Dhl\DhlManager');
- // 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());
- }
- }
-}
diff --git a/dev/app-bak/Http/Controllers/ShippingController.php b/dev/app-bak/Http/Controllers/ShippingController.php
deleted file mode 100755
index e49be466..00000000
--- a/dev/app-bak/Http/Controllers/ShippingController.php
+++ /dev/null
@@ -1,154 +0,0 @@
-middleware('superadmin');
-
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function index()
- {
- $data = [
- 'values' => Shipping::all(),
- ];
- return view('admin.shipping.index', $data);
- }
-
- public function edit($shipping_id)
- {
- if($shipping_id === "new"){
- $shipping = new Shipping();
- $shipping->active = 1;
- // For new shipping objects, create an empty collection for countries
- $shipping->setRelation('countries', collect());
-
- }else{
- $shipping = Shipping::with(['countries.country'])->findOrFail($shipping_id);
-
- }
- $data = [
- 'value' => $shipping,
- ];
- return view('admin.shipping.edit', $data);
-
-
- }
-
- /**
- * @param Request $request
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function store(Request $request)
- {
- $shipping = false;
- $data = Request::all();
-
- if($data['action'] === 'shipping'){
- if ($data['id'] === "new") {
- $shipping = new Shipping();
- $rules = array('name' => 'required');
- } else {
- $shipping = Shipping::findOrFail($data['id']);
- $rules = array('name' => 'required');
- }
- $ret = ['value' => $shipping];
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return view('admin.shipping.edit', $ret)->withErrors($validator);
- }
- $data = Request::all();
- $shipping->name = $data['name'];
- $shipping->free = $data['free'];
- $shipping->active = isset($data['active']) ? true : false;
- $shipping->save();
- }
-
- if($data['action'] === 'price'){
- $shipping = Shipping::findOrFail($data['shipping_id']);
- $rules = array('price' => 'required');
- $ret = ['value' => $shipping];
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return view('admin.shipping.edit', $ret)->withErrors($validator);
- }
- if ($data['id'] === "new") {
- $price = ShippingPrice::create($data);
- } else {
- $price = ShippingPrice::findOrFail($data['id']);
- if($price->shipping_id != $shipping->id){
- abort(404);
- }
- $price->fill($data);
- $price->save();
- }
-
- }
- if($data['action'] === 'country'){
- $shipping = Shipping::findOrFail($data['shipping_id']);
- foreach($data['country_ids'] as $country_id){
- if(ShippingCountry::where('country_id', $country_id)->count() == 0){
- ShippingCountry::create([
- 'shipping_id' => $shipping->id,
- 'country_id' => $country_id
- ]);
- }
- }
- }
-
- if($shipping){
- \Session()->flash('alert-save', true);
- return redirect(route('admin_shipping_edit', [$shipping->id]));
- }
- return redirect(route('admin_shippings'));
-
- }
-
-
- public function deleteShipping($id)
- {
- $model = Shipping::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', "Versandkosten gelöscht");
- return redirect('/admin/shippings');
- }
-
- public function deletePrice($id)
- {
- $model = ShippingPrice::findOrFail($id);
- $shipping = $model->shipping;
- $model->delete();
- \Session()->flash('alert-success', "Preis gelöscht");
- return redirect(route('admin_shipping_edit', [$shipping->id]));
- }
-
- public function deleteCountry($id)
- {
- $model = ShippingCountry::findOrFail($id);
- if($model->shopping_orders->count()){
- abort(403, 'Einträge vorhanden');
- }
- $shipping = $model->shipping;
- $model->delete();
- \Session()->flash('alert-success', "Preis gelöscht");
- return redirect(route('admin_shipping_edit', [$shipping->id]));
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/SitesController.php b/dev/app-bak/Http/Controllers/SitesController.php
deleted file mode 100755
index 014bd87f..00000000
--- a/dev/app-bak/Http/Controllers/SitesController.php
+++ /dev/null
@@ -1,148 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
- //
- }
-
- public function show($site)
- {
- $data = [
- 'value' => IqSite::find(1),
- 'site' => $site,
- ];
- return view('admin.site.edit', $data);
- }
-
- public function store($site)
- {
- $data = Request::all();
- $data['products'] = isset($data['products']) ? $data['products'] : null;
- $data['set_products'] = isset($data['set_products']) ? $data['set_products'] : null;
-
- if($site == "new"){
- // $model = IqSite::create($data);
- }else{
- $model = IqSite::find(1);
- $model->fill($data);
- $model->save();
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_sites', ['start']));
-
- }
-
-
- // Upload FILE -----------------------------------------------------------------------------------------------------------------------
-
- public function imageUpload($site){
-
- $model = IqSite::find(1);
-
- try {
- $image = \App\Services\Slim::getImages('images')[0];
-
- if ( isset($image['output']['data']) )
- {
-
- // Base64 of the image
- $data = $image['output']['data'];
- $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');
-
- if (!isset($file_ex[$image['output']['type']])) {
- \Session()->flash('alert-danger', 'File is not jpg or png!');
- return redirect(route('admin_sites', [$model->slug]));
- }
-
- $ext = $file_ex[$image['output']['type']];
- // Original file name
- $name = $image['output']['name'];
- $name = \App\Services\Slim::sanitizeFileName($name);
- $path = 'images/iq_images/';
-
- $image_name = "";
- do {
- $image_name = uniqid('', false) . '_' . $name;
- } while (\Storage::disk('public')->exists($path.$image_name));
-
- $data = \Storage::disk('public')->put(
- $path.$image_name,
- $data
- );
-
- $iq_image = IqImage::create([
- 'filename' => $image_name,
- 'original_name' => $image['output']['name'],
- 'ext' => $ext,
- 'mine' => $image['output']['type'],
- 'size' => $image['input']['size']
- ]);
-
- $model->iq_image_id = $iq_image->id;
- $model->save();
-
- \Session()->flash('alert-success', __('msg.file_uploaded'));
- return redirect(route('admin_sites', [$model->slug]));
- }
- \Session()->flash('alert-danger', __('msg.file_empty'));
- return redirect(route('admin_sites', [$model->slug]));
-
- }
- catch (Exception $e) {
- \Session()->flash('alert-danger', "Error: ".$e);
- return redirect(route('admin_sites', [$model->slug]));
- }
- }
-
- public function imageDelete($site, $image_id){
-
- $iq_image = IqImage::findOrFail($image_id);
- $model = IqSite::find(1);
-
-
- if($iq_image->id == $model->iq_image->id){
- $file = 'images/iq_images/'.$iq_image->filename;
- \Storage::disk('public')->delete($file);
- $model->iq_image_id = NULL;
- $model->save();
- $iq_image->delete();
-
-
- \Session()->flash('alert-success', __('msg.file_deleted'));
- return redirect(route('admin_sites', [$model->slug]));
-
- }
- \Session()->flash('alert-danger', __('msg.file_not_found'));
- return redirect(route('admin_sites', [$model->slug]));
-
- }
-
- public function imageAttribute($site, $image_id, $attr, $val = false){
-
- $iq_image = IqImage::findOrFail($image_id);
-
- $iq_image->{$attr} = $val;
- $iq_image->save();
-
- \Session()->flash('alert-success', "Wert gespeichert");
- return redirect()->back();
-
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/SyS/SettingController.php b/dev/app-bak/Http/Controllers/SyS/SettingController.php
deleted file mode 100755
index be8c5e69..00000000
--- a/dev/app-bak/Http/Controllers/SyS/SettingController.php
+++ /dev/null
@@ -1,50 +0,0 @@
-middleware('sysadmin');
-
- }
-
- public function index()
- {
-
- $data = [
- 'values' => SySetting::all(),
- ];
- return view('sys.settings.index', $data);
- }
-
- public function store()
- {
-
- $data = Request::all();
-
- $data['active'] = isset($data['active']) ? true : false;
- if($data['id'] === "new"){
- $model = SySetting::create($data);
- }else{
- $model = SySetting::find($data['id']);
- $model->fill($data);
- $model->save();
- }
-
-
- \Session()->flash('alert-save', '1');
- return redirect(route('sysadmin_settings'));
-
- }
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/SyS/SysController.php b/dev/app-bak/Http/Controllers/SyS/SysController.php
deleted file mode 100644
index 3a549bd9..00000000
--- a/dev/app-bak/Http/Controllers/SyS/SysController.php
+++ /dev/null
@@ -1,148 +0,0 @@
-middleware('sysadmin');
-
- }
-
- public function index()
- {
- return view('sys.index');
- }
-
- public function tool($serve)
- {
- switch ($serve) {
-
- case 'user_credit_items_add_from':
- return UserCreditItemsAddFrom::show();
- break;
- case 'buyings_products':
- return BuyingsProducts::show();
- break;
- case 'business_structur':
- return BusinessStructur::show();
- break;
- case 'sales_members':
- return Sales::show();
- break;
- case 'customers':
- return Customers::show();
- break;
- case 'cronjobs':
- return Cronjobs::show();
- break;
- case 'domainssl':
- return DomainSSL::show();
- break;
- case 'shopping_orders':
- return ShoppingOrders::show();
- break;
- case 'import':
- return Import::show();
- break;
- case 'corrections':
- return Correction::show();
- break;
- case 'change_user_businesses':
- return ChangeUserBusinesses::show();
- break;
- case 'repair_sales_volume_invoice':
- return RepairSalesVolumeInvoice::show();
- break;
- case 'user_credit_items_change_message':
- return UserCreditItemsChangeMessage::show();
- break;
- case 'clean_html_product_description':
- return CleanHTMLProductDescription::show();
- break;
- case 'import_dbip_country_lite':
- return ImportDbipCountry::show();
- break;
-
-
-
-
-
- }
- abort(403, 'not found tool');
- }
-
- public function store($serve)
- {
- switch ($serve) {
- case 'user_credit_items_add_from':
- return UserCreditItemsAddFrom::show();
- break;
- case 'buyings_products':
- return BuyingsProducts::store();
- break;
- case 'business_structur':
- return BusinessStructur::show();
- break;
- case 'sales_members':
- return Sales::show();
- break;
- case 'customers':
- return Customers::store();
- break;
- case 'cronjobs':
- return Cronjobs::store();
- break;
- case 'domainssl':
- return DomainSSL::store();
- break;
- case 'shopping_orders':
- return ShoppingOrders::store();
- break;
- case 'import':
- return Import::store();
- break;
- case 'corrections':
- return Correction::store();
- break;
- case 'change_user_businesses':
- return ChangeUserBusinesses::store();
- break;
- case 'repair_sales_volume_invoice':
- return RepairSalesVolumeInvoice::store();
- break;
- case 'user_credit_items_change_message':
- return UserCreditItemsChangeMessage::store();
- break;
- case 'clean_html_product_description':
- return CleanHTMLProductDescription::store();
- break;
- case 'import_dbip_country_lite':
- return ImportDbipCountry::store();
- break;
- }
- abort(403, 'not found tool');
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/TemplateController.php b/dev/app-bak/Http/Controllers/TemplateController.php
deleted file mode 100755
index 8a371d61..00000000
--- a/dev/app-bak/Http/Controllers/TemplateController.php
+++ /dev/null
@@ -1,27 +0,0 @@
-middleware('auth');
-
- }
-
- public function index()
- {
-
- if(Auth::check()) {
-
- }
- return view('templates.index', ['title' => 'Page 2']);
- }
-}
-
-
diff --git a/dev/app-bak/Http/Controllers/TranslationController.php b/dev/app-bak/Http/Controllers/TranslationController.php
deleted file mode 100755
index d02464de..00000000
--- a/dev/app-bak/Http/Controllers/TranslationController.php
+++ /dev/null
@@ -1,259 +0,0 @@
-sourceLanguage = 'de';
- $this->selectLanguage = 'en';
- $this->keys = [];
- $this->model = "";
- }
- /**
- */
- public function index($model, $lang=null)
- {
- //Request::get('key')
- //Request::get('language')
- $this->initByModel($model);
- $languages = $this->allLanguages();
- $languages->forget('de');
-
- $translations = $this->getTranslationsFormModel();
-
- $data = [
- 'keys' => $this->keys,
- 'languages' => $languages,
- 'model' => $this->model,
- 'select_language' => $this->selectLanguage,
- 'source_language' => $this->sourceLanguage,
- 'translations' => $translations,
- 'select_key' => $this->selectKey
- ];
- return view('translation::languages.translations.custom', $data);
-
- }
-
- /**
- */
- public function initByModel($model)
- {
- if($model === 'products'){
- $this->model = $model;
- $this->keys = [
- 'name'=>'Produktname',
- 'copy'=>'Produktbeschreibung',
- 'description'=>'Beschreibung',
- 'usage'=>'Anwendung',
- 'ingredients'=>'Hinweise',
- ];
- $this->selectKey = 'name';
- }
-
- if($model === 'ingredients'){
- $this->model = $model;
- $this->keys = [
- 'name'=>'Name',
- 'inci'=>'INCI',
- 'effect'=>'Wirkung',
- ];
- $this->selectKey = 'name';
- }
-
- if($model === 'user_levels'){
- $this->model = $model;
- $this->keys = [
- 'name'=>'Name',
- ];
- $this->selectKey = 'name';
- }
-
- if($model === 'shippings'){
- $this->model = $model;
- $this->keys = [
- 'name'=>'Name',
- ];
- $this->selectKey = 'name';
- }
-
- if($model === 'categories'){
- $this->model = $model;
- $this->keys = [
- 'name'=>'Name',
- 'headline'=>'Headline',
- ];
- $this->selectKey = 'name';
- }
-
- if(Request::get('key')){
- $this->selectKey = Request::get('key');
- }
- if(Request::get('language')){
- $this->selectLanguage = Request::get('language');
- }
- //Request::get('language')
- }
-
- public function getTranslationsFormModel(){
-
- if($this->model === 'products'){
- return Product::all()->mapWithKeys(function ($value) {
- return [$value->id => [
- 'master' => $value->name,
- 'source' => $value->{$this->selectKey},
- 'trans' => $value->getTrans($this->selectKey, $this->selectLanguage),
- ]
- ];
- });
- }
- if($this->model === 'ingredients'){
- return Ingredient::all()->mapWithKeys(function ($value) {
- return [$value->id => [
- 'master' => $value->name,
- 'source' => $value->{$this->selectKey},
- 'trans' => $value->getTrans($this->selectKey, $this->selectLanguage),
- ]
- ];
- });
- }
- if($this->model === 'user_levels'){
- return UserLevel::all()->mapWithKeys(function ($value) {
- return [$value->id => [
- 'master' => $value->name,
- 'source' => $value->{$this->selectKey},
- 'trans' => $value->getTrans($this->selectKey, $this->selectLanguage),
- ]
- ];
- });
- }
- if($this->model === 'shippings'){
- return Shipping::all()->mapWithKeys(function ($value) {
- return [$value->id => [
- 'master' => $value->name,
- 'source' => $value->{$this->selectKey},
- 'trans' => $value->getTrans($this->selectKey, $this->selectLanguage),
- ]
- ];
- });
- }
- if($this->model === 'categories'){
- return Category::all()->mapWithKeys(function ($value) {
- return [$value->id => [
- 'master' => $value->name,
- 'source' => $value->{$this->selectKey},
- 'trans' => $value->getTrans($this->selectKey, $this->selectLanguage),
- ]
- ];
- });
- }
- }
-
- public function update($model)
- {
- $id = Request::get('key'); //id
- $key = Request::get('group'); //key colum
- $language = Request::get('language'); //selectLanguage
-
- $value = Request::get('value') ?: ''; //value
-
- if($model === 'products'){
- TransProduct::updateOrCreate([
- 'language' => $language,
- 'product_id' => $id,
- 'key' => $key,
- ], [
- 'key' => $key,
- 'value' => $value,
- ]);
- }
-
- if($model === 'ingredients'){
- TransIngredient::updateOrCreate([
- 'language' => $language,
- 'ingredient_id' => $id,
- 'key' => $key,
- ], [
- 'key' => $key,
- 'value' => $value,
- ]);
- }
-
- if($model === 'user_levels'){
- TransUserLevel::updateOrCreate([
- 'language' => $language,
- 'user_level_id' => $id,
- 'key' => $key,
- ], [
- 'key' => $key,
- 'value' => $value,
- ]);
- }
-
- if($model === 'shippings'){
- TransShipping::updateOrCreate([
- 'language' => $language,
- 'shipping_id' => $id,
- 'key' => $key,
- ], [
- 'key' => $key,
- 'value' => $value,
- ]);
- }
-
- if($model === 'categories'){
- TransCategory::updateOrCreate([
- 'language' => $language,
- 'categorie_id' => $id,
- 'key' => $key,
- ], [
- 'key' => $key,
- 'value' => $value,
- ]);
- }
-
- return ['success' => true];
- }
-
- /**
- * Get all languages from the application.
- *
- * @return Collection
- */
-
- public function allLanguages()
- {
- return Language::all()->mapWithKeys(function ($language) {
- return [$language->language => $language->name ?: $language->language];
- });
- }
-
-
-}
diff --git a/dev/app-bak/Http/Controllers/TranslationFileController.php b/dev/app-bak/Http/Controllers/TranslationFileController.php
deleted file mode 100755
index 5e03150f..00000000
--- a/dev/app-bak/Http/Controllers/TranslationFileController.php
+++ /dev/null
@@ -1,282 +0,0 @@
-directory_separator = DIRECTORY_SEPARATOR;
- $this->translator = App::make('translator');
- $this->loader = Lang::getLoader();
- $this->languagesPath = App::langPath();
- $this->directory_separator = DIRECTORY_SEPARATOR;
- }
-
- /**
- * Show the application dashboard.
- *
- * @return \Illuminate\Http\Response
- */
- public function index()
- {
- $language = App::getLocale();
- $langsource = 'de';
- $this->languageRead = $language;
- $langs = array_keys(config('localization.supportedLocales'));
- $files = $this->files();
- $translations = null;
- $edit = false;
- $show = 'all';
- return view('translation.index_file', compact('files', 'translations', 'language', 'langsource', 'langs', 'edit', 'show'));
-
- //return view('admin.transitions', $data);
- }
-
- /**
- * Display edit form page
- *
- * @param string $language
- * @param string $file
- * @param string|null $namespace
- *
- * @return \Illuminate\Http\Response
- */
- public function edit($file, $language = 'en', $langsource = 'de', $show = 'all')
- {
- $this->languageRead = $language;
- $langs = array_keys(config('localization.supportedLocales'));
- $files = $this->files();
- $translations = $this->translations($file, $langsource);
- $prefix = $this->groupName($file);
- $langsource = $langsource;
- $edit = $file;
- $show = $show;
-
- return view('translation.index_file', compact('files', 'language', 'langsource', 'file', 'translations', 'prefix', 'langs', 'edit', 'show'));
- }
-
- /**
- * Save translation file
- *
- * @param \GeniusTS\TranslationManager\Requests\TranslationRequest $request
- * @param string $language
- * @param string $file
- *
- * @return \Illuminate\Http\Response
- */
- public function update(TranslationRequest $request, $file, $language, $langsource, $show)
- {
- $keys = array_keys($this->translations($file));
-
- $this->exportFile($request->only($keys), $file, $language);
-
- return redirect()
- ->route('admin_translate_file_edit', [$file, $language, $langsource, $show])
- ->with('message', 'Translation added successfully');
- }
-
- /**
- * Save a translation file
- *
- * @param array $translation
- * @param $filename
- * @param $language
- *
- * @return bool
- */
- public function exportFile($translation, $filename, $language)
- {
- $path = "{$this->languagesPath}{$this->directory_separator}{$language}{$this->directory_separator}{$filename}.php";
-
- $this->backup($path, $language, $filename);
-
- $content = "filesystem->write($path, $content, new Config);
- }
-
- /**
- * Backup the existing translation files
- */
- private function backup($path, $language, $filename)
- {
- if(!File::exists($path)){
- return;
- }
- if (!File::exists(storage_path('language/'.time().'/'.$language))) {
- File::makeDirectory(storage_path('language/'.time().'/'.$language), 0755, true);
- }
-
- return File::copy($path, storage_path('language/'.time().'/'.$language.'/'.$filename.'.php'));
- }
-
-
- /**
- * Get the translation of a group and name space
- *
- * @param string $file
- * @param string|null $namespace
- * @param string|null $language
- *
- * @return array
- */
- public function translations($file, $language = null)
- {
- $group = $this->groupName($file);
- $key = $group;
-
- return $this->translator->trans($key, [], $language ?: $this->defaultLanguage());
- }
-
- public function files($lang = false)
- {
- $path = $this->namespacePath($this->languagesPath, $lang);
-
- $content = $this->pathContent($path);
-
- return $content
- ->map(function ($file) use ($path) {
- $path = ltrim($path . DIRECTORY_SEPARATOR, '/');
- //read file empty entries
- $count = $this->countEmptyEntries(Str::replaceLast($path, '', $file));
- //var_dump($translations);
- return array(ltrim($this->groupName(Str::replaceLast($path, '', $file)), '/') => ltrim($this->groupName(Str::replaceLast($path, '', $file)), '/')." (".$count.")");
- })
- ->flatten();
- }
-
- public function countEmptyEntries($file){
-
- $translation = $this->translations($file);
- $group = $this->groupName($file);
- $entries = 0;
- $count = 0;
- foreach ($translation as $key => $value)
- {
- $this->searchForEmpty($key, $value, null, $count, $entries, $group);
- }
- return $entries."/".$count;
- }
-
- protected function searchForEmpty($key, $value, $prefix, &$count, &$entries, $group)
- {
- $prefix = $prefix ? "{$prefix}.{$key}" : $group.".".$key;
- if (is_array($value))
- {
- foreach ($value as $subKey => $subValue)
- {
- $this->searchForEmpty($subKey, $subValue, $prefix, $count,$entries, $group);
- }
- }
- else
- {
- if(Lang::has($prefix, $this->languageRead, false)){
- $count++;
- }
-
- if(Lang::has($prefix, 'de', false)){
- $entries ++;
- }
-
- }
- }
-
- /**
- * Get default language
- *
- * @return string
- */
- public function defaultLanguage()
- {
- return config('app.fallback_locale', 'de');
- }
-
-
- /**
- * Get the group name from a filename
- *
- * @param $filename
- *
- * @return mixed
- */
- public function groupName($filename)
- {
- return preg_replace('/\.php$/', '', $filename);
- }
- /**
- * Get default language
- *
- * @param string $path
- * @param string $language
- *
- * @return string
- */
- protected function namespacePath($path, $language = null)
- {
- return "{$path}{$this->directory_separator}" . ($language ?: $this->defaultLanguage());
- }
-
- /**
- * List content of a path
- *
- * @param null $path
- * @param bool $recursive
- *
- * @return \Illuminate\Support\Collection
- */
- protected function pathContent($path = null, $recursive = false)
- {
-
- //var_dump($this->filesystem->listContents($path, $recursive));
- //return new Collection(($this->filesystem->listContents($path, $recursive)));
- return new Collection(File::files($path));
- }
-
-}
diff --git a/dev/app-bak/Http/Controllers/User/AboController.php b/dev/app-bak/Http/Controllers/User/AboController.php
deleted file mode 100644
index ac9372b7..00000000
--- a/dev/app-bak/Http/Controllers/User/AboController.php
+++ /dev/null
@@ -1,322 +0,0 @@
-middleware('active.account');
- $this->aboRepository = $aboRepository;
- }
-
- public function index($view)
- {
-
- if ($view === 'me') {
- // Nur Abos des aktuellen Benutzers
- $user_abos = UserAbo::where('user_id', \Auth::user()->id)
- ->where('status', '>', 1);
-
- if ($user_abos->count() > 0) {
- return redirect(route('user_abos_detail', ['me', $user_abos->first()->id]));
- }
-
- return view('user.abo.index', [
- 'user_abos' => [],
- 'view' => 'me',
- 'isAdmin' => false
- ]);
- }
-
- if ($view === 'ot') {
- $user_abos = UserAbo::where('member_id', \Auth::user()->id)
- ->where('status', '>', 1)
- ->where('is_for', 'ot')
- ->orderBy('id', 'desc')
- ->get();
-
- return view('user.abo.index', [
- 'user_abos' => $user_abos,
- 'view' => 'ot',
- 'isAdmin' => false
- ]);
- }
-
- // Standardfall, wenn weder 'me' noch 'ot'
- return view('user.abo.index', [
- 'user_abos' => [],
- 'view' => 'me',
- 'isAdmin' => false
- ]);
- }
-
-
- public function detail($view, $id)
- {
- $data = Request::all();
- $user_abo = UserAbo::findOrFail($id);
-
-
- $this->checkPermissions($view, $user_abo);
-
- //init Yard
- AboOrderCart::initYard($user_abo);
- //holt die aktuellen UserAccount Daten oder die Userdaten des Abo
- $customer_detail = AboOrderCart::getCustomerDetail();
- AboOrderCart::makeOrderYard($user_abo);
-
- $comp_products = [];
- if ($user_abo->is_for === 'me') {
- $comp_products = Shop::getCompProducts('abo-me');
- }
-
- $data = [
- 'user_abo' => $user_abo,
- 'isAdmin' => false,
- 'customer_detail' => $customer_detail,
- '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);
- 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
- 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()) {
- $UserAboItem->qty = $UserAboItem->qty + 1;
- $UserAboItem->save();
- } else {
- UserAboItem::create([
- 'user_abo_id' => $user_abo->id,
- 'product_id' => $product->id,
- 'comp' => 0,
- 'qty' => 1,
- 'status' => 1,
- ]);
- }
- }
- }
-
- //updateCart
- if ($data['action'] === 'updateCart') {
- //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'])) {
- $qty = (int) $data['qty'];
- $qty = $qty < 1 ? 1 : $qty;
- $qty = $qty > 100 ? 100 : $qty;
- $UserAboItem->qty = $qty;
- $UserAboItem->save();
- }
- }
- }
- }
-
- //removeFromCart
- if ($data['action'] === 'removeFromCart') {
- 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->check_need_basis_product($user_abo, $product, $data['order_item_id']);
- if (!$has_basis_product) {
- $message = __('abo.need_basis_product');
- }
- if (!$message) {
-
-
- $userAboItem->delete();
- $user_abo->refresh(); // Abo neu laden um die aktualisierten Items zu erhalten
- }
- }
- //updateCompProduct
- if ($data['action'] === 'updateCompProduct') {
- if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('comp', $data['comp_num'])->first()) {
- $UserAboItem->product_id = $data['comp_product_id'];
- $UserAboItem->save();
- } else {
- UserAboItem::create([
- 'user_abo_id' => $user_abo->id,
- 'product_id' => $data['comp_product_id'],
- 'comp' => $data['comp_num'],
- 'qty' => 1,
- 'status' => 1,
- ]);
- }
- }
-
-
- AboOrderCart::initYard($user_abo);
- 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();
-
- $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]);
- }
- }
- }
-
- public function check_need_basis_product($user_abo, $product, $order_item_id)
- {
- // Wenn das zu entfernende Produkt kein Basis-Produkt ist, keine weitere Prüfung nötig
- if (AboHelper::getAboShowOn($product) !== 'base') {
- return true;
- }
-
- // Prüfe ob noch ein anderes Basis-Produkt vorhanden ist
- foreach ($user_abo->user_abo_items as $user_abo_item) {
- if ($user_abo_item->id == $order_item_id) {
- continue;
- }
- if (AboHelper::getAboShowOn($user_abo_item->product) === 'base') {
- return true;
- }
- }
-
- return false;
- }
-
- public function datatable($user_abo_id)
- {
- $user_abo = UserAbo::findOrFail($user_abo_id);
- if (!$user_abo) {
- abort(404);
- }
-
- //$user_abo->is_for === 'me'
-
- $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) use ($user_abo) {
- $ufactor = $user_abo->is_for === 'me' ? true : false;
- $tax_free = $user_abo->is_for === 'me' ? true : Yard::instance('shopping')->getUserTaxFree();
- return '';
- })
- ->addColumn('picture', function (Product $product) {
- if (count($product->images)) {
- return '
';
- }
- return "";
- })
- ->addColumn('name', function (Product $product) use ($user_abo) {
- return '' . $product->getLang('name') . '
' . get_abo_type_badge_by_product($product);
- })
-
- ->addColumn('price_net', function (Product $product) use ($user_abo) {
- $ufactor = $user_abo->is_for === 'me' ? true : false;
- return '' . $product->getFormattedPriceWith(true, $ufactor, Yard::instance('shopping')->getUserCountry()) . " €" . '' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '';
- })
- ->addColumn('price_gross', function (Product $product) use ($user_abo) {
- $ufactor = $user_abo->is_for === 'me' ? true : false;
- return '' . $product->getFormattedPriceWith(false, $ufactor, Yard::instance('shopping')->getUserCountry()) . " €" . '' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '';
- })
- ->addColumn('action', function (Product $product) {
- return '';
- })
- ->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', 'product', 'name', 'quantity', 'picture', 'price_net', 'price_gross', 'action'])
- ->make(true);
- }
-
-
-
- private function checkPermissions($view, $user_abo)
- {
- 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) {
- abort(403, 'Unauthorized action. Is not my abo');
- }
- if ($view === 'ot' && $user_abo->member_id !== \Auth::user()->id) {
- abort(403, 'Unauthorized action. Is not my customer abo');
- }
- }
-}
diff --git a/dev/app-bak/Http/Controllers/User/CustomerController.php b/dev/app-bak/Http/Controllers/User/CustomerController.php
deleted file mode 100755
index b946d01e..00000000
--- a/dev/app-bak/Http/Controllers/User/CustomerController.php
+++ /dev/null
@@ -1,322 +0,0 @@
-middleware('active.account');
- $this->customerRepository = $customerRepository;
-
- }
-
- public function index()
- {
- if(Request::get('reset') === 'filter'){
- // set_user_attr('filter_member_id', null);
- // set_user_attr('filter_customer_member', null);
- return redirect(route('admin_customers'));
- }
- $data = [
-
- ];
- return view('user.customer.index', $data);
- }
-
-
- public function detail($id)
- {
- $shopping_user = ShoppingUser::findOrFail($id);
- if($shopping_user->member_id != \Auth::user()->id){
- abort(404);
- }
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => false,
- 'isView' => 'customer',
- ];
- return view('user.customer.detail', $data);
- }
-
- public function edit($id)
- {
- $shopping_user = ShoppingUser::findOrFail($id);
- if($shopping_user->member_id != \Auth::user()->id){
- abort(404);
- }
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => false,
- 'isView' => 'customer',
-
- ];
- return view('user.customer.edit', $data);
- }
-
- public function add($id, $step=0)
- {
- if($id === "new"){
- $shopping_user = new ShoppingUser();
- $shopping_user->id = "new";
- }else{
- $shopping_user = ShoppingUser::findOrFail($id);
- if($shopping_user->member_id != \Auth::user()->id){
- abort(404);
- }
- }
-
- $billing_email = null;
- if(!session('errors')){
- if(old('email') || old('billing_email')){
- $step = 1;
- $shopping_user->same_as_billing = true;
- $billing_email = old('email');
- }
- if(old('switcher-without-email') === 'true'){
- $step = 1;
- $shopping_user->same_as_billing = true;
- $shopping_user->faker_mail = true;
- $billing_email = time()."-faker@mivita.care";
- }
- }
- $data = [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => false,
- 'isView' => $step === 0 ? 'customer' : 'customer-add',
- 'step' => $step,
- 'billing_email' => $billing_email,
-
- ];
- return view('user.customer.add', $data);
- }
-
- private function checkShoppingUsersEmail($email = 'email', $action = 'return', $id=null){
-
- $rules = array(
- $email => 'required|string|email|max:255|unique:shopping_users,billing_email',
- );
- $messages = [
- 'unique' => __('validation.custom.unique_email_client'),
- ];
- $validator = Validator::make(Request::all(), $rules, $messages);
- if ($validator->fails()) {
- \Session()->flash('alert-error', __('validation.custom.unique_email_client'));
- return back()->withErrors($validator)->withInput(Request::all());
- }
- $rules = array(
- $email => 'required|string|email|max:255|unique:users,email',
- );
- $messages = [
- 'unique' => __('validation.custom.unique_email_member'),
- ];
- $validator = Validator::make(Request::all(), $rules, $messages);
- if ($validator->fails()) {
- \Session()->flash('alert-error', __('validation.custom.unique_email_member'));
- return back()->withErrors($validator)->withInput(Request::all());
- }
- if($action === 'return'){
- return back()->withInput(Request::all());
- }
-
- if($action === 'save'){
- $shopping_user = ShoppingUser::findOrFail($id);
- $shopping_user->faker_mail = false;
- $shopping_user->billing_email = Request::get($email);
- $shopping_user->save();
- return redirect(route('user_customer_detail', [$shopping_user->id]));
- }
- }
-
- public function store($id)
- {
- $data = Request::all();
-
- if($id === 'new' && $data['action'] === 'add_customer_with_email'){
- return $this->checkShoppingUsersEmail('email', 'return');
- }
- if($id === 'new' && $data['action'] === 'add_customer_without_email'){
- return back()->withInput(Request::all());
- }
-
- if($id === 'new' && $data['action'] === ''){
- return back()->withInput(Request::all());
- }
-
- if($id !== 'new' && $data['action'] === 'add-mail-shopping-user-store'){
- return $this->checkShoppingUsersEmail('new_email_address', 'save', $id);
- }
-
- if($data['action'] === 'shopping-user-store-new' || $data['action']==='shopping-user-store'){
- $rules = array(
- 'billing_salutation' => 'required',
- 'billing_firstname'=>'required',
- 'billing_lastname'=>'required',
- 'billing_email'=>'required|email',
- 'billing_address'=>'required',
- 'billing_zipcode'=>'required',
- 'billing_city' => 'required',
- 'billing_country_id' => 'required',
- );
-
- if(!Request::get('same_as_billing')){
- $rules = array_merge($rules, [
- 'shipping_firstname'=>'required',
- 'shipping_lastname'=>'required',
- 'shipping_address'=>'required',
- 'shipping_zipcode'=>'required',
- 'shipping_city' => 'required',
- 'shipping_salutation' => 'required',
- 'shipping_country_id' => 'required'
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
- }
-
- $data['language'] = isset($data['language']) ? $data['language'] : \App::getLocale();
- $data['faker_mail'] = isset($data['faker_mail']) ? true : false;
- $data['has_buyed'] = isset($data['has_buyed']) ? true : false;
- $data['subscribed'] = isset($data['subscribed']) ? true : false;
- //subscribed can only true when has_buyed ist active
- $data['subscribed'] = $data['has_buyed'] ? $data['subscribed'] : false;
-
- $data['same_as_billing'] = isset($data['same_as_billing']) ? true : false;
- $data['shipping_country_id'] = isset($data['shipping_country_id']) ? $data['shipping_country_id'] : $data['billing_country_id'];
-
- if($id > 0 && $data['action'] === 'shopping-user-store'){
- $shopping_user = ShoppingUser::findOrFail($id);
- if($shopping_user->member_id != \Auth::user()->id){
- abort(404);
- }
- CustomerPriority::checkChangeOne($shopping_user, $data, true);
- $shopping_user->fill($data);
- $shopping_user->save();
-
- }
-
- if($id === 'new' && $data['action'] === 'shopping-user-store-new') {
- $shopping_user = ShoppingUser::create($data);
- $shopping_user->member_id = \Auth::user()->id;
- $shopping_user->save();
- CustomerPriority::checkNewOne($shopping_user, true);
- }
- \App\Services\Shop::newUserOrder($shopping_user->number);
-
- if($shopping_user->is_like){
- \Session()->flash('custom-error', __('validation.custom.match_found'));
- }
-
- \Session()->flash('alert-save', true);
- return redirect(route('user_customer_detail', [$shopping_user->id]));
- }
-
-
- private function checkShoppingUsersByEmail(){
-
- //ist an dieser stelle nicht machbar, zu viele Datenbankzugriffe
- //siehe App\Console\Commands\SyncShoppingUserData
- /* $user = User::find(\Auth::user()->id);
- ShoppingUserService::setFakerMail($user);
- ShoppingUserService::syncNumbersByEmail($user);
- ShoppingUserService::syncOrdersByEmail($user); */
-
- }
- public function getCustomers()
- {
- //$this->checkShoppingUsersByEmail();
-
-
- $user = User::find(\Auth::user()->id);
- //\Log::info('Current user ID: ' . $user->id);
-
- $query = ShoppingUser::select(['id', 'billing_company', 'billing_salutation', 'billing_firstname', 'billing_lastname', 'billing_email', 'faker_mail', 'billing_zipcode', 'billing_city', 'billing_country_id', 'orders', 'subscribed', 'created_at', 'number', 'mode', 'is_like', 'wp_order_number'])
- ->with('billing_country')
- ->whereIn('id', function($query) {
- $query->select(DB::raw('MAX(id)'))
- ->from('shopping_users')
- ->groupBy('billing_email');
- })->where('shopping_users.member_id', '=', $user->id)->where('shopping_users.auth_user_id', '=', NULL);
-
- if(Request::get('isfor') === 'ot-member'){ //Bestellung für Kunden
- }
- if(Request::get('isfor') === 'ot-customer' || Request::get('isfor') === 'abo-ot-customer'){ //Bestellung für Kunden Zahlungslink
- $query->where(function($q) {
- $q->where('shopping_users.faker_mail', '!=', 1)
- ->orWhereNull('shopping_users.faker_mail');
- });
- }
- //\Log::info('SQL Query: ' . $query->toSql());
- //\Log::info('Query Bindings: ' . print_r($query->getBindings(), true));
-
- return \DataTables::eloquent($query)
-
- ->addColumn('send_to', function (ShoppingUser $ShoppingUser) {
- $ot = Request::get('isfor') ? Request::get('isfor') : 'ot-member';
- if(Request::get('isfor') === 'abo-ot-customer' && AboHelper::memberHasAbo($ShoppingUser)){
- return ' '.__('abo.abo_assigned').'';
- }
- return $ShoppingUser->is_like ? ' '.__('customer.under_review').'' : ' '.__('customer.select').'';
- })
- ->addColumn('billing_email', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->faker_mail ? "-" : $ShoppingUser->billing_email;
- })
- ->addColumn('id', function (ShoppingUser $ShoppingUser) {
- return '';
- })
- ->addColumn('billing_salutation', function (ShoppingUser $ShoppingUser) {
- return HTMLHelper::getSalutationLang($ShoppingUser->billing_salutation);
- })
- ->addColumn('billing_country_id', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->billing_country ? $ShoppingUser->billing_country->getLocated() : '';
- })
- ->addColumn('first_created_at', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->firstEntryByNumber()->created_at->format('d.m.Y');
- })
- ->addColumn('orders', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->orders;
- })
- ->addColumn('subscribed', function (ShoppingUser $ShoppingUser) {
- return get_active_badge($ShoppingUser->subscribed);
- })
- ->addColumn('status', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->is_like ? ' '.__('customer.under_review').' ' : ' '.__('customer.assigned').'';
- })
- ->addColumn('extras', function (ShoppingUser $ShoppingUser) {
- return $ShoppingUser->wp_order_number.($ShoppingUser->mode==='dev' ? ' dev' : '');
- })
- ->filterColumn('billing_email', function($query, $keyword) {
- if($keyword != ""){
- $query->where('billing_email', 'LIKE', '%'.$keyword.'%');
- }
- })
- ->orderColumn('send_to', 'id $1')
- ->orderColumn('id', 'id $1')
- ->orderColumn('billing_email', 'billing_email $1')
- ->orderColumn('billing_country_id', 'billing_country_id $1')
- ->orderColumn('billing_salutation', 'billing_salutation $1')
- ->orderColumn('first_created_at', 'created_at $1')
- ->orderColumn('orders', 'orders $1')
- ->orderColumn('subscribed', 'subscribed $1')
- ->rawColumns(['send_to', 'id', 'subscribed', 'extras', 'status'])
- ->make(true);
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/DocumentsController.php b/dev/app-bak/Http/Controllers/User/DocumentsController.php
deleted file mode 100644
index 78646057..00000000
--- a/dev/app-bak/Http/Controllers/User/DocumentsController.php
+++ /dev/null
@@ -1,131 +0,0 @@
-middleware('auth');
- $this->fileRepo = $fileRepo;
- }
-
-
- public function index()
- {
- $user = User::find(Auth::user()->id);
-
- $data = [
- 'user' => $user,
- 'business_license_choose' => $user->account->getNotice('business_license'),
- ];
- return view('user.documents.index', $data);
-
- }
-
- public function store($action){
-
-
- $data = Request::all();
- $user = User::findOrFail(Auth::user()->id);
-
- if ($action == 'verification') {
- if(Request::get('submit') === 'do'){
- if(File::whereUserId($user->id)->whereIdentifier('id_card')->count() == 0){
- $validator = Validator::make(Request::all(), []);
- $validator->errors()->add('field', __('msg.no_id_card_deposited_please_upload_first'));
- $user->save();
- return redirect(route('user_documents'))->withErrors($validator)->withInput(Request::all());
- }
- $user->save();
- return redirect(route('user_documents'));
- }
- $this->fileRepo->_set('disk', 'user');
- $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());
- }
-
- if ($action == 'business_license') {
- if(Request::get('submit') === 'do'){
- $data = Request::all();
-
- 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->save();
- return redirect(route('user_documents'))->withErrors($validator)->withInput(Request::all());
- }
- $user->account->setNotice('business_license_reason', '');
-
- }
- if($data['business_license_choose'] === "later"){
- $user->account->setNotice('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->save();
- return redirect(route('user_documents'))->withErrors($validator)->withInput(Request::all());
- }else{
- $user->account->setNotice('business_license_reason', $data['non_business_license_reason']);
- }
- }
- $user->account->setNotice('business_license', $data['business_license_choose']);
- $user->save();
-
- if($user->isTestMode()){
- $mail = config('app.info_test_mail');
- }else{
- $mail = config('app.info_mail');
- }
-
- Mail::to($mail)->locale($user->getLocale())->send(new MailReleaseDocument($user));
-
- return redirect(route('user_documents'));
- }
- $this->fileRepo->_set('disk', 'user');
- $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());
- }
-
- }
-
- public function delete($id, $relation){
-
- if($relation === 'upload'){
- $user = User::findOrFail(Auth::user()->id);
- $file = $user->files()->findOrFail($id);
- //remove file
- \Storage::disk('user')->delete($file->dir.$file->filename);
- $file->delete();
- \Session()->flash('alert-success', __('msg.file_deleted'));
- }
- return back();
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/DownloadController.php b/dev/app-bak/Http/Controllers/User/DownloadController.php
deleted file mode 100644
index 76706385..00000000
--- a/dev/app-bak/Http/Controllers/User/DownloadController.php
+++ /dev/null
@@ -1,145 +0,0 @@
-middleware('active.account');
- }
-
- public function index()
- {
-
- $this->setFilterVars();
- $files = DcFile::where('active', true)->orderBy('id', 'desc')->get(); //File::all();
-
- $filter_list = $this->makeFilterList();
- $data = [
- 'files' => $files,
- 'filter_list' => $filter_list,
- 'tag_ids' => array(),
- 'resTagIds' => array(),
- 'search' => false,
-
- ];
-
- return view('user.downloadcenter.index', $data);
- }
-
- public function search(){
-
- $request = Request::all();
-
-
- if(Request::ajax()){
-
- $request['tagIds'] = isset($request['tagIds']) ? $request['tagIds'] : array();
- $request['searchinput'] = isset($request['searchinput']) ? $request['searchinput'] : "";
- $tag_ids = $request['tagIds'];
- $searchTags = [];
- foreach ($tag_ids as $tags) {
- if($tags != "" && $tags != "0"){
- if(is_array($tags)){
- foreach ($tags as $tag) {
- array_push($searchTags, $tag);
- }
- }else{
- array_push($searchTags, $tags);
- }
- }
- }
- $q = DcFile::with('fileTag')->where('active', 1);
- if($request['searchinput'] != ""){
- $q->where('original_name', 'LIKE', '%'.$request['searchinput'].'%');
- }
- if(count($searchTags) > 0){
- $q->whereHas('fileTag', function ($query) use ($searchTags){
- $query->whereIn('tag_id', $searchTags);
- });
- }
-
- $files = $q->orderBy('id', 'desc')->get();
- $returnContentFiles = view('user.downloadcenter.content-files')->with('files', $files)->render();
- /* if(strlen($files) < 1){
- $returnContentFiles = "Keine Einträge vorhanden";
- }*/
- /*
- $resTagIds = array();
- foreach ($files as $file) {
- foreach ($file->fileTag as $tagId) {
- if(empty($resTagIds[$tagId->tag_id])){
- $resTagIds[$tagId->tag_id] = 1;
- }else{
- $resTagIds[$tagId->tag_id]++;
- }
-
- }
- }
-
- $categories = DcCategory::orderBy('pos')->get();
- $data = [
- 'categories' => $categories,
- 'tag_ids' => $tag_ids,
- 'resTagIds' => $resTagIds,
- 'search' => true,
- ];
- $returnFilters = view('content-collapse')->with('data', $data)->render();
- */
- $returnFilters = "";
- return response()->json( array('success' => true, 'request' => $request, 'searchTags' => $searchTags, 'content_files'=>$returnContentFiles, 'content_filter'=>$returnFilters) );
- }
- return false;
-
- }
-
- private function setFilterVars(){
-
-
- /* if(!session('user_shop_api_orders_filter')){
- session(['user_shop_api_orders_filter' => 1]);
- }
- if(Request::get('user_shop_api_orders_filter')){
- session(['user_shop_api_orders_filter' => Request::get('user_shop_api_orders_filter')]);
- }
- */
- }
- private function makeFilterList($archive = false, $request = true)
- {
- $ret = [];
- $categories = DcCategory::where('active', true)->orderBy('pos')->get();
- foreach($categories as $category){
- $tags = DcTag::where('category_id', $category->id)->where('active', true)->orderBy('pos')->get();
- $items = [];
- foreach ($tags as $tag){
- //has file tags
- $count = DcFileTag::with('dc_file')->where('tag_id', $tag->id)->whereHas('dc_file', function ($query){
- $query->where('active', true);
- })->count();
- if($count > 0){
- $tag->count = $count;
- $items[] = $tag;
- }
- }
- if(isset($items) && count($items) > 0){
- $ret[$category->id]['items'] = $items;
- $ret[$category->id]['name'] = $category->name;
- }
- }
-
-
- return $ret;
- }
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/HomepartyController.php b/dev/app-bak/Http/Controllers/User/HomepartyController.php
deleted file mode 100755
index a349a063..00000000
--- a/dev/app-bak/Http/Controllers/User/HomepartyController.php
+++ /dev/null
@@ -1,654 +0,0 @@
-middleware('active.account');
- }
-
- public function index()
- {
- $data = [
- 'homepartys' => Homeparty::where('auth_user_id', '=', \Auth::user()->id)->orderByDesc('id')->get(),
- ];
- return view('user.homeparty.index', $data);
- }
-
- public function detail($id, $step = false)
- {
- if($id === 'new'){
- $homeparty = new Homeparty();
- $homeparty->id = 0;
- $step = 1;
- }else{
- $homeparty = $this->getHomparty($id);
- if($homeparty->step < 10){
- $step = $homeparty->step;
- }else{
- if(!$step){
- $step = 10;
- }
- }
- }
- if($homeparty->homeparty_host){
- $homeparty_user = $homeparty->homeparty_host;
- }else{
- $homeparty_user = new HomepartyUser();
- $homeparty_user->is_host = true;
- }
-
- if($homeparty->completed){
- abort(404);
- }
-
- $data = [
- 'homeparty' => $homeparty,
- 'homeparty_user' => $homeparty_user,
- 'step' => $step,
-
- ];
- return view('user.homeparty.detail', $data);
- }
-
- public function store($id = null, $step = false)
- {
- $data = Request::all();
-
- if($data['action'] === 'homeparty-party-store-detail'){
- $rules = array(
- 'date' => 'required',
- 'name' => 'required',
- 'place' => 'required',
- );
- if(!$id){
- $rules = array(
- 'date' => 'required',
- 'name' => 'required',
- 'place' => 'required',
- 'country_id' => 'required'
- );
- }
- }
- if($data['action'] === 'homeparty-party-store-address'){
- $rules = array(
- 'shipping_firstname' => 'required',
- 'shipping_lastname' => 'required',
- 'shipping_address' => 'required',
- 'shipping_zipcode' => 'required',
- 'shipping_city' => 'required',
- 'shipping_salutation' => 'required',
- 'shipping_country_id' => 'required'
- );
- }
-
- if($data['action'] === 'homeparty-party-store-host'){
- $rules = array(
- 'billing_salutation' => 'required',
- 'billing_firstname' => 'required',
- 'billing_lastname' => 'required',
- 'billing_address' => 'required',
- 'billing_zipcode' => 'required',
- 'billing_city' => 'required',
- 'billing_country_id' => 'required',
- );
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- if($data['action'] === 'homeparty-party-store-detail'){
- if(!$id){
- //first save create and empty user/host
- do {
- $token = Util::uuidToken();
- } while( Homeparty::where('token', $token)->count() );
- $data['token'] = $token;
- $data['auth_user_id'] = \Auth::user()->id;
- $data['step'] = 2;
- $step = 2;
- $homeparty = Homeparty::create($data);
- $this->storeTranslations($homeparty, \App::getLocale(), $data);
- $homeparty_user = HomepartyUser::create([
- 'homeparty_id' => $homeparty->id,
- 'auth_user_id' => \Auth::user()->id,
- 'shipping_country_id' => $homeparty->country_id,
- 'billing_country_id' => $homeparty->country_id,
- 'same_as_billing' => false,
- 'is_host' => true,
- ]);
- }else {
- $homeparty = $this->getHomparty($id);
- $homeparty->fill($data)->save();
- $this->storeTranslations($homeparty, \App::getLocale(), $data);
- $step = 10;
- }
- }
- if($data['action'] === 'homeparty-party-store-address'){
- $homeparty = $this->getHomparty($id);
- $homeparty_user = $homeparty->homeparty_host;
- $homeparty_user->fill($data)->save();
- if($homeparty->step === 2){
- $homeparty->step = 3;
- $homeparty->save();
- $step = 3;
- }else{
- $step = 12;
- }
- }
-
- if($data['action'] === 'homeparty-party-store-host'){
- $homeparty = $this->getHomparty($id);
- $homeparty_user = $homeparty->homeparty_host;
- $homeparty_user->fill($data)->save();
- if($homeparty->step === 3){
- $homeparty->step = 10;
- $homeparty->save();
- $step = 10;
- }else{
- $step = 13;
- }
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('user_homeparty_detail', [$homeparty->id, $step]));
- }
-
- private function storeTranslations($homeparty, $lang, $data){
-
- if($lang == 'de'){
- $homeparty->description = $data['description'];
- $homeparty->save();
- return;
- }
- $trans = $homeparty->trans_description;
- $trans[$lang] = $data['description'];
- $homeparty->trans_description = $trans;
- $homeparty->save();
- return;
- }
-
-
- public function guests($id = null)
- {
- $homeparty = $this->getHomparty($id);
- $data = [
- 'homeparty' => $homeparty,
- ];
- return view('user.homeparty.guests', $data);
- }
-
-
- public function guestDetail($id = null, $gid = null)
- {
- $homeparty = $this->getHomparty($id);
- if($gid === 'new'){
- $homeparty_user = new HomepartyUser();
- $homeparty_user->same_as_billing = true;
- $homeparty_user->billing_country_id = $homeparty->country_id;
- $homeparty_user->shipping_country_id = $homeparty->country_id;
- }else{
- $homeparty_user = HomepartyUser::findOrFail($gid);
- if($homeparty->id !== $homeparty_user->homeparty_id){
- abort(404);
- }
- }
- if($homeparty->completed){
- abort(404);
- }
- $data = [
- 'homeparty' => $homeparty,
- 'homeparty_user' => $homeparty_user,
- ];
- return view('user.homeparty.guest_detail', $data);
- }
-
- public function guestStore($id = null, $gid = null)
- {
- $data = Request::all();
- $rules = array(
- 'billing_salutation' => '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')) {
- $rules = array_merge($rules, [
- 'shipping_firstname' => 'required',
- 'shipping_lastname' => 'required',
- 'shipping_address' => 'required',
- 'shipping_zipcode' => 'required',
- 'shipping_city' => 'required',
- 'shipping_salutation' => 'required',
- 'shipping_country_id' => 'required'
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- $homeparty = $this->getHomparty($id);
- if($gid === null){
- $homeparty_user = HomepartyUser::create([
- 'homeparty_id' => $homeparty->id,
- 'auth_user_id' => \Auth::user()->id,
- 'is_host' => false,
- ]);
- }else{
- $homeparty_user = HomepartyUser::findOrFail($gid);
- }
- if($homeparty->id !== $homeparty_user->homeparty_id){
- abort(404);
- }
- $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'];
- $homeparty_user->fill($data)->save();
- \Session()->flash('alert-save', '1');
- return redirect(route('user_homeparty_guests', [$homeparty->id]));
- }
-
-
- public function order($id = null)
- {
- $user = User::find(Auth::user()->id);
- $homeparty = $this->getHomparty($id);
- $shipping_country_id = $this->checkShoppingCountry($homeparty->country_id);
- if(!$shipping_country_id){
- \Session()->flash('custom-error', __('validation.custom.shipping_not_found'));
- return redirect(route('user_homepartys'));
- }
- UserService::checkUserTaxShippingCountry($user, $shipping_country_id);
- if($this->userChangeCountry($homeparty)){
- \Session()->flash('custom-error', __('msg.country_account_has_been_changed__cost_has_been_reset'));
- return redirect(route('user_homeparty_order', [$homeparty->id]));
- }
- HomepartyCart::calculateHomeparty($homeparty);
- $homeparty->card_info = UserService::getYardInfo();
- $homeparty->save();
- $userHistoryPaymentOrder = UserHistory::whereUserId($user->id)->whereAction('payment_homeparty')->where('referenz', $homeparty->id)->get()->last();
- $data = [
- 'homeparty' => $homeparty,
- 'userHistoryPaymentOrder' => $userHistoryPaymentOrder,
- ];
- return view('user.homeparty.order', $data);
- }
-
- private function userChangeCountry($homeparty){
- if(isset($homeparty->card_info['user_country_id'])){
- if($homeparty->card_info['user_country_id'] !== UserService::$user_country->id){
- // es wurde schon eine order angelegt, aber das Rechungsland geändert
- if($homeparty->homeparty_order_items->count()){
- foreach($homeparty->homeparty_order_items as $homeparty_order_item){
- $homeparty_order_item->delete();
- }
- return true;
- }
- }
- }
- return false;
- }
-
- private function checkShoppingCountry($country_id){
- if($country_id){
- if($shipping_country = ShippingCountry::whereCountryId($country_id)->first()){
- return $shipping_country->id;
- }
- }
- return false;
- }
-
- //perform Request
- public function orderStore($id = null)
- {
- $homeparty = $this->getHomparty($id);
-
- if(Request::ajax()) {
- $data = Request::all();
-
- if($data['action'] === 'addProduct') {
- if($data['homeparty_id'] == $homeparty->id){
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- if($homeparty_user->homeparty_id !== $homeparty->id){
- abort(404);
- }
- if($product = Product::find($data['product_id'])){
- $margin = 0;
- if(\Auth::user() && \Auth::user()->user_level){
- $margin = \Auth::user()->user_level->margin;
- }
- $HomepartyUserOrderItem = HomepartyUserOrderItem::where('homeparty_user_id', $homeparty_user->id)->where('product_id', $product->id)->first();
- if($HomepartyUserOrderItem){
- $HomepartyUserOrderItem->qty = $HomepartyUserOrderItem->qty+1;
- $HomepartyUserOrderItem->save();
- }else{
- if($homeparty->getCardInfo('user_tax_free')){
- $HomepartyUserOrderItem = HomepartyUserOrderItem::create([
- 'homeparty_id' => $homeparty->id,
- 'homeparty_user_id' => $homeparty_user->id,
- 'product_id' => $product->id,
- 'qty' => 1,
- 'price' => $product->getPriceWith(true, false, $homeparty->getUserCountry()),
- 'price_net' => $product->getPriceWith(true, false, $homeparty->getUserCountry()),
- 'tax_rate' => 0,
- 'points' => $product->points,
- 'margin' => $margin,
- 'ek_price' => $product->getPriceWith(true, true, $homeparty->getUserCountry()),
- 'ek_price_net' => $product->getPriceWith(true, true, $homeparty->getUserCountry()),
- 'slug' => $product->slug
- ]);
- }else{
- $HomepartyUserOrderItem = HomepartyUserOrderItem::create([
- 'homeparty_id' => $homeparty->id,
- 'homeparty_user_id' => $homeparty_user->id,
- 'product_id' => $product->id,
- 'qty' => 1,
- 'price' => $product->getPriceWith(false, false, $homeparty->getUserCountry()),
- 'price_net' => $product->getPriceWith(true, false, $homeparty->getUserCountry()),
- 'tax_rate' => $product->getTaxWith($homeparty->getUserCountry()),
- 'points' => $product->points,
- 'margin' => $margin,
- 'ek_price' => $product->getPriceWith(false, true, $homeparty->getUserCountry()),
- 'ek_price_net' => $product->getPriceWith(true, true, $homeparty->getUserCountry()),
- 'slug' => $product->slug
- ]);
- }
- }
-
- }
-
- }
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- HomepartyCart::calculateHomeparty($homeparty);
- $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
- $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
- $html_host_bonus = view("user.homeparty.show_calc_bonus_host", ['homeparty' => $homeparty])->render();
- $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
- return response()->json(['response' => true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
- }
-
- if($data['action'] === 'updateCart') {
- if($data['homeparty_id'] == $homeparty->id){
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- if($homeparty_user->homeparty_id !== $homeparty->id){
- abort(404);
- }
- if(isset($data['product_id']) && $product = Product::find($data['product_id'])){
- if(isset($data['order_item_id']) && $HomepartyUserOrderItem = HomepartyUserOrderItem::find($data['order_item_id'])){
- if(isset($data['qty'])){
- $qty = (int) $data['qty'];
- $qty = $qty < 1 ? 1 : $qty;
- $qty = $qty > 100 ? 100 : $qty;
- $HomepartyUserOrderItem->qty = $qty;
- $HomepartyUserOrderItem->save();
- }
- }
- }
- }
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- HomepartyCart::calculateHomeparty($homeparty);
- $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
- $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
- $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
- $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
- return response()->json(['response' => true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
- }
-
- if($data['action'] === 'removeFromCart') {
- if($data['homeparty_id'] == $homeparty->id){
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- if($homeparty_user->homeparty_id !== $homeparty->id){
- abort(404);
- }
- if(isset($data['product_id']) && $product = Product::find($data['product_id'])){
- if(isset($data['order_item_id']) && $HomepartyUserOrderItem = HomepartyUserOrderItem::find($data['order_item_id'])){
- $HomepartyUserOrderItem->delete();
- }
- }
- }
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- HomepartyCart::calculateHomeparty($homeparty);
- $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
- $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
- $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
- $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
- return response()->json(['response' => true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
- }
-
- if($data['action'] === 'updateDeliveryOption') {
- if($data['homeparty_id'] == $homeparty->id){
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- if($homeparty_user->homeparty_id !== $homeparty->id){
- abort(404);
- }
- if(isset($data['delivery'])){
- $homeparty_user->delivery = $data['delivery'];
- $homeparty_user->save();
- }
- }
- $homeparty_user = HomepartyUser::findOrFail($data['homeparty_user_id']);
- HomepartyCart::calculateHomeparty($homeparty);
- $html_user_cart = view("user.homeparty.show_products_order", ['homeparty' => $homeparty, 'homeparty_guest' => $homeparty_user])->render();
- $html_bonus = view("user.homeparty.show_bonus", ['homeparty' => $homeparty])->render();
- $html_host_bonus = view("user.homeparty.show_calc_bonus_host")->render();
- $html_total = view("user.homeparty.show_total_order", ['homeparty' => $homeparty])->render();
- return response()->json(['response' => true, 'data'=>$data, 'html_user_cart'=>$html_user_cart, 'html_bonus'=>$html_bonus, 'html_host_bonus'=>$html_host_bonus, 'html_total'=>$html_total]);
- }
-
-
- return response()->json(['response' => false, 'data'=>$data]);
- }
-
- HomepartyCart::calculateHomeparty($homeparty);
- if(\App\Services\HomepartyCart::$price === 0){
- \Session()->flash('alert-error', __('msg.your_shopping_cart_is_empty_please_add_products_first'));
- return redirect(route('user_homeparty_order', [$homeparty->id]));
- }
-
- //save the calucalte card!
- $time = time();
- $date = date('d.m.Y H:i:s', $time);
- $user = User::find(Auth::user()->id);
- Yard::instance('shopping')->destroy();
- $cartItem = Yard::instance('shopping')->add($homeparty->id, 'Bestellung Homeparty '.$date, 1, \App\Services\HomepartyCart::$ek_price, false, false, ['image' => "", 'slug' => $time, 'weight' => 0]);
- Yard::setTax($cartItem->rowId, 0);
- do {
- $identifier = Util::getToken();
- } while( ShoppingInstance::where('identifier', $identifier)->count() );
-
- HomepartyCart::store($identifier, $date);
-
- $data = [];
- $data['is_from'] = 'homeparty';
-
- if($homeparty->getCardInfo('user_tax_free')){
- $data['shop_price'] = HomepartyCart::getFormattedEkPrice();
- $data['shop_price_net'] = HomepartyCart::getFormattedEkPrice();
- $data['shop_price_tax'] = 0;
- $data['user_tax_free'] = true;
- }else{
- $data['shop_price'] = HomepartyCart::getFormattedEkPrice();
- $data['shop_price_net'] = HomepartyCart::getFormattedEkPriceNet();
- $data['shop_price_tax'] = HomepartyCart::getFormattedEkPriceTax();
- $data['user_tax_free'] = false;
- }
-
- $data['homeparty_id'] = $homeparty->id;
- $data['is_for'] = 'hp';
- $data['user_price_infos'] = $homeparty->card_info;
-
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => 1, //is first faker shop for nuy intern
- 'auth_user_id' => Auth::user()->id,
- 'payment' => 5, //Berater Homeparty
- 'subdomain' => url('/'),
- 'country_id' => Yard::instance('shopping')->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'shopping_data' => $data,
- 'back' => url()->previous(),
-
- ]);
-
- HomepartyCart::store($identifier, $date);
- Yard::instance('shopping')->store($identifier);
-
- $path = route('checkout.checkout_card', ['identifier'=>$identifier]);
- UserHistory::create(['user_id' => $user->id, 'action'=>'payment_homeparty', 'status'=>1, 'referenz'=>$homeparty->id, 'identifier'=>$identifier]);
- //$path = str_replace('http', 'https', $path);
- return redirect()->secure($path);
- }
-
-
- public function delete($do, $id = null, $gid=null)
- {
- $homeparty = $this->getHomparty($id);
-
- if($do === 'hpu'){
- $homeparty_user = HomepartyUser::findOrFail($gid);
- if($homeparty->id !== $homeparty_user->homeparty_id){
- abort(404);
- }
- if($homeparty_user->homeparty_user_order_items){
- foreach($homeparty_user->homeparty_user_order_items as $homeparty_user_order_item){
- $homeparty_user_order_item->delete();
- }
- }
- //$homeparty_user->save();
- $homeparty_user->delete();
- \Session()->flash('alert-success', __('msg.homeparty_guest_delete'));
- return redirect(route('user_homeparty_guests', [$homeparty->id]));
-
- }
- if($do === 'hp') {
-
- foreach ($homeparty->homeparty_users as $homeparty_user){
- if ($homeparty->id !== $homeparty_user->homeparty_id) {
- abort(404);
- }
- if($homeparty_user->homeparty_user_order_items){
- foreach($homeparty_user->homeparty_user_order_items as $homeparty_user_order_item){
- $homeparty_user_order_item->delete();
- }
- }
- $homeparty_user->delete();
- }
- if($homeparty->homeparty_order_items){
- foreach($homeparty->homeparty_order_items as $homeparty_order_item){
- $homeparty_order_item->delete();
- }
- }
- $homeparty->delete();
- \Session()->flash('alert-success', __('msg.homeparty_delete'));
- return redirect(route('user_homepartys'));
-
- }
- abort(404);
- }
-
- private function getHomparty($id){
- $homeparty = Homeparty::findOrFail($id);
- if($homeparty->auth_user_id !== \Auth::user()->id){
- abort(404);
- }
- return $homeparty;
- }
-
- public function datatable($homeparty_id){
-
- $query = Product::select('products.*')->where('active', true)->whereJsonContains('show_on', '4');
- $homeparty = Homeparty::findOrFail($homeparty_id);
-
- return \DataTables::eloquent($query)
-
- ->addColumn('add_card', function (Product $product) use ($homeparty) {
- if($homeparty->getCardInfo('user_tax_free')){
- return '';
- }else{
- return '';
- }
-
- })
- ->addColumn('picture', function (Product $product) {
- if(count($product->images)){
- return '
';
- }
- return "";
- })
- /*->addColumn('price_net', function (Product $product) use ($homeparty) {
- return ''.$product->getFormattedPriceWith(true, true, $homeparty->getUserCountry()). " €".
- ''.$product->getFormattedPriceCurrencyWith(true, true, $homeparty->getUserCountry()).'';
- })
- */
- ->addColumn('price_gross', function (Product $product) use ($homeparty) {
- if($homeparty->getCardInfo('user_tax_free')){
- return ''.$product->getFormattedPriceWith(true, true, $homeparty->getUserCountry()). " €".
- ''.$product->getFormattedPriceCurrencyWith(true, true, $homeparty->getUserCountry()).'';
- }else{
- return ''.$product->getFormattedPriceWith(false, true, $homeparty->getUserCountry()). " €".
- ''.$product->getFormattedPriceCurrencyWith(false, true, $homeparty->getUserCountry()).'';
- }
- })
- ->addColumn('price_vk_gross', function (Product $product) use ($homeparty) {
- if($homeparty->getCardInfo('user_tax_free')){
- return ''.$product->getFormattedPriceWith(true, false, $homeparty->getUserCountry()). " €".
- ''.$product->getFormattedPriceCurrencyWith(true, false, $homeparty->getUserCountry()).'';
- }else{
- return ''.$product->getFormattedPriceWith(false, false, $homeparty->getUserCountry()). " €".
- ''.$product->getFormattedPriceCurrencyWith(false, false, $homeparty->getUserCountry()).'';
- }
- })
- ->addColumn('action', function (Product $product) {
- return '';
- })
- ->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('price_vk_gross', 'price $1')
- ->orderColumn('contents_total', 'contents_total $1')
- ->orderColumn('weight', 'weight $1')
-
- ->rawColumns(['add_card', 'product', 'quantity', 'picture', 'price_net', 'price_gross', 'price_vk_gross', 'action'])
- ->make(true);
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/MembershipController.php b/dev/app-bak/Http/Controllers/User/MembershipController.php
deleted file mode 100755
index 40dd1f3a..00000000
--- a/dev/app-bak/Http/Controllers/User/MembershipController.php
+++ /dev/null
@@ -1,240 +0,0 @@
-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;
- }
-
- $userShoppingOrders = ShoppingOrder::with('shopping_user', 'shopping_payments')->select('shopping_orders.*')
- ->where('auth_user_id', '=', $user->id)
- ->where('txaction', '!=', NULL)
- ->whereIn('payment_for', [1, 2])
- ->orderBy('created_at', 'DESC')
- ->get();
-
- $userHistoryPaymentOrder = null;
- $userHistoryUpgradeOrder = null;
-
- /* 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->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');
- $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');
- $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){
- 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(),
- 'upgrade' => Product::where('active', true)->whereJsonContains('show_on', '8')->where('identifier', 'upgrade')->get(),
- 'diff_months' => $diff_months,
- 'userHistoryPaymentOrder' => $userHistoryPaymentOrder,
- 'userHistoryUpgradeOrder' => $userHistoryUpgradeOrder,
- 'userHistoryDeleteMembership' => $userHistoryDeleteMembership,
- 'yard_info' => UserService::getYardInfo(),
- 'userShoppingOrders' => $userShoppingOrders,
- ];
- return view('user.membership.index', $data);
-
- }
-
- private function checkShoppingCountry($user ){
-
- $country_id = null;
- if($user->account->same_as_billing){
- $country_id = $user->account->country_id;
- }else{
- $country_id = $user->account->shipping_country_id;
- }
- if($country_id){
- if($shipping_country = ShippingCountry::whereCountryId($country_id)->first()){
- return $shipping_country->id;
- }
- }
- return false;
- }
-
- public function storePayment($action){
-
-
- $data = Request::all();
-
- //#### 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]);
- \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')){
- $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
- $user->save();
- }
-
- $shipping_country_id = $this->checkShoppingCountry($user);
- 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()){
- $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()){
- 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() );
-
- $data = [];
- $data['is_from'] = 'membership';
- $data['is_for'] = 'me';
- $data['user_price_infos'] = \App\Services\UserService::getUserPriceInfos();
-
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => 1, //is first faker shop for nuy intern
- 'auth_user_id' => Auth::user()->id,
- 'payment' => 3, //Berater Membership
- 'subdomain' => url('/'),
- 'country_id' => Yard::instance('shopping')->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'shopping_data' => $data,
- 'back' => url()->previous(),
-
- ]);
- 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);
- return redirect()->secure($path);
- }
- }
- }
-
- 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){
- \Session()->flash('alert-success', __('msg.no_change_made'));
- return back();
- }
- 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]);
- \Session()->flash('alert-success', __('msg.booked_package_has_been_changed'));
- return back();
-
- }
- }
- }
- if($action === "delete_membership"){
- if(Request::get('delete_membership_mivita')){
- //TODO
- $user = User::find(Auth::user()->id);
- if($user->isTestMode()){
- $mail = config('app.info_test_mail');
- }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]);
- \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();
-
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/OrderController.php b/dev/app-bak/Http/Controllers/User/OrderController.php
deleted file mode 100755
index c47a89e7..00000000
--- a/dev/app-bak/Http/Controllers/User/OrderController.php
+++ /dev/null
@@ -1,965 +0,0 @@
-middleware('active.account');
- }
-
- public function index()
- {
- return view('user.order.index');
- }
-
- public function detail($id)
- {
- $user = User::find(Auth::user()->id);
- $shopping_order = ShoppingOrder::findOrFail($id);
-
- if ($shopping_order->auth_user_id !== $user->id) {
- Log::channel(self::LOG_CHANNEL)->warning("Unauthorized access attempt to order #{$id} by user #{$user->id}");
- abort(404);
- }
-
- if ($shopping_order->payment_for === 6 || $shopping_order->payment_for === 7) {
- Log::channel(self::LOG_CHANNEL)->info("Redirecting user #{$user->id} to customer order detail for order #{$id}");
- return redirect(route('user_shop_order_detail', [$shopping_order->id]));
- }
-
- $shopping_order->getLastShoppingPayment();
-
- return view('user.order.detail', [
- 'shopping_order' => $shopping_order,
- 'isAdmin' => false,
- ]);
- }
-
- public function ordersDatatable()
- {
- $user = User::find(Auth::user()->id);
- $query = ShoppingOrder::with('shopping_user', 'shopping_payments')
- ->select('shopping_orders.*')
- ->where('auth_user_id', '=', $user->id)
- ->where('txaction', '!=', NULL);
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getShoppingOrderBadge($ShoppingOrder);
- })
- ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getFormattedTotalShipping()." €";
- })
- ->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
- })
- ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
- if ($ShoppingOrder->payment_for === 8) {
- return '';
- }
- return ''.$ShoppingOrder->getShippedType().'';
- })
- ->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getPaymentForBadge($ShoppingOrder);
- })
- ->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->isInvoice() ? '
- ' : '-';
- })
- ->addColumn('reference', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->getLastShoppingPayment('reference');
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('shipped', 'shipped $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
- ->orderColumn('payment_for', 'payment_for $1')
- ->rawColumns(['id', 'txaction', 'payment_for', 'total_shipping', 'invoice', 'shipped'])
- ->make(true);
- }
-
- /*
- $for = me, ot-member, ot-customer, abo-ot-member, abo-ot-customer, abo-me
- */
- public function delivery($for, $id = null)
- {
- $user = User::find(Auth::user()->id);
- $shopping_user = null;
- $delivery_id = null;
-
- if (strpos($for, 'ot') !== false) {
- $shopping_user = Shop::checkShoppingUser($id, $user);
- $delivery_id = $shopping_user->id;
-
- 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'));
- 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]));
- }
-
- if ($for === 'abo-ot-customer') {
- 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]));
- Log::channel(self::LOG_CHANNEL)->info("User #{$user->id} attempted to create abo for email that already has one: {$shopping_user->billing_email}");
- return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
- }
- }
- }
-
- if (Request::get('action') === 'next') {
- Yard::instance('shopping')->destroy();
- 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]));
- }
-
- return view('user.order.delivery', [
- 'shopping_user' => $shopping_user,
- 'isAdmin' => false,
- 'isView' => 'customer',
- 'for' => $for,
- 'delivery_id' => $delivery_id,
- ]);
- }
-
- public function list($for, $id = null)
- {
- $user = User::find(Auth::user()->id);
-
- if ($for === 'abo-me' && AboHelper::userHasAbo($user)) {
- Log::channel(self::LOG_CHANNEL)->warning("User #{$user->id} attempted to create abo but already has one");
- abort(403, 'User has an Abo. Cannot order.');
- }
-
- $shopping_user = null;
- $delivery_id = null;
-
- if (strpos($for, 'ot') !== false) {
- $shopping_user = Shop::checkShoppingUser($id, $user);
- $delivery_id = $shopping_user->id;
- }
-
- if ($for === 'ot-customer' || $for === 'abo-ot-customer') {
- UserService::initCustomerYard($shopping_user, $for);
- } else {
- $shipping_country_id = Shop::checkShoppingCountry($for, $id);
- if (!$shipping_country_id) {
- $country = Shop::getDeliveryCountry($for, $id);
- \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);
- }
-
- return view('user.order.list', [
- 'shopping_user' => $shopping_user,
- 'user' => $user,
- 'isAdmin' => false,
- 'isView' => 'customer',
- 'for' => $for,
- 'template' => str_replace('abo-', '', $for),
- 'delivery_id' => $delivery_id,
- 'is_abo' => strpos($for, 'abo') !== false,
- 'comp_products' => Shop::getCompProducts($for),
- ]);
- }
-
- public function payment($for, $id = null)
- {
- $data = Request::all();
- $user = User::find(Auth::user()->id);
-
- $rules = [
- 'shipping_salutation' => 'required',
- 'shipping_firstname' => 'required',
- 'shipping_lastname' => 'required',
- 'shipping_address' => 'required',
- 'shipping_zipcode' => 'required',
- 'shipping_city' => 'required',
- 'shipping_state' => 'required',
- ];
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
- Log::channel(self::LOG_CHANNEL)->info("Validation failed for payment form", ['errors' => $validator->errors()->toArray()]);
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- try {
- $this->checkSendYardForPayment($data, $id);
- } catch (\Exception $e) {
- Log::channel(self::LOG_CHANNEL)->error("Error checking yard for payment: " . $e->getMessage(), [
- 'user_id' => $user->id,
- 'for' => $for,
- 'id' => $id
- ]);
- return back()->with('error', $e->getMessage());
- }
-
- if (Yard::instance('shopping')->getNumComp() > 0) {
- if (!isset($data['switchers-comp-product'])) {
- $validator->errors()->add('switchers-comp-product', __('msg.please_select_compensation_product'));
- Log::channel(self::LOG_CHANNEL)->info("Compensation product not selected");
- } else if (!is_array($data['switchers-comp-product'])) {
- $validator->errors()->add('switchers-comp-product', __('msg.please_select_compensation_product'));
- Log::channel(self::LOG_CHANNEL)->info("Compensation product selection is not an array");
- } else if (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()]));
- Log::channel(self::LOG_CHANNEL)->info("Incorrect number of compensation products selected", [
- 'required' => Yard::instance('shopping')->getNumComp(),
- 'selected' => count($data['switchers-comp-product'])
- ]);
- }
-
- if ($validator->errors()->count()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
- }
-
- // Generate unique identifier
- do {
- $identifier = Util::getToken();
- } while (ShoppingInstance::where('identifier', $identifier)->count());
-
- // Prepare common data
- $data['is_from'] = 'user_order';
- $data['is_for'] = $for;
- $data['is_abo'] = $data['is_abo'] ?? 0;
- $data['abo_interval'] = $data['abo_interval'] ?? 0;
- $data['shopping_user_id'] = $id;
- $data['user_price_infos'] = Yard::instance('shopping')->getUserPriceInfos();
- $data['mode'] = config('app.mode') === 'test' ? 'test' : 'live';
-
- // Remove unnecessary data
- unset($data['quantity']);
- unset($data['_token']);
-
- Log::channel(self::LOG_CHANNEL)->info("Processing payment for user #{$user->id}", [
- 'for' => $for,
- 'identifier' => $identifier,
- 'is_abo' => $data['is_abo']
- ]);
-
- if ($for === 'ot-customer' || $for === 'abo-ot-customer') {
- return $this->processCustomerPayment($user, $identifier, $data, $id, $for);
- } else {
- return $this->processUserPayment($user, $identifier, $data, $id, $for);
- }
- }
-
- /**
- * Process payment for customer orders
- */
- private function processCustomerPayment($user, $identifier, $data, $id, $for)
- {
- $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(),
- 'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
- 'status' => 0,
- 'shopping_user_id' => $id,
- 'shopping_data' => $data,
- 'back' => url()->previous(),
- ]);
-
- Yard::instance('shopping')->store($identifier);
- $yard_shopping_items = OrderPaymentService::getRestoredYardShoppingItems($shopping_instance);
-
- // Send Mail to Customer
- try {
- $this->customPaymentSendMail($user, $identifier, $yard_shopping_items, $data);
- Log::channel(self::LOG_CHANNEL)->info("Custom payment email sent successfully", [
- 'identifier' => $identifier,
- 'user_id' => $user->id
- ]);
- } catch (\Exception $e) {
- Log::channel(self::LOG_CHANNEL)->error("Failed to send custom payment email: " . $e->getMessage(), [
- 'identifier' => $identifier,
- 'user_id' => $user->id
- ]);
- }
-
- UserHistory::create([
- 'user_id' => $user->id,
- 'action' => 'user_order_customer',
- 'status' => 1,
- 'product_id' => null,
- 'identifier' => $identifier,
- 'is_abo' => $data['is_abo']
- ]);
-
- return redirect(route('user_order_my_custom_payment', ['identifier' => $identifier]));
- }
-
- /**
- * Process payment for user orders
- */
- private function processUserPayment($user, $identifier, $data, $id, $for)
- {
- Shop::deleteCheckoutInstance();
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => 1, // is first faker shop for buy intern
- 'auth_user_id' => Auth::user()->id,
- 'payment' => 2, // Berater Shop
- 'subdomain' => url('/'),
- 'country_id' => Yard::instance('shopping')->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
- 'status' => 0,
- 'shopping_user_id' => $id,
- 'shopping_data' => $data,
- 'back' => url()->previous(),
- ]);
-
- Yard::instance('shopping')->store($identifier);
-
- UserHistory::create([
- 'user_id' => $user->id,
- 'action' => 'user_order_payment',
- 'status' => 1,
- 'product_id' => null,
- 'identifier' => $identifier,
- 'is_abo' => $data['is_abo']
- ]);
-
- $path = route('checkout.checkout_card', ['identifier' => $identifier]);
- return redirect()->secure($path);
- }
-
- /**
- * Validate the yard before payment
- */
- private function checkSendYardForPayment($data, $id)
- {
- $user = User::find(Auth::user()->id);
- $shopping_user = null;
-
- if (strpos($data['shipping_is_for'], 'ot') !== false) {
- $shopping_user = Shop::checkShoppingUser($id, $user);
- }
-
- $shipping_country_id = Shop::checkShoppingCountry($data['shipping_is_for'], $id);
- 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
- ];
-
- 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);
- 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()
- ];
-
- 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);
- Yard::instance('shopping')->store($identifier);
- $logData = [
- 'user_id' => Auth::user()->id,
- 'shopping_user_id' => $id,
- '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);
-
- 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);
- Yard::instance('shopping')->store($identifier);
- $logData = [
- 'user_id' => Auth::user()->id,
- 'shopping_user_id' => $id,
- '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);
-
- throw new \Exception(__('msg.shopping_cart_was_not_user_shop'));
- }
- }
-
- $shipping_price = Shop::getShippingPriceByShippingCountryId($shipping_country_id, Yard::instance('shopping')->weight());
-
- // 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()
- ];
-
- 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);
- 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()
- ];
-
- 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()
- ];
-
- 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);
- 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()
- ];
-
- 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);
- 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()
- ];
-
- 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);
- 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()
- ];
-
- 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'));
- }
- }
-
- }
- }
-
- public function datatable()
- {
- $isAbo = Request::get('is_abo');
- $shippingIsFor = Request::get('shipping_is_for');
-
- if ($shippingIsFor === 'me' || $shippingIsFor === 'abo-me') {
- $show_on_ids = $isAbo ? ['12', '13'] : ['2'];
-
- $query = Product::with('product_buyings')
- ->select('products.*')
- ->where('products.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]]);
- } else {
- $show_on_ids = $isAbo ? ['12', '13'] : ['3'];
-
- $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]]);
- }
-
- Log::channel(self::LOG_CHANNEL)->info("Datatable query executed", [
- 'is_abo' => $isAbo,
- 'shipping_is_for' => $shippingIsFor,
- 'show_on_ids' => $show_on_ids
- ]);
-
- return \DataTables::eloquent($query)
- ->addColumn('product', function (Product $product) {
- $cartItem = Yard::instance('shopping')->getCartItemByProduct($product->id);
- $qty = isset($cartItem->qty) ? $cartItem->qty : 0;
- $rowId = isset($cartItem->rowId) ? $cartItem->rowId : '';
- return ''.$product->getLang('name').'
-
-
-
-
-
-
-
-
-
-
- ';
- })
- ->addColumn('abo', function (Product $product) {
- return AboHelper::getAboTypeBadge(AboHelper::getAboShowOn($product));
- })
- ->addColumn('picture', function (Product $product) {
- if(count($product->images)){
- return '
';
- }
- return "";
- })
- ->addColumn('price_net', function (Product $product) {
- return ''.$product->getFormattedPriceWith(true, true, Yard::instance('shopping')->getUserCountry()). " €".''.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'';
- })
- ->addColumn('price_gross', function (Product $product) {
- return ''.$product->getFormattedPriceWith(false, true, Yard::instance('shopping')->getUserCountry()). " €".''.$product->getFormattedPriceCurrencyWith(false, true, Yard::instance('shopping')->getUserCountry()).'';
- })
- ->addColumn('price_vk_gross', function (Product $product) {
- return ''.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()). " €".''.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'';
- })
- ->addColumn('customer_price_net', function (Product $product) {
- return ''.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()). " €".''.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry()).'';
- })
- ->addColumn('customer_price_gross', function (Product $product) {
- return ''.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()). " €".''.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'';
- })
- ->addColumn('my_commission_net', function (Product $product) {
- return ''.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry(), true). " €".''.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry(), true).'';
- })
- ->addColumn('action', function (Product $product) {
- return '';
- })
- ->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('price_vk_gross', 'price $1')
- ->orderColumn('customer_price_net', 'price $1')
- ->orderColumn('customer_price_gross', 'price $1')
- ->orderColumn('my_commission_net', 'price $1')
- ->orderColumn('contents_total', 'contents_total $1')
- ->orderColumn('weight', 'weight $1')
- ->orderColumn('abo', 'show_on $1')
- ->rawColumns(['add_card', 'price_net', 'price_gross', 'price_vk_gross', 'customer_price_net', 'customer_price_gross', 'my_commission_net', 'product', 'quantity', 'picture', 'abo', 'action'])
- ->make(true);
- }
-
- /**
- * Handle AJAX requests for cart operations
- */
- public function performRequest()
- {
- 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']);
- }
-
- $data = Request::all();
- $is_for = isset($data['shipping_is_for']) ? $data['shipping_is_for'] : 'ot-member';
- $data['for'] = $is_for;
- $data['comp_products'] = Shop::getCompProducts($is_for);
-
- Log::channel(self::LOG_CHANNEL)->info("Performing cart action", [
- 'action' => $data['action'] ?? 'unknown',
- 'is_for' => $is_for
- ]);
-
- if ($data['action'] === 'updateCart' && isset($data['product_id'])) {
- return $this->handleUpdateCart($data, $is_for);
- }
-
- if ($data['action'] === 'clearCart') {
- Yard::instance('shopping')->destroy();
- Log::channel(self::LOG_CHANNEL)->info("Cart cleared");
- return response()->json(['response' => true, 'data' => Yard::instance('shopping')->count(), 'html_card' => '', 'html_comp' => '']);
- }
-
- if ($data['action'] === 'updateShippingCountry') {
- return $this->handleUpdateShippingCountry($data, $is_for);
- }
-
- if ($data['action'] === 'updateCompProduct') {
- return $this->handleUpdateCompProduct($data, $is_for);
- }
-
- Log::channel(self::LOG_CHANNEL)->warning("Unknown action in performRequest", ['action' => $data['action'] ?? 'not set']);
- return response()->json(['response' => false, 'data' => $data]);
- }
-
- /**
- * Handle updating cart items
- */
- 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']]);
- return response()->json(['response' => false, 'message' => 'Product not found']);
- }
-
- $image = "";
- if ($product->images->count()) {
- $image = $product->images->first()->slug;
- }
-
- // Get the cart item
- if ($is_for === 'ot-customer' || $is_for === 'abo-ot-customer') {
- $cartItem = Yard::instance('shopping')
- ->add($product->id, $product->getLang('name'), 1,
- 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]);
- } else {
- $cartItem = Yard::instance('shopping')
- ->add($product->id, $product->getLang('name'), 1,
- $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]);
- }
-
- if (Yard::instance('shopping')->getUserTaxFree()) {
- Yard::setTax($cartItem->rowId, 0);
- } else {
- Yard::setTax($cartItem->rowId, $product->getTaxWith(Yard::instance('shopping')->getUserCountry()));
- }
-
- if (isset($data['qty']) && $data['qty'] > 0) {
- Yard::instance('shopping')->update($cartItem->rowId, $data['qty']);
- Log::channel(self::LOG_CHANNEL)->info("Cart item updated", [
- 'product_id' => $product->id,
- 'product_name' => $product->getLang('name'),
- 'qty' => $data['qty']
- ]);
- } else {
- // If 0 get the item by qty:1 and remove it
- Yard::instance('shopping')->remove($cartItem->rowId);
- Log::channel(self::LOG_CHANNEL)->info("Cart item removed", [
- 'product_id' => $product->id,
- 'product_name' => $product->getLang('name')
- ]);
- }
-
- 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();
-
- return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
- }
-
- /**
- * Handle updating shipping country
- */
- private function handleUpdateShippingCountry($data, $is_for)
- {
- if (isset($data['shipping_country_id'])) {
- $shipping_country = ShippingCountry::find($data['shipping_country_id']);
- if ($shipping_country) {
- Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country->id, $is_for);
- $this->checkCompProduct(Yard::instance('shopping')->getNumComp());
-
- Log::channel(self::LOG_CHANNEL)->info("Shipping country updated", [
- 'shipping_country_id' => $shipping_country->id,
- 'shipping_country_name' => $shipping_country->name ?? 'unknown'
- ]);
- } else {
- 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();
-
- return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
- }
-
- /**
- * Handle updating compensation products
- */
- private function handleUpdateCompProduct($data, $is_for)
- {
- $this->updateCompProduct($data);
- Yard::instance('shopping')->reCalculateShippingPrice();
-
- Log::channel(self::LOG_CHANNEL)->info("Compensation product updated", [
- 'comp_product_id' => $data['comp_product_id'] ?? null,
- 'comp_num' => $data['comp_num'] ?? null,
- 'count_comp_products' => $data['count_comp_products'] ?? null
- ]);
-
- $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]);
- }
-
- /**
- * Check and remove compensation products if needed
- */
- private function checkCompProduct($count_comp_products)
- {
- foreach (Yard::instance('shopping')->content() as $row) {
- // If equal or greater, delete due to new shipping costs
- if ($row->options->comp && $row->options->comp > intval($count_comp_products)) {
- Yard::instance('shopping')->remove($row->rowId);
- Log::channel(self::LOG_CHANNEL)->info("Compensation product removed due to count change", [
- 'product_id' => $row->id,
- 'product_name' => $row->name,
- 'comp_value' => $row->options->comp,
- 'required_comp' => $count_comp_products
- ]);
- }
- }
- }
-
- /**
- * Update compensation products
- */
- private function updateCompProduct($data)
- {
- // Clear old
- 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
- 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);
- Log::channel(self::LOG_CHANNEL)->info("Compensation product removed during update", [
- 'product_id' => $row->id,
- 'product_name' => $row->name,
- 'comp_value' => $row->options->comp,
- 'comp_num' => $data['comp_num'],
- 'count_comp_products' => $data['count_comp_products']
- ]);
- }
- }
-
- if (isset($data['comp_product_id'])) {
- $product = Product::find($data['comp_product_id']);
- if ($product) {
- $image = "";
- if ($product->images->count()) {
- $image = $product->images->first()->slug;
- }
- $cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, 0, false, false, [
- 'image' => $image,
- 'slug' => $product->slug,
- 'weight' => 0,
- 'points' => 0,
- 'comp' => intval($data['comp_num']),
- 'product_id' => $product->id
- ]
- );
-
- Yard::setTax($cartItem->rowId, 0);
-
- Log::channel(self::LOG_CHANNEL)->info("Compensation product added", [
- 'product_id' => $product->id,
- 'product_name' => $product->getLang('name'),
- 'comp_num' => $data['comp_num']
- ]);
- } else {
- Log::channel(self::LOG_CHANNEL)->warning("Compensation product not found", [
- 'comp_product_id' => $data['comp_product_id']
- ]);
- }
- }
- }
-
- /**
- * Display custom payment page
- */
- public function customPayment($identifier)
- {
- try {
- $data = OrderPaymentService::getCustomPayment($identifier);
- Log::channel(self::LOG_CHANNEL)->info("Custom payment page accessed", ['identifier' => $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]);
- abort(404, 'Custom payment not found');
- }
- }
-
- /**
- * Send custom payment email
- */
- private function customPaymentSendMail($user, $identifier, $yard_shopping_items, $data)
- {
- $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]);
- 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']]);
- throw new \Exception(__('msg.shopping_user_not_found'));
- }
-
- $route = route('checkout.checkout_card', ['identifier' => $identifier]);
-
- $billing_email = $shopping_user->billing_email;
- if (!$billing_email) {
- $billing_email = $data['mode'] === 'test' ? config('app.checkout_test_mail') : config('app.checkout_mail');
- }
-
- $bcc[] = $data['mode'] === 'test' ? config('app.checkout_test_mail') : config('app.checkout_mail');
- $bcc[] = $shopping_user->member ? $shopping_user->member->email : $user->email;
-
- Log::channel(self::LOG_CHANNEL)->info("Sending custom payment email", [
- 'to' => $billing_email,
- 'bcc' => $bcc,
- 'identifier' => $identifier
- ]);
-
- Mail::to($billing_email)
- ->bcc($bcc)
- ->locale(\App::getLocale())
- ->send(new MailCustomPaymet($route, $shopping_user, $shopping_instance, $yard_shopping_items, $data['mode']));
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/OrderPaymentController.php b/dev/app-bak/Http/Controllers/User/OrderPaymentController.php
deleted file mode 100644
index 5934028e..00000000
--- a/dev/app-bak/Http/Controllers/User/OrderPaymentController.php
+++ /dev/null
@@ -1,97 +0,0 @@
-middleware('active.account');
- }
-
- public function index()
- {
- $data = [
- ];
- return view('user.order.payment.index', $data);
- }
-
- public function detail($identifier)
- {
- $data = OrderPaymentService::getCustomPayment($identifier);
- $data['backlink'] = route('user_order_payment_links');
- return view('user.order.payment.custom_payment', $data);
- }
-
- public function delete($identifier){
- OrderPaymentService::deleteInstance($identifier);
- return redirect(route('user_order_payment_links'));
- }
-
- public function datatable(){
-
- $user = User::find(\Auth::user()->id);
- $user_shop_id = $user->shop ? $user->shop->id : null;
- $query = ShoppingInstance::select('*')
- ->where('user_shop_id', '=', $user_shop_id)
- ->where('payment', 6);
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingInstance $shoppingInstance) {
- return '';
- })
- ->addColumn('created_at', function (ShoppingInstance $shoppingInstance) {
- return $shoppingInstance->created_at->format("d.m.Y");
- })
- ->addColumn('status', function (ShoppingInstance $shoppingInstance) {
- return OrderPaymentService::getStatusBadge($shoppingInstance);
- })
- ->addColumn('payment_method', function (ShoppingInstance $shoppingInstance) {
- return $shoppingInstance->payment_method ? $shoppingInstance->payment_method->name : '-';
- })
- ->addColumn('total', function (ShoppingInstance $shoppingInstance) {
- if($shoppingInstance->amount > 0){
- return ''.$shoppingInstance->getAmountFormatted()." €";
- }else{
- return '-';
- }
- })
- ->addColumn('type', function (ShoppingInstance $shoppingInstance) {
- return OrderPaymentService::getTypeBadge($shoppingInstance);
- })
- ->addColumn('billing_firstname', function (ShoppingInstance $shoppingInstance) {
- return $shoppingInstance->shopping_data['billing_firstname'] ?? '-';
- })
- ->addColumn('billing_lastname', function (ShoppingInstance $shoppingInstance) {
- return $shoppingInstance->shopping_data['billing_lastname'] ?? '-';
- })
- ->addColumn('billing_email', function (ShoppingInstance $shoppingInstance) {
- return $shoppingInstance->shopping_data['billing_email'] ?? '-';
- })
- ->addColumn('delete', function (ShoppingInstance $shoppingInstance) {
- return '';
- })
-
- ->orderColumn('id', 'identifier $1')
- ->orderColumn('created_at', 'created_at $1')
- ->orderColumn('status', 'status $1')
- ->orderColumn('total', 'total $1')
- ->orderColumn('type', 'type $1')
- ->orderColumn('billing_firstname', 'billing_firstname $1')
- ->orderColumn('billing_lastname', 'billing_lastname $1')
- ->orderColumn('billing_email', 'billing_email $1')
- ->rawColumns(['id', 'status', 'type', 'total', 'invoice', 'delete'])
- ->make(true);
- }
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/PaymentController.php b/dev/app-bak/Http/Controllers/User/PaymentController.php
deleted file mode 100644
index dd340f33..00000000
--- a/dev/app-bak/Http/Controllers/User/PaymentController.php
+++ /dev/null
@@ -1,137 +0,0 @@
-middleware('auth');
- /* $this->startYear = 2021;
- $this->endYear = date('Y');
- $this->rangeYears = range($this->startYear, $this->endYear);
- $this->activeYear = $this->endYear;*/
- }
-
- public function credit()
- {
- $user = \Auth::user();
- $data = [
- 'user' => $user,
- ];
- return view('user.payment.credit', $data);
- }
-
-
- public function credit_datatable(){
-
- $user = \Auth::user();
- $query = UserCredit::with('user', 'user.account')->select('user_credits.*')->where('user_id', $user->id);
-
- return \DataTables::eloquent($query)
-
- ->addColumn('view', function (UserCredit $UserCredit) {
- $ret = "";
- if(Credit::isCredit($UserCredit)){
- $ret .= ' ';
- $ret .= '
';
- $ret .= ' ';
- $ret .= ' ';
-
- }else{
- $ret = "-";
- }
- return $ret;
- })
- ->addColumn('total', function (UserCredit $UserCredit) {
- 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')."
";
-
- }
- }
- return $ret;
- })
- ->addColumn('status', function (UserCredit $UserCredit) {
- return ''.$UserCredit->getStatusType().' ';
- })
- ->orderColumn('id', 'id $1')
- ->orderColumn('status', 'status $1')
- ->orderColumn('total', 'total $1')
- ->rawColumns(['total', 'credits', 'status', 'view'])
- ->make(true);
- }
-
- 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)." €";
- })
- ->addColumn('created_at', function (UserCreditItem $user_credit_item) {
- return formatDate($user_credit_item->created_at);
- })
- ->addColumn('status', function (UserCreditItem $user_credit_item) {
- return ''.$user_credit_item->getStatusType().' ';
- })
- ->addColumn('paid', function (UserCreditItem $user_credit_item) {
- return ($user_credit_item->paid && $user_credit_item->user_credit) ?
- ' '.$user_credit_item->user_credit->full_number.''
- : '';
- })
-
- ->orderColumn('message', 'message $1')
- ->orderColumn('credit', 'credit $1')
- ->orderColumn('created_at', 'created_at $1')
- ->orderColumn('status', 'status $1')
- ->rawColumns(['message', 'status', 'paid'])
- ->make(true);
- }
-
-
- /*private function setActiveYears(){
- if(Request::get('filter_year')){
- $this->activeYear = Request::get('filter_year');
- }
- }
-
- public function revenue()
- {
- $this->setActiveYears();
-
- $user = \Auth::user();
- $data = [
- 'user' => $user,
- 'years' => $this->rangeYears,
- 'active_year' => $this->activeYear,
- 'months' => range(1, 12),
- ];
- return view('user.payment.revenue', $data);
- }*/
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/ShopApiController.php b/dev/app-bak/Http/Controllers/User/ShopApiController.php
deleted file mode 100644
index 8ff418fc..00000000
--- a/dev/app-bak/Http/Controllers/User/ShopApiController.php
+++ /dev/null
@@ -1,171 +0,0 @@
- 'bitte wählen', 'order' => 'markierte bezahlen', 'remove' => 'markierte entfernen', 'reset' => 'markierte zurücksetzen/bestellt'];
- private $filter_show = [10 => 'alle anzeigen', 1 => 'bestellt', 2 => 'bezahlt', 5 => 'entfernt'];
- protected $shopApiRepository;
-
- public function __construct(ShopApiRepository $shopApiRepository)
- {
- $this->middleware('active.shop');
- $this->shopApiRepository = $shopApiRepository;
- }
-
- public function orders()
- {
- $this->setFilterVars();
- $data = [
- 'api_action' => $this->api_action,
- 'filter_show' => $this->filter_show,
- ];
- return view('user.shop.sales.api_orders', $data);
- }
-
- public function action(){
- $data = Request::all();
-
- if(isset($data['user_shop_api_orders_action'])){
- switch($data['user_shop_api_orders_action']){
- case 'order':
- $shopApiOrderCart = $this->shopApiRepository->order($data);
- return view('user.shop.sales.api_order_list', compact('shopApiOrderCart', 'data'));
- break;
- case 'remove':
- $this->shopApiRepository->remove($data);
- break;
- case 'reset':
- $this->shopApiRepository->reset($data);
- break;
-
- }
- }
- return redirect(route('user_shop_api_orders'));
- }
-
- public function checkout(){
-
- $data = Request::all();
- return $this->shopApiRepository->checkout($data);
- }
-
-
- private function setFilterVars(){
-
- if(!session('user_shop_api_orders_filter')){
- session(['user_shop_api_orders_filter' => 1]);
- }
- if(Request::get('user_shop_api_orders_filter')){
- session(['user_shop_api_orders_filter' => Request::get('user_shop_api_orders_filter')]);
- }
- }
-
- private function initSearch($archive = false, $request = true)
- {
- $this->setFilterVars();
-
- $user = User::find(\Auth::user()->id);
- $query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')
- ->where('shopping_orders.member_id', $user->id)
- ->where('shopping_orders.payment_for', 7); //7 payment for extern
-
-
- if(Request::get('user_shop_api_orders_filter')){
- if(Request::get('user_shop_api_orders_filter') < 10){
- if(Request::get('user_shop_api_orders_filter') == 1){
- $query->where(function($query) {
- return $query->where('shopping_orders.api_status', 0)
- ->orWhere('shopping_orders.api_status', 1)
- ->orWhereNull('shopping_orders.api_status');
- });
- }else{
- $query->where('shopping_orders.api_status', Request::get('user_shop_api_orders_filter'));
- }
- }
-
- }
- return $query;
- }
-
- public function ordersDatatable(){
-
- $query = $this->initSearch();
- return \DataTables::eloquent($query)
-
- ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('api_status', function (ShoppingOrder $ShoppingOrder) {
- if($ShoppingOrder->api_status === 2){
- $shopping_oder_id = isset($ShoppingOrder->api_notice['shopping_order_id']) ? $ShoppingOrder->api_notice['shopping_order_id'] : null;
- if($shopping_oder_id){
- return ' '.$shopping_oder_id.'';
- }
- }
- return ''.$ShoppingOrder->getAPIStatusType().'';
- })
- ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getShoppingOrderBadge($ShoppingOrder);
- })
-
- ->addColumn('api_action', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getFormattedTotalShipping()." €";
- })
- ->addColumn('orders', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->orders : '';
- })
- ->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->user_shop ? ''.$ShoppingOrder->user_shop->getSubdomain(false).'' : '';
- })
- ->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getPaymentForBadge($ShoppingOrder);
- })
- ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getShippedType().'
- ';
- })
-
- ->orderColumn('payment_for', 'payment_for $1')
-
- ->orderColumn('id', 'id $1')
- ->orderColumn('api_action', 'id $1')
-
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('user_shop_id', 'user_shop_id $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
-
- ->rawColumns(['id', 'api_status', 'txaction', 'user_shop_id', 'api_action', 'shipped', 'total_shipping', 'payment_for'])
- ->make(true);
- }
-
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/ShopSalesController.php b/dev/app-bak/Http/Controllers/User/ShopSalesController.php
deleted file mode 100755
index 9003cf6a..00000000
--- a/dev/app-bak/Http/Controllers/User/ShopSalesController.php
+++ /dev/null
@@ -1,92 +0,0 @@
-middleware('active.shop');
- }
-
- public function orders()
- {
- $data = [
- ];
- return view('user.shop.sales.orders', $data);
- }
-
- public function orderDetail($id)
- {
- $user = User::find(\Auth::user()->id);
- $shopping_order = ShoppingOrder::findOrFail($id);
- if($shopping_order->member_id !== $user->id){
- abort(403, 'Unauthorized action. User ID does not match.');
- }
- if( $shopping_order->payment_for !== 6 && $shopping_order->payment_for !== 7){
- return redirect(route('user_order_detail', [$shopping_order->id]));
- abort(403, 'Beraterbestellung');
- }
- $data = [
- 'shopping_order' => $shopping_order,
- 'isAdmin' => false,
- ];
-
- return view('user.shop.sales.order_detail', $data);
- }
-
- public function ordersDatatable(){
-
- $user = User::find(\Auth::user()->id);
- $query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.member_id', $user->id);
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
- return '';
- })
- ->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->created_at->format("d.m.Y");
- })
- ->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getShoppingOrderBadge($ShoppingOrder);
- })
- ->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getFormattedTotalShipping()." €";
- })
- ->addColumn('orders', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->shopping_user ? $ShoppingOrder->shopping_user->orders : '';
- })
- ->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->user_shop ? ''.$ShoppingOrder->user_shop->getSubdomain(false).'' : '';
- })
- ->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
- return Payment::getPaymentForBadge($ShoppingOrder);
- })
- ->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
- return ''.$ShoppingOrder->getShippedType().'
- ';
- })
- ->addColumn('invoice', function (ShoppingOrder $ShoppingOrder) {
- return $ShoppingOrder->isInvoice() ? '
- ' : '-';
- })
- ->orderColumn('payment_for', 'payment_for $1')
- ->orderColumn('id', 'id $1')
- ->orderColumn('txaction', 'txaction $1')
- ->orderColumn('user_shop_id', 'user_shop_id $1')
- ->orderColumn('total_shipping', 'total_shipping $1')
-
- ->rawColumns(['id', 'txaction', 'user_shop_id', 'total_shipping', 'invoice', 'shipped', 'payment_for'])
- ->make(true);
- }
-
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/User/TeamController.php b/dev/app-bak/Http/Controllers/User/TeamController.php
deleted file mode 100755
index 4b8f90f8..00000000
--- a/dev/app-bak/Http/Controllers/User/TeamController.php
+++ /dev/null
@@ -1,1137 +0,0 @@
- '', 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()
- {
- $this->middleware('active.account');
- }
-
-
-
- /**
- * Zeigt die Team-Übersicht mit optimierter TreeCalcBotOptimized-Datenverarbeitung
- * Lädt Team-Daten für DataTable-Anzeige
- */
- public function show()
- {
- $startTime = microtime(true);
- $startMemory = memory_get_usage();
-
- try {
- $this->setFilterVars();
- $user = User::find(\Auth::user()->id);
- $this->month = session('team_user_filter_month');
- $this->year = session('team_user_filter_year');
-
- // 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 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);
- $endTime = microtime(true);
- $endMemory = memory_get_usage();
-
- $executionTime = round(($endTime - $startTime) * 1000, 2);
- $memoryUsed = $this->formatBytes($endMemory - $startMemory);
-
- $calculationType = $forceLiveCalculation ? " (LIVE)" : " (CACHE)";
- \Log::info("TeamController: Optimized team overview built in {$executionTime}ms, Memory: {$memoryUsed}{$calculationType}");
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- 'filter_active' => $this->getFilterActive(),
- 'filter_levels' => $this->getFilterLevels(),
- 'filter_next_level' => $this->getFilterNextLevel(),
- //'TreeCalcBot' => $TreeCalcBot,
- 'performance' => [
- 'execution_time' => $executionTime,
- 'memory_used' => $memoryUsed,
- 'user_id' => $user->id,
- 'user_count' => 0, //$TreeCalcBot->getTotalUserCount(),
- 'version' => 'Optimized',
- '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());
-
- // Fallback mit minimalen Daten
- $endTime = microtime(true);
- $executionTime = round(($endTime - $startTime) * 1000, 2);
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- 'filter_active' => $this->getFilterActive(),
- 'filter_levels' => $this->getFilterLevels(),
- 'filter_next_level' => $this->getFilterNextLevel(),
- 'error' => __('team.error_loading_optimized_overview') . $e->getMessage(),
- 'performance' => [
- 'execution_time' => $executionTime,
- 'memory_used' => 'N/A',
- 'version' => 'Fallback',
- 'calculation_type' => 'Error'
- ],
- 'optimized' => false,
- ];
-
- return view('user.team.show', $data);
- }
- }
-
- public function structure()
- {
- $startTime = microtime(true);
- $startMemory = memory_get_usage();
-
- $user = User::find(\Auth::user()->id);
- if (config('app.debug')) {
- $user = User::find(454);
- }
- $this->setFilterVars();
-
- // Prüfe ob optimierte Version explizit angefordert wird
- $useOptimized = Request::get('use_optimized', true);
-
- // Prüfe ob Live-Berechnung erzwungen werden soll
- $forceLiveCalculation = Request::get('force_live_calculation', false) || Request::get('live', false);
-
- try {
- if ($useOptimized) {
- // Verwende User-spezifische optimierte Version
- $TreeCalcBot = new TreeCalcBotOptimized(
- session('team_user_filter_month'),
- session('team_user_filter_year'),
- 'member',
- $forceLiveCalculation
- );
- $TreeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
- $optimizedUsed = true;
- } else {
- // Standard TreeCalcBot mit Performance-Monitoring
- $TreeCalcBot = new TreeCalcBot(
- session('team_user_filter_month'),
- session('team_user_filter_year'),
- 'member'
- );
-
- // Standard TreeCalcBot unterstützt forceLiveCalculation nicht
- $TreeCalcBot->initStructureUser($user->id);
- $optimizedUsed = false;
- }
-
- $endTime = microtime(true);
- $endMemory = memory_get_usage();
-
- $executionTime = round(($endTime - $startTime) * 1000, 2);
- $memoryUsed = $this->formatBytes($endMemory - $startMemory);
-
- $versionInfo = ($optimizedUsed ? "OPTIMIZED" : "STANDARD") .
- ($forceLiveCalculation ? " + LIVE" : " + CACHE");
-
- \Log::info("TeamController: Structure built for user {$user->id} in {$executionTime}ms, Memory: {$memoryUsed} ({$versionInfo})");
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- 'TreeCalcBot' => $TreeCalcBot,
- 'performance' => [
- 'execution_time' => $executionTime,
- 'memory_used' => $memoryUsed,
- 'user_count' => $optimizedUsed && method_exists($TreeCalcBot, 'getTotalUserCount')
- ? $TreeCalcBot->getTotalUserCount()
- : '-',
- 'version' => $optimizedUsed ? 'Optimized' : 'Standard',
- 'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache'
- ],
- 'optimized' => $optimizedUsed,
- 'forceLiveCalculation' => $forceLiveCalculation,
- ];
-
- return view('user.team.structure', $data);
- } catch (\Exception $e) {
- \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');
- $TreeCalcBot->initStructureUser($user->id);
-
- $endTime = microtime(true);
- $executionTime = round(($endTime - $startTime) * 1000, 2);
-
- $data = [
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- 'TreeCalcBot' => $TreeCalcBot,
- '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')
- ],
- 'optimized' => false,
- 'forceLiveCalculation' => $forceLiveCalculation,
- ];
-
- return view('user.team.structure', $data);
- }
- }
- public function structureOld()
- {
- abort(403, 'This page is removed');
- $user = User::find(\Auth::user()->id);
- if (config('app.debug')) {
- $user = User::find(454);
- }
- $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);
- $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
- */
- public function datatableOptimized()
- {
- try {
- $startTime = microtime(true);
- $this->setFilterVars();
-
- $user = User::find(\Auth::user()->id);
- $this->month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
- $this->year = Request::get('team_user_filter_year') ?: session('team_user_filter_year');
-
- // 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" : ""));
-
- // Lade TreeCalcBotOptimized-Daten
- $TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
- $TreeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
- // Extrahiere alle User aus der Struktur
- $teamUsersRaw = $this->getTeamUsersFromStructure($TreeCalcBot);
-
- // 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());
- $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");
-
- return \DataTables::of($teamUsers)
- ->addColumn('id', function ($teamUser) {
- return '';
- })
- ->addColumn('m_account', function ($teamUser) {
- return $teamUser->m_account;
- })
- ->addColumn('email', function ($teamUser) {
- return e($teamUser->email);
- })
- ->addColumn('first_name', function ($teamUser) {
- return e($teamUser->first_name);
- })
- ->addColumn('last_name', function ($teamUser) {
- return e($teamUser->last_name);
- })
- ->addColumn('user_level', function ($teamUser) {
- return $teamUser->user_level_name ? TranslationHelper::transUserLevelName($teamUser->user_level_name) : '';
- })
- ->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) {
- return formatNumber($teamUser->sales_volume_points_KP_sum, 0);
- })
- ->addColumn('sales_volume_total', function ($teamUser) {
-
- return formatNumber($teamUser->payline_points_qual_kp, 0);
- })
- ->addColumn('next_level_qualified', function ($teamUser) {
-
- $userBusiness = UserBusiness::where('user_id', $teamUser->user_id)
- ->where('month', $this->month)
- ->where('year', $this->year)
- ->first();
- 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) : "-";
- })
- ->rawColumns(['id', '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());
-
- // Fallback zur Standard-DataTable
- return $this->datatable();
- }
- }
-
- /**
- * Standard DataTable für Team-Übersicht (Fallback-Version)
- */
- public function datatable()
- {
- try {
- $user = User::find(\Auth::user()->id);
- $query = $this->initTeamSearch($user);
-
- return \DataTables::eloquent($query)
- ->addColumn('id', function (User $teamUser) {
- return '';
- })
- ->addColumn('m_account', function (User $teamUser) {
- return $teamUser->account ? e($teamUser->account->m_account) : '';
- })
- ->addColumn('user_level', function (User $teamUser) {
- return $teamUser->user_level ? e($teamUser->user_level->getLang('name')) : '';
- })
- ->addColumn('is_qual_kp', function (User $teamUser) {
- if (!$teamUser->user_level) {
- return '-';
- }
- $qualKP = (int) $teamUser->user_level->qual_kp;
- $month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
- $year = Request::get('team_user_filter_year') ?: session('team_user_filter_year');
- $pointsSum = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_KP_sum');
- $isQual = $pointsSum >= $qualKP;
- $badgeClass = $isQual ? 'badge-outline-success' : 'badge-outline-warning-dark';
- return ' KU ' . $qualKP . '';
- })
- ->addColumn('sales_volume_KP_points', function (User $teamUser) {
- $month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
- $year = Request::get('team_user_filter_year') ?: session('team_user_filter_year');
- $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 '' . $total . '' .
- 'E: ' . $individual . ' | S: ' . $shop . '';
- })
- ->addColumn('sales_volume_total', function (User $teamUser) {
- $month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
- $year = Request::get('team_user_filter_year') ?: session('team_user_filter_year');
- $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 '' . formatNumber($total) . ' €' .
- 'E: ' . formatNumber($individual) . ' | S: ' . formatNumber($shop) . ' €';
- })
- ->addColumn('email', function (User $teamUser) {
- return e($teamUser->email);
- })
- ->addColumn('first_name', function (User $teamUser) {
- return $teamUser->account ? e($teamUser->account->first_name) : '';
- })
- ->addColumn('last_name', function (User $teamUser) {
- return $teamUser->account ? e($teamUser->account->last_name) : '';
- })
- ->addColumn('sponsor', function (User $teamUser) {
- if (!$teamUser->user_sponsor) {
- return '-';
- }
- $sponsor = $teamUser->user_sponsor;
- $html = '';
- if ($sponsor->account) {
- $html .= e($sponsor->account->first_name . ' ' . $sponsor->account->last_name);
- $html .= '
' . e($sponsor->email);
- $html .= ' | ' . e($sponsor->account->m_account);
- $html .= '';
- }
- 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) : "-";
- })
- ->addColumn('next_level_qualified', function (User $teamUser) {
- // Verwende bereits berechnete UserBusiness-Daten für bessere Performance
- $month = Request::get('team_user_filter_month') ?: session('team_user_filter_month');
- $year = Request::get('team_user_filter_year') ?: session('team_user_filter_year');
-
- $userBusiness = UserBusiness::where('user_id', $teamUser->id)
- ->where('month', $month)
- ->where('year', $year)
- ->first();
-
- if ($userBusiness) {
- return NextLevelBadgeHelper::generateBadgeFromUserBusiness($userBusiness);
- }
-
- return NextLevelBadgeHelper::renderNoDataBadge();
- })
- ->filterColumn('m_account', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('account', function ($q) use ($keyword) {
- $q->where('m_account', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->filterColumn('first_name', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('account', function ($q) use ($keyword) {
- $q->where('first_name', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->filterColumn('last_name', function ($query, $keyword) {
- if ($keyword != "") {
- $query->whereHas('account', function ($q) use ($keyword) {
- $q->where('last_name', 'LIKE', '%' . $keyword . '%');
- });
- }
- })
- ->filterColumn('email', function ($query, $keyword) {
- if ($keyword != "") {
- $query->where('email', 'LIKE', '%' . $keyword . '%');
- }
- })
- ->orderColumn('id', 'users.id $1')
- ->orderColumn('m_account', 'user_accounts.m_account $1')
- ->orderColumn('first_name', 'user_accounts.first_name $1')
- ->orderColumn('last_name', 'user_accounts.last_name $1')
- ->orderColumn('email', 'users.email $1')
- ->orderColumn('active_account', 'users.payment_account $1')
- ->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());
-
- return response()->json([
- 'error' => 'Team-Datatable konnte nicht geladen werden: ' . $e->getMessage()
- ], 500);
- }
- }
-
- /**
- * Zeigt den Marketingplan für User an
- * Übersichtliche Darstellung aller Karriere-Level mit wichtigen Informationen
- */
- public function marketingplan()
- {
- $startTime = microtime(true);
-
- try {
- $user = User::find(\Auth::user()->id);
- $currentLevel = $user->user_level;
-
- // Lade alle aktiven User Level, sortiert nach Position
- $userLevels = \App\Models\UserLevel::where('active', true)
- ->orderBy('pos', 'asc')
- ->get();
-
- $endTime = microtime(true);
- $executionTime = round(($endTime - $startTime) * 1000, 2);
-
- \Log::info("TeamController: Marketingplan loaded for user {$user->id} in {$executionTime}ms");
-
- $data = [
- 'userLevels' => $userLevels,
- 'currentUser' => $user,
- 'currentLevel' => $currentLevel,
- 'performance' => [
- 'execution_time' => $executionTime
- ]
- ];
-
- return view('user.team.marketingplan', $data);
- } catch (\Exception $e) {
- \Log::error("TeamController: Error loading marketingplan: " . $e->getMessage());
-
- return view('user.team.marketingplan', [
- 'error' => __('marketingplan.loading_error') . ' ' . $e->getMessage(),
- 'userLevels' => collect(),
- 'currentUser' => null,
- 'currentLevel' => null
- ]);
- }
- }
-
- /**
- * Link für neue Mitglieder
- */
- public function addMember()
- {
- $user = User::find(\Auth::user()->id);
- if ($user->isActiveShop() && $user->shop) {
- $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;
- }
- $data = [
- 'shop_register_link' => $shop_register_link
- ];
- return view('user.team.members', $data);
- }
-
- /**
- * Initialisiert die Team-Suche für den eingeloggten User
- */
- private function initTeamSearch($currentUser)
- {
- $this->setFilterVars();
-
- // Finde alle Team-Mitglieder des aktuellen Users (direkte und indirekte)
- $query = User::with(['account', 'user_level', 'user_sponsor.account'])
- ->select('users.*', 'user_accounts.m_account', 'user_accounts.first_name', 'user_accounts.last_name')
- ->leftJoin('user_accounts', 'users.id', '=', 'user_accounts.id')
- ->where('users.deleted_at', '=', null)
- ->where('users.id', '!=', 1)
- ->where('users.admin', '<', 4)
- ->where('users.m_level', '!=', null)
- ->where('users.payment_account', '!=', null);
-
- // Filtere Team-Mitglieder basierend auf Sponsor-Hierarchie
- // TODO: Hier müsste die Logik implementiert werden, um nur Team-Mitglieder des aktuellen Users zu finden
- // Für jetzt zeigen wir alle aktiven User (kann später spezifiziert werden)
-
- $activeFilter = Request::get('team_user_filter_active') ?: session('team_user_filter_active', 1);
- if ($activeFilter == 1) {
- $query->where('users.payment_account', '>=', now());
- } elseif ($activeFilter == 2) {
- $query->where('users.payment_account', '<', now());
- }
- // activeFilter == 3 bedeutet alle (keine weitere Einschränkung)
-
- return $query;
- }
-
- public function points()
- {
- $this->setFilterVars();
- $user = User::find(\Auth::user()->id);
- $userSalesVolume = $user->getUserSalesVolume(intval(session('team_user_points_filter_month')), intval(session('team_user_points_filter_year')), 'first');
- $data = [
- 'userSalesVolume' => $userSalesVolume,
- 'filter_months' => HTMLHelper::getTransMonths(),
- 'filter_years' => HTMLHelper::getYearRange(2022),
- ];
- return view('user.team.points', $data);
- }
-
- public function export()
- {
-
- $user = User::find(\Auth::user()->id);
- if (!$user->isVIP()) {
- abort(404);
- }
- $ExportBot = new ExportBot('member');
- $ExportBot->initStructureUser($user, 'list'); //tree or list
- $data = [
- 'ExportBot' => $ExportBot,
- ];
- return view('user.team.export', $data);
- }
-
- public function userTeamExport()
- {
-
- if (Request::get('action') === "export") {
- $user = User::find(\Auth::user()->id);
- $ExportBot = new ExportBot('member');
- $ExportBot->initStructureUser($user, 'list'); //tree or list
- $columns = [];
- $filename = __('team.filename_export') . date('Y-m-d-H-i-s');
- $headers = array(
- __('tables.line'),
- __('tables.level'),
- __('tables.email'),
- __('tables.firstname'),
- __('tables.lastname'),
- __('tables.address'),
- __('tables.addition'),
- __('tables.postcode'),
- __('tables.city'),
- __('tables.country'),
- __('tables.phone'),
- __('tables.mobil'),
- __('tables.birthday'),
- __('tables.partner_since'),
- __('tables.account'),
- __('tables.account_to'),
- __('tables.sponsor'),
- );
- if (isset($ExportBot->user_list->childs)) {
- foreach ($ExportBot->user_list->childs as $child) {
- $columns[] = array(
- __('tables.line') => $child->line,
- __('tables.level') => $child->level_name,
- __('tables.email') => $child->email,
- __('tables.firstname') => $child->first_name,
- __('tables.lastname') => $child->last_name,
- __('tables.address') => $child->address,
- __('tables.addition') => $child->address_2,
- __('tables.postcode') => $child->zipcode,
- __('tables.city') => $child->city,
- __('tables.country') => $child->country_id,
- __('tables.phone') => $child->phone,
- __('tables.mobil') => $child->mobil,
- __('tables.birthday') => $child->birthday,
- __('tables.partner_since') => $child->partner_since,
- __('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');
- }
- }
-
- private function setFilterVars()
- {
-
- if (!session('team_user_filter_month')) {
- session(['team_user_filter_month' => intval(date('m'))]);
- }
- if (!session('team_user_filter_year')) {
- session(['team_user_filter_year' => intval(date('Y'))]);
- }
- if (!session('team_user_points_filter_month')) {
- session(['team_user_points_filter_month' => intval(date('m'))]);
- }
- if (!session('team_user_points_filter_year')) {
- session(['team_user_points_filter_year' => intval(date('Y'))]);
- }
- if (!session('team_user_filter_active')) {
- session(['team_user_filter_active' => 1]);
- }
- if (!session('team_user_filter_level')) {
- session(['team_user_filter_level' => 0]);
- }
- if (!session('team_user_filter_next_level')) {
- session(['team_user_filter_next_level' => 0]);
- }
-
- if (Request::get('team_user_filter_month')) {
- session(['team_user_filter_month' => Request::get('team_user_filter_month')]);
- }
- if (Request::get('team_user_filter_year')) {
- session(['team_user_filter_year' => Request::get('team_user_filter_year')]);
- }
-
- if (Request::get('team_user_points_filter_month')) {
- session(['team_user_points_filter_month' => Request::get('team_user_points_filter_month')]);
- }
- if (Request::get('team_user_points_filter_year')) {
- session(['team_user_points_filter_year' => Request::get('team_user_points_filter_year')]);
- }
- if (Request::get('team_user_filter_active')) {
- session(['team_user_filter_active' => Request::get('team_user_filter_active')]);
- }
- if (Request::get('team_user_filter_level')) {
- session(['team_user_filter_level' => Request::get('team_user_filter_level')]);
- } else {
- session(['team_user_filter_level' => 0]);
- }
- if (Request::get('team_user_filter_next_level')) {
- session(['team_user_filter_next_level' => Request::get('team_user_filter_next_level')]);
- } else {
- session(['team_user_filter_next_level' => 0]);
- }
- }
-
- private function initSearchPoints()
- {
- $this->setFilterVars();
-
- $user_id = \Auth::user()->id;
- $query = UserSalesVolume::with('user', 'user.account')->with('shopping_order')->select('user_sales_volumes.*')
- ->where('user_sales_volumes.user_id', '=', $user_id)
- ->where('user_sales_volumes.month', '=', Request::get('team_user_points_filter_month'))
- ->where('user_sales_volumes.year', '=', Request::get('team_user_points_filter_year'));
-
- 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 '' . $UserSalesVolume->shopping_order->id . '';
- }
- if (($UserSalesVolume->status === 2 || $UserSalesVolume->status === 3) && $UserSalesVolume->shopping_order->member_id === $UserSalesVolume->user_id) {
- return '' . $UserSalesVolume->shopping_order->id . '';
- }
- }
- return '';
- })
- ->addColumn('total_net', function (UserSalesVolume $UserSalesVolume) {
- return formatNumber($UserSalesVolume->total_net) . ' €';
- })
- ->addColumn('status_turnover', function (UserSalesVolume $UserSalesVolume) {
- return '' . $UserSalesVolume->getStatusTurnoverType() . '';
- })
- ->addColumn('status', function (UserSalesVolume $UserSalesVolume) {
- return '' . $UserSalesVolume->getStatusType() . '';
- })
- ->addColumn('message', function (UserSalesVolume $UserSalesVolume) {
- return '' . $UserSalesVolume->message . '';
- })
- ->addColumn('info', function (UserSalesVolume $UserSalesVolume) {
- return '' . $UserSalesVolume->info . '';
- })
-
- ->orderColumn('id', 'id $1')
- ->orderColumn('order', 'order $1')
- ->orderColumn('status', 'status $1')
- ->orderColumn('message', 'message $1')
- ->orderColumn('info', 'info $1')
-
- ->rawColumns(['id', 'order', 'status_turnover', 'status', 'message', 'info', 'total_net'])
- ->make(true);
- }
-
- public function load()
- {
-
- $user = User::find(\Auth::user()->id);
- $userSalesVolume = $user->getUserSalesVolume(intval(session('team_user_points_filter_month')), intval(session('team_user_points_filter_year')), 'first');
-
- $data = [
- 'userSalesVolume' => $userSalesVolume,
- ];
- $html = view('user.team._points_sum', $data)->render();
- return response()->json(['response' => true, 'data' => $data, 'html' => $html]);
- }
-
- /**
- * Formatiert Bytes in lesbare Einheiten (aus BusinessControllerOptimized übernommen)
- */
- private function formatBytes(int $bytes, int $precision = 2): string
- {
- $units = array('B', 'KB', 'MB', 'GB', 'TB');
-
- for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
- $bytes /= 1024;
- }
-
- return round($bytes, $precision) . ' ' . $units[$i];
- }
-
- /**
- * Holt verfügbare User Level für Filter
- */
- private function getFilterLevels(): array
- {
- $levels = [0 => 'Alle Level'];
-
- $userLevels = \App\Models\UserLevel::orderBy('pos')->get(['id', 'name']);
- foreach ($userLevels as $level) {
- $levels[$level->id] = $level->name;
- }
-
- return $levels;
- }
-
- /**
- * Holt übersetzte Filter für Aktiv-Status
- */
- private function getFilterActive(): array
- {
- return [
- 1 => __('team.filter_active'),
- 2 => __('team.filter_not_active'),
- 3 => __('team.filter_all')
- ];
- }
-
- /**
- * Holt übersetzte Filter für Next Level Status
- */
- private function getFilterNextLevel(): array
- {
- return [
- 0 => __('team.all_status'),
- 1 => __('team.qualified_green'),
- 2 => __('team.in_progress_yellow'),
- 3 => __('team.no_level_red')
- ];
- }
-
- // Performance-optimierte Badge-Generierung wurde in NextLevelBadgeHelper ausgelagert
- // Alte performance-lastige Methoden wurden entfernt um die Datatable-Performance zu verbessern
-
- /**
- * Extrahiert alle User aus TreeCalcBotOptimized-Struktur für DataTable-Anzeige
- * Sammelt rekursiv alle User aus der Struktur und macht sie als FLACHE Liste verfügbar
- */
- public function getTeamUsersFromStructure(TreeCalcBotOptimized $treeCalcBot): array
- {
- $allUsers = [];
- $processedIds = [];
-
- // Debug: Prüfe TreeCalcBot-Inhalt
- $businessUsers = $treeCalcBot->getItems();
- \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", [
- '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])) {
- $processedIds[$userId] = true;
- $businessUser->deep = 0;
- $allUsers[] = $businessUser;
- $this->collectAllBusinessUserItemsFlat($businessUser->businessUserItems ?? [], $allUsers, $processedIds, 1);
- \Log::debug("TeamController: Root-User hinzugefügt: {$userId}");
- }
- }
- // Sammle parentless User, kann bei usern eigenlich nicht vorkommen, da sie immer teil des baums sind
- if ($treeCalcBot->isParentless()) {
- $parentless = $treeCalcBot->__get('parentless');
- if (is_array($parentless)) {
- foreach ($parentless as $businessUser) {
- if ($businessUser) {
- // WICHTIG: user_id korrekt über b_user abrufen (Magic Method Problem mit isset())
- $userId = $businessUser->user_id; // Über __get() Method
-
- if ($userId) {
- // Prüfe ob dieser parentless User bereits gesammelt wurde
- if (!isset($processedIds[$userId])) {
- $processedIds[$userId] = true;
- $businessUser->deep = 0;
- $allUsers[] = $businessUser;
-
- \Log::debug("TeamController: Parentless-User hinzugefügt: {$userId}");
-
- // Sammle ALLE verschachtelten businessUserItems rekursiv
- $this->collectAllBusinessUserItemsFlat($businessUser->businessUserItems ?? [], $allUsers, $processedIds, 1);
- } else {
- \Log::debug("TeamController: Parentless-User übersprungen: {$userId} (bereits verarbeitet)");
- }
- } else {
- \Log::warning("TeamController: Parentless BusinessUser ohne user_id übersprungen");
- }
- }
- }
- }
- }
-
- \Log::info("TeamController: AllUsers before filtering: " . count($allUsers));
- // Filter anwenden
- $filteredUsers = $this->applyTeamFiltersToBusinessUsers($allUsers);
- \Log::info("TeamController: AllUsers after filtering: " . count($filteredUsers));
-
- return $filteredUsers;
- }
-
- /**
- * Wendet Team-Filter auf BusinessUser-Objekte an
- */
- private function applyTeamFiltersToBusinessUsers($businessUsers): array
- {
- $activeFilter = Request::get('team_user_filter_active') ?: session('team_user_filter_active', 1);
- $levelFilter = Request::get('team_user_filter_level') ?: session('team_user_filter_level', 0);
- $nextLevelFilter = Request::get('team_user_filter_next_level') ?: session('team_user_filter_next_level', 0);
-
- \Log::info("TeamController: Applying filters - Active: {$activeFilter}, Level: {$levelFilter}, NextLevel: {$nextLevelFilter}");
-
- // Debug: Zeige verfügbare Eigenschaften des ersten BusinessUsers
- if (!empty($businessUsers)) {
- $firstUser = $businessUsers[0];
- \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',
- 'next_qual_user_level' => isset($firstUser->next_qual_user_level) ? 'set' : 'not set',
- 'next_can_user_level' => isset($firstUser->next_can_user_level) ? 'set' : 'not set',
- ]);
- }
-
- $filtered = array_filter($businessUsers, function ($businessUser) use ($activeFilter, $levelFilter, $nextLevelFilter) {
- // Active Filter anwenden
- if ($activeFilter == 1) { // Nur aktive
- if (!$businessUser->active_account) {
- return false;
- }
- } elseif ($activeFilter == 2) { // Nur inaktive
- if ($businessUser->active_account) {
- return false;
- }
- }
- // activeFilter == 3 bedeutet alle (keine Einschränkung)
-
- // Level Filter anwenden
- if ($levelFilter && $levelFilter != 0) {
- if ($businessUser->m_level_id != $levelFilter) {
- return false;
- }
- }
-
- // Next Level Filter anwenden
- if ($nextLevelFilter && $nextLevelFilter != 0) {
- $hasNextQual = ($businessUser->next_qual_user_level) && $businessUser->next_qual_user_level !== '[]';
- $hasNextCan = ($businessUser->next_can_user_level) && $businessUser->next_can_user_level !== '[]';
-
- switch ($nextLevelFilter) {
- case 1: // Qualifiziert (grün) - hat next_qual_user_level
- if (!$hasNextQual) {
- return false;
- }
- break;
- case 2: // In Arbeit (gelb) - hat next_can_user_level aber kein next_qual_user_level
- if ($hasNextQual || !$hasNextCan) {
- return false;
- }
- break;
- case 3: // Kein Level (rot) - hat weder next_qual noch next_can
- if ($hasNextQual || $hasNextCan) {
- return false;
- }
- break;
- }
- }
-
- return true; // Alle Filter bestanden
- });
-
- // Array-Indizes neu setzen für korrekte DataTable-Verarbeitung
- return array_values($filtered);
- }
-
- /**
- * NEUE OPTIMIERTE Methode: Sammelt ALLE BusinessUserItems in einer flachen Liste
- * Perfekt für DataTable-Verarbeitung - keine verschachtelte Struktur
- */
- private function collectAllBusinessUserItemsFlat(array $businessUserItems, &$allUsers, &$processedIds, $depth = 1): void
- {
- // Schutz vor zu tiefer Rekursion (maximale Tiefe: 20 Levels)
- $maxDepth = 20;
- if ($depth > $maxDepth) {
- \Log::warning("TeamController: Maximale Sammlungstiefe ({$maxDepth}) erreicht bei Tiefe {$depth}");
- return;
- }
-
- foreach ($businessUserItems as $businessUserItem) {
- if ($businessUserItem) {
- // WICHTIG: user_id korrekt über b_user abrufen (Magic Method Problem mit isset())
- $userId = $businessUserItem->user_id; // Über __get() Method
- if ($userId) {
- // KRITISCHER SCHUTZ: Prüfe ob User bereits gesammelt wurde
- if (isset($processedIds[$userId])) {
- \Log::debug("TeamController: Überspringe bereits gesammelten User {$userId} (Duplikat verhindert)");
- continue;
- }
-
- // User zu flacher Liste hinzufügen
- $processedIds[$userId] = true;
- $businessUserItem->deep = $depth;
- $allUsers[] = $businessUserItem;
-
- \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}");
- $this->collectAllBusinessUserItemsFlat($businessUserItem->businessUserItems, $allUsers, $processedIds, $depth + 1);
- }
- } else {
- \Log::warning("TeamController: BusinessUserItem ohne user_id bei Tiefe {$depth} übersprungen");
- }
- }
- }
- }
-
- /**
- * DEPRECATED: Alte Methode zum rekursiven Sammeln von User-IDs aus BusinessUser-Struktur
- * Wird durch collectAllBusinessUserItemsFlat() ersetzt
- */
- private function collectUserIdsFromBusinessUser($businessUser, &$allUsers, $deep, $parentless, &$processedIds = []): void
- {
- // Schutz vor zu tiefer Rekursion (maximale Tiefe: 20 Levels)
- $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}");
-
- foreach ($businessUser->businessUserItems as $subBusinessUser) {
- if ($subBusinessUser) {
- // WICHTIG: user_id korrekt über b_user abrufen (Magic Method Problem mit isset())
- $userId = $subBusinessUser->user_id; // Über __get() Method
-
- if ($userId) {
- // 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;
- }
-
- $processedIds[$userId] = true;
- $subBusinessUser->deep = $deep;
- $allUsers[] = $subBusinessUser;
-
- \Log::debug("TeamController: Collected user ID: {$userId} at depth {$deep}");
-
- // Rekursiver Aufruf für weitere Unter-User mit Schutz vor Zyklen
- $newDeep = $parentless ? 0 : $deep + 1;
- $this->collectUserIdsFromBusinessUser($subBusinessUser, $allUsers, $newDeep, $parentless, $processedIds);
- } else {
- \Log::warning("TeamController: SubBusinessUser ohne user_id bei Tiefe {$deep} übersprungen");
- }
- }
- }
- }
- }
-
- /**
- * KRITISCHE METHODE: Bereinigt BusinessUserItemOptimized Objekte für DataTables
- * Entfernt zirkuläre Referenzen und extrahiert nur nötige Properties
- */
- private function cleanBusinessUserItemsForDataTable(array $businessUserItems): array
- {
- $cleanedUsers = [];
-
- foreach ($businessUserItems as $businessUserItem) {
- if (!$businessUserItem) {
- continue;
- }
-
- try {
- // Extrahiere nur die Properties, die für DataTable benötigt werden
- $cleanedUser = new \stdClass();
-
- // Basis Properties (direkt über Magic Method __get)
- $cleanedUser->user_id = $businessUserItem->user_id;
- $cleanedUser->m_account = $businessUserItem->m_account;
- $cleanedUser->email = $businessUserItem->email;
- $cleanedUser->first_name = $businessUserItem->first_name;
- $cleanedUser->last_name = $businessUserItem->last_name;
- $cleanedUser->user_level_name = $businessUserItem->user_level_name;
- $cleanedUser->active_account = $businessUserItem->active_account;
- $cleanedUser->active_date = $businessUserItem->active_date;
-
- // Sales Volume Properties
- $cleanedUser->sales_volume_points_KP_sum = $businessUserItem->sales_volume_points_KP_sum ?? 0;
- $cleanedUser->payline_points_qual_kp = $businessUserItem->payline_points_qual_kp ?? 0;
-
- // Depth für Debug/Sortierung (falls gesetzt)
- $cleanedUser->deep = $businessUserItem->deep ?? 0;
-
- // Level-Informationen für Filter
- $cleanedUser->m_level_id = $businessUserItem->m_level_id;
- $cleanedUser->next_qual_user_level = $businessUserItem->next_qual_user_level;
- $cleanedUser->next_can_user_level = $businessUserItem->next_can_user_level;
-
- $cleanedUsers[] = $cleanedUser;
-
- \Log::debug("TeamController: Cleaned user {$cleanedUser->user_id} for DataTable");
- } catch (\Exception $e) {
- \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)");
-
- return $cleanedUsers;
- }
-}
diff --git a/dev/app-bak/Http/Controllers/UserDataController.php b/dev/app-bak/Http/Controllers/UserDataController.php
deleted file mode 100755
index 2936081f..00000000
--- a/dev/app-bak/Http/Controllers/UserDataController.php
+++ /dev/null
@@ -1,233 +0,0 @@
-middleware('auth');
- $this->userRepo = $userRepo;
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function userEdit(){
- $user = Auth::user();
-
- /*if(!$user->account){
- $user->account = new UserAccount();
- }*/
- $data = [
- 'user' => $user,
- ];
- return view('user.edit', $data);
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function userEditStore(){
-
- $user = Auth::user();
- /*if(!$user->account){
- $user->account = new UserAccount();
- }*/
- $data = Request::all();
-
- if(isset($data['action']) && $data['action'] == "reverse_charge_validate"){
- return $this->userRepo->reverse_charge_validate($data, $user, route('user_edit', [$user->id]));
- }
-
- if(isset($data['action']) && $data['action'] == "reverse_charge_delete"){
- return $this->userRepo->reverse_charge_delete($data, $user, route('user_edit', [$user->id]));
- }
-
- $rules = array(
- 'salutation' => 'required',
- 'first_name'=>'required',
- 'last_name'=>'required',
- 'address'=>'required',
- 'zipcode'=>'required',
- 'city' => 'required',
- 'email' => 'required|string|email|max:255|exists:users,email',
- 'email-confirm' => 'required|same:email',
- 'bank_owner' => 'required',
- 'bank_iban' => 'required',
- 'bank_bic' => 'required',
- );
- 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'
-
- ]);
- }
- $data = [
- 'user' => $user,
- ];
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
- return view('user.edit', $data)->withErrors($validator);
-
- } else {
- $this->userRepo->update(Request::all());
- \Session()->flash('alert-save', true);
- return redirect('/user/edit');
- }
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function userDataStore(){
-
- $user = User::findOrFail(Auth::user()->id);
- if(!$user->account){
- $user->account = new UserAccount();
- }
- $rules = array(
- 'salutation' => 'required',
- 'last_name' => 'required|max:255',
- 'country_id' => 'required|integer|min:1',
- 'email' => 'required|string|email|max:255|exists:users,email',
- 'email-confirm' => 'required|same:email',
- );
- if($user->active == 0){
- $rules['accepted_data_protection'] = 'required';
- $rules['accepted_active'] = 'required';
- }
-
- if(Request::get('company') == 1){
- $rules['company_name'] = 'required|max:255';
- $rules['company_country_id'] = 'required|integer|min:1';
- }
-
- $data = [
- 'user' => $user,
- ];
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
-
- // get the error messages from the validator
- $messages = $validator->messages();
- // redirect our user back to the form with the errors from the validator
- return view('user.edit', $data)->withErrors($validator);
-
- } else {
- $this->userRepo->update(Request::all());
-
- if($user->active == 0) {
- $account = $user->account;
- $account->data_protection = now();
- $account->save();
-
- $user->active = 1;
- $user->active_date = now();
- $user->save();
- }
-
- if(Request::get('accepted_active') == "on"){
- $user->agreement = now();
- }else{
- $user->agreement = null;
- }
-
-
- \Session()->flash('alert-save', true);
- return redirect('/home');
- }
- }
-
- /**
- * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
- */
- public function userDataAcceptedForm(){
- $user = Auth::user();
-
- if(Request::get('accepted_active') == "on"){
- $user->agreement = now();
- }else {
- $user->agreement = null;
- }
-
- $user->save();
- \Session()->flash('alert-save', true);
- return redirect('/home');
- }
-
-
- /**
- * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
- */
- public function userDataFree(){
- $user = Auth::user();
- $user->active = 1;
- $user->active_date = now();
- $user->save();
- return redirect('/home');
-
- }
-
- /**
- * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
- */
- public function userDataFreeForm(){
- $user = Auth::user();
-
- $rules = array(
- 'accepted_data_protection' => 'required'
- );
-
- $data = [
- 'user' => $user,
- ];
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
- // get the error messages from the validator
- $messages = $validator->messages();
- // redirect our user back to the form with the errors from the validator
- return view('home', $data)->withErrors($validator);
- } else {
- $account = $user->account;
- $account->data_protection = now();
- $account->save();
-
- if(Request::get('accepted_active') == "on"){
- $user->agreement = now();
- }else{
- $user->agreement = null;
- }
-
-
-
- $user->active = 1;
- $user->active_date = now();
- $user->save();
-
- }
- return redirect('/home');
-
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/UserDeleteController.php b/dev/app-bak/Http/Controllers/UserDeleteController.php
deleted file mode 100755
index 39eb5e45..00000000
--- a/dev/app-bak/Http/Controllers/UserDeleteController.php
+++ /dev/null
@@ -1,72 +0,0 @@
-middleware('auth');
- $this->userRepo = $userRepo;
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function deleteAccount(){
- return view('user.delete_account');
- }
-
- /**
- * @param Request $request
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function deleteAccountAction(Request $request)
- {
- $user = Auth::user();
-
- $rules = array(
- 'old_password' => 'required|old_password:' . Auth::user()->password,
- );
-
- Validator::extend('old_password', function ($attribute, $value, $parameters, $validator) {
-
- return Hash::check($value, current($parameters));
-
- });
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
-
- // get the error messages from the validator
- $messages = $validator->messages();
- // redirect our user back to the form with the errors from the validator
- return view('user.delete_account')->withErrors($validator);
-
- }else{
- $this->userRepo->deleteUser($user);
- //make delete
- Auth::logout();
- \Session()->flash('alert-danger', __('account deleted'));
- return redirect(route('home'));
- }
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/UserLevelController.php b/dev/app-bak/Http/Controllers/UserLevelController.php
deleted file mode 100755
index 68d6f3e8..00000000
--- a/dev/app-bak/Http/Controllers/UserLevelController.php
+++ /dev/null
@@ -1,74 +0,0 @@
-middleware('admin');
- }
-
- public function index()
- {
- $data = [
- 'values' => UserLevel::orderBy('pos', 'asc')->get(),
- 'trans' => array_keys(config('localization.supportedLocales')),
- ];
- return view('admin.level.index', $data);
- }
-
- public function store()
- {
-
- $data = Request::all();
- $data['active'] = isset($data['active']) ? true : false;
- $data['default'] = isset($data['default']) ? true : false;
- $data['next_id'] = (isset($data['next_id']) && $data['next_id'] != 0) ? $data['next_id'] : null;
- //is true -> set all other of false;
- if($data['default'] === true){
- $values = UserLevel::all();
- foreach ($values as $value) {
- $value->default = false;
- $value->save();
- }
- }
- //set paylines //pr_line_1
- for ($i=1; $i <=8; $i++) {
- if(isset($data['pr_line_'.$i])){
- $data['paylines'] = $i;
- }
- }
- if($data['id'] == "new"){
- $model = UserLevel::create($data);
- }else{
- $model = UserLevel::find($data['id']);
- $model->fill($data);
- $model->save();
- }
-
- \Session()->flash('alert-save', '1');
- return redirect(route('admin_levels'));
- }
-
-
- /*public function delete($id){
-
- if(ProductAttribute::where('attribute_id', $id)->count()){
- \Session()->flash('alert-error', 'Eintrag wird als Produktattribute verwendet');
- return redirect(route('admin_product_attributes'));
- }
-
- $model = Attribute::findOrFail($id);
- $model->delete();
- \Session()->flash('alert-success', 'Eintrag gelöscht');
- return redirect(route('admin_product_attributes'));
- }
- */
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/UserShopController.php b/dev/app-bak/Http/Controllers/UserShopController.php
deleted file mode 100755
index 60a3a369..00000000
--- a/dev/app-bak/Http/Controllers/UserShopController.php
+++ /dev/null
@@ -1,469 +0,0 @@
-middleware('active.shop');
- $this->userRepo = $userRepo;
- }
-
- public function index()
- {
- $user = Auth::user();
- if ($user->shop && !$user->shop->set_defaults) {
- if ($user->account) {
- $user->shop->title = $user->account->first_name . " " . $user->account->last_name;
- }
- if ($user->account) {
- $user->shop->contact = $this->generate_contact($user);
- } else {
- $user->shop->contact = __('shop.shop_contact_text');
- }
- $user->shop->accessibility =__('shop.shop_accessibility_text');
-
- }
- $data = [
- 'user' => $user,
- ];
- return view('user.shop', $data);
-
- }
-
- public function translate()
- {
- $user = Auth::user();
- $data = [
- 'user' => $user,
- 'localizations' => array_keys(config('localization.supportedLocales')),
-
- ];
- return view('user.shop.translate', $data);
-
- }
-
- public function translateStore()
- {
- $user = Auth::user();
- $data = Request::all();
-
- if (!$user->shop) {
- abort(404);
- }
- foreach($data['trans'] as $lang => $val){
- $this->storeTranslations($user->shop, $lang, $val);
- }
- \Session()->flash('alert-save', true);
- return redirect(route('user_shop_translate'));
- }
-
- public function store()
- {
- $user = Auth::user();
- $data = Request::all();
-
- if (!$user->shop) {
- abort(404);
- }
- $user->shop->title = $data['title'];
- $user->shop->active = isset($data['active']) ? true : false;
- $user->shop->set_defaults = true;
- $user->shop->save();
- $this->storeTranslations($user->shop, \App::getLocale(), $data);
- \Session()->flash('alert-save', true);
-
- return redirect(route('user_shop'));
-
- }
-
- private function storeTranslations($user_shop, $lang, $data){
-
- if($lang == 'de'){
- $user_shop->contact = trim(preg_replace('/\s*\n+/',"\n", $data['contact']));
- $user_shop->accessibility = trim(preg_replace('/\s*\n+/',"\n", $data['accessibility']));
- $user_shop->about = trim(preg_replace('/\s+/', ' ',$data['about']));
- $user_shop->save();
- return;
- }
- $trans = $user_shop->trans;
- $trans[$lang]['contact'] = trim(preg_replace('/\s*\n+/',"\n", $data['contact']));
- $trans[$lang]['accessibility'] = trim(preg_replace('/\s*\n+/',"\n", $data['accessibility']));
- $trans[$lang]['about'] = trim(preg_replace('/\s+/', ' ',$data['about']));
- $user_shop->trans = $trans;
- $user_shop->save();
- return;
- }
-
- private function generate_contact($user)
- {
- $ret = "";
- $sep = "\n";
-
- $ret = $user->account->street != "" ? $user->account->street : __('shop.your_street_number');
- $ret .= " • ";
- $ret.= $user->account->postal_code != "" ? $user->account->postal_code." " : __('shop.your_zip_code');
- $ret.= $user->account->city != "" ? $user->account->city : __('shop.your_city');
- $ret.= $sep;
-
- $pre = $user->account->pre_phone_id != "" ? $user->account->pre_phone->phone." " : "";
- $ret.= __('shop.phone').": ".($user->account->phone != "" ? $pre.$user->account->phone : __('shop.your_phone_number'));
- $ret.= $sep;
-
- $pre = $user->account->pre_mobil_id != "" ? $user->account->pre_mobil->phone." " : "";
- $ret.= __('shop.mobil').": ".($user->account->mobil != "" ? $pre.$user->account->mobil : __('shop.your_mobile_number'));
- $ret.= $sep;
-
- $ret.= $user->email;
-
- return $ret;
-
- }
-
- // Upload FILE -----------------------------------------------------------------------------------------------------------------------
-
- public function uploadImage(){
-
- $user = Auth::user();
-
- if(!$user->shop){
- abort(404);
- }
-
- try {
- $image = \App\Services\Slim::getImages('images')[0];
-
- if ( isset($image['output']['data']) )
- {
- // Base64 of the image
- $data = $image['output']['data'];
- $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');
-
- if (!isset($file_ex[$image['output']['type']])) {
- \Session()->flash('alert-danger', 'File is not jpg or png!');
- return redirect(route('user_shop'));
- }
-
- $ext = $file_ex[$image['output']['type']];
- // Original file name
- $name = $image['output']['name'];
- $name = \App\Services\Slim::sanitizeFileName($name);
- $name = uniqid() . '_' . $name;
-
- $data = \Storage::disk('public')->put(
- 'images/shop/'.$name,
- $data
- );
-
- $user->shop->filename = $name;
- $user->shop->originalname = $image['output']['name'];
- $user->shop->ext = $ext;
- $user->shop->mine = $image['output']['type'];
- $user->shop->size = $image['input']['size'];
- $user->shop->save();
-
-
-
- \Session()->flash('alert-success', __('msg.file_uploaded'));
- return redirect(route('user_shop'));
- }
- \Session()->flash('alert-danger', __('msg.file_empty'));
- return redirect(route('user_shop'));
-
- }
- catch (\Exception $e) {
- \Session()->flash('alert-danger', "Error: ".$e);
- return redirect(route('user_shop'));
- }
- }
-
- public function deleteImage(){
-
- $user = Auth::user();
-
- if(!$user->shop){
- abort(404);
- }
-
- if($user->shop->filename){
- $file = 'images/shop/'.$user->shop->filename;
- \Storage::disk('public')->delete($file);
-
- $user->shop->filename = null;
- $user->shop->originalname = null;
- $user->shop->ext = null;
- $user->shop->mine = null;
- $user->shop->size = null;
- $user->shop->save();
-
- \Session()->flash('alert-success', __('msg.file_deleted'));
- return redirect(route('user_shop'));
-
- }
- \Session()->flash('alert-danger', __('msg.file_not_found'));
- return redirect(route('user_shop'));
-
- }
-
- public function uploadOnSiteImage(){
-
- $user = Auth::user();
- $user_shop_id = Request::get('user_shop_id');
-
- if(!$user->shop || $user->shop->id != $user_shop_id){
- abort(404);
- }
-
- try {
- $image = \App\Services\Slim::getImages('images')[0];
-
- if ( isset($image['output']['data']) )
- {
-
- // Base64 of the image
- $data = $image['output']['data'];
- $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');
-
- if (!isset($file_ex[$image['output']['type']])) {
- \Session()->flash('alert-danger', 'File is not jpg or png!');
- return redirect(route('user_shop'));
- }
-
- $ext = $file_ex[$image['output']['type']];
- // Original file name
- $name = $image['output']['name'];
- $name = \App\Services\Slim::sanitizeFileName($name);
- $name = uniqid() . '_' . $name;
-
- $data = \Storage::disk('public')->put(
- 'images/user_shop/'.$user->shop->id.'/'.$name,
- $data
- );
-
- UserShopOnSite::create([
- 'user_shop_id' => $user->shop->id,
- 'filename' => $name,
- 'original_name' => $image['output']['name'],
- 'ext' => $ext,
- 'mine' => $image['output']['type'],
- 'size' => $image['input']['size']
- ]);
-
- \Session()->flash('alert-success', __('msg.file_uploaded'));
- return redirect(route('user_shop'));
- }
- \Session()->flash('alert-danger', __('msg.file_empty'));
- return redirect(route('user_shop'));
-
- }
- catch (\Exception $e) {
- \Session()->flash('alert-danger', "Error: ".$e);
- return redirect(route('user_shop'));
- }
- }
-
- public function deleteOnSiteImage($image_id, $user_shop_id){
-
- $user = Auth::user();
- if(!$user->shop || $user->shop->id != $user_shop_id){
- abort(404);
- }
- $image = UserShopOnSite::findOrFail($image_id);
-
- if($image->user_shop_id == $user_shop_id){
- $file = 'images/user_shop/'.$user_shop_id.'/'.$image->filename;
- \Storage::disk('public')->delete($file);
-
- $image->delete();
-
- \Session()->flash('alert-success', __('msg.file_deleted'));
- return redirect(route('user_shop'));
-
- }
- \Session()->flash('alert-danger', __('msg.file_not_found'));
- return redirect(route('user_shop'));
-
- }
-
-
-
-
- public function userShopRegisterForm(){
-
- if(Request::get('shop_submit') == 'check'){
- $rules = array(
- 'user_shop_name' => ' required|alpha_dash|unique:user_shops,name|min:4|max:20|full_word_check',
- );
- Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
- if(in_array($value, config('profanity.full_word_check'))){
- return false;
- }
- return true;
- });
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
- \Session()->flash('shop-name-error', 'error');
- return redirect()->back()->withErrors($validator)->withInput(Request::all());
- }
- \Session()->flash('shop-name-error', 'check');
- if(Request::get('user_shop_id')){
- return back()->withInput(Request::all());
- }
- return redirect(route('user_shop'))->withInput(Request::all());
- }
-
- if(Request::get('shop_submit') == 'action') {
-
- $rules = array(
- 'user_shop_name' => ' required|alpha_dash|unique:user_shops,name|min:4|max:20|full_word_check',
- 'user_shop_active' => 'accepted',
-
- );
- Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
- if(in_array($value, config('profanity.full_word_check'))){
- return false;
- }
- return true;
- });
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- \Session()->flash('shop-name-error', 'error');
- return redirect()->back()->withErrors($validator)->withInput(Request::all());
- }
- \Session()->flash('shop-name-error', 'check');
-
- //all is right - save
- $user = Auth::user();
- $data = Request::all();
- $slug = SlugService::createSlug(UserShop::class, 'slug', $data['user_shop_name']);
- if(isset($data['user_shop_id'])){
- $user_shop = UserShop::find($data['user_shop_id']);
- if($user_shop->user_id != $user->id){
- abort(404);
- }
- $user_shop->name = $slug;
- $user_shop->slug = $slug;
- $user_shop->save();
- }else{
- $user_shop = UserShop::create([
- 'user_id' => $user->id,
- 'name' => $slug,
- 'active' => true,
- 'active_date' => now(),
- ]
- );
- }
- \Session()->flash('alert-save', true);
- return redirect(route('user_shop'));
- /*$ret = $this->userShopRegisterSubDomain($user_shop->slug);
- if($ret['success'] === true){
- \Session()->flash('alert-save', true);
- }else{
- $user_shop->forceDelete();
- \Session()->flash('alert-error', $ret['error']);
- }
- return redirect(route('user_shop'));*/
- }
-
- }
-
-
- public function userShopRegisterSubDomain($slug){
-
- $kas = new KasController();
- $domain = 'mivita.care';
-
-
- //check if exisist
- $subdomains = $kas->action('get_subdomains');
- foreach ($subdomains as $subdomain){
- if(!isset($subdomain['subdomain_name'])){
- continue;
- }
- $sub = str_replace(".".$domain, '', $subdomain['subdomain_name']);
- if($sub == $slug){
- return ['success' => false, 'error' => __('shop.error_subdomain_exists')];
- }
- }
- //add
- $full_subdomain_name = $slug.".".$domain;
- $pra = array(
- 'subdomain_name' => $slug,
- 'domain_name' => $domain,
- 'subdomain_path' => '/mein.mivita.care/public/',
- 'php_version' => config('app.php_version'),
- //'ssl_proxy' => 'Y',
- //'redirect_status' => 0
- );
- $add_subdomain = $kas->action('add_subdomain', $pra);
- if($add_subdomain == $full_subdomain_name){
- return ['success' => true];
- }
- return ['success' => false, 'error' => $add_subdomain];
- }
-
- /**
- * @return string to ajax
- */
- public function checkUserShopName(){
-
- $rules = array(
- 'user_shop_name' => ' required|alpha_dash|unique:user_shops,name|min:4|max:20|full_word_check',
- );
- Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
- if(in_array($value, config('profanity.full_word_check'))){
- return false;
- }
- return true;
- });
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
- //$messages = $validator->messages();
- return Response::json(array(
- 'success' => false,
- 'errors' => $validator->getMessageBag()->toArray()
-
- ));
- }
- $slug = SlugService::createSlug(UserShop::class, 'slug', Request::get('user_shop_name'));
-
- return Response::json(array(
- 'success' => true,
- 'preview_user_shop_name' => "https://".$slug.".".config('app.domain').config('app.tld_care'),
- ));
- }
-
- public function editName(){
- $user = Auth::user();
- $user_shop = $user->shop;
- if(!$user_shop){
- abort(404);
- }
- $user_shop_domain = $user_shop->getSubdomain(false);
- $data = [
- 'user' => $user,
- 'user_shop_id' => $user_shop->id,
- 'user_shop_domain' => $user_shop_domain,
- ];
- return view('user.shop_edit_name', $data);
- }
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/UserUpdateEmailController.php b/dev/app-bak/Http/Controllers/UserUpdateEmailController.php
deleted file mode 100755
index e77e651e..00000000
--- a/dev/app-bak/Http/Controllers/UserUpdateEmailController.php
+++ /dev/null
@@ -1,209 +0,0 @@
-db = $db;
- }
-
- public function index()
- {
- return view('user.update_email');
-
- }
-
- public function update()
- {
- $user = Auth::user();
-
- $rules = array(
- 'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . Auth::user()->id,
- //'email-confirm' => 'required|same:email',
- );
-
- Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
- if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
- return false;
- }
- return true;
-
- });
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- // redirect our user back to the form with the errors from the validator
- $messages = $validator->messages();
-
- return view('user.update_email')->withErrors($validator);
-
-
- }else{
- $this->sendActivationMail($user, Request::all());
- \Session()->flash('alert-success', __('We sent you an activation code. Check your email!'));
- return redirect(route('user_update_email'));
- }
-
- }
-
-
- public function adminChangeMail($user_id)
- {
- if(!Auth::user()->isAdmin()){
- abort(404);
- }
- $data = [
- 'user' => User::findOrFail($user_id),
- ];
- return view('admin.change_email', $data);
-
- }
- public function adminUpdateMail(Request $request, $user_id)
- {
- if(!Auth::user()->isAdmin()){
- abort(404);
- }
- $user = User::findOrFail($user_id);
- $data = [
- 'user' => $user,
- ];
-
-
- $rules = array(
- 'email' => 'required|string|email|max:255|unique:users|confirmed|users_update_email:' . $user->id,
- //'email-confirm' => 'required|same:email',
- );
-
- Validator::extend('users_update_email', function ($attribute, $value, $parameters, $validator) {
- if($this->db->table($this->table)->where('email', '=', $value)->where('user_id', '!=', $parameters[0])->count()){
- return false;
- }
- return true;
-
- });
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- // redirect our user back to the form with the errors from the validator
- $messages = $validator->messages();
-
- return view('admin.change_email', $data)->withErrors($validator);
-
-
- }else{
-
- $this->sendActivationMail($user, Request::all());
- \Session()->flash('alert-success', __('An activation code was sent to the account by e-mail!'));
- return redirect(route('admin_lead_edit', [$user->id]));
- }
-
- }
-
-
-
-
- public function activateMail($token)
- {
-
- if ($updateEmail = $this->getUpdateEmailByToken($token)) {
- $user = User::findOrFail($updateEmail->user_id);
- if($user->id == $updateEmail->user_id){
- $user->fill([
- 'email' => $updateEmail->email
- ])->save();
- $this->deleteUpdateEmail($token);
- //Login!
- Auth::login($user);
- \Session()->flash('alert-success', __('Your e-mail has been changed.'));
- return redirect('/home');
-
- }
- }
- return redirect('/home');
- abort(404);
- }
-
-
- public function sendActivationMail($user, array $data)
- {
- $token = $this->createActivation($user, $data);
- Mail::to($data['email'])->locale($user->getLocale())->send(new MailActivateUser($token, $user));
- }
-
-
- protected function getToken()
- {
- return hash_hmac('sha256', Str::random(40), config('app.key'));
- }
-
- public function createActivation($user, array $data)
- {
-
- $updateEmail = $this->getUpdateEmail($user);
-
- if (!$updateEmail) {
- return $this->createToken($user, $data);
- }
- return $this->regenerateToken($user, $data);
-
- }
-
- private function regenerateToken($user, array $data)
- {
-
- $token = $this->getToken();
- $this->db->table($this->table)->where('user_id', $user->id)->update([
- 'email' => $data['email'],
- 'token' => $token,
- 'created_at' => new Carbon()
- ]);
- return $token;
- }
-
- private function createToken($user, array $data)
- {
- $token = $this->getToken();
- $this->db->table($this->table)->insert([
- 'user_id' => $user->id,
- 'email' => $data['email'],
- 'token' => $token,
- 'created_at' => new Carbon()
- ]);
- return $token;
- }
-
- public function getUpdateEmail($user)
- {
- return $this->db->table($this->table)->where('user_id', $user->id)->first();
- }
-
-
- public function getUpdateEmailByToken($token)
- {
- return $this->db->table($this->table)->where('token', $token)->first();
- }
-
- public function deleteUpdateEmail($token)
- {
- $this->db->table($this->table)->where('token', $token)->delete();
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/UserUpdatePasswordController.php b/dev/app-bak/Http/Controllers/UserUpdatePasswordController.php
deleted file mode 100755
index 5c37a74f..00000000
--- a/dev/app-bak/Http/Controllers/UserUpdatePasswordController.php
+++ /dev/null
@@ -1,106 +0,0 @@
-middleware('auth');
- }
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
- */
- public function updatePassword()
- {
- return view('user.update_password');
- }
-
-
-
- public function updatePasswordStore()
- {
- $rules = array(
- 'old_password' => 'required|old_password:' . Auth::user()->password,
- 'password' => 'required|string|min:8|confirmed',
- );
-
- Validator::extend('old_password', function ($attribute, $value, $parameters, $validator) {
-
- return Hash::check($value, current($parameters));
-
- });
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
-
- // get the error messages from the validator
- $messages = $validator->messages();
- // redirect our user back to the form with the errors from the validator
- return view('user.update_password')->withErrors($validator);
-
- }
- $user = Auth::user();
- $data = Request::all();
- $user->fill([
- 'password' => Hash::make($data['password'])
- ])->save();
-
-
- \Session()->flash('alert-save', '1');
- return redirect(route('user_update_password'));
-
- }
-
-
- /**
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
- */
- public function updatePasswordFirst(){
- if(!Auth::user()->isPasswort()){
- return view('user.update_password_first');
- }
- return redirect(route('user_update_password'));
- }
-
-
- public function updatePasswordFirstStore()
- {
- $rules = array(
- 'password' => 'required|string|min:6|confirmed',
- );
-
-
- $validator = Validator::make(Request::all(), $rules);
-
- if ($validator->fails()) {
-
- // get the error messages from the validator
- $messages = $validator->messages();
- // redirect our user back to the form with the errors from the validator
- return view('user.update_password_first')->withErrors($validator);
-
- }
- $user = Auth::user();
- $data = Request::all();
- $user->fill([
- 'password' => Hash::make($data['password'])
- ])->save();
-
-
-
- \Session()->flash('alert-save', '1');
- return redirect('/home');
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Web/CardController.php b/dev/app-bak/Http/Controllers/Web/CardController.php
deleted file mode 100755
index fa4da516..00000000
--- a/dev/app-bak/Http/Controllers/Web/CardController.php
+++ /dev/null
@@ -1,232 +0,0 @@
-add('sdjk922', 'Product 2', 1, 19.95, ['size' => 'medium']);
- public function addToCardGet($id, $quantity = 1, $product_slug = false)
- {
- $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();
-
- // Debug: Yard-Status nach Hinzufügen
- $yardCount = \Yard::instance($this->instance)->count();
- $yardTotal = \Yard::instance($this->instance)->total();
-
- \Log::info('✅ Product added to Yard successfully', [
- 'product_id' => $product->id,
- 'product_name' => $product->getLang('name'),
- 'quantity' => $quantity,
- 'instance' => $this->instance,
- 'yard_total_items' => $yardCount,
- 'yard_total_price' => $yardTotal,
- 'session_id' => \Session::getId()
- ]);
-
- \Session()->flash('show-card-after-add', true);
-
- // CRITICAL: Error-Messages bereinigen und Session für Redirect vorbereiten
- \App\Services\SessionCleaner::cleanAndSave('CardController::addToCardGet');
- }
- return back();
- }
-
- public function addToCardPost($id)
- {
-
- $product = Product::find($id);
- if ($product) {
- $image = "";
- if ($product->images->count()) {
- $image = $product->images->first()->slug;
- }
- $quantity = Request::get('quantity') ? Request::get('quantity') : 1;
- $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);
- \App\Services\SessionCleaner::cleanAndSave('CardController::addToCardPost');
- }
-
- return back();
- }
-
- public function showCard()
- {
-
- if (Request::get('selected_country')) {
- Yard::instance($this->instance)->setShippingCountryWithPrice(Request::get('selected_country'));
- } else {
- Yard::instance($this->instance)->reCalculateShippingPrice();
- }
-
- //show konflikt wenn user eingeloggt ist und country nicht gesetzt ist
- $shipping_error = $this->checkShippingError();
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange($this->instance),
- 'yard_instance' => $this->instance,
- 'shipping_error' => $shipping_error ?? false,
- ];
- return view('web.templates.card', $data);
- }
-
- public function updateCard()
- {
-
- $data = Request::all();
- if (isset($data['quantity'])) {
- foreach ($data['quantity'] as $rowId => $qty) {
- Yard::instance($this->instance)->update($rowId, $qty);
- Yard::instance($this->instance)->reCalculateShippingPrice();
- }
- } else {
- $this->deleteCard();
- }
- \App\Services\SessionCleaner::cleanAndSave('CardController::updateCard');
- return back();
- }
-
- public function checkoutServer()
- {
-
- $user_shop = Util::getUserShop();
-
- do {
- $identifier = Util::getToken();
- } while (ShoppingInstance::where('identifier', $identifier)->count());
-
- $data = [];
- $data['is_from'] = 'shopping';
- $data['user_price_infos'] = Yard::instance($this->instance)->getUserPriceInfos();
-
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => $user_shop->id,
- 'payment' => 1, //Customer Shop Payment
- 'subdomain' => url('/'),
- 'country_id' => Yard::instance($this->instance)->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'shopping_data' => $data,
- 'back' => url()->previous(),
-
- ]);
-
- Yard::instance($this->instance)->store($identifier);
- //add to DB
- $path = route('checkout.checkout_card', ['identifier' => $identifier]);
- if (strpos($path, 'https') === false) {
- $path = str_replace('http', 'https', $path);
- }
- return redirect()->secure($path);
- }
-
- public function backToShop()
- {
- $this->deleteCard();
- return redirect(url('/'));
- }
- public function removeCard($rowId)
- {
- Yard::instance($this->instance)->remove($rowId);
- \App\Services\SessionCleaner::cleanAndSave('CardController::removeCard');
- return back();
- }
-
- public function deleteCard()
- {
-
- $setCode = Shop::getUserShopLang(null, $this->instance);
- $mylangs = Shop::getLangChange($this->instance);
- foreach ($mylangs as $code => $country) {
- if (strtolower($setCode) === strtolower($code)) {
- Shop::initUserShopLang($country, $this->instance);
- return back();
- }
- }
- }
-
- private function checkShippingError()
- {
- $shipping_error = false;
- if (\Auth::guard('customers')->check()) {
- $user = \Auth::guard('customers')->user();
- if ($user->shopping_user_id) {
- $shopping_user = ShoppingUser::find($user->shopping_user_id);
- if ($shopping_user->same_as_billing) {
- if ($shopping_user->billing_country_id != Yard::instance($this->instance)->getUserCountryId()) {
- $user_country = Yard::instance($this->instance)->getUserCountry();
- $user_country_name = $user_country ? $user_country->getLocated() : '';
- $billing_country = $shopping_user->billing_country;
- $country_name = $billing_country ? $billing_country->getLocated() : '';
- $shipping_error = __('website.shipping_error_billing', ['shipping_country' => $user_country_name, 'billing_country' => $country_name]);
- }
- } else {
- if ($shopping_user->shipping_country_id != Yard::instance($this->instance)->getUserCountryId()) {
- $user_country = Yard::instance($this->instance)->getUserCountry();
- $user_country_name = $user_country ? $user_country->getLocated() : '';
- $shipping_country = $shopping_user->shipping_country;
- $country_name = $shipping_country ? $shipping_country->getLocated() : '';
- $shipping_error = __('website.shipping_error_delivery', ['shipping_country' => $user_country_name, 'billing_country' => $country_name]);
- }
- }
- }
- }
- return $shipping_error;
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Web/CheckoutController.php b/dev/app-bak/Http/Controllers/Web/CheckoutController.php
deleted file mode 100755
index b5ceabe5..00000000
--- a/dev/app-bak/Http/Controllers/Web/CheckoutController.php
+++ /dev/null
@@ -1,568 +0,0 @@
-checkoutRepo = $checkoutRepository;
- }
-
- /**
- * Zeigt die Checkout-Seite an
- *
- * @return \Illuminate\View\View
- */
- public function checkout()
- {
- /*
- @if(Auth::guard('customers')->check())
- {{ __('navigation.logout') }}
- @else
- {{ __('website.to_customer_portal') }}
- @endif
- @if(Auth::guard('user')->check())
- */
- $shopping_data = Yard::instance($this->instance)->getYardExtra('shopping_data');
- $is_from = $shopping_data['is_from'] ?? 'shopping';
- $is_for = $shopping_data['is_for'] ?? false;
- $is_abo = isset($shopping_data['is_abo']) ? (bool) $shopping_data['is_abo'] : false;
- $abo_interval = $shopping_data['abo_interval'] ?? 0;
- $homeparty_id = $shopping_data['homeparty_id'] ?? null;
- $shopping_user = null;
-
- if ($is_for === 'ot-customer' || $is_for === 'abo-ot-customer') {
- $is_from = 'shopping';
- }
- Util::setInstanceStatus(1, true); // link_check
- if ($is_abo) {
- $instance_status = Util::getInstanceStatus();
- if ($instance_status === 'link_paid') {
- return $this->redirectToIsFinal($instance_status);
- }
- }
- if (Session::has('new_session')) {
- $this->checkoutRepo->sessionDestroy();
- Session::forget('new_session');
- }
- $shopping_user = $this->initializeShoppingUserSession($is_from, $is_for, $shopping_data, $homeparty_id);
-
- $this->prepareShoppingUserData($shopping_user);
- $payment_methods = $this->checkoutRepo->getPaymentsMethods($is_from, $is_abo);
-
- if ($shopping_user === null) {
- abort(403, 'ShoppingUser not found');
- }
- $data = [
- 'is_from' => $is_from,
- 'is_for' => $is_for,
- 'is_abo' => $is_abo,
- 'abo_interval' => $abo_interval,
- 'shopping_data' => $shopping_data,
- 'user_shop' => Util::getUserShop(),
- 'shopping_user' => $shopping_user,
- 'shopping_mode' => Util::getUserShoppingMode(),
- 'payment_methods' => $payment_methods['default'],
- 'payment_methods_active' => $payment_methods['active'],
- 'payment_data' => $payment_methods['data'],
- 'instance_status' => $instance_status ?? false,
- '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) {
- $shopping_user->same_as_billing = false;
- }
- 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) {
- $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();
- }
- if (old('selected_country') && old('selected_country') === 'change') {
- Session::forget('_old_input.selected_country');
- $shopping_user->billing_state = old('billing_state');
- $shopping_user->shipping_state = old('shipping_state');
- } else {
- $shopping_user->billing_state = Yard::instance($this->instance)->getShippingCountryId();
- $shopping_user->shipping_state = Yard::instance($this->instance)->getShippingCountryId();
- }
- }
-
- /**
- * Verarbeitet den Checkout-Prozess
- *
- * @return \Illuminate\Http\RedirectResponse
- */
- public function checkoutFinal()
- {
- dd("checkoutFinal");
- $data = Request::all();
- if (isset($data['payment_method'])) {
- $this->checkoutRepo->isPaymentsMethodsActive($data['payment_method'], $data['is_from'], $data['is_abo']);
- }
-
- Util::setInstanceStatus(2, true); // link_check
-
- // Länderwechsel verarbeiten
- if (isset($data['selected_country']) && $data['selected_country'] === 'change') {
- return $this->handleCountryChange($data);
- }
-
- // Validierung
- $validator = $this->validateCheckoutData();
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- // Benutzer und Bestellung erstellen
- $shopping_user = $this->checkoutRepo->makeShoppingUser($data);
- $shopping_order = $this->checkoutRepo->makeShoppingOrder($shopping_user, $data);
-
- // CustomerPriority prüfen
- if ($shopping_user->is_from === 'shopping') {
- CustomerPriority::checkOne(ShoppingUser::find($shopping_user->id), true);
- }
-
- Util::setUserHistoryValue(['status' => 2, 'shopping_order_id' => $shopping_order->id]);
-
- // Zahlungsmethode verarbeiten
- if (Request::get('payment_method')) {
- return $this->processPaymentMethod($data, $shopping_user, $shopping_order);
- }
-
- return redirect()->back();
- }
-
- /**
- * Verarbeitet den Länderwechsel
- *
- * @param array $data
- * @return \Illuminate\Http\RedirectResponse
- */
- private function handleCountryChange($data)
- {
- 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']);
- }
-
- return back()->withInput(Request::all());
- }
-
- /**
- * Validiert die Checkout-Daten
- *
- * @return \Illuminate\Validation\Validator
- */
- private function validateCheckoutData()
- {
- $rules = [
- 'billing_salutation' => 'required',
- 'billing_firstname' => 'required',
- 'billing_lastname' => 'required',
- 'billing_email' => 'required|email',
- 'billing_address' => 'required',
- 'billing_zipcode' => 'required',
- 'billing_city' => 'required',
- 'accepted_data_checkbox' => 'accepted',
- ];
-
- 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'
- ]);
- }
-
- return Validator::make(Request::all(), $rules);
- }
-
- /**
- * Verarbeitet die Zahlungsmethode
- *
- * @param array $data
- * @param ShoppingUser $shopping_user
- * @param ShoppingOrder $shopping_order
- * @return mixed
- */
- private function processPaymentMethod($data, $shopping_user, $shopping_order)
- {
- $result = [];
- $payment_method = Request::get('payment_method');
-
- // Kreditkarte prüfen
- if ($payment_method === 'cc') {
- $result = $this->checkCreditCard($data, $shopping_user, $shopping_order);
- if (!isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
- return $result;
- }
- }
-
- // SEPA prüfen
- if ($payment_method === 'elv') {
- $result = $this->checkSepaAccount($data, $shopping_user, $shopping_order);
- if (!isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
- return $result;
- }
- }
-
- // Zahlung vorbereiten
- $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);
- $this->checkoutRepo->putSessionPayments('payment_reference', $reference);
- $pay->setPersonalData();
-
- return $pay->ResponseData();
- }
-
- /**
- * Prüft die Kreditkartendaten
- *
- * @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->init($shopping_user, $shopping_order);
- $ret['cc'] = $pay->checkCreditCard($data);
-
- if ($ret['cc']['status'] === 'ERROR' || $ret['cc']['status'] === 'INVALID') {
- 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
- * @return bool|\Illuminate\Http\RedirectResponse
- */
- private function checkSepaAccount($data, $shopping_user, $shopping_order)
- {
- if (is_null(Request::get('mandate_identification'))) {
- $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);
-
- if ($ret['elv']['status'] === 'ERROR' || $ret['elv']['status'] === 'INVALID') {
- 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") {
- 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());
- }
-
- $ret['elv']['bankaccountholder'] = $data['elv_bankaccountholder'];
- } else {
- $ret['elv'] = [
- 'mandate_identification' => Request::get('mandate_identification'),
- 'creditor_identifier' => Request::get('creditor_identifier'),
- 'iban' => $data['elv_iban'],
- 'bic' => $data['elv_bic'],
- '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()
- {
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'is_checkout' => true,
- 'yard_instance' => $this->instance,
- ];
-
- return view('web.templates.checkout-is-final', $data);
- }
-
- /**
- * Verarbeitet den Transaktionsstatus
- *
- * @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();
-
- 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'));
- }
-
- $ShoppingPayment->status = $status;
- $ShoppingPayment->save();
-
- if ($status === "success") {
- return $this->handleSuccessfulTransaction($ShoppingPayment, $reference);
- }
-
- 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'));
- }
-
- 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'));
- }
- }
-
- /**
- * Verarbeitet eine erfolgreiche Transaktion
- *
- * @param ShoppingPayment $ShoppingPayment
- * @param string $reference
- * @return \Illuminate\View\View
- */
- private function handleSuccessfulTransaction($ShoppingPayment, $reference)
- {
- Yard::instance($this->instance)->destroy();
- $this->checkoutRepo->sessionDestroy(true);
- Util::setInstanceStatus(3, true); // link_pending
-
- // Abo erstellen, falls nötig
- if ($ShoppingPayment->shopping_order->is_abo) {
- AboHelper::createNewAbo($ShoppingPayment);
- }
-
- $payt = $ShoppingPayment->payment_transactions->last();
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'order_reference' => $reference,
- 'pay_trans' => $payt,
- 'is_checkout' => true,
- 'yard_instance' => $this->instance,
- ];
-
- return view('web.templates.checkout-final', $data);
- }
-
- /**
- * Verarbeitet eine genehmigte Transaktion
- *
- * @param int $transactionId
- * @param string $reference
- * @return \Illuminate\View\View
- */
- public function transactionApproved($transactionId, $reference)
- {
- $payt = PaymentTransaction::findOrFail($transactionId);
- if ($payt->shopping_payment->reference != $reference) {
- abort(404);
- }
- Yard::instance($this->instance)->destroy();
- $this->checkoutRepo->sessionDestroy(true);
- Util::setInstanceStatus(3, true); // link_pending
-
- // Abo erstellen, falls nötig
- if ($payt->shopping_payment->shopping_order->is_abo) {
- AboHelper::createNewAbo($payt->shopping_payment);
- }
-
- // Rechnung MIV
- if ($payt->status === 'FNCMIV') {
- $this->directPaymentStatus($payt);
- }
-
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'order_reference' => $payt->shopping_payment->reference,
- 'pay_trans' => $payt,
- 'is_checkout' => true,
- 'yard_instance' => $this->instance,
- ];
-
- return view('web.templates.checkout-final', $data);
- }
-
- /**
- * Speichert die Zahlungsdaten des Benutzers
- *
- * @param ShoppingUser $shopping_user
- * @param array $ret
- * @return void
- */
- private function storeUserPaymentsData($shopping_user, $ret)
- {
- if ($shopping_user->auth_user_id) {
- $user = User::find($shopping_user->auth_user_id);
- if ($user && $user->account) {
- if (isset($ret['elv']) && is_array($ret['elv'])) {
- $user->account->payment_data = $ret['elv'];
- $user->account->save();
- }
- }
- }
- }
-
- /**
- * Verarbeitet den direkten Zahlungsstatus (Rechnung MIV)
- *
- * @param PaymentTransaction $payt
- * @return void
- */
- private function directPaymentStatus(PaymentTransaction $payt)
- {
- if (isset($payt->transmitted_data['param'])) {
- $shopping_order = ShoppingOrder::find($payt->transmitted_data['param']);
- $shopping_order->txaction = 'invoice_open';
- $shopping_order->save();
-
- $shopping_payment = ShoppingPayment::where('reference', $payt->transmitted_data['reference'])->first();
- if ($shopping_payment) {
- $shopping_payment->txaction = 'invoice_open';
- $shopping_payment->save();
- }
-
- $send_link = Payment::paymentStatusPaidAction($shopping_order, false, $shopping_payment);
- $data = [
- 'mode' => $payt->transmitted_data['mode'],
- 'txaction' => $payt->txaction,
- 'send_link' => $send_link,
- ];
-
- Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
- }
- }
-
- /**
- * 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
- * @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
- if ($this->checkoutRepo->getSessionPayments('shopping_user_id')) {
- return $this->getExistingShoppingUser();
- }
- //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
- if ($is_from === 'shopping') {
- //Bestelllink
- if ($is_for === 'ot-customer' || $is_for === 'abo-ot-customer') {
- //customer shop mit den Daten aus dem Salescenter shopping_data
- return $this->checkoutRepo->makeCustomerShoppingUser($shopping_data, $is_for, $is_from);
- }
- //Webshop
- return $this->checkoutRepo->initShoppingUser($is_for, $is_from, $homeparty_id);
- }
-
- return $this->getExistingShoppingUser();
- }
-
- /**
- * Holt den existierenden ShoppingUser und bereitet ihn vor
- *
- * @return ShoppingUser
- */
- private function getExistingShoppingUser()
- {
- $shopping_user = ShoppingUser::findOrFail($this->checkoutRepo->getSessionPayments('shopping_user_id'));
- $shopping_user->billing_state = Shop::getCountryShippingCountryId($shopping_user->billing_country_id);
- $shopping_user->shipping_state = Shop::getCountryShippingCountryId($shopping_user->shipping_country_id);
- $shopping_user->same_as_billing = $shopping_user->same_as_billing ? false : true; // reinvert
-
- return $shopping_user;
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Web/ContactController.php b/dev/app-bak/Http/Controllers/Web/ContactController.php
deleted file mode 100755
index a2d56eb4..00000000
--- a/dev/app-bak/Http/Controllers/Web/ContactController.php
+++ /dev/null
@@ -1,127 +0,0 @@
- $this->GOOGLE_ReCAPTCHA_KEY,
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'yard_instance' => 'webshop',
-
- ];
- return view('web.templates.kontakt', $data);
- }
-
- public function store()
- {
-
- $user_shop = Util::getUserShop();
-
-
- $rules = array(
- 'salutation' => 'required',
- 'first_name' => 'required',
- 'last_name' => 'required',
- 'email' => 'required|email',
- 'message' => 'required',
- 'g-recaptcha-response' => 'required|recaptcha',
- 'accepted_data_protection' => 'required',
- );
- if (!$user_shop || $user_shop->id === 22) {
- $rules['sales_partnership'] = 'required';
- if (Request::get('sales_partnership') === 'JA') {
- $rules['sales_partnership_message'] = 'required';
- }
- }
-
-
- Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {
- return $this->reCaptcha_validate($attribute, $value, $parameters, $validator);
- });
-
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
-
- $contact = [];
- $contact['salutation'] = Request::get('salutation');
- $contact['first_name'] = Request::get('first_name');
- $contact['last_name'] = Request::get('last_name');
- $contact['email'] = Request::get('email');
- $contact['phone'] = Request::get('phone');
- $contact['message'] = Request::get('message');
- if (!$user_shop){
- $contact['sales_partnership'] = Request::get('sales_partnership');
- $contact['sales_partnership_message'] = Request::get('sales_partnership_message');
- }
-
-
- $contact_mail = config('app.contact_mail');
- if($user_shop){
- Mail::to($contact['email'])->bcc([$user_shop->user->email, $contact_mail])->locale(\App::getLocale())->send(new MailContact($contact));
- }else{
- Mail::to($contact['email'])->bcc($contact_mail)->locale(\App::getLocale())->send(new MailContact($contact));
- }
-
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.contact-final', $data);
-
- }
-
-
- private function reCaptcha_validate($attribute, $value, $parameters, $validator)
- {
-
- $client = new Client();
-
- $response = $client->post(
- 'https://www.google.com/recaptcha/api/siteverify',
- ['form_params' =>
- [
- 'secret' => $this->GOOGLE_ReCAPTCHA_SECRET,
- 'response' => $value
- ]
- ]
- );
-
- $body = json_decode((string)$response->getBody());
- return $body->success;
- }
-
-
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Web/HomepartyController.php b/dev/app-bak/Http/Controllers/Web/HomepartyController.php
deleted file mode 100755
index 77cfd7c1..00000000
--- a/dev/app-bak/Http/Controllers/Web/HomepartyController.php
+++ /dev/null
@@ -1,131 +0,0 @@
-where('token_active', true)->first();
- if(!$homeparty){
- abort(403, __('msg.link_for_homeparty_not_found'));
- }
- $homeparty_user = null;
- if($gid){
- if($gid === 'new'){
- $homeparty_user = new HomepartyUser();
- $homeparty_user->same_as_billing = true;
- $homeparty_user->billing_country_id = $homeparty->country_id;
- $homeparty_user->shipping_country_id = $homeparty->country_id;
-
- }else{
- //no edit
- abort(403, __('msg.link_for_homeparty_not_found'));
-
- $homeparty_user = HomepartyUser::find($gid);
- if(!$homeparty_user || $homeparty_user->homeparty_id !== $homeparty->id){
- abort(403, __('msg.link_for_homeparty_not_found'));
- }
- }
- }
- $data = [
- 'homeparty' => $homeparty,
- 'homeparty_user' => $homeparty_user,
- 'homeparty_host' => $homeparty->homeparty_host,
- 'mivita_member' => $homeparty->auth_user
- ];
- return view('user.homeparty.self_guest_detail', $data);
- }
-
-
- public function detailStore($token = null, $gid = null)
- {
- if(!$token){
- abort(404);
- }
- $homeparty = Homeparty::where('token', $token)->where('token_active', true)->first();
- if(!$homeparty){
- abort(403, __('msg.link_for_homeparty_not_found'));
- }
-
- $rules = array(
- 'billing_salutation' => 'required',
- 'billing_firstname' => 'required',
- 'billing_lastname' => 'required',
- 'billing_address' => 'required',
- 'billing_zipcode' => 'required',
- 'billing_city' => 'required',
- 'billing_country_id' => 'required',
- 'checkbox_datenverarbeitung' => 'required',
- 'checkbox_daten_completely' => 'required'
- );
-
- 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_country_id' => 'required'
- ]);
- }
-
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- if($gid === null){
- $homeparty_user = HomepartyUser::create([
- 'homeparty_id' => $homeparty->id,
- 'auth_user_id' => $homeparty->auth_user_id,
- 'is_host' => false,
- ]);
- }else{
- //no edit
- abort(403, __('msg.link_for_homeparty_not_found'));
- $homeparty_user = HomepartyUser::find($gid);
- if(!$homeparty_user || $homeparty_user->homeparty_id !== $homeparty->id){
- abort(403, __('msg.link_for_homeparty_not_found'));
- }
- }
-
- if(!$homeparty_user){
- abort(403, __('msg.link_for_homeparty_not_found'));
- }
-
- $data = Request::all();
- $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'];
- $homeparty_user->fill($data)->save();
- \Session()->flash('alert-save', '1');
- return redirect(route('homeparty', [$token]));
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Controllers/Web/RegisterController.php b/dev/app-bak/Http/Controllers/Web/RegisterController.php
deleted file mode 100755
index 0596ba6d..00000000
--- a/dev/app-bak/Http/Controllers/Web/RegisterController.php
+++ /dev/null
@@ -1,168 +0,0 @@
-userRepo = $userRepo;
- }
-
- public function index()
- {
- if (config('app.debug')) {
- \Log::channel('domain')->debug('RegisterController: index - Session user_shop', [
- 'session_user_shop_id' => \Session::get('user_shop')?->id,
- 'session_user_shop_name' => \Session::get('user_shop')?->name,
- 'session_user_shop_user_id' => \Session::get('user_shop')?->user_id,
- 'session_id' => \Session::getId(),
- 'session_domain' => config('session.domain'),
- 'request_host' => request()->getHost(),
- 'all_session_keys' => array_keys(\Session::all())
- ]);
- }
-
- $data = [
- 'GOOGLE_ReCAPTCHA_KEY' => $this->GOOGLE_ReCAPTCHA_KEY,
- 'user_shop' => Util::getUserShop(),
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.registrierung', $data);
- }
-
- public function member($member_id = false)
- {
- if (!$member_id) {
- return redirect('/registrierung');
- }
- $user_id = (int) str_replace('m', '', $member_id) - config('mivita.add_number_id');
- $user = User::find($user_id);
- if (!$user || !$user->isActive() || !$user->isActiveAccount()) {
- return redirect('/registrierung');
- }
- $data = [
- 'GOOGLE_ReCAPTCHA_KEY' => $this->GOOGLE_ReCAPTCHA_KEY,
- 'user_shop' => Util::getUserShop(),
- 'from_member_id' => $member_id,
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.registrierung', $data);
- }
-
- public function register()
- {
-
- $rules = array(
- 'salutation' => 'required',
- 'first_name' => 'required',
- 'last_name' => 'required',
- 'email' => 'required|string|email|max:255|unique:users',
- 'email-confirm' => 'required|same:email',
- 'password' => 'required|string|min:6|confirmed',
- 'password_confirmation' => 'required|string|min:6',
- 'g-recaptcha-response' => 'required|recaptcha',
- 'accepted_data_protection' => 'required',
- );
-
- Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {
- return $this->reCaptcha_validate($attribute, $value, $parameters, $validator);
- });
-
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return back()->withErrors($validator)->withInput(Request::all());
- }
-
- $user_shop = Util::getUserShop();
-
- $data = Request::all();
- $user = $this->userRepo->create($data);
-
- $confirmation_code = UserService::createConfirmationCode();
- $m_sponsor_id = 1;
- if ($user_shop) {
- $m_sponsor_id = $user_shop->user->id;
- }
- if (isset($data['from_member_id'])) {
- $m_sponsor_id = (int) str_replace('m', '', $data['from_member_id']) - config('mivita.add_number_id');
- }
- $user->lang = !empty(\App::getLocale()) ? \App::getLocale() : "de";
- $user->confirmation_code = $confirmation_code;
- $user->confirmation_code_to = date('Y-m-d H:i:s', strtotime('+1 week'));
- $user->confirmation_code_remider = 0;
- $user->m_sponsor = $m_sponsor_id;
-
- $UserLevel = UserLevel::where('default', 1)->first();
- if ($UserLevel) {
- $user->m_level = $UserLevel->id;
- } else {
- $user->m_level = 10;
- }
-
- $user->save();
-
- $user->account->data_protection = now();
- $user->account->save();
-
- Mail::to($user->email)->locale($user->getLocale())->send(new MailVerifyAccount($confirmation_code, User::find($user->id)));
- return redirect('/registrierung/finish');
- }
-
- public function finish()
- {
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.registrierung_finish', $data);
- }
-
- private function reCaptcha_validate($attribute, $value, $parameters, $validator)
- {
-
- $client = new Client();
-
- $response = $client->post(
- 'https://www.google.com/recaptcha/api/siteverify',
- [
- 'form_params' =>
- [
- 'secret' => $this->GOOGLE_ReCAPTCHA_SECRET,
- 'response' => $value
- ]
- ]
- );
-
- $body = json_decode((string)$response->getBody());
- return $body->success;
- }
-}
diff --git a/dev/app-bak/Http/Controllers/Web/SiteController.php b/dev/app-bak/Http/Controllers/Web/SiteController.php
deleted file mode 100755
index ae28447a..00000000
--- a/dev/app-bak/Http/Controllers/Web/SiteController.php
+++ /dev/null
@@ -1,239 +0,0 @@
- \Session::getId(),
- 'user_shop_id' => session('shop.id'),
- 'user_shop_slug' => session('shop.slug'),
- 'user_init_country' => session('user_init_country'),
- 'locale' => session('locale'),
- 'request_host' => request()->getHost(),
- 'domain_context' => request()->attributes->get('domain_context')?->type,
- 'gpt5_v3_status' => 'active'
- ]);
- }
-
- $this->setIPInfo();
- $products = ['aloe-vera-gel-99', 'aloe-vera-saft-500-ml', 'aloe-vera-lippenbalsam'];
- // $set_products = ['aloe-vera-cleaner-set', 'aloe-vera-koerper-set', 'aloe-vera-repair-set'];
- $set_products = ['aloe-vera-koerper-set', 'baby-set', 'aloe-vera-gel-set'];
- $data = [
- 'products' => Product::whereIn('slug', $products)->where('active', true)->whereJsonContains('show_on', '1')->get(),
- 'set_products' => Product::whereIn('slug', $set_products)->where('active', true)->whereJsonContains('show_on', '1')->get(),
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'site' => IqSite::find(1),
- 'yard_instance' => 'webshop',
- ];
-
- return view('web.index', $data);
- }
-
- public function domainCheck()
- {
- die("checked");
- }
-
- public function changeLang()
- {
- $data = Request::all();
-
- if (isset($data['change_country_id'])) {
- $mylangs = Shop::getLangChange('webshop');
-
- foreach ($mylangs as $code => $country) {
- if (strtolower($data['change_country_id']) === strtolower($code)) {
- $countryCode = strtolower($code); //lieferland
- $localeCode = strtolower($data['change_locale_id'] ?? $countryCode); //sprache
-
- // Optimierte Session-Schreibvorgänge
- \Session::put('user_init_country', $countryCode); //lieferland
- \Session::forget('user_init_country_options'); // Land löschen, da es vom User gesetzt wurde
- \Session::put('locale', $localeCode); //sprache
-
-
- // Sprache für Laravel setzen
- \App::setLocale($localeCode);
- // UserShop-Sprache initialisieren für Checkout
- Shop::initUserShopLang($country, 'webshop');
-
- // Session bereinigen und speichern (wichtig für Domain-Wechsel)
- \App\Services\SessionCleaner::cleanAndSave('SiteController::changeLang');
-
- // Debug-Logging für changeLang
- if (config('app.debug')) {
- \Log::info('SiteController: changeLang() - Sprache/Land geändert', [
- 'country_code' => $countryCode,
- 'locale_code' => $localeCode,
- 'session_id' => \Session::getId(),
- 'user_shop_id' => session('shop.id'),
- 'checkout_ready' => true,
- 'request_host' => request()->getHost()
- ]);
- }
-
- return back();
- }
- }
- }
-
- return back()->withError('Ungültiges Land/Sprache ausgewählt');
- }
-
- private function setIPInfo()
- {
- // GPT-5 v3.1: Cache-Check - wurde schon gesetzt?
- if (\Session::has('user_init_country')) {
- return;
- }
-
- $country = 'de'; // Default-Wert für DACH-Region
-
- // IP-basierte Länder-Erkennung
- if (config('app.ipinfo')) {
- $ipCountry = strtolower(Shop::getIPDatabaseInfo());
- if ($ipCountry === 'error') {
- $country = 'de'; // Fallback bei IP-Service-Fehlern
- } else {
- $country = $ipCountry;
- }
- }
-
- // Sprache setzen (mit Validation)
- if (array_key_exists($country, \App\Services\UserService::getTransChange())) {
- \Session::put('user_init_country', $country);
- \Session::put('locale', $country);
- \App::setLocale($country);
- } else {
- // Default: Deutschland
- \Session::put('user_init_country', 'de');
- \Session::put('locale', 'de');
- \App::setLocale('de');
- $country = 'de'; // Für nachfolgende Logik
- }
-
- // Option für den Init setzen, hier wird das Lieferland für die Auswahl im Sidepanel gesetzt
- if (array_key_exists($country, Shop::getLangChange('webshop'))) {
- \Session::put('user_init_country_options', $country);
- } else {
- \Session::put('user_init_country_options', 'de');
- }
-
- // GPT-5 v3.1: Session bereinigen und speichern für Domain-Wechsel-Stabilität
- \App\Services\SessionCleaner::cleanAndSave('SiteController::setIPInfo');
-
- // GPT-5 v3.1: Optimiertes Debug-Logging
- if (config('app.debug')) {
- \Log::info('SiteController: setIPInfo() - Länder/Sprache initialisiert', [
- 'detected_country' => $country,
- 'user_init_country' => \Session::get('user_init_country'),
- 'locale' => \Session::get('locale'),
- 'delivery_country' => \Session::get('user_init_country_options'),
- 'session_id' => \Session::getId(),
- 'user_shop_id' => session('shop.id'),
- 'user_shop_slug' => session('shop.slug'),
- 'checkout_ready' => true,
- 'ip_detection' => config('app.ipinfo') ? 'enabled' : 'disabled'
- ]);
- }
- }
-
- public function site($site, $subsite = false, $product_slug = false)
- {
- $this->setIPInfo();
- $subsite = trim($subsite, '/');
- $product_slug = trim($product_slug, '/');
- if ($product_slug) {
- $category = Category::where('slug', $subsite)->where('active', true)->first();
- $product = Product::where('slug', $product_slug)->where('active', true)->whereJsonContains('show_on', '1')->first();
- if ($category && $product) {
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'subsite' => $subsite,
- 'categories' => Category::where('active', true)->orderBy('pos', 'ASC')->get(),
- 'product' => $product,
- 'p_count' => Product::where('active', true)->whereJsonContains('show_on', '1')->count(),
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.produkte-show', $data);
- }
- }
- if ($site == 'produkte') {
- if ($subsite && $subsite !== 'alle-produkte') {
- $category = Category::where('slug', $subsite)->where('active', true)->first();
- if ($category) {
- $headline_image = false;
- if ($category->headline_image_id && $category->iq_image && $category->iq_image->active) {
- $headline_image = $category->iq_image;
- }
-
- $product_categories = ProductCategory::where('category_id', $category->id)->whereHas('product', function ($query) use ($category) {
- $query->where('active', true)->whereJsonContains('show_on', '1');
- })->orderBy('pos', 'DESC')->get();
-
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'subsite' => $subsite,
- 'categories' => Category::where('active', true)->orderBy('pos', 'DESC')->get(),
- 'products' => false,
- 'product_categories' => $product_categories,
- 'p_count' => Product::where('active', true)->whereJsonContains('show_on', '1')->count(),
- 'headline' => $category->getLang('headline'),
- 'headline_image' => $headline_image,
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.' . $site, $data);
- }
- }
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'subsite' => 'alle-produkte',
- 'categories' => Category::where('active', true)->orderBy('pos', 'DESC')->get(),
- 'products' => Product::where('active', true)->whereJsonContains('show_on', '1')->orderBy('pos', 'DESC')->get(),
- 'product_categories' => false,
- 'p_count' => Product::where('active', true)->whereJsonContains('show_on', '1')->count(),
- 'headline' => __('website.productworld'),
- 'headline_image' => false,
- 'yard_instance' => 'webshop',
- ];
- return view('web.templates.' . $site, $data);
- }
- $data = [
- 'user_shop' => Util::getUserShop(),
- 'mylangs' => Shop::getLangChange('webshop'),
- 'yard_instance' => 'webshop',
- ];
- if ($subsite) {
- if (!view()->exists('web.templates.' . $subsite)) {
- abort(404);
- }
- return view('web.templates.' . $subsite, $data);
- }
- if (!view()->exists('web.templates.' . $site)) {
- abort(404);
- }
- return view('web.templates.' . $site, $data);
- }
-}
diff --git a/dev/app-bak/Http/Controllers/WizardController.php b/dev/app-bak/Http/Controllers/WizardController.php
deleted file mode 100755
index 53ec93ff..00000000
--- a/dev/app-bak/Http/Controllers/WizardController.php
+++ /dev/null
@@ -1,646 +0,0 @@
-fileRepo = $fileRepo;
- }
-
- public function create()
- {
- if (!Auth::check()) {
- return redirect('login');
- }
-
- $user = User::findOrFail(Auth::user()->id);
- if (!$user->account) {
- $account = UserAccount::create([]);
- $user->account_id = $account->id;
- $user->save();
- return redirect(route('wizard_create'));
- }
-
- $step = !$user->wizard ? 0 : $user->wizard;
-
- if ($step >= 20) {
- return redirect('/home');
- }
- $userHistoryWizardPayment = UserHistory::whereUserId($user->id)->whereAction('wizard_payment')->get()->last();
-
- $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(),
- 'userHistoryWizardPayment' => $userHistoryWizardPayment,
- ];
-
- if ($step == 15) {
- return view('user.wizard.create_release', $data);
- }
-
- return view('user.wizard.create', $data);
- }
-
- public function register()
- {
-
- if (!Auth::check()) {
- return redirect('login');
- }
- $user = User::findOrFail(Auth::user()->id);
- if (!$user->account) {
- $account = UserAccount::create([]);
- $user->account_id = $account->id;
- $user->save();
- return redirect(route('wizard_register'));
- }
-
- $step = !$user->wizard ? 0 : $user->wizard;
-
- if ($step >= 10) {
- return redirect('/home');
- }
-
- $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(),
- ];
- if ($step == 5) {
- if ($user->active) {
- $user->active = false;
- $user->save();
- }
- return view('user.wizard.register_release', $data);
- }
-
- return view('user.wizard.register', $data);
- }
-
- public function payment()
- {
- if (!Auth::check()) {
- return redirect('login');
- }
-
- $user = User::findOrFail(Auth::user()->id);
- 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) {
- 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());
-
- $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(),
- 'userHistoryWizardPayment' => $userHistoryWizardPayment,
- 'yard_info' => UserService::getYardInfo(),
- ];
-
-
- if ($user->wizard == 20) {
- return view('user.wizard.register_payment', $data);
- }
-
- return redirect(route('/'));
- }
-
- private function checkShoppingCountry($user)
- {
-
- $country_id = null;
- if ($user->account->same_as_billing) {
- $country_id = $user->account->country_id;
- } else {
- $country_id = $user->account->shipping_country_id;
- }
- if ($country_id) {
- if ($shipping_country = ShippingCountry::whereCountryId($country_id)->first()) {
- return $shipping_country->id;
- }
- }
- return false;
- }
-
- public function storeRegister($step = false)
- {
-
- if (!Auth::check()) {
- return redirect('login');
- }
- $user = User::findOrFail(Auth::user()->id);
- 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(
- 'accepted_data_protection' => 'required',
- 'accepted_active' => '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_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;
- if ($account->accepted_contract === null) {
- $account->accepted_contract = now();
- }
- if ($account->data_protection === null) {
- $account->data_protection = now();
- }
- $account->save();
- if ($user->agreement === null) {
- $user->agreement = now();
- }
-
- $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") {
- $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") {
- $user->wizard = 1;
- $user->save();
- $userRepo = new UserRepository($user);
- return $userRepo->reverse_charge_delete($data, $user, route('wizard_register', [0]));
- }
-
- $rules = array(
- 'salutation' => 'required',
- 'first_name' => 'required',
- 'last_name' => 'required',
- 'address' => 'required',
- 'zipcode' => 'required',
- 'city' => 'required',
- 'phone' => 'required_without:mobil',
- 'mobil' => 'required_without:phone',
- 'country_id' => 'required|integer|min:1',
- 'birthday' => 'required',
- 'bank_owner' => 'required',
- 'bank_iban' => 'required',
- 'bank_bic' => 'required',
- );
-
- 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_country_id' => 'required|integer|min:1',
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- 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;
- $user->account->fill($data)->save();
- $user->wizard = 2;
- $user->save();
- return redirect(route('wizard_register'));
- }
-
- if ($step == 2) {
- if (Request::get('submit') === 'do') {
- if (File::whereUserId($user->id)->whereIdentifier('id_card')->count() == 0) {
- $validator = Validator::make(Request::all(), []);
- $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('user_id', $user->id);
- $this->fileRepo->_set('identifier', 'id_card');
- return $this->fileRepo->uploadFile(Request::all());
- }
-
- if ($step == 3) {
- if (Request::get('submit') === 'do') {
- $data = Request::all();
-
- 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'] === "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']);
- }
- }
-
- $user->account->setNotice('business_license', $data['business_license_choose']);
- $user->wizard = 4;
- $user->save();
-
- return redirect(route('wizard_register'));
- }
- $this->fileRepo->_set('disk', 'user');
- $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());
- }
-
- if ($step == 4) {
-
- return $this->releaseAccount($user);
- /*
- $user->wizard = 5; // muss freigeschaltet werden
- $user->release_account = now();
- UserHistory::create(['user_id' => $user->id, 'action'=>'release_account', 'status'=>0]);
- $user->save();
-
- if($user->isTestMode()){
- $mail = config('app.info_test_mail');
- }else{
- $mail = config('app.info_mail');
- }
- //Mail zur Freischaltung
- Mail::to($mail)->locale($user->getLocale())->send(new MailReleaseAccount($user));
-
- //return redirect(route('wizard_register'));
- */
- }
- }
-
- //auto release account
- public function releaseAccount($user)
- {
-
- $user->m_sponsor = $user->m_sponsor ? $user->m_sponsor : 1;
- $user->account->m_first_name = $user->account->m_first_name ? $user->account->m_first_name : $user->account->first_name;
- $user->account->m_last_name = $user->account->m_last_name ? $user->account->m_last_name : $user->account->last_name;
- $user->account->m_account = UserAccount::withTrashed()->max('m_account') + 1;
- $user->account->save();
- $user->save();
- //create PDF
- $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->createContractPDF();
-
- //set wizard tp payments
- $user->wizard = 20;
- $user->active = 1;
- $user->active_date = now();
- $user->release_account = now();
- $user->confirmation_code = null;
- $user->confirmation_code_to = null;
- $user->confirmation_code_remider = 0;
- $user->save();
-
- //mail with code to user?
- if ($user->isTestMode()) {
- $mail = config('app.info_test_mail');
- } else {
- $mail = config('app.info_mail');
- }
- Mail::to($mail)->locale($user->getLocale())->send(new MailAutoReleaseAccount($user));
- UserHistory::create(['user_id' => $user->id, 'action' => 'release_account', 'status' => 0]);
- 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()) {
- return redirect('login');
- }
-
- $user = User::findOrFail(Auth::user()->id);
- if (!$user->account) {
- $user->account = new UserAccount();
- }
-
- if ($step == 10) {
- $rules = array(
- '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_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;
- if ($account->accepted_contract === null) {
- $account->accepted_contract = now();
- }
- if ($account->data_protection === null) {
- $account->data_protection = now();
- }
- $account->save();
- if ($user->agreement === null) {
- $user->agreement = now();
- }
- $user->wizard = 11;
- $user->save();
-
- return redirect(route('wizard_create', [11]));
- }
- if ($step == 11) {
-
- if ($user->isPasswort()) {
- $user->wizard = 12;
- $user->save();
- return redirect(route('wizard_create', [12]));
- }
- $rules = array(
- '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_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'))
- ])->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") {
- $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") {
- $user->wizard = 12;
- $user->save();
- $userRepo = new UserRepository($user);
- return $userRepo->reverse_charge_delete($data, $user, route('wizard_create', [12]));
- }
-
-
- $rules = array(
- 'salutation' => 'required',
- 'first_name' => 'required',
- 'last_name' => 'required',
- 'address' => 'required',
- 'zipcode' => 'required',
- 'city' => 'required',
- 'phone' => 'required_without:mobil',
- 'mobil' => 'required_without:phone',
- 'country_id' => 'required|integer|min:1',
- 'birthday' => 'required',
- );
-
- 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'
-
- ]);
- }
- $validator = Validator::make(Request::all(), $rules);
- if ($validator->fails()) {
- return redirect(route('wizard_create', [12]))->withErrors($validator)->withInput(Request::all());
- }
-
- $data = Request::all();
- $data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
- $user->account->fill($data)->save();
-
- $user->wizard = 13;
- $user->active_date = now();
- $user->active = 1;
- $user->confirmation_code = null;
- $user->confirmation_code_to = null;
- $user->confirmation_code_remider = 0;
- $user->save();
- return redirect(route('wizard_create', [13]));
- }
- }
-
-
- public function storePayment($step = 0)
- {
-
- 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
- $user->save();
- }
-
- $shipping_country_id = $this->checkShoppingCountry($user);
- 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) {
- //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]);
- 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());
-
- $data = [];
- $data['is_from'] = 'wizard';
- $data['is_for'] = 'me';
- $data['user_price_infos'] = \App\Services\UserService::getUserPriceInfos();
-
- ShoppingInstance::create([
- 'identifier' => $identifier,
- 'user_shop_id' => 1, //is first faker shop for buy intern
- 'auth_user_id' => Auth::user()->id,
- 'payment' => 4, //Berater Wizard
- 'subdomain' => url('/'),
- 'country_id' => Yard::instance('shopping')->getShippingCountryId(),
- 'language' => \App::getLocale(),
- 'shopping_data' => $data,
- 'back' => url()->previous(),
-
- ]);
- Yard::instance('shopping')->store($identifier);
- //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);
- return redirect()->secure($path);
- }
- }
- \Session()->flash('alert-error', "Fehler beim Produkt");
- return back();
- }
-
- public function delete($id, $relation)
- {
-
- if ($relation === 'upload') {
- $user = User::findOrFail(Auth::user()->id);
- $file = $user->files()->findOrFail($id);
- //remove file
- \Storage::disk('user')->delete($file->dir . $file->filename);
- $file->delete();
- \Session()->flash('alert-success', __('msg.file_deleted'));
- }
- return back();
- }
-}
diff --git a/dev/app-bak/Http/Kernel.php b/dev/app-bak/Http/Kernel.php
deleted file mode 100755
index 26a0f22c..00000000
--- a/dev/app-bak/Http/Kernel.php
+++ /dev/null
@@ -1,88 +0,0 @@
- [
- \App\Http\Middleware\EncryptCookies::class,
- \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
- \App\Http\Middleware\DomainBootstrap::class,
- \Illuminate\Session\Middleware\StartSession::class,
- \Illuminate\Session\Middleware\AuthenticateSession::class,
- \App\Http\Middleware\DomainSessionSync::class,
- \Illuminate\View\Middleware\ShareErrorsFromSession::class,
- \App\Http\Middleware\VerifyCsrfToken::class,
- \Illuminate\Routing\Middleware\SubstituteBindings::class,
- //\App\Http\Middleware\DomainResolver::class, // MUSS vor StartSession kommen!
- \App\Http\Middleware\Localization::class,
- ],
- 'api' => [
- 'throttle:60,1',
- 'bindings',
- ],
- 'admin' => [
- 'web',
- 'auth',
- \App\Http\Middleware\Admin::class,
- ],
- 'superadmin' => [
- 'web',
- 'auth',
- \App\Http\Middleware\SuperAdmin::class,
- ],
- 'sysadmin' => [
- 'web',
- 'auth',
- \App\Http\Middleware\SysAdmin::class,
- ],
- ];
-
- /**
- * The application's route middleware.
- *
- * These middleware may be assigned to groups or used individually.
- *
- * @var array
- */
- protected $routeMiddleware = [
- 'auth' => \App\Http\Middleware\Authenticate::class,
- 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
- 'admin' => \App\Http\Middleware\Admin::class,
- 'superadmin' => \App\Http\Middleware\SuperAdmin::class,
- 'sysadmin' => \App\Http\Middleware\SysAdmin::class,
- 'active.account' => \App\Http\Middleware\ActiveAccount::class,
- 'active.shop' => \App\Http\Middleware\ActiveShop::class,
- 'checkout' => \App\Http\Middleware\Checkout::class,
- 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
- 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
- 'can' => \Illuminate\Auth\Middleware\Authorize::class,
- 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
- 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
- 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
- ];
-}
diff --git a/dev/app-bak/Http/Middleware/ActiveAccount.php b/dev/app-bak/Http/Middleware/ActiveAccount.php
deleted file mode 100755
index 6a51438b..00000000
--- a/dev/app-bak/Http/Middleware/ActiveAccount.php
+++ /dev/null
@@ -1,26 +0,0 @@
-isActiveAccount() )
- {
- return $next($request);
- }
- return redirect('/home');
-
- }
-}
diff --git a/dev/app-bak/Http/Middleware/ActiveShop.php b/dev/app-bak/Http/Middleware/ActiveShop.php
deleted file mode 100755
index 59bdd59a..00000000
--- a/dev/app-bak/Http/Middleware/ActiveShop.php
+++ /dev/null
@@ -1,26 +0,0 @@
-isActiveShop() )
- {
- return $next($request);
- }
- return redirect('/home');
-
- }
-}
diff --git a/dev/app-bak/Http/Middleware/Admin.php b/dev/app-bak/Http/Middleware/Admin.php
deleted file mode 100755
index 03e0673e..00000000
--- a/dev/app-bak/Http/Middleware/Admin.php
+++ /dev/null
@@ -1,37 +0,0 @@
-admin == 1) {
- abort(403, 'VIP-Benutzer haben keinen Zugang zum Admin-Bereich.');
- }
-
- // Nur echte Admins (admin >= 2) durchlassen
- if ($user->admin >= 2) {
- return $next($request);
- }
-
- return redirect('/home');
- }
-}
diff --git a/dev/app-bak/Http/Middleware/Authenticate.php b/dev/app-bak/Http/Middleware/Authenticate.php
deleted file mode 100644
index ec4875e0..00000000
--- a/dev/app-bak/Http/Middleware/Authenticate.php
+++ /dev/null
@@ -1,92 +0,0 @@
-auth = $auth;
- }
-
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @param string[] ...$guards
- * @return mixed
- *
- * @throws \Illuminate\Auth\AuthenticationException
- */
- public function handle($request, Closure $next, ...$guards)
- {
-
- $this->authenticate($guards);
-
- //is blocked
- if(in_array('user', $guards) && $this->auth->user()->blocked == 1){
- return redirect(route('user_blocked'));
- }
-
- //100 wizzard is finish
- if(in_array('user', $guards) && $this->auth->user()->wizard !== 100){
- //0-10 == start wizard form register
- if(in_array('user', $guards) && $this->auth->user()->wizard < 10){
- return redirect(route('wizard_register'));
- }
- //10-20 == start wizard form create Lead
- if(in_array('user', $guards) && $this->auth->user()->wizard < 20){
- return redirect(route('wizard_create'));
- }
- //20 is payment
- if(in_array('user', $guards) && $this->auth->user()->wizard == 20){
- return redirect(route('wizard_payment'));
- }
- }
-
-
-
- return $next($request);
- }
-
- /**
- * Determine if the user is logged in to any of the given guards.
- *
- * @param array $guards
- * @return void
- *
- * @throws \Illuminate\Auth\AuthenticationException
- */
- protected function authenticate(array $guards)
- {
- if (empty($guards)) {
- return $this->auth->authenticate();
- }
-
- foreach ($guards as $guard) {
- if ($this->auth->guard($guard)->check()) {
- return $this->auth->shouldUse($guard);
- }
- }
-
- throw new AuthenticationException('Unauthenticated.', $guards);
- }
-}
diff --git a/dev/app-bak/Http/Middleware/Checkout.php b/dev/app-bak/Http/Middleware/Checkout.php
deleted file mode 100755
index 748841c2..00000000
--- a/dev/app-bak/Http/Middleware/Checkout.php
+++ /dev/null
@@ -1,85 +0,0 @@
- $request->url(),
- 'host' => $request->getHost()
- ]);
- $instance = 'checkout';
- if($shopping_instance = ShoppingInstance::where('identifier', $request->route('identifier'))->first()){
- //user shop
- //set Lang
- \Session::put('locale', $shopping_instance->getLocale());
- \App::setLocale($shopping_instance->getLocale());
- $user_shop = $shopping_instance->user_shop;
-
- if($user_shop && $user_shop->active == 1 && $user_shop->user->isActiveShop()){
- Util::setPostRoute('user/');
- \Session::put('user_shop', $user_shop);
- \Session::put('user_shop_domain', $shopping_instance->subdomain);
- \Session::put('user_shop_payment', $shopping_instance->payment);
- \Session::put('user_shop_identifier', $shopping_instance->identifier);
-
- if($shopping_instance->auth_user_id){
- \Session::put('auth_user', $shopping_instance->auth_user);
- }
- }
- if($shopping_instance->back){
- \Session::put('back_link', $shopping_instance->back);
- }
- \Session::put('new_session', true);
- Yard::instance($instance)->destroy();
- //restore yard
- if($shopping_instance->payment !== 6){
- Yard::instance($instance)->restore($request->route('identifier'), [], true, $instance);
- }else{
- //dont delete shopping instance
- Yard::instance($instance)->restore($request->route('identifier'), [], false, $instance);
- }
-
- Yard::instance($instance)->putYardExtra('user_shop_payment', $shopping_instance->payment);
-
- Yard::instance($instance)->putYardExtra('shopping_data', $shopping_instance->shopping_data);
- $is_for = isset($shopping_instance->shopping_data['is_for']) ? $shopping_instance->shopping_data['is_for'] : 'ot-member';
-
- Yard::instance($instance)->setUserPriceInfos($shopping_instance->shopping_data['user_price_infos']);
- Yard::instance($instance)->setShippingCountryWithPrice($shopping_instance->country_id, $is_for);
-
- if($shopping_instance->payment !== 6){
- //delete shopping instance is not save for restore, payment link
- ShoppingInstance::where('identifier', $request->route('identifier'))->delete();
- }
-
- $request->route()->forgetParameter('identifier');
-
- return $next($request);
- }
- // \Session::has('user_shop_identifier')
- if(\Session::has('user_shop') && Yard::instance($instance)->count() > 0){
- return $next($request);
- }
- return redirect(Util::getUserCardBackUrl('/card/show', 'checkout'));
-
- }
-}
\ No newline at end of file
diff --git a/dev/app-bak/Http/Middleware/CsrfDebugger.php b/dev/app-bak/Http/Middleware/CsrfDebugger.php
deleted file mode 100644
index 90fc8b63..00000000
--- a/dev/app-bak/Http/Middleware/CsrfDebugger.php
+++ /dev/null
@@ -1,79 +0,0 @@
-attributes->get('domain_resolver_session_id');
-
- if (config('app.debug')) {
- \Log::channel('domain')->debug('CsrfDebugger: VOR VerifyCsrfToken', [
- 'session_id_before_csrf' => $sessionIdBeforeCsrf,
- 'domain_resolver_session_id' => $domainResolverSessionId,
- 'session_consistent_with_domain_resolver' => $domainResolverSessionId === $sessionIdBeforeCsrf,
- 'request_method' => $request->method(),
- 'request_path' => $request->path(),
- 'has_csrf_token' => $request->has('_token'),
- 'csrf_token_in_session' => Session::has('_token'),
- 'request_host' => $request->getHost(),
- 'middleware_position' => 'Vor VerifyCsrfToken'
- ]);
- }
-
- // Request weiterleiten (VerifyCsrfToken läuft hier)
- $response = $next($request);
-
- // Session-ID nach CSRF-Token-Überprüfung vergleichen
- $sessionIdAfterCsrf = Session::getId();
-
- if (config('app.debug')) {
- \Log::channel('domain')->debug('CsrfDebugger: NACH VerifyCsrfToken', [
- 'session_id_before_csrf' => $sessionIdBeforeCsrf,
- 'session_id_after_csrf' => $sessionIdAfterCsrf,
- 'session_changed_by_csrf' => $sessionIdBeforeCsrf !== $sessionIdAfterCsrf,
- 'domain_resolver_session_id' => $domainResolverSessionId,
- 'request_method' => $request->method(),
- 'request_path' => $request->path(),
- 'response_status' => $response->getStatusCode(),
- 'request_host' => $request->getHost()
- ]);
-
- if ($sessionIdBeforeCsrf !== $sessionIdAfterCsrf) {
- \Log::channel('domain')->warning('🚨 CsrfDebugger: VerifyCsrfToken hat Session-ID geändert!', [
- 'session_id_before' => $sessionIdBeforeCsrf,
- 'session_id_after' => $sessionIdAfterCsrf,
- 'domain_resolver_session_id' => $domainResolverSessionId,
- 'request_method' => $request->method(),
- 'request_path' => $request->path(),
- 'has_csrf_token' => $request->has('_token'),
- 'response_status' => $response->getStatusCode(),
- 'request_host' => $request->getHost(),
- 'user_agent' => $request->userAgent(),
- 'possible_cause' => 'CSRF-Token fehlt oder ist ungültig'
- ]);
- }
- }
-
- return $response;
- }
-}
diff --git a/dev/app-bak/Http/Middleware/DomainBootstrap.php b/dev/app-bak/Http/Middleware/DomainBootstrap.php
deleted file mode 100644
index d54cc9af..00000000
--- a/dev/app-bak/Http/Middleware/DomainBootstrap.php
+++ /dev/null
@@ -1,363 +0,0 @@
-shouldHandle($request)) {
- return $next($request);
- }
-
- $host = $request->getHost();
-
- try {
- // Domain-Context mit Caching erstellen (KEIN Session-Zugriff!)
- $context = $this->resolveDomainContext($host);
-
- // Frühe Konfiguration ohne Session-Zugriff
- $this->configureApplication($context);
-
- // UserShop-Domains: PostRoute für korrekte Card-URLs setzen
- $this->configurePostRoute($context);
-
- // Context verfügbar machen
- $this->registerContext($context, $request);
-
- // UserShop-Routing: subdomain aus Route-Parametern entfernen
- $this->cleanupRouteParameters($request, $context);
-
- // Minimal Debug-Logging für Production
- $this->logDomainResolution($context, $host);
- } catch (\Throwable $e) {
- // Graceful Degradation: Bei Fehlern System nicht stoppen
- Log::error('DomainBootstrap failed', [
- 'host' => $host,
- 'error' => $e->getMessage(),
- 'fallback' => 'using_main_domain'
- ]);
-
- // Fallback: Main-Domain Context
- $context = $this->createFallbackContext($host);
- $this->registerContext($context, $request);
- }
-
- return $next($request);
- }
-
- /**
- * Domain-Context mit Request-Level Caching auflösen
- */
- private function resolveDomainContext(string $host): DomainContext
- {
- // Request-Level Cache-Check (verhindert wiederholte Domain-Resolution)
- $cacheKey = 'domain_' . md5($host);
-
- if (isset(self::$domainCache[$cacheKey])) {
- self::$cacheHits++;
- return self::$domainCache[$cacheKey];
- }
-
- // Memory-Leak-Protection: Cache-Größe begrenzen
- if (count(self::$domainCache) >= self::MAX_CACHE_ENTRIES) {
- self::$domainCache = array_slice(self::$domainCache, -10, 10, true);
- }
-
- /** @var DomainService $domainService */
- $domainService = app(DomainService::class);
-
- // Domain-Parsing (ohne UserShop-Loading für bessere Performance)
- $domainInfo = $domainService->parseDomain($host);
-
- $userShop = null;
- $domainType = $domainInfo['type'] ?? 'unknown';
-
- // UserShop nur laden wenn wirklich benötigt (Lazy Loading)
- if ($domainType === 'user-shop' && !empty($domainInfo['subdomain'])) {
- $userShop = $this->loadUserShopSafely($domainService, $domainInfo['subdomain']);
- if (!$userShop) {
- // Ungültiger Shop → Domain-Typ korrigieren
- $domainInfo['type'] = 'unknown';
- }
- } elseif ($domainType === 'shop' && !empty($domainInfo['default_user_shop'])) {
- // Fallback-Shop für Hauptdomain (Fix: Type-Mismatch)
- $userShop = $this->loadUserShopSafely($domainService, $domainInfo['default_user_shop']);
- }
-
- $context = DomainContext::fromArray($domainInfo, $userShop);
-
- // In Cache speichern
- self::$domainCache[$cacheKey] = $context;
-
- return $context;
- }
-
- /**
- * UserShop sicher laden ohne Exception-Risk
- */
- private function loadUserShopSafely(DomainService $domainService, string $slug): ?object
- {
- try {
- return $domainService->getUserShop($slug);
- } catch (\Throwable $e) {
- // Fehler beim UserShop-Loading nicht propagieren
- Log::warning('UserShop loading failed', [
- 'slug' => $slug,
- 'error' => $e->getMessage()
- ]);
- return null;
- }
- }
-
- /**
- * Fallback-Context für Fehlerbehandlung
- */
- private function createFallbackContext(string $host): DomainContext
- {
- return DomainContext::fromArray([
- 'type' => 'main',
- 'host' => $host,
- 'subdomain' => null,
- 'domain' => config('app.domain', 'mivita'),
- 'tld' => config('app.tld_care', '.care'),
- ]);
- }
-
- /**
- * Optimierter Request-Filter (reduziert unnötige Verarbeitung)
- */
- private function shouldHandle(Request $request): bool
- {
- // Schnelle Ausschluss-Checks zuerst
- if ($request->is('api/*')) {
- return false;
- }
-
- // Asset-Requests mit optimiertem Pattern
- if ($request->isMethod('GET') && $this->isStaticAsset($request->path())) {
- return false;
- }
-
- // Laravel-interne und Monitoring-Requests
- $skipPaths = ['_debugbar', '_ignition', 'telescope', 'health', 'status', 'ping'];
- foreach ($skipPaths as $path) {
- if ($request->is($path) || $request->is($path . '/*')) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Optimierte Asset-Erkennung
- */
- private function isStaticAsset(string $path): bool
- {
- // Datei-Endungen (Original-Logic)
- if (preg_match('/\.(css|js|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot|map|json)$/i', $path)) {
- return true;
- }
-
- // Pfad-basierte Assets (häufige Laravel-Patterns)
- $assetPaths = [
- 'css/',
- 'js/',
- 'fonts/',
- 'images/',
- 'img/',
- 'assets/',
- 'storage/',
- 'mix-manifest',
- 'favicon',
- 'robots.txt',
- 'sitemap',
- '.well-known/',
- 'shop/product/image/'
- ];
-
- foreach ($assetPaths as $assetPath) {
- if (str_starts_with($path, $assetPath) || str_contains($path, $assetPath)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Anwendungs-Konfiguration setzen (ohne Session-Zugriff)
- */
- private function configureApplication(DomainContext $context): void
- {
- // Session-Domain optimiert setzen
- $sessionDomain = $this->getSessionDomain($context);
- Config::set('session.domain', $sessionDomain);
-
- // App-URL für URL-Generierung
- if (!empty($context->host)) {
- $protocol = $this->getProtocol();
- Config::set('app.url', $protocol . $context->host);
- }
- }
-
- /**
- * Session-Domain intelligenter bestimmen
- */
- private function getSessionDomain(DomainContext $context): string
- {
- $baseDomain = config('app.domain', 'mivita');
-
- if ($context->type === 'shop') {
- return '.' . $baseDomain . config('app.tld_shop', '.shop');
- }
- return '.' . $baseDomain . config('app.tld_care', '.care');
- }
-
- /**
- * Protocol-Detection für app.url
- */
- private function getProtocol(): string
- {
- return (config('app.env') === 'production' || request()->isSecure()) ? 'https://' : 'http://';
- }
-
- /**
- * Context in Container und Request registrieren
- */
- private function registerContext(DomainContext $context, Request $request): void
- {
- // Container-Binding (für Dependency Injection)
- app()->instance(DomainContext::class, $context);
-
- // Request-Attribut (für direkten Zugriff) - Fix: Einheitlicher Key für Interoperabilität
- $request->attributes->set('domain_context', $context);
- }
-
- /**
- * Minimal Debug-Logging (nur bei Bedarf)
- */
- private function logDomainResolution(DomainContext $context, string $host): void
- {
- if (!config('subdomain.debug.log_domain_switches', false)) {
- return;
- }
-
- Log::debug('Domain resolved', [
- 'host' => $host,
- 'type' => $context->type ?? 'unknown',
- 'subdomain' => $context->subdomain,
- 'user_shop' => $context->userShop?->slug,
- 'cache_hits' => self::$cacheHits,
- 'cache_size' => count(self::$domainCache)
- ]);
- }
-
- /**
- * UserShop-Domains: PostRoute für korrekte URL-Generierung konfigurieren
- *
- * Das Problem: Util::getPostRoute() ist standardmäßig 'base.' was zu URLs wie
- * base.card/add/... führt. Diese Routes sind auskommentiert → 404
- *
- * Lösung: Für UserShop-Domains PostRoute auf 'user/' setzen für URLs wie
- * user/card/add/... die in den UserShop-Routes definiert sind.
- */
- private function configurePostRoute(DomainContext $context): void
- {
- // Nur für UserShop-Domains PostRoute anpassen
- if ($context->type !== 'user-shop') {
- return;
- }
-
- // PostRoute für UserShop-URLs setzen
- \App\Services\Util::setPostRoute('user/');
-
- // Debug-Logging (optional)
- if (config('subdomain.debug.log_domain_switches', false)) {
- Log::debug('UserShop PostRoute configured', [
- 'user_shop_slug' => $context->userShop?->slug ?? 'unknown',
- 'post_route' => 'user/',
- 'impact' => 'Card URLs now generate user/card/add/... instead of base.card/add/...'
- ]);
- }
- }
-
- /**
- * UserShop-Routing: subdomain aus Route-Parametern entfernen
- *
- * Wenn ein UserShop erkannt wird, muss die subdomain aus den Route-Parametern
- * entfernt werden, damit sie nicht in die Controller-Parameter weitergegeben wird.
- *
- * Route-Beispiel: /{site}/{subsite?}/{product_slug?}
- * Erwartet: site, subsite, product_slug - NICHT subdomain!
- */
- private function cleanupRouteParameters(Request $request, DomainContext $context): void
- {
- // Nur bei UserShop-Domains Route-Parameter bereinigen
- if ($context->type !== 'user-shop') {
- return;
- }
-
- // Route muss existieren und subdomain Parameter haben
- if (!$request->route() || !$request->route('subdomain')) {
- return;
- }
-
- try {
- // subdomain aus Route-Parametern entfernen
- $request->route()->forgetParameter('subdomain');
-
- // Optional: Debug-Logging in Development
- if (config('subdomain.debug.log_domain_switches', false)) {
- Log::debug('UserShop routing: subdomain parameter removed', [
- 'user_shop_slug' => $context->userShop?->slug ?? 'unknown',
- 'remaining_route_params' => $request->route()->parameters()
- ]);
- }
- } catch (\Throwable $e) {
- // Fehler beim Route-Parameter-Cleanup nicht kritisch
- Log::warning('Failed to cleanup route parameters', [
- 'user_shop_slug' => $context->userShop?->slug ?? 'unknown',
- 'error' => $e->getMessage()
- ]);
- }
- }
-
- /**
- * Cache-Statistiken für Debugging (optional)
- */
- public static function getCacheStats(): array
- {
- return [
- 'hits' => self::$cacheHits,
- 'entries' => count(self::$domainCache),
- 'memory_kb' => round(memory_get_usage() / 1024, 2)
- ];
- }
-}
diff --git a/dev/app-bak/Http/Middleware/DomainSessionSync.php b/dev/app-bak/Http/Middleware/DomainSessionSync.php
deleted file mode 100644
index ba664e9a..00000000
--- a/dev/app-bak/Http/Middleware/DomainSessionSync.php
+++ /dev/null
@@ -1,112 +0,0 @@
-attributes->has($middlewareKey)) {
- Log::warning('DomainSessionSync: Middleware bereits ausgeführt - Skip um Cookie-Duplikate zu vermeiden', [
- 'request_id' => $request->header('X-Request-ID') ?? uniqid(),
- 'url' => $request->getUri()
- ]);
- return $next($request);
- }
-
- // Markieren dass diese Middleware läuft
- $request->attributes->set($middlewareKey, true);
-
- try {
- // Domain-Context aus Container holen
- /** @var DomainContext|null $context */
- $context = app(DomainContext::class);
-
- // Session-Synchronisation VOR Controller (Fix: Timing-Problem)
- if ($context && $this->shouldSync($context)) {
- $this->sessionManager->synchronize($request, $context);
- }
- } catch (\Throwable $e) {
- // Kritisch: Session-Sync-Fehler dürfen Response nicht stoppen
- Log::error('Session synchronization failed', [
- 'error' => $e->getMessage(),
- 'host' => $request->getHost(),
- 'path' => $request->path(),
- 'user_agent' => $request->userAgent(),
- 'fallback' => 'continuing_without_sync'
- ]);
- }
-
- // Controller läuft NACH Session-Sync und kann synchronisierte Daten nutzen
- $response = $next($request);
-
- // Optional: Nur Cleanup/Logging nach Response
- try {
- $context = app(DomainContext::class);
- if ($context) {
- $this->logSessionSync($context);
- }
- } catch (\Throwable $e) {
- // Logging-Fehler ignorieren
- }
-
- return $response;
- }
-
- /**
- * Prüft, ob Session-Sync benötigt wird (Performance-Optimierung)
- */
- private function shouldSync(DomainContext $context): bool
- {
- // Skip für unbekannte Domains (keine Session-Daten nötig)
- if ($context->type === 'unknown') {
- return false;
- }
-
- // Skip für Hauptdomain ohne UserShop-Kontext
- if ($context->type === 'main' && !$context->userShop) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Minimal Debug-Logging (nur bei aktivierter Debug-Konfiguration)
- */
- private function logSessionSync(DomainContext $context): void
- {
- if (!config('subdomain.debug.log_domain_switches', false)) {
- return;
- }
-
- Log::debug('Session synchronized', [
- 'domain_type' => $context->type ?? 'unknown',
- 'user_shop_slug' => $context->userShop?->slug,
- 'session_id' => session()->getId(),
- 'memory_usage_mb' => round(memory_get_usage() / 1024 / 1024, 2)
- ]);
- }
-}
diff --git a/dev/app-bak/Http/Middleware/EncryptCookies.php b/dev/app-bak/Http/Middleware/EncryptCookies.php
deleted file mode 100755
index 033136ad..00000000
--- a/dev/app-bak/Http/Middleware/EncryptCookies.php
+++ /dev/null
@@ -1,17 +0,0 @@
-check()) {
- return redirect('/home');
- }
-
- return $next($request);
- }
-}
diff --git a/dev/app-bak/Http/Middleware/RemoveExcessWhitespaceMiddleware.php b/dev/app-bak/Http/Middleware/RemoveExcessWhitespaceMiddleware.php
deleted file mode 100755
index 1abc08af..00000000
--- a/dev/app-bak/Http/Middleware/RemoveExcessWhitespaceMiddleware.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getOriginalContent();
-
- $filters = array(
- '/