20-02-2026

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

42
.env
View file

@ -28,6 +28,8 @@ EXCEPTION_MAIL=exception@adametz.media
SESSION_DOMAIN=.mivita.test
#SESSION_DOMAIN=.mivita.care
BUSINESS_FORCE_EXECUTE=true
APP_MODE=test
APP_IPINFO=true
@ -105,14 +107,24 @@ MIVITA_ADD_NUMBER_ID=946
# DHL VERSANDMODUL KONFIGURATION (acme/laravel-dhl)
# =============================================================================
# =============================================================================
# DHL KONFIGURATION - PRIORITÄT
# =============================================================================
# Steuert, welche Konfigurationsquelle Vorrang hat:
# - 'database' (Standard): Werte aus Admin-Settings überschreiben .env Werte
# - 'env': .env Werte überschreiben Admin-Settings
# Nützlich für Test-Server, wo du .env Werte verwenden möchtest,
# ohne die Datenbank-Settings ändern zu müssen
DHL_CONFIG_SOURCE=env
# DHL API Zugangsdaten (konsolidiert)
#DHL_BASE_URL=https://api-eu.dhl.com
DHL_SANDBOX_URL=https://api-sandbox.dhl.com
DHL_BASE_URL=https://api-eu.dhl.com
DHL_SANDBOX=false
DHL_TEST_MODE=false
DHL_API_KEY=AxGBdF8DBdIAmuhqvG0ASBRKFvyV7ypX
#DHL_USERNAME=riwa-tec
#DHL_PASSWORD=MivitaCare!!2025
#DHL_BILLING_NUMBER=63144073550101
# DHL Standard-Einstellungen
DHL_PRODUCT=V01PAK
@ -127,20 +139,23 @@ DHL_PROFILE=STANDARD_GRUPPENPROFIL
DHL_USE_QUEUE=false
# DHL Account Numbers (für verschiedene Produkte)
DHL_USERNAME=riwa-tec
DHL_PASSWORD=MivitaCare!!2025
DHL_BILLING_NUMBER=63144073550101
DHL_ACCOUNT_NUMBER_DEFAULT=63144073550101
DHL_ACCOUNT_NUMBER_V01PAK=63144073550101 # DHL Paket National
DHL_ACCOUNT_NUMBER_V62WP=63144073556201 # Warenpost National
DHL_ACCOUNT_NUMBER_V53PAK=63144073555301 # DHL Paket International
DHL_ACCOUNT_NUMBER_V07PAK=63144073550701 # DHL Retoure Online
#sandbox
DHL_USERNAME=user-valid
DHL_PASSWORD=SandboxPasswort2023!
DHL_BILLING_NUMBER=33333333330101
DHL_ACCOUNT_NUMBER_DEFAULT=33333333330101
DHL_ACCOUNT_NUMBER_V01PAK=33333333330102 # DHL Paket National
DHL_ACCOUNT_NUMBER_V62WP=33333333336601 # Warenpost National
DHL_ACCOUNT_NUMBER_V53PAK=33333333335301 # DHL Paket International
DHL_ACCOUNT_NUMBER_V07PAK=33333333330702 # DHL Retoure Online
#DHL_USERNAME=user-valid
#DHL_PASSWORD=SandboxPasswort2023!
#DHL_BILLING_NUMBER=33333333330101
#DHL_ACCOUNT_NUMBER_DEFAULT=33333333330101
#DHL_ACCOUNT_NUMBER_V01PAK=33333333330102 # DHL Paket National
#DHL_ACCOUNT_NUMBER_V62WP=33333333336601 # Warenpost National
#DHL_ACCOUNT_NUMBER_V53PAK=33333333335301 # DHL Paket International
#DHL_ACCOUNT_NUMBER_V07PAK=33333333330702 # DHL Retoure Online
#V66WPI|33333333336601
#VO1PAK 33333333330102 33333333330101
@ -161,5 +176,4 @@ DHL_SENDER_PHONE="+49 123 456789"
# DHL Legacy/Compatibility Settings
DHL_API_TYPE=developer
DHL_API_SECRET=OyoeePEbYmY1EuOG
DHL_SANDBOX=true
DHL_TEST_MODE=true

View file

@ -4,6 +4,17 @@
# Diese Datei enthält alle DHL-spezifischen Environment-Variablen
# Kopieren Sie die benötigten Variablen in Ihre .env Datei
# =============================================================================
# DHL KONFIGURATION - PRIORITÄT
# =============================================================================
# Steuert, welche Konfigurationsquelle Vorrang hat:
# - 'database' (Standard): Werte aus Admin-Settings überschreiben .env Werte
# - 'env': .env Werte überschreiben Admin-Settings
#
# Nützlich für Test-Server, wo du .env Werte verwenden möchtest,
# ohne die Datenbank-Settings ändern zu müssen
DHL_CONFIG_SOURCE=database
# DHL API Zugangsdaten
# Option 1: DHL Developer API (developer.dhl.com) - Empfohlen
DHL_API_KEY=your_api_key_from_developer_dhl_com
@ -72,3 +83,7 @@ DHL_CACHE_TTL=3600 # Sekunden
DHL_FAKE_API_CALLS=false # true um API-Calls zu simulieren
DHL_MOCK_RESPONSES=false # true um Mock-Responses zu verwenden
DHL_DEBUG_MODE=false # true für detaillierte Debug-Informationen
# Business Commands Configuration
# Erlaubt Business-Commands an jedem Tag (nur für Test-Server!)
# Auf Live-Server muss dies false sein oder weggelassen werden
BUSINESS_FORCE_EXECUTE=false

27
.mcp.json Normal file
View file

@ -0,0 +1,27 @@
{
"mcpServers": {
"laravel-boost": {
"command": "php",
"args": [
"artisan",
"boost:mcp"
]
},
"context7": {
"command": "npx",
"args": [
"-y",
"@upstash/context7-mcp",
"--api-key",
"ctx7sk-119cd4ab-8983-4229-8702-e84c59c34fc9"
]
},
"sequential-thinking": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sequential-thinking"
]
}
}
}

View file

@ -1 +1 @@
C:37:"PHPUnit\Runner\DefaultTestResultCache":44:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:0:{}}}
{"version":1,"defects":{"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_uses_database_locking_for_invoice_numbers":5,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_prevents_double_processing_of_same_payment":8},"times":{"Tests\\Unit\\Services\\InvoiceServiceTest::it_gets_current_invoice_number":0.002,"Tests\\Unit\\Services\\InvoiceServiceTest::it_increments_invoice_number":0.002,"Tests\\Unit\\Services\\InvoiceServiceTest::it_increments_sequentially":0.004,"Tests\\Unit\\Services\\InvoiceServiceTest::it_formats_invoice_number_with_year_prefix":0.001,"Tests\\Unit\\Services\\InvoiceServiceTest::it_generates_correct_storage_paths":0.001,"Tests\\Unit\\Services\\InvoiceServiceTest::it_generates_correct_filenames":0.001,"Tests\\Unit\\Services\\InvoiceServiceTest::it_initializes_invoice_number_when_not_exists":0.002,"Tests\\Unit\\Services\\InvoiceServiceTest::it_uses_transaction_for_invoice_number_increment":0.003,"Tests\\Unit\\Services\\InvoiceServiceTest::it_locks_setting_during_increment":0.001,"Tests\\Unit\\Services\\InvoiceServiceTest::it_pads_invoice_numbers_correctly":0.001,"Tests\\Unit\\Services\\InvoiceServiceTest::it_returns_zero_when_invoice_number_not_set":0.002,"Tests\\Unit\\Services\\InvoiceServiceTest::it_handles_rapid_increments_without_gaps":0.009,"Tests\\Unit\\Services\\InvoiceServiceTest::it_returns_integer_invoice_number":0.002,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_generates_unique_invoice_numbers_under_concurrent_load":0.02,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_atomically_increments_invoice_numbers":0.004,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_does_not_skip_invoice_numbers_on_transaction_rollback":0.002,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_uses_database_locking_for_invoice_numbers":0.003,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_prevents_double_processing_of_same_payment":0.006,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_can_lock_settings_for_update":0.001,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_creates_invoice_numbers_with_correct_format":0.001,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_handles_rapid_sequential_invoice_creation":0.012,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_initializes_invoice_number_if_not_exists":0.002,"Tests\\Feature\\Payment\\ConcurrentPaymentTest::it_handles_concurrent_transaction_commits":0.003,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_locks_shopping_order_during_payment_processing":0.001,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_prevents_double_payment_processing":0.002,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_serializes_concurrent_payment_requests":0.003,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_rolls_back_payment_on_error":0.003,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_tracks_payment_status_transitions":0.003,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_handles_concurrent_payments_for_different_orders":0.003,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_isolates_payment_transactions":0.002,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_prevents_concurrent_modifications":0.001,"Tests\\Feature\\Payment\\PayoneRaceConditionTest::it_enforces_unique_payment_references":0.002}}

293
CLAUDE.md
View file

@ -7,7 +7,7 @@
## Tech Stack
| Komponente | Technologie |
|------------|-------------|
| ----------- | -------------------------------------------- |
| Framework | Laravel 11 (Classic MVC) |
| Frontend | Bootstrap 4 (Appwork Theme), Blade Templates |
| Auth | Laravel Passport (OAuth2/API) |
@ -31,10 +31,22 @@
## Custom Packages
| Package | Pfad | Beschreibung |
|---------|------|--------------|
| --------------- | ------------------------------------ | --------------------------- |
| DHL Integration | `packages/acme-laravel-dhl` | Versand-Labels und Tracking |
| Shopping Cart | `packages/digital-bird/shoppingcart` | Warenkorb-System |
## Environment
This project runs inside a **Dev Container**. Commands are executed directly with `php`, `composer`, and `npm`**without** the `vendor/bin/sail` prefix. All `sail`-prefixed commands in docs or rules should be translated to their direct equivalents:
| Sail | Dev Container |
| ------------------------------ | ------------------- |
| `vendor/bin/sail artisan ...` | `php artisan ...` |
| `vendor/bin/sail composer ...` | `composer ...` |
| `vendor/bin/sail npm ...` | `npm ...` |
| `vendor/bin/sail php ...` | `php ...` |
| `vendor/bin/sail bin pint` | `./vendor/bin/pint` |
## Projekt-Struktur
```
@ -60,6 +72,7 @@ dev/ # Dokumentation
## Development Commands
### Laravel Basis
```bash
php artisan serve # Dev Server
php artisan migrate # Migrations
@ -70,6 +83,7 @@ php artisan view:clear
```
### Code Quality
```bash
./vendor/bin/pint # Code formatieren
./vendor/bin/pest # Tests ausführen
@ -77,6 +91,7 @@ php artisan view:clear
```
### IDE Helper
```bash
php artisan ide-helper:generate
php artisan ide-helper:models
@ -84,12 +99,14 @@ php artisan ide-helper:meta
```
### Assets
```bash
npm install && npm run dev # Development
npm run production # Production Build
```
### Business Commands
```bash
# Provisionsberechnung (empfohlen: optimierte Version)
php artisan business:store-optimized {month} {year}
@ -115,7 +132,7 @@ php artisan business:test-account
## Scheduled Tasks (Cron)
| Zeit | Command | Beschreibung |
|------|---------|--------------|
| ----- | ------------------------------ | -------------------- |
| 02:00 | `payments:check-accounts` | Zahlungsprüfung |
| 03:00 | `business:store-optimized 0 0` | Provisionsberechnung |
| 03:30 | `user:cleanup` | User-Bereinigung |
@ -130,6 +147,7 @@ docker-compose up -d # Services starten
```
### Services
- **laravel.test** - Hauptanwendung (Traefik + SSL)
- **horizon** - Queue Worker
- **mysql** - MySQL 8.0
@ -137,6 +155,7 @@ docker-compose up -d # Services starten
- **mailpit** - Mail Testing (`mivita-mail.test`)
### Domains
- Main: `mivita.test`
- Wildcard: `*.mivita.test`
- Mail: `mivita-mail.test`
@ -144,11 +163,13 @@ docker-compose up -d # Services starten
## MLM-Architektur
### Kernkonzepte
- **Consultants (Berater)**: Hierarchie mit Upline/Downline
- **TreeCalcBotOptimized**: Provisionsberechnung für MLM-Strukturen
- **BusinessPlan Services**: Sales Volumes, Ränge, Boni
### Performance
- Memory Monitoring in optimierten Commands
- Automatic Garbage Collection
- Performance Logging
@ -159,3 +180,269 @@ docker-compose up -d # Services starten
- Prüfe Custom Packages in `packages/` vor Änderungen
- Beachte Multi-Tenant Domain-Logik bei Routing-Änderungen
- DHL-Integration unterstützt Sandbox/Production Mode
===
<laravel-boost-guidelines>
=== foundation rules ===
# Laravel Boost Guidelines
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
## Foundational Context
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
- php - 8.4.12
- laravel/framework (LARAVEL) - v11
- laravel/horizon (HORIZON) - v5
- laravel/passport (PASSPORT) - v12
- laravel/prompts (PROMPTS) - v0
- laravel/mcp (MCP) - v0
- laravel/pint (PINT) - v1
- laravel/sail (SAIL) - v1
- pestphp/pest (PEST) - v2
- phpunit/phpunit (PHPUNIT) - v10
## Conventions
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
- Check for existing components to reuse before writing a new one.
## Verification Scripts
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
## Application Structure & Architecture
- Stick to existing directory structure; don't create new base folders without approval.
- Do not change the application's dependencies without approval.
## Frontend Bundling
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them.
## Replies
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
## Documentation Files
- You must only create documentation files if explicitly requested by the user.
=== boost rules ===
## Laravel Boost
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
## Artisan
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
## URLs
- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
## Tinker / Debugging
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
- Use the `database-query` tool when you only need to read from the database.
## Reading Browser Logs With the `browser-logs` Tool
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
- Only recent browser logs will be useful - ignore old logs.
## Searching Documentation (Critically Important)
- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches.
- Search the documentation before making code changes to ensure we are taking the correct approach.
- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
### Available Search Syntax
- You can and should pass multiple queries at once. The most relevant results will be returned first.
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order.
4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit".
5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms.
=== php rules ===
## PHP
- Always use curly braces for control structures, even if it has one line.
### Constructors
- Use PHP 8 constructor property promotion in `__construct()`.
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
### Type Declarations
- Always use explicit return type declarations for methods and functions.
- Use appropriate PHP type hints for method parameters.
<code-snippet name="Explicit Return Types and Method Params" lang="php">
protected function isAccessible(User $user, ?string $path = null): bool
{
...
}
</code-snippet>
## Comments
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on.
## PHPDoc Blocks
- Add useful array shape type definitions for arrays when appropriate.
## Enums
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
=== sail rules ===
## Laravel Sail
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`.
- Open the application in the browser by running `vendor/bin/sail open`.
- Always prefix PHP, Artisan, Composer, and Node commands with `vendor/bin/sail`. Examples:
- Run Artisan Commands: `vendor/bin/sail artisan migrate`
- Install Composer packages: `vendor/bin/sail composer install`
- Execute Node commands: `vendor/bin/sail npm run dev`
- Execute PHP scripts: `vendor/bin/sail php [script]`
- View all available Sail commands by running `vendor/bin/sail` without arguments.
=== tests rules ===
## Test Enforcement
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter.
=== laravel/core rules ===
## Do Things the Laravel Way
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`.
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
### Database
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
- Use Eloquent models and relationships before suggesting raw database queries.
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
- Generate code that prevents N+1 query problems by using eager loading.
- Use Laravel's query builder for very complex database operations.
### Model Creation
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`.
### APIs & Eloquent Resources
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
### Controllers & Validation
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
- Check sibling Form Requests to see if the application uses array or string based validation rules.
### Queues
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
### Authentication & Authorization
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
### URL Generation
- When generating links to other pages, prefer named routes and the `route()` function.
### Configuration
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
### Testing
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
### Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`.
=== laravel/v11 rules ===
## Laravel 11
- Use the `search-docs` tool to get version-specific documentation.
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel 11 file structure.
- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the Laravel 11 structure unless the user explicitly requests it.
### Laravel 10 Structure
- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`.
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
- Middleware registration is in `app/Http/Kernel.php`
- Exception handling is in `app/Exceptions/Handler.php`
- Console commands and schedule registration is in `app/Console/Kernel.php`
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
### Database
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
- Laravel 11 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
### Models
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
### New Artisan Commands
- List Artisan commands using Boost's MCP tool, if available. New commands available in Laravel 11:
- `vendor/bin/sail artisan make:enum`
- `vendor/bin/sail artisan make:class`
- `vendor/bin/sail artisan make:interface`
=== pint/core rules ===
## Laravel Pint Code Formatter
- You must run `vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
- Do not run `vendor/bin/sail bin pint --test --format agent`, simply run `vendor/bin/sail bin pint --format agent` to fix any formatting issues.
=== pest/core rules ===
## Pest
### Testing
- If you need to verify a feature is working, write or update a Unit / Feature test.
### Pest Tests
- All tests must be written using Pest. Use `vendor/bin/sail artisan make:test --pest {name}`.
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
- Tests should test all of the happy paths, failure paths, and weird paths.
- Tests live in the `tests/Feature` and `tests/Unit` directories.
- Pest tests look and behave like this:
<code-snippet name="Basic Pest Test Example" lang="php">
it('is true', function () {
expect(true)->toBeTrue();
});
</code-snippet>
### Running Tests
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
- To run all tests: `vendor/bin/sail artisan test --compact`.
- To run all tests in a file: `vendor/bin/sail artisan test --compact tests/Feature/ExampleTest.php`.
- To filter on a particular test name: `vendor/bin/sail artisan test --compact --filter=testName` (recommended after making a change to a related file).
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
### Pest Assertions
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
it('returns all', function () {
$response = $this->postJson('/api/docs', []);
$response->assertSuccessful();
});
</code-snippet>
### Mocking
- Mocking can be very helpful when appropriate.
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
- You can also create partial mocks using the same import or self method.
### Datasets
- Use datasets in Pest to simplify tests that have a lot of duplicated data. This is often the case when testing validation rules, so consider this solution when writing tests for validation rules.
<code-snippet name="Pest Dataset Example" lang="php">
it('has emails', function (string $email) {
expect($email)->not->toBeEmpty();
})->with([
'james' => 'james@laravel.com',
'taylor' => 'taylor@laravel.com',
]);
</code-snippet>
</laravel-boost-guidelines>

View file

@ -261,6 +261,126 @@ namespace App\Models{
class DashboardNews extends \Eloquent {}
}
namespace App\Models{
/**
* @property int $id
* @property \Illuminate\Support\Carbon $period_from
* @property \Illuminate\Support\Carbon $period_to
* @property int $month
* @property int $year
* @property int $status
* @property string|null $berater_nr
* @property string|null $mandant_nr
* @property int $invoice_count
* @property int $credit_count
* @property int $cancellation_count
* @property numeric $total_revenue
* @property numeric $total_commissions
* @property string|null $filename
* @property string|null $file_path
* @property string|null $file_hash
* @property int|null $created_by
* @property int $warning_count
* @property int $error_count
* @property array<array-key, mixed>|null $validation_summary
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property-read \App\User|null $creator
* @property-read string $period_label
* @property-read string $status_badge
* @property-read string $status_label
* @property-read int $total_lines
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\DatevExportLine> $lines
* @property-read int|null $lines_count
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport forPeriod(int $month, int $year)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport generated()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport locked()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereBeraterNr($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereCancellationCount($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereCreatedBy($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereCreditCount($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereErrorCount($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereFileHash($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereFilePath($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereFilename($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereInvoiceCount($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereMandantNr($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereMonth($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport wherePeriodFrom($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport wherePeriodTo($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereStatus($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereTotalCommissions($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereTotalRevenue($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereValidationSummary($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereWarningCount($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport whereYear($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport withTrashed(bool $withTrashed = true)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExport withoutTrashed()
*/
class DatevExport extends \Eloquent {}
}
namespace App\Models{
/**
* @property int $id
* @property int $datev_export_id
* @property string $source_type
* @property int $source_id
* @property int $line_number
* @property numeric $amount_gross
* @property string $soll_haben
* @property int $konto
* @property int $gegenkonto
* @property int $bu_schluessel
* @property \Illuminate\Support\Carbon $belegdatum
* @property string $belegfeld1
* @property string $buchungstext
* @property string|null $eu_ustid
* @property string|null $eu_land
* @property string|null $row_csv
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\Models\DatevExport $datev_export
* @property-read string $formatted_amount
* @property-read string $formatted_belegdatum
* @property-read string $source_type_label
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine cancellations()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine credits()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine invoices()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereAmountGross($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereBelegdatum($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereBelegfeld1($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereBuSchluessel($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereBuchungstext($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereDatevExportId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereEuLand($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereEuUstid($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereGegenkonto($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereKonto($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereLineNumber($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereRowCsv($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereSollHaben($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereSourceId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereSourceType($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DatevExportLine whereUpdatedAt($value)
*/
class DatevExportLine extends \Eloquent {}
}
namespace App\Models{
/**
* Class DbipLookup
@ -1584,6 +1704,9 @@ namespace App\Models{
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Acme\Dhl\Models\DhlShipment> $dhlShipments
* @property-read int|null $dhl_shipments_count
* @mixin \Eloquent
* @property-read \App\Models\UserInvoice|null $user_cancellation_invoice
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\UserInvoice> $user_invoices
* @property-read int|null $user_invoices_count
*/
class ShoppingOrder extends \Eloquent {}
}
@ -2044,7 +2167,6 @@ namespace App\Models{
* @property Carbon|null $user_deleted_at
* @property User $user
* @property Collection|UserAboOrder[] $user_abo_orders
* @package App\Models
* @property int|null $member_id
* @property int $shopping_user_id
* @property string|null $email
@ -2087,6 +2209,8 @@ namespace App\Models{
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withoutTrashed()
* @mixin \Eloquent
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\UserAboItemHistory> $user_abo_item_histories
* @property-read int|null $user_abo_item_histories_count
*/
class UserAbo extends \Eloquent {}
}
@ -2122,6 +2246,61 @@ namespace App\Models{
class UserAboItem extends \Eloquent {}
}
namespace App\Models{
/**
* @property int $id
* @property int $user_abo_id
* @property int|null $user_abo_item_id
* @property int $product_id
* @property string $action
* @property string $product_name
* @property string|null $product_number
* @property float $unit_price
* @property float $total_price
* @property int|null $qty_before
* @property int|null $qty_after
* @property int|null $old_product_id
* @property string|null $old_product_name
* @property int $comp
* @property int|null $changed_by_user_id
* @property string|null $changed_by_name
* @property string $channel
* @property string|null $batch_id
* @property bool $is_initial
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\User|null $changed_by
* @property-read \App\Models\Product|null $old_product
* @property-read \App\Models\Product $product
* @property-read \App\Models\UserAbo $user_abo
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereAction($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereBatchId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereChangedByName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereChangedByUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereChannel($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereComp($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereIsInitial($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereOldProductId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereOldProductName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereProductId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereProductName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereProductNumber($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereQtyAfter($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereQtyBefore($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereTotalPrice($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereUnitPrice($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereUserAboId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAboItemHistory whereUserAboItemId($value)
*/
class UserAboItemHistory extends \Eloquent {}
}
namespace App\Models{
/**
* Class UserAboOrder
@ -2277,6 +2456,8 @@ namespace App\Models{
* @method static \Illuminate\Database\Eloquent\Builder|UserAccount whereBankOwner($value)
* @mixin \Eloquent
* @property string|null $shipping_postnumber
* @property string $language
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAccount whereLanguage($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|UserAccount whereShippingPostnumber($value)
*/
class UserAccount extends \Eloquent {}
@ -2500,7 +2681,6 @@ namespace App\Models{
* @property string|null $deleted_at
* @property User $user
* @property Collection|UserCreditItem[] $user_credit_items
* @package App\Models
* @property bool $taxable
* @property-read int|null $user_credit_items_count
* @method static \Illuminate\Database\Eloquent\Builder|UserCredit newModelQuery()
@ -2641,7 +2821,6 @@ namespace App\Models{
* @property Carbon|null $updated_at
* @property string|null $deleted_at
* @property ShoppingOrder $shopping_order
* @package App\Models
* @property string|null $filename
* @property string|null $dir
* @property string|null $delivery_filename
@ -2806,7 +2985,6 @@ namespace App\Models{
* @property Carbon|null $updated_at
* @property ShoppingOrder|null $shopping_order
* @property User $user
* @package App\Models
* @property int|null $user_invoice_id
* @property int|null $month_shop_points
* @property float|null $month_shop_total_net

View file

@ -2,11 +2,11 @@
namespace App\Console\Commands;
use App\Models\Setting;
use Illuminate\Console\Command;
use App\Cron\BusinessUsersStore;
use App\Cron\UserLevelUpdate;
use App\Cron\UserPaymentCredits;
use App\Models\Setting;
use Illuminate\Console\Command;
class BusinessStore extends Command
{
@ -27,14 +27,15 @@ class BusinessStore extends Command
protected $description = 'Create Business Structure and UserDetails with optimized performance';
private $timeStart;
private $month;
private $year;
private $sendCreditMail = false;
private $sendUpdateMail = false;
/**
* Create a new command instance.
*
@ -45,6 +46,58 @@ class BusinessStore extends Command
parent::__construct();
}
/**
* Prüft ob der Command heute ausgeführt werden soll
*
* WICHTIG: Diese Methode verhindert, dass der Command täglich läuft!
* Der Command sollte nur am konfigurierten Tag des Monats laufen.
*
* @return bool True wenn Command ausgeführt werden soll, False sonst
*/
private function shouldExecuteToday(): bool
{
// Hole konfigurierten Ausführungstag (Standard: 1 = Monatserster)
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
// Fallback: Wenn Setting leer oder 0, verwende Tag 1
if ($executeDay === 0) {
$executeDay = 1;
$this->warn('Setting "day-exectute-business-structur" ist leer oder 0. Verwende Standard: Tag 1');
\Log::channel('cron')->warning('BusinessStore: Setting day-exectute-business-structur is empty, using default: 1');
}
$presentDay = (int) date('d');
// Logging für Debugging
$this->info("BusinessStore: Configured Day: {$executeDay}, Present Day: {$presentDay}");
\Log::channel('cron')->info("BusinessStore: Configured Day: {$executeDay}, Present Day: {$presentDay}");
// Prüfe ob heute der konfigurierte Tag ist
if ($executeDay !== $presentDay) {
// Erlaubnis zum Überschreiben für Entwicklung/Testing
// ENV-Variable BUSINESS_FORCE_EXECUTE=true überschreibt den Check
if (env('BUSINESS_FORCE_EXECUTE', false) === true) {
$this->warn('⚠️ BUSINESS_FORCE_EXECUTE ist aktiv - Command wird trotz falschem Tag ausgeführt!');
$this->warn('⚠️ Dies sollte NUR auf Test-Servern verwendet werden!');
\Log::channel('cron')->warning('BusinessStore: FORCED execution via BUSINESS_FORCE_EXECUTE');
return true;
}
// Command sollte heute NICHT laufen
$this->info("❌ Command wird NICHT ausgeführt - falscher Tag (erwartet: {$executeDay}, heute: {$presentDay})");
\Log::channel('cron')->info("BusinessStore: NOT EXECUTED - wrong day (expected: {$executeDay}, today: {$presentDay})");
return false;
}
// Command wird ausgeführt
$this->info("✅ Command wird ausgeführt - korrekter Tag ({$presentDay})");
\Log::channel('cron')->info("BusinessStore: EXECUTING - correct day ({$presentDay})");
return true;
}
/**
* Execute the console command.
*
@ -53,26 +106,18 @@ class BusinessStore extends Command
public function handle()
{
try {
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
$presentDay = (int) date('d');
$this->info('RUN Command BusinessStore on Day: ' . $executeDay);
$this->info('RUN Command BusinessStore present Day: ' . $presentDay);
\Log::channel('cron')->info('RUN Command BusinessStore on Day: ' . $executeDay);
\Log::channel('cron')->info('RUN Command BusinessStore present Day: ' . $presentDay);
$this->logMemoryUsage('Command Start');
if ($executeDay !== $presentDay) {
$this->info('NOT RUN Command BusinessStore is not present Day: ' . $presentDay);
\Log::channel('cron')->info('NOT RUN Command BusinessStore is not present Day: ' . $presentDay);
// Prüfe ob Command am richtigen Tag ausgeführt werden soll
if (! $this->shouldExecuteToday()) {
return 0;
}
$this->logMemoryUsage('Command Start');
$this->timeStart = microtime(true);
// Argumente mit Standardwerten für den Vormonat
$this->month = $this->argument('month') ?: (int) date("m", strtotime("-1 month"));
$this->year = $this->argument('year') ?: (int) date("Y", strtotime("-1 month"));
$this->month = $this->argument('month') ?: (int) date('m', strtotime('-1 month'));
$this->year = $this->argument('year') ?: (int) date('Y', strtotime('-1 month'));
$this->info('RUN Command BusinessStore on month: '.$this->month.' | year: '.$this->year);
\Log::channel('cron')->info('RUN Command BusinessStore on month: '.$this->month.' | year: '.$this->year);
@ -101,6 +146,7 @@ class BusinessStore extends Command
$this->error('Command failed with error: '.$e->getMessage());
$this->error('Stack trace: '.$e->getTraceAsString());
$this->logExecutionTime('COMMAND FAILED');
return 1;
}
}
@ -165,8 +211,6 @@ class BusinessStore extends Command
$this->logExecutionTime('END Command userLevelUpdate:');
}
private function storeBusinessStructureUsersDetailPeriod($from, $to)
{
for ($i = $from; $i <= $to; $i++) {
@ -186,6 +230,6 @@ class BusinessStore extends Command
$sec = intval($diff);
$micro = $diff - $sec;
$this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info($message.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
}

View file

@ -2,13 +2,13 @@
namespace App\Console\Commands;
use App\Models\Setting;
use App\Models\UserBusinessStructure;
use App\Models\UserBusiness;
use Illuminate\Console\Command;
use App\Cron\BusinessUsersStoreOptimized;
use App\Cron\UserLevelUpdate;
use App\Cron\UserPaymentCredits;
use App\Models\Setting;
use App\Models\UserBusiness;
use App\Models\UserBusinessStructure;
use Illuminate\Console\Command;
class BusinessStoreOptimized extends Command
{
@ -29,10 +29,13 @@ class BusinessStoreOptimized extends Command
protected $description = 'Create Business Structure and UserDetails with optimized performance and monitoring';
private $timeStart;
private $month;
private $year;
private $sendCreditMail = false;
private $sendUpdateMail = false;
/**
@ -51,6 +54,58 @@ class BusinessStoreOptimized extends Command
$this->sendUpdateMail = $sendUpdateMail;
}
/**
* Prüft ob der Command heute ausgeführt werden soll
*
* WICHTIG: Diese Methode verhindert, dass der Command täglich läuft!
* Der Command sollte nur am konfigurierten Tag des Monats laufen.
*
* @return bool True wenn Command ausgeführt werden soll, False sonst
*/
private function shouldExecuteToday(): bool
{
// Hole konfigurierten Ausführungstag (Standard: 1 = Monatserster)
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
// Fallback: Wenn Setting leer oder 0, verwende Tag 1
if ($executeDay === 0) {
$executeDay = 1;
$this->warn('Setting "day-exectute-business-structur" ist leer oder 0. Verwende Standard: Tag 1');
\Log::channel('cron')->warning('BusinessStoreOptimized: Setting day-exectute-business-structur is empty, using default: 1');
}
$presentDay = (int) date('d');
// Logging für Debugging
$this->info("BusinessStoreOptimized: Configured Day: {$executeDay}, Present Day: {$presentDay}");
\Log::channel('cron')->info("BusinessStoreOptimized: Configured Day: {$executeDay}, Present Day: {$presentDay}");
// Prüfe ob heute der konfigurierte Tag ist
if ($executeDay !== $presentDay) {
// Erlaubnis zum Überschreiben für Entwicklung/Testing
// ENV-Variable BUSINESS_FORCE_EXECUTE=true überschreibt den Check
if (env('BUSINESS_FORCE_EXECUTE', false) === true) {
$this->warn('⚠️ BUSINESS_FORCE_EXECUTE ist aktiv - Command wird trotz falschem Tag ausgeführt!');
$this->warn('⚠️ Dies sollte NUR auf Test-Servern verwendet werden!');
\Log::channel('cron')->warning('BusinessStoreOptimized: FORCED execution via BUSINESS_FORCE_EXECUTE');
return true;
}
// Command sollte heute NICHT laufen
$this->info("❌ Command wird NICHT ausgeführt - falscher Tag (erwartet: {$executeDay}, heute: {$presentDay})");
\Log::channel('cron')->info("BusinessStoreOptimized: NOT EXECUTED - wrong day (expected: {$executeDay}, today: {$presentDay})");
return false;
}
// Command wird ausgeführt
$this->info("✅ Command wird ausgeführt - korrekter Tag ({$presentDay})");
\Log::channel('cron')->info("BusinessStoreOptimized: EXECUTING - correct day ({$presentDay})");
return true;
}
/**
* Create a new command instance.
*
@ -69,26 +124,18 @@ class BusinessStoreOptimized extends Command
public function handle()
{
try {
$executeDay = (int) Setting::getContentBySlug('day-exectute-business-structur');
$presentDay = (int) date('d');
$this->info('RUN Command BusinessStoreOptimized on Day: ' . $executeDay);
$this->info('RUN Command BusinessStoreOptimized present Day: ' . $presentDay);
\Log::channel('cron')->info('RUN Command BusinessStoreOptimized on Day: ' . $executeDay);
\Log::channel('cron')->info('RUN Command BusinessStoreOptimized present Day: ' . $presentDay);
$this->logMemoryUsage('Command Start');
if ($executeDay !== $presentDay) {
$this->info('NOT RUN Command BusinessStoreOptimized is not present Day: ' . $presentDay);
\Log::channel('cron')->info('NOT RUN Command BusinessStoreOptimized is not present Day: ' . $presentDay);
// return 0;
// Prüfe ob Command am richtigen Tag ausgeführt werden soll
if (! $this->shouldExecuteToday()) {
return 0;
}
$this->logMemoryUsage('Command Start');
$this->timeStart = microtime(true);
// Argumente mit Standardwerten für den Vormonat
$this->month = $this->argument('month') ?: (int) date("m", strtotime("-1 month"));
$this->year = $this->argument('year') ?: (int) date("Y", strtotime("-1 month"));
$this->month = $this->argument('month') ?: (int) date('m', strtotime('-1 month'));
$this->year = $this->argument('year') ?: (int) date('Y', strtotime('-1 month'));
$this->info('RUN Command BusinessStoreOptimized on month: '.$this->month.' | year: '.$this->year);
$this->logMemoryUsage('Parameters initialized');
@ -130,6 +177,7 @@ class BusinessStoreOptimized extends Command
$this->error('Stack trace: '.$e->getTraceAsString());
$this->logExecutionTime('COMMAND FAILED');
\Log::channel('cron')->info('COMMAND FAILED');
return 1;
}
}
@ -219,7 +267,7 @@ class BusinessStoreOptimized extends Command
$userLevelUpdate = new UserLevelUpdate($this->month, $this->year);
$levelUpdateUsers = $userLevelUpdate->getUserBusinessByMonthYear();
$this->info("Found " . $levelUpdateUsers->count() . " user businesses with level promotions to process");
$this->info('Found '.$levelUpdateUsers->count().' user businesses with level promotions to process');
$updatedCount = 0;
$skippedCount = 0;
@ -241,12 +289,13 @@ class BusinessStoreOptimized extends Command
// Memory-Check alle 50 User
if (($updatedCount + $skippedCount) % 50 === 0) {
$this->logMemoryUsage("After processing " . ($updatedCount + $skippedCount) . " users");
$this->logMemoryUsage('After processing '.($updatedCount + $skippedCount).' users');
}
} catch (\Exception $e) {
$errorCount++;
$this->warn('Error updating level for UserBusiness '.$userBusiness->id.': '.$e->getMessage());
\Log::channel('cron')->warning('UserLevelUpdate error for UserBusiness '.$userBusiness->id.': '.$e->getMessage());
// Weiter mit nächstem User statt abzubrechen
continue;
}
@ -299,6 +348,7 @@ class BusinessStoreOptimized extends Command
if (! $existingStructure) {
$this->info('No stored business structure found to clear');
return;
}
@ -333,7 +383,7 @@ class BusinessStoreOptimized extends Command
$sec = intval($diff);
$micro = $diff - $sec;
$this->info($message . ' | Time: ' . $sec . 'sec :' . round($micro * 1000, 4) . " ms");
$this->info($message.' | Time: '.$sec.'sec :'.round($micro * 1000, 4).' ms');
}
/**
@ -354,7 +404,7 @@ class BusinessStoreOptimized extends Command
$this->logMemoryUsage("After {$processName}");
} catch (\Exception $e) {
$this->error("Error in {$processName}: ".$e->getMessage());
$this->error("Stack trace: " . $e->getTraceAsString());
$this->error('Stack trace: '.$e->getTraceAsString());
throw $e;
}
}
@ -406,7 +456,7 @@ class BusinessStoreOptimized extends Command
*/
private function formatBytes(int $bytes, int $precision = 2): string
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,13 +2,13 @@
namespace App\Http\Controllers\Admin;
use Request;
use App\Services\Shop;
use App\Models\UserAbo;
use App\Services\AboOrderCart;
use App\Repositories\AboRepository;
use App\Http\Controllers\Controller;
use App\Models\UserAbo;
use App\Repositories\AboRepository;
use App\Services\AboItemHistoryService;
use App\Services\AboOrderCart;
use App\Services\Shop;
use Request;
class AboController extends Controller
{
@ -26,6 +26,7 @@ class AboController extends Controller
set_user_attr('filter_user_shop_id', null);
set_user_attr('filter_status', null);
set_user_attr('filter_member_id', null);
return redirect(route('admin_sales_customers'));
}
@ -36,10 +37,10 @@ class AboController extends Controller
// 'filter_user_shops' => $filter_user_shops,
'filter_members' => $filter_members,
];
return view('admin.abo.index', $data);
}
public function detail($id)
{
$data = Request::all();
@ -62,10 +63,10 @@ class AboController extends Controller
'view' => $user_abo->is_for,
'comp_products' => $comp_products,
];
return view('admin.abo.detail', $data);
}
public function update($id)
{
$data = Request::all();
@ -74,23 +75,45 @@ class AboController extends Controller
$user_abo = UserAbo::findOrFail($data['id']);
$this->aboRepository->setModel($user_abo);
$this->aboRepository->update($data);
return redirect(route('admin_abos_detail', [$id]));
}
}
}
public function rollback($id)
{
$user_abo = UserAbo::findOrFail($id);
AboOrderCart::initYard($user_abo);
$success = AboItemHistoryService::rollbackToInitial($user_abo);
if ($success) {
$user_abo->refresh();
AboOrderCart::makeOrderYard($user_abo);
AboOrderCart::checkNumOfCompProducts($user_abo);
\Session()->flash('alert-success', __('abo_history.rollback_success'));
} else {
\Session()->flash('alert-error', __('abo_history.rollback_no_data'));
}
return redirect(route('admin_abos_detail', [$id]));
}
public function datatable()
{
$query = UserAbo::with('user_abo_orders')->with('shopping_user')->select('user_abos.*');
set_user_attr('filter_member_id', Request::get('filter_member_id'));
if (Request::get('filter_member_id') != "") {
if (Request::get('filter_member_id') != '') {
$query->where('user_id', '=', Request::get('filter_member_id'));
}
set_user_attr('filter_status', Request::get('filter_status'));
if (Request::get('filter_status') != "") {
if (Request::get('filter_status') != '') {
$query->where('status', '=', Request::get('filter_status'));
}

View file

@ -2,21 +2,20 @@
namespace App\Http\Controllers\Admin;
use Util;
use Response;
use Request;
use App\Models\DcTag;
use App\Models\DcFile;
use App\Models\DcCategory;
use App\Http\Controllers\Controller;
use App\Repositories\DC\TagRepository;
use App\Models\DcCategory;
use App\Models\DcFile;
use App\Models\DcTag;
use App\Repositories\DC\FileRepository;
use App\Repositories\DC\TagRepository;
use Request;
use Response;
use Util;
class DownloadController extends Controller
{
protected $tagRepository;
protected $fileRepository;
public function __construct(TagRepository $tagRepository, FileRepository $fileRepository)
@ -26,39 +25,47 @@ class DownloadController extends Controller
$this->fileRepository = $fileRepository;
}
public function files(){
public function files()
{
$q = DcFile::orderBy('id', 'desc')->get(); // File::all();
$data = [
'files' => $q,
];
return view('admin.downloadcenter.files', $data);
}
public function fileEdit($id = null){
public function fileEdit($id = null)
{
$file = $id ? DcFile::find($id) : new DcFile;
$data = [
'file' => $file,
'categories' => DcCategory::where('active', true)->orderBy('pos')->get(),
'tags' => DcTag::orderBy('pos')->get(),
];
return view('admin.downloadcenter.file_edit', $data);
}
public function fileUpdate($do, $id){
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') {
@ -66,6 +73,7 @@ class DownloadController extends Controller
$file->active = false;
$file->save();
\Session()->flash('alert-success', 'Datei nicht anzeigen!');
return back();
}
@ -74,22 +82,26 @@ class DownloadController extends Controller
$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'));
$tags = Request::get('nestable_check', []);
$this->fileRepository->tagsUpdate($id, is_array($tags) ? $tags : []);
\Session()->flash('alert-success', 'Tags aktualisiert!');
return back();
}
}
public function upload(){
public function upload()
{
return view('admin.downloadcenter.file_upload');
}
public function uploadFile(){
public function uploadFile()
{
$data = Request::all();
$file = $this->fileRepository->uploadFile($data);
@ -97,13 +109,14 @@ class DownloadController extends Controller
'error' => false,
'filename' => $file->filename,
'filedata' => '',
'code' => 200
'code' => 200,
], 200);
// return response()->json(['success'=>basename($file)]);
}
public function tags($flash = false){
public function tags($flash = false)
{
$active = DcCategory::orderBy('pos')->get();
$inactive = DcTag::where('category_id', null)->get();
@ -114,24 +127,31 @@ class DownloadController extends Controller
if ($flash) {
\Session()->flash('alert-success', 'gespeichert!');
}
return view('admin.downloadcenter.tags', $data);
}
public function storeItem($obj = false){
public function storeItem($obj = false)
{
$data = Request::all();
return $this->tagRepository->storeItem($obj, $data);
return redirect(route('admin_downloadcenter_tags'));
}
public function deleteItem($obj, $id){
public function deleteItem($obj, $id)
{
$this->tagRepository->deleteItem($obj, $id);
return redirect(route('admin_downloadcenter_tags'));
}
public function datatable(){
public function datatable()
{
$query = DcFile::with('tags')->select('dc_files.*');
return \DataTables::eloquent($query)
->addColumn('id', function (DcFile $file) {
return '<a href="'.route('admin_downloadcenter_file_edit', [$file->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
@ -170,7 +190,7 @@ class DownloadController extends Controller
return '<a onclick="return confirm(\'Diese Datei wirklich löschen?\');" class="btn btn-sm btn-danger" href="'.route('admin_downloadcenter_file', ['delete', $file->id]).'"><i class="fa fa-trash"></i></a>';
})
->filterColumn('name', function ($query, $keyword) {
if($keyword != ""){
if ($keyword != '') {
$query->where('original_name', 'LIKE', '%'.$keyword.'%');
}
})
@ -184,5 +204,4 @@ class DownloadController extends Controller
->rawColumns(['id', 'image', 'name', 'active', 'tags', 'action'])
->make(true);
}
}

View file

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

View file

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

View file

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Mail\MailCheckout;
use App\Models\Country;
use App\Models\Product;
@ -10,24 +11,19 @@ use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Services\CustomerPriority;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use PHPUnit\Framework\Constraint\Count;
use Yard;
class ShoppingUserController extends Controller
{
// protected static API_MAIL = 'api.thomas.krummel@gmail.com';
// protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
protected $successStatus = 200;
protected $member_id = 3; //service@aloe-vera.bio
protected $member_id = 3; // service@aloe-vera.bio
/**
* @param Request $request
@ -52,7 +48,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => false,
'message' => 'wp_order_numbers need as json [1234, 1234] ',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -70,7 +66,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => true,
'data' => $status,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
@ -92,7 +88,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'order' => false,
'status' => false,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if (! $shopping_user->shopping_order) {
@ -101,7 +97,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' has no order',
'order' => false,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if ($shopping_user->shopping_order->shipped > 0) {
@ -110,7 +106,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' can not cancel',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -122,12 +118,11 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' is cancel',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* wp_order_number [1234]
@ -145,7 +140,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'order' => false,
'status' => false,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if (! $shopping_user->shopping_order) {
@ -154,7 +149,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' has no order',
'order' => false,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if ($shopping_user->shopping_order->shipped !== 10) {
@ -163,7 +158,7 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' can not open',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -175,12 +170,11 @@ class ShoppingUserController extends Controller
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' is open',
'order' => true,
'status' => $shopping_user->getAPIShippedType(),
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* wp_order_numbers [1234, 1234]
@ -204,7 +198,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => false,
'message' => 'wp_order_numbers need as json [1234, 1234] ',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$data = [];
@ -225,16 +219,16 @@ class ShoppingUserController extends Controller
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user ? $shopping_user->getAPIShippedType() : false, ];
}
return response()->json([
'success' => true,
'data' => $data,
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
@ -267,6 +261,7 @@ class ShoppingUserController extends Controller
\App\Services\Shop::newUserOrder($shopping_user->number);
// exists //like //update
$user = $this->prepareForShow($shopping_user);
return response()->json([
'success' => true,
'data' => [
@ -276,13 +271,12 @@ class ShoppingUserController extends Controller
'customer_number' => $shopping_user->number,
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request)
@ -295,7 +289,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -308,6 +302,7 @@ class ShoppingUserController extends Controller
if ($updated) {
$user = $this->prepareForShow($shopping_user);
$order = $this->prepareForShowOrder($shopping_user->shopping_order);
return response()->json([
'success' => true,
'data' => [
@ -319,12 +314,13 @@ class ShoppingUserController extends Controller
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user ? $shopping_user->getAPIShippedType() : false,
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
return response()->json([
'success' => false,
'message' => 'Entry could not be updated'
'message' => 'Entry could not be updated',
], 500);
}
@ -335,13 +331,12 @@ class ShoppingUserController extends Controller
'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()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
@ -349,7 +344,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => false,
'message' => 'Order with wp_order_number '.$request->wp_order_number.' exists',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
if (! is_array($request->wp_order)) {
@ -373,6 +368,7 @@ class ShoppingUserController extends Controller
if ($wp_order) {
$user = $this->prepareForShow($shopping_user);
$order = $this->prepareForShowOrder($shopping_user->shopping_order);
return response()->json([
'success' => true,
'data' => [
@ -387,12 +383,13 @@ class ShoppingUserController extends Controller
'member_email' => ($shopping_user && $shopping_user->member) ? $shopping_user->member->email : false,
'status' => $shopping_user->getAPIShippedType(),
],
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 200);
}
return response()->json([
'success' => false,
'message' => 'Order could not be stored'
'message' => 'Order could not be stored',
], 500);
}
@ -406,7 +403,7 @@ class ShoppingUserController extends Controller
return response()->json([
'success' => false,
'message' => 'Entry with wp_order_number '.$request->wp_order_number.' not found or mode != dev',
'time' => Carbon::now()->toDateTimeString()
'time' => Carbon::now()->toDateTimeString(),
], 400);
}
$shopping_order = $shopping_user->shopping_order;
@ -420,16 +417,18 @@ class ShoppingUserController extends Controller
$shopping_user->save();
if ($shopping_user->delete()) {
return response()->json([
'success' => true
'success' => true,
]);
}
return response()->json([
'success' => false,
'message' => 'Entry could not be deleted'
'message' => 'Entry could not be deleted',
], 500);
}
private function prepareForShow($shopping_user){
private function prepareForShow($shopping_user)
{
if (! $shopping_user) {
return false;
@ -461,10 +460,12 @@ class ShoppingUserController extends Controller
$ret[$key] = $value;
}
}
return $ret;
}
private function prepareForShowOrder($shopping_order){
private function prepareForShowOrder($shopping_order)
{
if (! $shopping_order) {
return false;
@ -489,10 +490,12 @@ class ShoppingUserController extends Controller
'price' => ($item->price * 100),
];
}
return $ret;
}
private function prepareForUpdate($data){
private function prepareForUpdate($data)
{
// $salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
@ -526,10 +529,12 @@ class ShoppingUserController extends Controller
$ret[$key] = $value;
}
}
return $ret;
}
private function prepareForStore($data){
private function prepareForStore($data)
{
// $salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
if (isset($data['billing_salutation'])) {
@ -570,10 +575,12 @@ class ShoppingUserController extends Controller
}
$ret['has_buyed'] = true;
$ret['subscribed'] = false;
return $ret;
}
private function prepareOrder($wp_shopping_order, $shopping_user, $wp_invoice_path, $api_notice){
private function prepareOrder($wp_shopping_order, $shopping_user, $wp_invoice_path, $api_notice)
{
Yard::instance('shopping')->destroy();
$ret = [];
@ -583,17 +590,17 @@ class ShoppingUserController extends Controller
$order = (object) $order;
$error = [];
if (! isset($order->article) || ! isset($order->qty) || ! isset($order->price)) {
$error[] = "article parameter is missing";
$error[] = 'article parameter is missing';
} else {
$product = Product::whereWpNumber($order->article)->first();
if (! $product) {
$error[] = "article not found";
$error[] = 'article not found';
} else {
if ($order->price != ($product->price * 100)) {
$error[] = "different price: " . ($product->price * 100);
$error[] = 'different price: '.($product->price * 100);
}
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), (int) $order->qty, $product->price, false, false, ['image' => [], 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), (int) $order->qty, $product->price, false, false, ['image' => [], 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
Yard::setTax($cartItem->rowId, $product->getTaxWith());
}
}
@ -611,10 +618,12 @@ class ShoppingUserController extends Controller
$shopping_user->shopping_order = $shopping_order;
Yard::instance('shopping')->destroy();
}
return $ret;
}
private function makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice){
private function makeShoppingOrder($shopping_user, $wp_invoice_path, $api_notice)
{
$data = [
'shopping_user_id' => $shopping_user->id,
@ -649,7 +658,6 @@ class ShoppingUserController extends Controller
}
$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, '.', '');
@ -669,13 +677,14 @@ class ShoppingUserController extends Controller
'points' => $item->options->points,
'slug' => $item->options->slug,
])->save();
return false;
}
}
return $model->delete();
});
foreach ($items as $item) {
if (! ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()) {
$price_net = Yard::instance('shopping')->rowPriceNet($item, 2, '.', '');
@ -692,17 +701,18 @@ class ShoppingUserController extends Controller
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
'slug' => $item->options->slug,
]);
}
}
$shopping_order->makeTaxSplit();
return $shopping_order;
}
public function orderStatusSendMail(ShoppingOrder $shopping_order){
public function orderStatusSendMail(ShoppingOrder $shopping_order)
{
$bcc = [];
$user_mail = $shopping_order->shopping_user->member->email;
@ -714,5 +724,4 @@ class ShoppingUserController extends Controller
Mail::to($user_mail)->bcc($bcc)->locale($shopping_order->getLocale())->send(new MailCheckout($shopping_order->txaction, $shopping_order, null, false, $shopping_order->mode));
}
}

View file

@ -1,19 +1,14 @@
<?php
namespace App\Http\Controllers;
use Carbon;
use Request;
use App\Services\Payment;
use App\Models\UserInvoice;
use App\Services\HTMLHelper;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\HTMLHelper;
use Request;
class BusinessPointsController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -26,7 +21,6 @@ class BusinessPointsController extends Controller
->groupBy('user_id')->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('users.id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')->get();
$this->setFilterVars();
$data = [
'filter_months' => HTMLHelper::getTransMonths(),
@ -34,8 +28,8 @@ class BusinessPointsController extends Controller
'filter_members' => $filter_members,
'filter_status_types' => UserSalesVolume::getTransStatusType(),
];
return view('admin.business.points', $data);
}
@ -47,24 +41,27 @@ class BusinessPointsController extends Controller
}
if (! isset($data['change_member_key']) || $data['change_member_key'] !== config('mivita.edit_data_pass')) {
\Session()->flash('alert-error', 'Das Passwort ist falsch.');
return back();
}
if (! isset($data['is_checked_action'])) {
\Session()->flash('alert-error', 'Änderung nicht bestätigt');
return back();
}
if ($data['action'] === 'add_user_sales_volume') {
SalesPointsVolume::addSalesPointsVolume($data);
return back();
}
if ($data['action'] === 'edit_user_sales_volume') {
SalesPointsVolume::editSalesPointsVolume($data);
return back();
}
return redirect(route('admin_business_points'));
}
@ -76,17 +73,19 @@ class BusinessPointsController extends Controller
if (! $user_id) {
\Session()->flash('alert-error', 'Kein Berater ausgewählt.');
return back();
}
if (! $month || ! $year) {
\Session()->flash('alert-error', 'Monat und Jahr müssen angegeben sein.');
return back();
}
try {
SalesPointsVolume::reCalculateSalesPointsVolume($user_id, $month, $year);
\Session()->flash('alert-success', 'Punkte für den ausgewählten Berater im Monat ' . str_pad($month, 2, "0", STR_PAD_LEFT) . '/' . $year . ' wurden erfolgreich neu berechnet.');
\Session()->flash('alert-success', 'Punkte für den ausgewählten Berater im Monat '.str_pad($month, 2, '0', STR_PAD_LEFT).'/'.$year.' wurden erfolgreich neu berechnet.');
} catch (\Exception $e) {
\Session()->flash('alert-error', 'Fehler bei der Neuberechnung: '.$e->getMessage());
}
@ -94,7 +93,6 @@ class BusinessPointsController extends Controller
return back();
}
private function setFilterVars()
{
@ -132,6 +130,7 @@ class BusinessPointsController extends Controller
if (Request::get('points_filter_status_type_id')) {
$query->where('user_sales_volumes.status', '=', Request::get('points_filter_status_type_id'));
}
return $query;
}
@ -144,7 +143,7 @@ class BusinessPointsController extends Controller
if (! $user_id || ! $month || ! $year) {
return response()->json([
'success' => false,
'data' => null
'data' => null,
]);
}
@ -158,7 +157,7 @@ class BusinessPointsController extends Controller
if (! $lastEntry) {
return response()->json([
'success' => false,
'data' => null
'data' => null,
]);
}
@ -173,7 +172,7 @@ class BusinessPointsController extends Controller
'total_KP_points' => ($lastEntry->month_KP_points ?? 0) + ($lastEntry->month_shop_points ?? 0),
'total_TP_points' => ($lastEntry->month_TP_points ?? 0) + ($lastEntry->month_shop_points ?? 0),
'total_net' => ($lastEntry->month_total_net ?? 0) + ($lastEntry->month_shop_total_net ?? 0),
]
],
]);
}
@ -181,6 +180,7 @@ class BusinessPointsController extends Controller
{
$query = $this->initSearch();
return \DataTables::eloquent($query)
->addColumn('id', function (UserSalesVolume $UserSalesVolume) {
return '<button type="button" class="btn btn-xs btn-secondary" data-toggle="modal" data-target="#modals-load-content"
@ -193,13 +193,25 @@ class BusinessPointsController extends Controller
})
->addColumn('order', function (UserSalesVolume $UserSalesVolume) {
if ($UserSalesVolume->shopping_order) {
// Status 1 = Beraterbestellung
if ($UserSalesVolume->status === 1) {
return '<a href="'.route('admin_sales_users_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-primary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
// Status 2/3 = Shop-Bestellung
if ($UserSalesVolume->status === 2 || $UserSalesVolume->status === 3) {
return '<a href="'.route('admin_sales_customers_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-secondary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
// Status 6 = Storno - Link zur ursprünglichen Bestellung mit Storno-Icon
if ($UserSalesVolume->status === 6) {
// Prüfen ob Berater- oder Shop-Bestellung anhand des payment_for Feldes
$route = ($UserSalesVolume->shopping_order->payment_for === 6 || $UserSalesVolume->shopping_order->payment_for === 7)
? route('admin_sales_customers_detail', [$UserSalesVolume->shopping_order->id])
: route('admin_sales_users_detail', [$UserSalesVolume->shopping_order->id]);
return '<a href="'.$route.'" class="btn btn-xs btn-danger" title="Storno-Eintrag"><i class="fa fa-undo"></i> '.$UserSalesVolume->shopping_order->id.'</a>';
}
}
return '';
})
->addColumn('points', function (UserSalesVolume $UserSalesVolume) {
@ -225,23 +237,23 @@ class BusinessPointsController extends Controller
})
->filterColumn('m_account', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("m_account LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('m_account LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('first_name', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("first_name LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('first_name LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('last_name', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("last_name LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('last_name LIKE ?', '%'.$keyword.'%');
}
})
->filterColumn('email', function ($query, $keyword) {
if ($keyword != "") {
$query->whereRaw("email LIKE ?", '%' . $keyword . '%');
if ($keyword != '') {
$query->whereRaw('email LIKE ?', '%'.$keyword.'%');
}
})

View file

@ -52,7 +52,6 @@ class DhlShipmentController extends Controller
// Get DHL configuration with admin settings
$settingController = new \App\Http\Controllers\SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Create DhlClient with merged configuration
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlConfig['base_url'],
@ -67,7 +66,7 @@ class DhlShipmentController extends Controller
if ($connectionTest) {
$result = [
'success' => true,
'message' => 'DHL API Verbindung erfolgreich getestet!',
'message' => 'DHL API Verbindung erfolgreich getestet! '.config('dhl.config_source').' '.$dhlConfig['base_url'],
'details' => [
'base_url' => $dhlConfig['base_url'],
'using_admin_config' => ! empty($dhlConfig['api_key']),
@ -153,6 +152,7 @@ class DhlShipmentController extends Controller
->editColumn('id', function ($shipment) {
$class = $shipment->type === 'return' ? 'text-warning font-weight-bold' : 'text-primary font-weight-semibold';
$icon = $shipment->type === 'return' ? '<i class="fas fa-undo mr-1"></i>' : '';
return '<a href="'.route('admin.dhl.show', $shipment).'" class="'.$class.'">'.$icon.'#'.$shipment->id.'</a>';
})
->addColumn('type', function ($shipment) {
@ -220,7 +220,7 @@ class DhlShipmentController extends Controller
if ($shipment->canCancel()) {
$buttons .= '<button type="button" class="btn btn-sm btn-outline-danger cancel-shipment-btn" data-shipment-id="'.$shipment->id.'" data-toggle="tooltip" title="Sendung stornieren"><i class="fas fa-ban"></i></button>';
}
// Return label button
// Return label button (for outbound shipments without existing return)
if ($shipment->type == 'outbound' && ! $shipment->returns()->count()) {
$buttons .= '<button type="button" class="btn btn-sm btn-outline-info create-return-btn" data-shipment-id="'.$shipment->id.'" data-toggle="tooltip" title="Retourenlabel erstellen"><i class="fas fa-undo"></i></button>';
}
@ -351,7 +351,11 @@ class DhlShipmentController extends Controller
*/
public function show(DhlShipment $shipment): View
{
$shipment->load(['shoppingOrder.shopping_user', 'relatedShipment']);
$shipment->load([
'shoppingOrder.shopping_user',
'relatedShipment',
'trackingEvents' => fn ($q) => $q->orderBy('event_time', 'desc'),
]);
return view('admin.dhl.show', compact('shipment'));
}
@ -426,7 +430,7 @@ class DhlShipmentController extends Controller
}
// Check DHL_USE_QUEUE configuration
$settingController = new SettingController();
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
$useQueue = $dhlConfig['use_queue'] ?? false;
@ -467,6 +471,54 @@ class DhlShipmentController extends Controller
}
}
/**
* Get billing address for return label (used when original delivery was to Packstation)
*/
private function getBillingAddressForReturn($shippingUser, array $recipient): array
{
if (! $shippingUser) {
Log::warning('[DHL Controller] No shipping user found, using recipient data', [
'recipient' => $recipient,
]);
// Fallback: use recipient data but without Packstation fields
return [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => 'Adresse fehlt',
'houseNumber' => '',
'postalCode' => $recipient['postalCode'] ?? '',
'city' => $recipient['city'] ?? '',
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
];
}
// Parse billing address to extract street and house number
$billingAddress = trim($shippingUser->billing_address ?? '');
$street = $billingAddress;
$houseNumber = '';
// Try to extract house number from address
if (preg_match('/^(.+?)\s+(\d+[a-zA-Z]?[-\/\d]*)$/u', $billingAddress, $matches)) {
$street = trim($matches[1]);
$houseNumber = trim($matches[2]);
}
return [
'name' => trim(($shippingUser->billing_firstname ?? '').' '.($shippingUser->billing_lastname ?? '')),
'name2' => $shippingUser->billing_company ?? '',
'street' => $street,
'houseNumber' => $houseNumber,
'postalCode' => $shippingUser->billing_zipcode ?? '',
'city' => $shippingUser->billing_city ?? '',
'country' => $shippingUser->billing_country?->code ?? 'DEU',
'email' => $shippingUser->billing_email ?? '',
'phone' => $shippingUser->billing_phone ?? '',
];
}
/**
* Create return label synchronously
*/
@ -478,7 +530,7 @@ class DhlShipmentController extends Controller
]);
// Get DHL configuration
$settingController = new SettingController();
$settingController = new SettingController;
$dhlConfig = $settingController->getDhlConfig();
// Initialize DHL client
@ -496,14 +548,21 @@ class DhlShipmentController extends Controller
$order = $shipment->shoppingOrder;
$recipient = $shipment->recipient ?? [];
$returnData = [
'order_id' => $order->id,
'original_shipment_id' => $shipment->id,
'weight_kg' => $shipment->weight_kg,
'label_format' => $shipment->label_format ?? 'PDF',
// Check if this is a Packstation delivery - use billing address as return sender
$hasPostNumber = ! empty($recipient['postnumber'] ?? $recipient['postNumber'] ?? '');
// Shipper: Customer sends back to us (swap addresses)
'shipper' => [
if ($hasPostNumber) {
Log::info('[DHL Controller] Packstation detected - using billing address for return sender', [
'shipment_id' => $shipment->id,
'order_id' => $order->id,
]);
// Load billing address from order
$shippingUser = $order->shopping_user;
$shipperAddress = $this->getBillingAddressForReturn($shippingUser, $recipient);
} else {
// Use original recipient address (normal delivery)
$shipperAddress = [
'name' => trim(($recipient['firstname'] ?? '').' '.($recipient['lastname'] ?? '')),
'name2' => $recipient['company'] ?? '',
'street' => $recipient['street'] ?? '',
@ -513,7 +572,17 @@ class DhlShipmentController extends Controller
'country' => $recipient['country'] ?? 'DEU',
'email' => $recipient['email'] ?? '',
'phone' => $recipient['phone'] ?? '',
],
];
}
$returnData = [
'order_id' => $order->id,
'original_shipment_id' => $shipment->id,
'weight_kg' => $shipment->weight_kg,
'label_format' => $shipment->label_format ?? 'PDF',
// Shipper: Customer sends back to us (using billing address for Packstation)
'shipper' => $shipperAddress,
// Consignee: Our warehouse
'consignee' => [

View file

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

View file

@ -4,9 +4,8 @@ namespace App\Http\Controllers;
use App\Models\ShoppingPayment;
use App\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Config;
use Illuminate\Support\Facades\Auth;
use Request;
use Util;
@ -19,15 +18,23 @@ class HomeController extends Controller
*/
public function __construct() {}
public function index()
{
if (! Auth::check()) {
return redirect('login');
}
return redirect('home');
}
public function newsArchive(): \Illuminate\View\View
{
return view('dashboard.news_archive', [
'currentNews' => \App\Models\DashboardNews::getActiveNews(),
'archiveNews' => \App\Models\DashboardNews::getArchiveNews(),
]);
}
// login / Dashboard
public function show()
{
@ -41,17 +48,17 @@ class HomeController extends Controller
'now' => Carbon::now(),
'dashboardNews' => \App\Models\DashboardNews::getActiveNews(),
];
return view('home', $data);
}
public function loadingModal()
{
$data = Request::get('data');
$target = Request::get('target');
$response = "";
if ($data === "data_protection") {
$response = '';
if ($data === 'data_protection') {
$data = [
'modal' => true,
'user_shop' => true,
@ -59,21 +66,21 @@ class HomeController extends Controller
];
$response = view('legal.data_protect_de', $data)->render();
}
if ($data === "imprint") {
if ($data === 'imprint') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
];
$response = view('legal.imprint_de', $data)->render();
}
if ($data === "shop_term_of_use") {
if ($data === 'shop_term_of_use') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
];
$response = view('legal.shop_term_of_use_de', $data)->render();
}
if ($data === "agb") {
if ($data === 'agb') {
$data = [
'modal' => true,
'user_shop' => Util::getUserShop(),
@ -154,6 +161,7 @@ class HomeController extends Controller
'isMivitaShop' => Util::isMivitaShop(),
'yard_instance' => 'webshop',
];
return view('legal.data_protected', $data);
}
@ -166,6 +174,7 @@ class HomeController extends Controller
'yard_instance' => 'webshop',
];
return view('legal.agb', $data);
}
@ -177,6 +186,7 @@ class HomeController extends Controller
'user_shop' => Util::getUserShop(),
'yard_instance' => 'webshop',
];
return view('legal.imprint', $data);
}
@ -208,6 +218,7 @@ class HomeController extends Controller
Auth::login($user);
}
$url = Util::getMyMivitaUrl();
return redirect($url);
}
@ -215,20 +226,22 @@ class HomeController extends Controller
{
return view('status.status_register');
}
public function statusVerify()
{
return view('status.status_verify');
}
public function statusError()
{
return view('status.status_error');
}
public function notFound()
{
return view('status.not_found');
}
/**
* @return string
*/
@ -236,7 +249,7 @@ class HomeController extends Controller
{
$data = Request::all();
if ($data['user_id'] === "new") {
if ($data['user_id'] === 'new') {
if (User::where('email', $data['email'])->count()) {
return json_encode(false);
}
@ -245,6 +258,7 @@ class HomeController extends Controller
return json_encode(false);
}
}
return json_encode(true);
}
@ -253,7 +267,7 @@ class HomeController extends Controller
return view('status.user_blocked');
}
public function backToShop($reference = "")
public function backToShop($reference = '')
{
if ($reference) {
@ -264,10 +278,12 @@ class HomeController extends Controller
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(url('/'));
}
}

View file

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

View file

@ -2,26 +2,23 @@
namespace App\Http\Controllers;
use Request;
use App\User;
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\Homeparty;
use App\Models\UserLevel;
use App\Models\UserCredit;
use App\Models\ShoppingUser;
use App\Services\HTMLHelper;
use App\Models\HomepartyUser;
use App\Models\Product;
use App\Models\ShoppingOrder;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserCredit;
use App\Models\UserLevel;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\Services\DhlModalService;
use App\User;
use Request;
class ModalController extends Controller
{
public function __construct()
{
$this->middleware('auth');
@ -30,18 +27,18 @@ class ModalController extends Controller
public function load()
{
$data = Request::all();
$ret = "";
$ret = '';
$status = false;
if (Request::ajax()) {
if ($data['action'] === 'shopping-order-change-member') {
$value = ShoppingOrder::find($data['id']);
$route = route('admin_sales_customers_detail', [$value->id]);
$ret = view("admin.modal.member", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.member', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'shopping-user-change-member') {
$value = ShoppingUser::find($data['id']);
$route = route('admin_customer_edit', [$value->id]);
$ret = view("admin.modal.member", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.member', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'shopping-user-is-like-member') {
$current = ShoppingUser::find($data['id']); // current user form order
@ -52,21 +49,21 @@ class ModalController extends Controller
$possibles[] = ShoppingUser::find($like_id);
}
}
$ret = view("admin.modal.is_like_member", compact('current', 'possibles', 'data'))->render();
$ret = view('admin.modal.is_like_member', compact('current', 'possibles', 'data'))->render();
}
if ($data['action'] === 'shopping-order-change-points') {
$value = ShoppingOrder::find($data['id']);
$route = route('admin_sales_customers_detail', [$value->id]);
$ret = view("admin.modal.change_points", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.change_points', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'user-order-show-product') {
$product = Product::find($data['id']); // current user form order
$ret = view("admin.modal.show_product", compact('product', 'data'))->render();
$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();
$ret = view('admin.modal.show_product', compact('product', 'data'))->render();
}
if ($data['action'] === 'shop-user-order-detail') {
@ -76,7 +73,7 @@ class ModalController extends Controller
abort(404);
}
$isAdmin = false;
$ret = view("user.shop.sales.modal_api_order_detail", compact('shopping_order', 'isAdmin', 'data'))->render();
$ret = view('user.shop.sales.modal_api_order_detail', compact('shopping_order', 'isAdmin', 'data'))->render();
}
if ($data['action'] === 'shop-user-order-shipping-detail') {
@ -86,12 +83,12 @@ class ModalController extends Controller
abort(404);
}
$isAdmin = false;
$ret = view("user.shop.sales.modal_api_order_shipping_detail", compact('shopping_order', 'isAdmin', 'data'))->render();
$ret = view('user.shop.sales.modal_api_order_shipping_detail', compact('shopping_order', 'isAdmin', 'data'))->render();
}
if ($data['action'] === 'user-order-my-delivery-show') {
$user = \Auth::user();
$ret = view("admin.modal.show_user_customers", compact('user', 'data'))->render();
$ret = view('admin.modal.show_user_customers', compact('user', 'data'))->render();
}
if ($data['action'] === 'user-order-my-delivery-add') {
@ -103,18 +100,18 @@ class ModalController extends Controller
$homeparty = Homeparty::find($data['id']);
$homeparty_user = HomepartyUser::find($data['user_id']);
$data['homeparty'] = $homeparty;
$ret = view("user.homeparty.modal_hp_show_products", compact('data', 'homeparty', 'homeparty_user'))->render();
$ret = view('user.homeparty.modal_hp_show_products', compact('data', 'homeparty', 'homeparty_user'))->render();
}
if ($data['action'] === 'user-level-edit') {
$value = UserLevel::find($data['id']);
$route = route('admin_level_store', [$value->id]);
$ret = view("admin.modal.user_level_edit", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.user_level_edit', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'user-level-add') {
$value = new UserLevel();
$value = new UserLevel;
$route = route('admin_level_store', ['new']);
$ret = view("admin.modal.user_level_edit", compact('value', 'data', 'route'))->render();
$ret = view('admin.modal.user_level_edit', compact('value', 'data', 'route'))->render();
}
if ($data['action'] === 'business-user-detail') {
$user = User::findOrFail($data['id']);
@ -128,35 +125,37 @@ class ModalController extends Controller
$data['live'] = $data['live'] ?? false;
$data['optimized'] = $data['optimized'] ?? false;
$TreeCalcBot = $this->getForBusinessUserDetail($user, $data);
$route = "";
$ret = view("admin.modal.business_user_detail", compact('TreeCalcBot', 'user', 'data'))->render();
$route = '';
$ret = view('admin.modal.business_user_detail', compact('TreeCalcBot', 'user', 'data'))->render();
}
if ($data['action'] === 'business-user-show') {
$user = User::find($data['id']);
if ($user && $user->account) {
$route = "";
$ret = view("admin.modal.business_user_show", compact('user', 'data'))->render();
$user = User::with(['account', 'account.country', 'account.shipping_country', 'user_level', 'user_sponsor.account'])->find($data['id']);
\Log::info('business-user-show', ['user' => $user]);
if ($user) {
$route = '';
$ret = view('admin.modal.business_user_show', compact('user', 'data'))->render();
} else {
$ret = view('admin.modal.business_user_notfound', compact('data'))->render();
}
$ret = view("admin.modal.business_user_notfound", compact('data'))->render();
}
if ($data['action'] === 'edit_user_sales_volume') {
$userSalesVolume = UserSalesVolume::findOrFail($data['id']);
$route = route('admin_business_points_store',);
$ret = view("admin.business.modal_edit_points", compact('userSalesVolume', 'data', 'route'))->render();
$route = route('admin_business_points_store');
$ret = view('admin.business.modal_edit_points', compact('userSalesVolume', 'data', 'route'))->render();
}
if ($data['action'] === 'add_user_sales_volume') {
$userSalesVolume = new UserSalesVolume();
$route = route('admin_business_points_store',);
$ret = view("admin.business.modal_add_points", compact('userSalesVolume', 'data', 'route'))->render();
$userSalesVolume = new UserSalesVolume;
$route = route('admin_business_points_store');
$ret = view('admin.business.modal_add_points', compact('userSalesVolume', 'data', 'route'))->render();
}
if ($data['action'] === 'add-user-credit') {
$value = [];
$ret = view("admin.payment.modal_add_credit", compact('value', 'data'))->render();
$ret = view('admin.payment.modal_add_credit', compact('value', 'data'))->render();
}
if ($data['action'] === 'user-credit-status') {
$UserCredit = UserCredit::find($data['id']); // current user form order
$ret = view("admin.payment.modal_credit_status", compact('UserCredit', 'data'))->render();
$ret = view('admin.payment.modal_credit_status', compact('UserCredit', 'data'))->render();
}
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::find($data['id']);
@ -165,11 +164,11 @@ class ModalController extends Controller
} else {
$route = route('user_abos_update', [$data['view'], $user_abo->id]);
}
$ret = view("admin.abo.modal_abo_update", compact('user_abo', 'data', 'route'))->render();
$ret = view('admin.abo.modal_abo_update', compact('user_abo', 'data', 'route'))->render();
}
if ($data['action'] === 'abo-add-product') {
$user_abo = UserAbo::find($data['id']);
$ret = view("user.abo.modal_abo_show_products", compact('data', 'user_abo'))->render();
$ret = view('user.abo.modal_abo_show_products', compact('data', 'user_abo'))->render();
}
if ($data['action'] === 'create-dhl-shipment') {
@ -177,6 +176,7 @@ class ModalController extends Controller
$ret = $this->handleDhlShipmentModal($id, $data);
}
}
return response()->json(['response' => $data, 'html' => $ret, 'status' => $status]);
}
@ -195,7 +195,9 @@ class ModalController extends Controller
if (! $TreeCalcBot->business_user) {
abort(403, 'no user found');
}
return $TreeCalcBot;
// }
return null;
}
@ -210,21 +212,21 @@ class ModalController extends Controller
private function handleDhlShipmentModal($id, array $data): string
{
try {
$dhlModalService = new DhlModalService();
$dhlModalService = new DhlModalService;
$modalData = $dhlModalService->prepareModalData($id, $data);
// Merge the prepared data with the original request data
$viewData = array_merge($data, $modalData, [
'id' => $id,
'data' => $data
'data' => $data,
]);
return view("admin.dhl.modal_create_shipment", $viewData)->render();
return view('admin.dhl.modal_create_shipment', $viewData)->render();
} catch (\Exception $e) {
\Log::error('[ModalController] Error in DHL shipment modal', [
'order_id' => $id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
'trace' => $e->getTraceAsString(),
]);
// Return error view or fallback
@ -240,16 +242,14 @@ class ModalController extends Controller
'V53WPAK' => 'DHL Paket International',
],
'errors' => ['Fehler beim Laden der Daten: '.$e->getMessage()],
'warnings' => []
'warnings' => [],
];
return view("admin.dhl.modal_create_shipment", $errorData)->render();
return view('admin.dhl.modal_create_shipment', $errorData)->render();
}
}
}
/* <button type="button" class="btn btn-sm btn-primary" data-toggle="modal"
data-target="#modals-load-content"
data-id="{{ $value->id }}"

View file

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

View file

@ -1,29 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Repositories\CreditRepository;
use App\Services\Credit;
use App\Services\HTMLHelper;
use App\Services\Payment;
use App\Services\Util;
use App\User;
use Carbon;
use Request;
use App\User;
use App\Services\Util;
use App\Services\Credit;
use App\Services\Payment;
use App\Models\UserCredit;
use App\Services\HTMLHelper;
use App\Models\UserCreditItem;
use App\Models\UserCreditMargin;
use Illuminate\Support\Collection;
use App\Models\ShoppingOrderMargin;
use App\Repositories\CreditRepository;
use App\Models\Models\UserCreditMargin as ModelsUserCreditMargin;
use App\Models\UserAccount;
use stdClass;
class PaymentCreditController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -37,31 +28,34 @@ class PaymentCreditController extends Controller
'filter_years' => HTMLHelper::getYearRange(2022),
'user_credit_items' => $this->makeUserCreditItems(),
];
return view('admin.payment.credit', $data);
}
public function store()
{
$data = Request::all();
if (isset($data['action']) && $data['action'] === 'add-user-credit') {
if (! isset($data['member_id']) || ! $user = User::find($data['member_id'])) {
\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");
\Session()->flash('alert-success', 'Guthaben hinzugefügt');
}
return redirect(route('admin_payments_credit'));
@ -78,14 +72,16 @@ class PaymentCreditController extends Controller
$user = User::findOrFail($data['userid']);
$credit_repo = new CreditRepository($user);
$credit_repo->create($data);
\Session()->flash('alert-success', "Gutschrift erstellt");
\Session()->flash('alert-success', 'Gutschrift erstellt');
return redirect($data['back']);
}
if ($data['action'] === 'user-credit-status') {
$UserCredit = UserCredit::findOrFail($data['id']);
$UserCredit->status = $data['status'];
$UserCredit->save();
\Session()->flash('alert-success', "Status gespeichert");
\Session()->flash('alert-success', 'Status gespeichert');
return back();
}
}
@ -147,6 +143,7 @@ class PaymentCreditController extends Controller
}
}
}
return $ret;
}
@ -157,11 +154,12 @@ class PaymentCreditController extends Controller
$UserCreditItem = UserCreditItem::findOrFail($id);
if ($deleteTime = $UserCreditItem->deleteTime()) {
$UserCreditItem->delete();
\Session()->flash('alert-success', "Guthaben ist gelöscht");
\Session()->flash('alert-success', 'Guthaben ist gelöscht');
} else {
\Session()->flash('alert-error', "Guthaben kann nicht gelöscht werden");
\Session()->flash('alert-error', 'Guthaben kann nicht gelöscht werden');
}
}
return redirect(route('admin_payments_credit'));
}
@ -181,6 +179,7 @@ class PaymentCreditController extends Controller
->orWhere('last_name', 'LIKE', '%'.Request::get('credit_filter_name').'%');
});
}
return $query;
}
@ -192,38 +191,49 @@ class PaymentCreditController extends Controller
return \DataTables::eloquent($query)
->addColumn('user.account.first_name', function (UserCredit $UserCredit) {
return isset($UserCredit->user->account) ? $UserCredit->user->account->first_name : "gelöscht";
return isset($UserCredit->user->account) ? $UserCredit->user->account->first_name : 'gelöscht';
})
->addColumn('user.account.last_name', function (UserCredit $UserCredit) {
return isset($UserCredit->user->account) ? $UserCredit->user->account->last_name : "gelöscht";
return isset($UserCredit->user->account) ? $UserCredit->user->account->last_name : 'gelöscht';
})
->addColumn('user.email', function (UserCredit $UserCredit) {
return isset($UserCredit->user) ? $UserCredit->user->email : "gelöscht";
return isset($UserCredit->user) ? $UserCredit->user->email : 'gelöscht';
})
->addColumn('view', function (UserCredit $UserCredit) {
$ret = "";
$ret = '';
if ($UserCredit->isCredit()) {
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit', 'download']) . '" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit', 'stream']) . '" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a><br>';
// Deutsches Original (ausgefüllter Button)
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download']).'" class="btn btn-primary btn-xs mb-2 mr-1" title="Gutschrift DE"><i class="fa fa-download"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream']).'" target="_blank" class="btn btn-warning btn-xs mb-2 mr-1" title="Vorschau DE"><i class="fa fa-eye"></i></a>';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit_detail', 'html']) . '" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="' . route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']) . '" target="_blank" class="btn btn-secondary btn-xs mt-2"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
} else {
$ret = "-";
// Lokalisierte Versionen (outline Buttons)
$availableLocales = $UserCredit->getAvailableLocales();
foreach ($availableLocales as $locale) {
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'download', $locale]).'" class="btn btn-outline-primary btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-download"></i> '.strtoupper($locale).'</a>';
$ret .= ' <a href="'.route('storage_file', [$UserCredit->id, 'credit', 'stream', $locale]).'" class="btn btn-outline-warning btn-xs mb-2 mr-1" title="Gutschrift '.strtoupper($locale).'"><i class="fa fa-eye"></i> '.strtoupper($locale).'</a>';
}
$ret .= '<br>';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'html']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1"><i class="fa fa-eye"></i></a> ';
$ret .= '<a href="'.route('storage_file', [$UserCredit->id, 'credit_detail', 'pdf']).'" target="_blank" class="btn btn-secondary btn-xs mb-2 mr-1"><i class="fa fa-file-pdf" style="min-width:13.5px"></i></a> ';
} else {
$ret = '-';
}
return $ret;
})
->addColumn('total', function (UserCredit $UserCredit) {
return '<span class="no-line-break">' . $UserCredit->getFormattedTotal() . " €</span>";
return '<span class="no-line-break">'.$UserCredit->getFormattedTotal().' €</span>';
})
->addColumn('credits', function (UserCredit $UserCredit) {
$ret = "";
$ret = '';
if ($UserCredit->user_credit_items) {
foreach ($UserCredit->user_credit_items as $user_credit_item) {
$ret .= nl2br($user_credit_item->getTransMessage()) . " / " . $user_credit_item->created_at->format('d.m.Y') . "<br>";
$ret .= nl2br($user_credit_item->getTransMessage()).' / '.$user_credit_item->created_at->format('d.m.Y').'<br>';
}
}
return $ret;
})
->addColumn('status', function (UserCredit $UserCredit) {
@ -233,21 +243,21 @@ class PaymentCreditController extends Controller
</a>';
})
->filterColumn('user.account.first_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user.account', function ($query) use ($keyword) {
return $query->where('first_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('user.account.last_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user.account', function ($query) use ($keyword) {
return $query->where('last_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('user.email', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('user', function ($query) use ($keyword) {
return $query->where('email', 'LIKE', '%'.$keyword.'%');
});

View file

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

View file

@ -2,25 +2,27 @@
namespace App\Http\Controllers\Portal;
use Auth;
use Yard;
use Request;
use Validator;
use App\Services\Shop;
use App\Services\Util;
use App\Models\Product;
use App\Models\UserAbo;
use App\Services\AboHelper;
use App\Models\ShoppingUser;
use App\Models\ShoppingOrder;
use App\Services\UserService;
use App\Models\ShoppingInstance;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ShoppingInstance;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Repositories\AboRepository;
use App\Services\AboHelper;
use App\Services\AboItemHistoryService;
use App\Services\AboOrderCart;
use App\Services\Shop;
use App\Services\UserService;
use App\Services\Util;
use Auth;
use Request;
use Yard;
class AboController extends Controller
{
private $instance = 'subscription';
private $yard;
/**
@ -34,7 +36,6 @@ class AboController extends Controller
$this->yard = Yard::instance($this->instance);
}
public function myAbo()
{
$user = Auth::guard('customers')->user();
@ -52,14 +53,287 @@ class AboController extends Controller
->where('status', '>', 1)
->first();
return $user_abo
? view('portal.abo.my_abo', ['user_abo' => $user_abo])
: view('portal.abo.my_abo_create', [
if (! $user_abo) {
return view('portal.abo.my_abo_create', [
'shopping_user' => $shopping_user,
'step' => 0,
]);
}
$this->checkPortalPermission($user_abo);
$view = 'portal';
// Init Yard und Customer-Detail
AboOrderCart::initYard($user_abo);
$customer_detail = AboOrderCart::getCustomerDetail();
AboOrderCart::makeOrderYard($user_abo);
return view('portal.abo.my_abo', [
'user_abo' => $user_abo,
'customer_detail' => $customer_detail,
'view' => $view,
'comp_products' => [],
'isAdmin' => false,
]);
}
public function update($view, $id)
{
$data = Request::all();
$user_abo = UserAbo::findOrFail($id);
$this->checkPortalPermission($user_abo);
$isAddOnlyMode = AboHelper::isAddOnlyMode($user_abo, $view);
if (isset($data['action'])) {
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::findOrFail($data['id']);
$this->checkPortalPermission($user_abo);
$aboRepository = new AboRepository;
$aboRepository->setModel($user_abo);
$aboRepository->update($data);
return redirect(route('portal.my_subscriptions'));
}
if (Request::ajax()) {
$message = false;
// addProduct
if ($data['action'] === 'addProduct') {
if ($product = Product::find($data['product_id'])) {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('product_id', $product->id)->where('comp', 0)->first()) {
$qtyBefore = $UserAboItem->qty;
$UserAboItem->qty = $UserAboItem->qty + 1;
$UserAboItem->save();
AboItemHistoryService::logProductAdded($user_abo, $UserAboItem, $qtyBefore, $view);
} else {
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $product->id,
'comp' => 0,
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
}
// updateCart
if ($data['action'] === 'updateCart') {
if (isset($data['product_id']) && $product = Product::find($data['product_id'])) {
if (isset($data['order_item_id']) && $UserAboItem = UserAboItem::find($data['order_item_id'])) {
if (isset($data['qty'])) {
$qtyBefore = $UserAboItem->qty;
$qty = (int) $data['qty'];
$qty = $qty < 1 ? 1 : $qty;
$qty = $qty > 100 ? 100 : $qty;
if ($isAddOnlyMode && $qty < $UserAboItem->qty) {
$qty = $UserAboItem->qty;
}
$UserAboItem->qty = $qty;
$UserAboItem->save();
AboItemHistoryService::logQtyChanged($user_abo, $UserAboItem, $qtyBefore, $qty, $view);
}
}
}
}
// removeFromCart
if ($data['action'] === 'removeFromCart') {
if ($isAddOnlyMode) {
return response()->json([
'response' => false,
'message' => __('abo.error_add_only_no_remove'),
], 403);
}
if (! isset($data['product_id']) || ! ($product = Product::find($data['product_id']))) {
$message = __('abo.product_not_found');
}
if (! isset($data['order_item_id']) || ! ($userAboItem = UserAboItem::find($data['order_item_id']))) {
$message = __('abo.abo_item_not_found');
}
$has_basis_product = $this->checkNeedBasisProduct($user_abo, $product, $data['order_item_id']);
if (! $has_basis_product) {
$message = __('abo.need_basis_product');
}
if (! $message) {
AboItemHistoryService::logProductRemoved($user_abo, $userAboItem, $view);
$userAboItem->delete();
$user_abo->refresh();
}
}
// updateCompProduct
if ($data['action'] === 'updateCompProduct') {
if ($UserAboItem = UserAboItem::where('user_abo_id', $user_abo->id)->where('comp', $data['comp_num'])->first()) {
$oldProduct = $UserAboItem->product;
$UserAboItem->product_id = $data['comp_product_id'];
$UserAboItem->save();
$UserAboItem->load('product');
AboItemHistoryService::logCompProductChanged($user_abo, $UserAboItem, $oldProduct, $UserAboItem->product, $view);
} else {
$newItem = UserAboItem::create([
'user_abo_id' => $user_abo->id,
'product_id' => $data['comp_product_id'],
'comp' => $data['comp_num'],
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logProductAdded($user_abo, $newItem, 0, $view);
}
}
AboOrderCart::initYard($user_abo);
AboOrderCart::makeOrderYard($user_abo);
AboOrderCart::checkNumOfCompProducts($user_abo);
$error_message = $message ? $message : false;
$html_cart = view('admin.abo._order_abo_show', ['user_abo' => $user_abo, 'error_message' => $error_message, 'add_only_mode' => $isAddOnlyMode])->render();
$html_comp = view('user.order.comp_product', $data)->render();
$amount = $user_abo->getFormattedAmount();
return response()->json(['response' => true, 'data' => $data, 'html_cart' => $html_cart, 'html_comp' => $html_comp, 'amount' => $amount]);
}
}
}
public function datatable($user_abo_id)
{
$user_abo = UserAbo::findOrFail($user_abo_id);
$this->checkPortalPermission($user_abo);
$show_on_ids = ['12', '13'];
$query = Product::select('products.*')
->where('active', true)
->where(function ($q) use ($show_on_ids) {
foreach ($show_on_ids as $id) {
$q->orWhereJsonContains('show_on', $id);
}
})
->orderByRaw(
"CASE
WHEN JSON_CONTAINS(show_on, ?, '$') THEN 1
WHEN JSON_CONTAINS(show_on, ?, '$') THEN 2
ELSE 3 END",
[$show_on_ids[0], isset($show_on_ids[1]) ? $show_on_ids[1] : $show_on_ids[0]]
);
return \DataTables::eloquent($query)
->addColumn('add_card', function (Product $product) {
$tax_free = Yard::instance('shopping')->getUserTaxFree();
$price = $product->getFormattedPriceWith($tax_free, false, Yard::instance('shopping')->getUserCountry());
return '<button type="button" class="btn btn-sm btn-md-extra btn-secondary add-product-basket" data-product-id="'.$product->id.'" data-product-name="'.e($product->getLang('name')).'" data-product-price="'.$price.' &euro;">
<strong>&euro; '.$price.'</strong>&nbsp; +<span class="ion ion-md-cart"></span>
</button>';
})
->addColumn('picture', function (Product $product) {
if (count($product->images)) {
return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
}
return '';
})
->addColumn('name', function (Product $product) {
return '<strong>'.$product->getLang('name').'</strong><br>'.get_abo_type_badge_by_product($product);
})
->addColumn('points', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPoints().'</span>';
})
->addColumn('price_net', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_gross', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('action', function (Product $product) {
return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg"
data-toggle="modal" data-target="#modals-load-content" data-id="'.$product->id.'" data-route="'.route('portal.loading_modal').'"
data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
})
->filterColumn('product', function ($query, $keyword) {
if ($keyword != '') {
$query->where('name', 'LIKE', '%'.$keyword.'%');
}
})
->orderColumn('name', 'name $1')
->orderColumn('product', 'name $1')
->orderColumn('number', 'number $1')
->orderColumn('points', 'points $1')
->orderColumn('price_net', 'price_net $1')
->orderColumn('price_gross', 'price_gross $1')
->orderColumn('contents_total', 'contents_total $1')
->orderColumn('weight', 'weight $1')
->rawColumns(['add_card', 'points', 'product', 'name', 'quantity', 'picture', 'price_net', 'price_gross', 'action'])
->make(true);
}
public function modalLoad()
{
$data = Request::all();
$ret = '';
if (isset($data['action'])) {
if ($data['action'] === 'abo-add-product') {
$user_abo = UserAbo::find($data['id']);
$this->checkPortalPermission($user_abo);
$ret = view('user.abo.modal_abo_show_products', compact('data', 'user_abo'))->render();
}
if ($data['action'] === 'abo_update_settings') {
$user_abo = UserAbo::find($data['id']);
$this->checkPortalPermission($user_abo);
$route = route('user_abos_update', [$data['view'], $user_abo->id]);
$ret = view('admin.abo.modal_abo_update', compact('user_abo', 'data', 'route'))->render();
}
if ($data['action'] === 'user-order-show-product') {
$product = Product::find($data['id']);
$ret = view('admin.modal.show_product', compact('product', 'data'))->render();
}
}
if (Request::ajax()) {
return response()->json(['response' => $data, 'html' => $ret, 'status' => true]);
}
abort(404);
}
public function checkNeedBasisProduct($user_abo, $product, $order_item_id)
{
if (AboHelper::getAboShowOn($product) !== 'base') {
return true;
}
foreach ($user_abo->user_abo_items as $user_abo_item) {
if ($user_abo_item->id == $order_item_id) {
continue;
}
if ($user_abo_item->comp) {
continue;
}
if (AboHelper::getAboShowOn($user_abo_item->product) === 'base') {
return true;
}
}
return false;
}
private function checkPortalPermission($user_abo)
{
$user = Auth::guard('customers')->user();
if (! $user || ! $user->shopping_user_id) {
abort(403, 'Unauthorized action.');
}
$shopping_user = ShoppingUser::find($user->shopping_user_id);
if (! $shopping_user || $user_abo->email !== $shopping_user->billing_email) {
abort(403, 'Unauthorized action.');
}
}
public function myAboCreate($step)
{
$user = Auth::guard('customers')->user();
@ -73,6 +347,7 @@ class AboController extends Controller
if (isset($data['checkout_url'])) {
return redirect($data['checkout_url']);
}
return view('portal.abo.my_abo_create', $data);
}
@ -164,7 +439,8 @@ class AboController extends Controller
Shop::initUserShopLang($delivery_country, $this->instance);
}
private function preCheckCheckout(){
private function preCheckCheckout()
{
$result = false;
// alle inhlate des warenkorb
$cartItems = $this->yard->content();
@ -173,11 +449,10 @@ class AboController extends Controller
$result = true;
}
}
return $result;
}
private function checkBasisProduct()
{
$data = Request::all();
@ -195,13 +470,13 @@ class AboController extends Controller
}
$result = true;
$this->addProductToCart($product, $quantity);
}
return $result;
}
private function upgradeProductToCart(){
private function upgradeProductToCart()
{
$data = Request::all();
$result = false;
@ -235,6 +510,7 @@ class AboController extends Controller
foreach ($cartItems as $item) {
$this->yard->remove($item->rowId);
}
return;
}
@ -265,7 +541,7 @@ class AboController extends Controller
'points' => $product->points,
'no_commission' => $product->no_commission,
'no_free_shipping' => $product->no_free_shipping,
'show_on' => $product->show_on
'show_on' => $product->show_on,
]
);
}
@ -274,8 +550,8 @@ class AboController extends Controller
$this->yard->reCalculateShippingPrice();
}
private function processCheckout(){
private function processCheckout()
{
$user_shop = Util::getUserShop();
if (! $user_shop) {
$user_shop = Util::getDefaultUserShop();
@ -306,6 +582,7 @@ class AboController extends Controller
if (strpos($path, 'https') === false) {
$path = str_replace('http', 'https', $path);
}
return $path;
}
}

View file

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

View file

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

View file

@ -2,20 +2,19 @@
namespace App\Http\Controllers;
use Request;
use App\Models\UserShop;
use App\Services\Payment;
use App\Models\ShoppingUser;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\PaymentTransaction;
use App\Services\CustomerPriority;
use App\Models\ShoppingUser;
use App\Models\UserShop;
use App\Repositories\InvoiceRepository;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\CustomerPriority;
use App\Services\Payment;
use Request;
class SalesController extends Controller
{
public function __construct()
{
$this->middleware('admin');
@ -28,6 +27,7 @@ class SalesController extends Controller
return redirect(route('admin_sales_users'));
}
$data = [];
return view('admin.sales.users', $data);
}
@ -48,36 +48,38 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_user',
];
return view('admin.sales.user_detail', $data);
}
public function usersStore($id)
{
die("keine funktion");
exit('keine funktion');
$data = [
'shopping_order' => ShoppingOrder::find($id),
'isAdmin' => true,
];
return view('admin.sales.user_detail', $data);
}
public function usersDatatable()
{
$query = ShoppingOrder::with('shopping_user', 'user_shop', 'shopping_payments')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', '!=', NULL);
$query = ShoppingOrder::with('shopping_user', 'user_shop', 'shopping_payments')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', '!=', null);
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
return '<a href="'.route('admin_sales_users_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
@ -92,6 +94,7 @@ class SalesController extends Controller
data-init_from="user"
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
}
return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
})
->addColumn('dhl_button', function (ShoppingOrder $ShoppingOrder) {
@ -118,6 +121,7 @@ class SalesController extends Controller
})
->addColumn('auth_user_shop', function (ShoppingOrder $ShoppingOrder) {
$auth_user_shop = UserShop::whereUserId($ShoppingOrder->auth_user_id)->first();
return $auth_user_shop ? '<a href="'.$auth_user_shop->getSubdomain(false).'" target="_blank">'.$auth_user_shop->getSubdomain(false).'</span>' : '-';
})
->orderColumn('id', 'id $1')
@ -137,6 +141,7 @@ class SalesController extends Controller
set_user_attr('filter_user_shop_id', null);
set_user_attr('filter_txaction', null);
set_user_attr('filter_member_id', null);
return redirect(route('admin_sales_customers'));
}
$filter_user_shops = ShoppingOrder::select('user_shops.id', 'user_shops.slug')
@ -148,12 +153,11 @@ class SalesController extends Controller
$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);
}
@ -178,6 +182,7 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_customer',
];
return view('admin.sales.customer_detail', $data);
}
@ -187,22 +192,25 @@ class SalesController extends Controller
$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.";
$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']);
@ -212,20 +220,24 @@ class SalesController extends Controller
// 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]));
}
}
@ -235,27 +247,28 @@ class SalesController extends Controller
'isAdmin' => true,
'isView' => 'sales_customer',
];
return view('admin.sales.customer_detail', $data);
}
public function customersDatatable()
{
$query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', NULL);
$query = ShoppingOrder::with('shopping_user')->select('shopping_orders.*')->where('shopping_orders.auth_user_id', null);
set_user_attr('filter_user_shop_id', Request::get('filter_user_shop_id'));
if (Request::get('filter_user_shop_id') != "") {
if (Request::get('filter_user_shop_id') != '') {
$query->where('user_shop_id', '=', Request::get('filter_user_shop_id'));
}
set_user_attr('filter_txaction', Request::get('filter_txaction'));
if (Request::get('filter_txaction') != "") {
if (Request::get('filter_txaction') != '') {
if (Request::get('filter_txaction') === 'NULL') {
$query->where('txaction', '=', NULL);
$query->where('txaction', '=', null);
} else {
$query->where('txaction', '=', Request::get('filter_txaction'));
}
}
set_user_attr('filter_member_id', Request::get('filter_member_id'));
if (Request::get('filter_member_id') != "") {
if (Request::get('filter_member_id') != '') {
$query->where('member_id', '=', Request::get('filter_member_id'));
}
@ -264,13 +277,13 @@ class SalesController extends Controller
return '<a href="'.route('admin_sales_customers_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
if ($ShoppingOrder->txaction === 'extern_paid') {
@ -279,6 +292,7 @@ class SalesController extends Controller
return '<a class="btn btn-xs btn-default btn-round" href="'.route('admin_sales_users_detail', [$shopping_oder_id]).'"><i class="fa fa-check fa-check-circle-o"> '.$shopping_oder_id.'</a>';
}
}
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
})
->addColumn('shipped', function (ShoppingOrder $ShoppingOrder) {
@ -297,6 +311,7 @@ class SalesController extends Controller
if (($ShoppingOrder->txaction === 'extern' || $ShoppingOrder->txaction === 'extern_paid') && $ShoppingOrder->wp_invoice_path) {
return '<span class="no-line-break"><a href="'.$ShoppingOrder->wp_invoice_path.'" class="btn btn-secondary btn-xs"><i class="fa fa-external-link-alt"></i> <i class="fa fa-download"></i></a> </div>';
}
return $ShoppingOrder->isInvoice() ? '<span class="no-line-break"><a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'download']).'" class="btn btn-primary btn-xs"><i class="fa fa-download"></i></a>
<a href="'.route('storage_file', [$ShoppingOrder->id, 'invoice', 'stream']).'" target="_blank" class="btn btn-warning btn-xs"><i class="fa fa-eye"></i></a></span>' : '-';
})
@ -315,6 +330,7 @@ class SalesController extends Controller
data-modal="modal-xl"
data-route="'.route('modal_load').'"><span class="fa fa-edit"></span> Berater zuordnen</button>';
}
return '';
})
->addColumn('user_shop_id', function (ShoppingOrder $ShoppingOrder) {
@ -354,7 +370,7 @@ class SalesController extends Controller
'txid' => 0,
'userid' => 0,
'status' => 'FNCMIV',
'transmitted_data' => NULL,
'transmitted_data' => null,
'txaction' => $data['txaction'],
'mode' => $shopping_payment->mode,
]);
@ -398,8 +414,56 @@ class SalesController extends Controller
if (isset($data['view']) && $data['view'] === 'sales_customer') {
return redirect(route('admin_sales_customers_detail', [$shopping_order->id]));
}
return redirect(route('admin_sales_users_detail', [$shopping_order->id]));
}
}
}
/**
* Stornorechnung erstellen mit Punktekorrektur
*/
public function invoiceCancellation()
{
$data = Request::all();
if (! isset($data['id'])) {
abort(404);
}
if (isset($data['action']) && $data['action'] === 'create_cancellation_invoice') {
$shopping_order = ShoppingOrder::findOrFail($data['id']);
// Prüfen ob Rechnung existiert
if (! $shopping_order->isInvoice()) {
\Session()->flash('alert-error', 'Es existiert keine Rechnung für diese Bestellung.');
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
// Prüfen ob bereits storniert
if ($shopping_order->isCancellationInvoice()) {
\Session()->flash('alert-error', 'Diese Rechnung wurde bereits storniert.');
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
try {
$invoice_repo = new InvoiceRepository($shopping_order);
$cancellation_invoice = $invoice_repo->createCancellation($data);
\Session()->flash('alert-success', 'Stornorechnung wurde erfolgreich erstellt und Punkte wurden korrigiert.');
} catch (\Exception $e) {
\Log::error('Fehler beim Erstellen der Stornorechnung: '.$e->getMessage(), [
'order_id' => $shopping_order->id,
'exception' => $e,
]);
\Session()->flash('alert-error', 'Fehler beim Erstellen der Stornorechnung: '.$e->getMessage());
}
return redirect($data['back'] ?? route('admin_sales_users_detail', [$shopping_order->id]));
}
abort(404);
}
}

View file

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

View file

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

View file

@ -2,23 +2,22 @@
namespace App\Http\Controllers\User;
use Auth;
use Util;
use Yard;
use Carbon;
use Request;
use App\User;
use App\Http\Controllers\Controller;
use App\Mail\MailInfo;
use App\Models\Product;
use App\Services\Payment;
use App\Models\UserHistory;
use App\Models\ShoppingOrder;
use App\Services\UserService;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use App\Http\Controllers\Controller;
use App\Models\ShoppingOrder;
use App\Models\UserHistory;
use App\Services\Payment;
use App\Services\UserService;
use App\User;
use Auth;
use Carbon;
use Illuminate\Support\Facades\Mail;
use Request;
use Util;
use Yard;
class MembershipController extends Controller
{
@ -32,7 +31,6 @@ class MembershipController extends Controller
$this->middleware('auth');
}
public function index()
{
$user = User::find(Auth::user()->id);
@ -44,7 +42,7 @@ class MembershipController extends Controller
$userShoppingOrders = ShoppingOrder::with('shopping_user', 'shopping_payments')->select('shopping_orders.*')
->where('auth_user_id', '=', $user->id)
->where('txaction', '!=', NULL)
->where('txaction', '!=', null)
->whereIn('payment_for', [1, 2])
->orderBy('created_at', 'DESC')
->get();
@ -69,7 +67,6 @@ class MembershipController extends Controller
}
$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'));
@ -88,11 +85,13 @@ class MembershipController extends Controller
'yard_info' => UserService::getYardInfo(),
'userShoppingOrders' => $userShoppingOrders,
];
return view('user.membership.index', $data);
}
private function checkShoppingCountry($user ){
private function checkShoppingCountry($user)
{
$country_id = null;
if ($user->account->same_as_billing) {
@ -105,16 +104,17 @@ class MembershipController extends Controller
return $shipping_country->id;
}
}
return false;
}
public function storePayment($action){
public function storePayment($action)
{
$data = Request::all();
// #### remove_abo
if($action === "remove_abo"){
if ($action === 'remove_abo') {
if (Request::get('abo_options_remove')) {
$user = User::find(Auth::user()->id);
$user->abo_options = false;
@ -123,14 +123,16 @@ class MembershipController extends Controller
$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 ($action === 'upgrade_order' || $action === 'payment_order') {
if (Request::get('switchers-package-wizard')) {
$user = User::find(Auth::user()->id);
Yard::instance('shopping')->destroy();
@ -151,14 +153,13 @@ class MembershipController extends Controller
Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id);
if ($product && $product->active) {
$image = "";
$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]);
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), $qty, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
@ -190,18 +191,20 @@ class MembershipController extends Controller
// 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 ($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) {
@ -209,12 +212,13 @@ class MembershipController extends Controller
$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 ($action === 'delete_membership') {
if (Request::get('delete_membership_mivita')) {
// TODO
$user = User::find(Auth::user()->id);
@ -226,15 +230,17 @@ class MembershipController extends Controller
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();
}
}

View file

@ -11,15 +11,14 @@ use App\Models\ShoppingOrder;
use App\Models\ShoppingUser;
use App\Models\UserHistory;
use App\Services\AboHelper;
use App\Services\MyLog;
use App\Services\OrderPaymentService;
use App\Services\Payment;
use App\Services\Shop;
use App\Services\UserService;
use App\Services\Util;
use App\Services\MyLog;
use App\User;
use Auth;
use Illuminate\Http\Request as IlluminateRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Request;
@ -68,20 +67,20 @@ class OrderController extends Controller
$query = ShoppingOrder::with('shopping_user', 'shopping_payments')
->select('shopping_orders.*')
->where('auth_user_id', '=', $user->id)
->where('txaction', '!=', NULL);
->where('txaction', '!=', null);
return \DataTables::eloquent($query)
->addColumn('id', function (ShoppingOrder $ShoppingOrder) {
return '<a href="'.route('user_order_detail', [$ShoppingOrder->id]).'" class="btn icon-btn btn-sm btn-primary"><span class="fa fa-edit"></span></a>';
})
->addColumn('created_at', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->created_at->format("d.m.Y");
return $ShoppingOrder->created_at->format('d.m.Y');
})
->addColumn('txaction', function (ShoppingOrder $ShoppingOrder) {
return Payment::getShoppingOrderBadge($ShoppingOrder);
})
->addColumn('total_shipping', function (ShoppingOrder $ShoppingOrder) {
return '<span class="no-line-break">' . $ShoppingOrder->getFormattedTotalShipping() . " €</span>";
return '<span class="no-line-break">'.$ShoppingOrder->getFormattedTotalShipping().' €</span>';
})
->addColumn('payment', function (ShoppingOrder $ShoppingOrder) {
return $ShoppingOrder->getLastShoppingPayment('getPaymentType');
@ -96,6 +95,7 @@ class OrderController extends Controller
data-init_from="user"
data-route="'.route('modal_load').'"><span class="fa fa-eye"></span></button>';
}
return '<span class="badge badge-pill badge-'.$ShoppingOrder->getShippedColor().'">'.$ShoppingOrder->getShippedType().'</span>';
})
->addColumn('payment_for', function (ShoppingOrder $ShoppingOrder) {
@ -132,14 +132,16 @@ class OrderController extends Controller
if (! Shop::checkShoppingCountry($for, $delivery_id) && ! \Session()->has('custom-error')) {
$country = Shop::getDeliveryCountry($for, $delivery_id);
\Session()->flash('custom-error', $country . ": " . __('validation.custom.shipping_not_found'));
\Session()->flash('custom-error', $country.': '.__('validation.custom.shipping_not_found'));
Log::channel(self::LOG_CHANNEL)->error("Shipping country not found for user #{$user->id}, country: {$country}");
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
if ($for === 'abo-ot-customer') {
if (AboHelper::hasAboByEmail($shopping_user->billing_email) && ! \Session()->has('custom-error')) {
\Session()->flash('custom-error', __('abo.error_email_has_abo', ['email' => $shopping_user->billing_email]));
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
}
@ -150,6 +152,7 @@ class OrderController extends Controller
if (strpos(Request::get('switchers-radio-is-for'), 'ot') !== false) {
$delivery_id = $id;
}
return redirect(route('user_order_my_list', [Request::get('switchers-radio-is-for'), $delivery_id]));
}
@ -185,8 +188,9 @@ class OrderController extends Controller
$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'));
\Session()->flash('custom-error', $country.': '.__('validation.custom.shipping_not_found'));
Log::channel(self::LOG_CHANNEL)->warning("Shipping country not found for user #{$user->id}, country: {$country}");
return redirect(route('user_order_my_delivery', [$for, $delivery_id]));
}
UserService::initUserYard($user, $shipping_country_id, $for);
@ -221,7 +225,6 @@ class OrderController extends Controller
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput(Request::all());
}
@ -229,12 +232,13 @@ class OrderController extends Controller
try {
$this->checkSendYardForPayment($data, $id);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Error checking yard for payment: " . $e->getMessage(), [
Log::channel(self::LOG_CHANNEL)->error('Error checking yard for payment: '.$e->getMessage(), [
'user_id' => $user->id,
'for' => $for,
'id' => $id
'id' => $id,
]);
return back()->with('error', $e->getMessage());
return back()->withErrors(['error' => $e->getMessage()])->withInput(Request::all());
}
if (Yard::instance('shopping')->getNumComp() > 0) {
@ -245,7 +249,6 @@ class OrderController extends Controller
} elseif (count($data['switchers-comp-product']) !== Yard::instance('shopping')->getNumComp()) {
$validator->errors()->add('switchers-comp-product', __('mdg.please_select_count_compensation_products', ['count' => Yard::instance('shopping')->getNumComp()]));
}
if ($validator->errors()->count()) {
return back()->withErrors($validator)->withInput(Request::all());
}
@ -268,7 +271,6 @@ class OrderController extends Controller
// Remove unnecessary data
unset($data['quantity']);
unset($data['_token']);
if ($for === 'ot-customer' || $for === 'abo-ot-customer') {
return $this->processCustomerPayment($user, $identifier, $data, $id, $for);
} else {
@ -281,13 +283,14 @@ class OrderController extends Controller
*/
private function processCustomerPayment($user, $identifier, $data, $id, $for)
{
$shopping_user = ShoppingUser::find($id);
$shopping_instance = ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => $user->shop->id,
'payment' => 6, // Berater Shop to Customer Shop
'subdomain' => $user->shop->getSubdomain(),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
'language' => $shopping_user->getLocale(), // hier wird die Sprache des Kunden verwendet
'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
'status' => 0,
'shopping_user_id' => $id,
@ -302,9 +305,9 @@ class OrderController extends Controller
try {
$this->customPaymentSendMail($user, $identifier, $yard_shopping_items, $data);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Failed to send custom payment email: " . $e->getMessage(), [
Log::channel(self::LOG_CHANNEL)->error('Failed to send custom payment email: '.$e->getMessage(), [
'identifier' => $identifier,
'user_id' => $user->id
'user_id' => $user->id,
]);
}
@ -314,7 +317,7 @@ class OrderController extends Controller
'status' => 1,
'product_id' => null,
'identifier' => $identifier,
'is_abo' => $data['is_abo']
'is_abo' => $data['is_abo'],
]);
return redirect(route('user_order_my_custom_payment', ['identifier' => $identifier]));
@ -333,7 +336,7 @@ class OrderController extends Controller
'payment' => 2, // Berater Shop
'subdomain' => url('/'),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
'language' => \App::getLocale(), // das ist richtig, hier wird die App-Locale verwendet da es vom user kommt
'amount' => Yard::instance('shopping')->totalWithShipping(2, '.', ''),
'status' => 0,
'shopping_user_id' => $id,
@ -349,10 +352,11 @@ class OrderController extends Controller
'status' => 1,
'product_id' => null,
'identifier' => $identifier,
'is_abo' => $data['is_abo']
'is_abo' => $data['is_abo'],
]);
$path = route('checkout.checkout_card', ['identifier' => $identifier]);
return redirect()->secure($path);
}
@ -375,11 +379,11 @@ class OrderController extends Controller
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'no shipping_country_id found | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping country not found", $logData);
Log::channel(self::LOG_CHANNEL)->error('Shipping country not found', $logData);
throw new \Exception(__('msg.shipping_country_was_not_found'));
}
@ -393,11 +397,11 @@ class OrderController extends Controller
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_country_id,
'actual' => Yard::instance('shopping')->getShippingCountryId()
'actual' => Yard::instance('shopping')->getShippingCountryId(),
];
MyLog::writeLog('payment', 'error', 'shipping_country_id is not the same from Yard | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping country mismatch", $logData);
Log::channel(self::LOG_CHANNEL)->error('Shipping country mismatch', $logData);
throw new \Exception(__('msg.shipping_country_was_not_correctly'));
}
@ -409,11 +413,11 @@ class OrderController extends Controller
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'Yard can by not shipping_free | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Yard cannot be shipping free", $logData);
Log::channel(self::LOG_CHANNEL)->error('Yard cannot be shipping free', $logData);
throw new \Exception(__('msg.shopping_cart_was_shipping_free'));
}
@ -426,11 +430,11 @@ class OrderController extends Controller
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier
'yard_identifier' => $identifier,
];
MyLog::writeLog('payment', 'error', 'User has no Shop for an User to Customer order| Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("User has no shop for customer order", $logData);
Log::channel(self::LOG_CHANNEL)->error('User has no shop for customer order', $logData);
throw new \Exception(__('msg.shopping_cart_was_not_user_shop'));
}
@ -440,23 +444,34 @@ class OrderController extends Controller
// 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) {
// Prüfe ob Versandkostenfreiheit durch Freigrenze legitimiert ist
$shipping_free = Yard::instance('shopping')->getShippingFree();
$total = Yard::instance('shopping')->total(2, '.', '');
$isFreeDueToThreshold = $shipping_free && $total >= $shipping_free && Yard::instance('shopping')->weightByFreeShipping() == 0;
if (! Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
// Nur Fehler werfen, wenn Versandpreis 0 NICHT durch Freigrenze legitimiert ist
if (! $isFreeDueToThreshold) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight()
'weight' => Yard::instance('shopping')->weight(),
'total' => $total,
'shipping_free' => $shipping_free,
];
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);
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) {
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
@ -464,35 +479,46 @@ class OrderController extends Controller
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard OT shipping_price is not the same from shipping_price | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch", $logData);
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) {
// Prüfe ob Versandkostenfreiheit durch Freigrenze legitimiert ist
$shipping_free = Yard::instance('shopping')->getShippingFree();
$total = Yard::instance('shopping')->total(2, '.', '');
$isFreeDueToThreshold = $shipping_free && $total >= $shipping_free && Yard::instance('shopping')->weightByFreeShipping() == 0;
if (! Yard::instance('shopping')->getShippingPrice() || Yard::instance('shopping')->getShippingPrice() == 0) {
// Nur Fehler werfen, wenn Versandpreis 0 NICHT durch Freigrenze legitimiert ist
if (! $isFreeDueToThreshold) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
'user_id' => Auth::user()->id,
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'weight' => Yard::instance('shopping')->weight()
'weight' => Yard::instance('shopping')->weight(),
'total' => $total,
'shipping_free' => $shipping_free,
];
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);
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) {
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price_comp) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
@ -500,11 +526,11 @@ class OrderController extends Controller
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price_comp,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price with comp products | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch for personal order", $logData);
Log::channel(self::LOG_CHANNEL)->error('Shipping price mismatch for personal order', $logData);
throw new \Exception(__('msg.shipping_costs_were_not_calculated_correctly'));
}
@ -517,16 +543,17 @@ class OrderController extends Controller
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->num_comp,
'actual' => Yard::instance('shopping')->getNumComp()
'actual' => Yard::instance('shopping')->getNumComp(),
];
MyLog::writeLog('payment', 'error', 'Yard num_comp is not correct | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Compensation product count mismatch", $logData);
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) {
// Preisvergleich nur durchführen, wenn NICHT versandkostenfrei durch Freigrenze
if (! $isFreeDueToThreshold && Yard::instance('shopping')->getShippingPrice() != $shipping_price->price) {
$identifier = 'error-'.time().mt_rand(1000000, 9999999);
Yard::instance('shopping')->store($identifier);
$logData = [
@ -534,11 +561,11 @@ class OrderController extends Controller
'shopping_user_id' => $id,
'yard_identifier' => $identifier,
'expected' => $shipping_price->price,
'actual' => Yard::instance('shopping')->getShippingPrice()
'actual' => Yard::instance('shopping')->getShippingPrice(),
];
MyLog::writeLog('payment', 'error', 'Yard ME shipping_price is not the same from shipping_price without comp products | Yard identifier: '.$identifier, $data);
Log::channel(self::LOG_CHANNEL)->error("Shipping price mismatch for personal order", $logData);
Log::channel(self::LOG_CHANNEL)->error('Shipping price mismatch for personal order', $logData);
throw new \Exception(__('msg.shipping_costs_were_not_calculated_correctly'));
}
@ -593,6 +620,7 @@ class OrderController extends Controller
$cartItem = Yard::instance('shopping')->getCartItemByProduct($product->id);
$qty = isset($cartItem->qty) ? $cartItem->qty : 0;
$rowId = isset($cartItem->rowId) ? $cartItem->rowId : '';
return '<strong>'.$product->getLang('name').'</strong><br>
<div class="no-line-break input-group-min-w">
<div class="input-group d-inline-flex w-auto">
@ -613,28 +641,29 @@ class OrderController extends Controller
if (count($product->images)) {
return '<img class="img-fluid img-extra" alt="" src="'.route('product_image', [$product->images->first()->slug]).'">';
}
return "";
return '';
})
->addColumn('points', function (Product $product) {
return '<span class="no-line-break">'.$product->getFormattedPoints().'</span>';
})
->addColumn('price_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, true, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, true, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, true, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, true, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, true, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, true, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('price_vk_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('customer_price_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('customer_price_gross', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(false, false, Yard::instance('shopping')->getUserCountry()).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(false, false, Yard::instance('shopping')->getUserCountry()).'</span>';
})
->addColumn('my_commission_net', function (Product $product) {
return '<span class="no-line-break">' . $product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry(), true) . " €</span>" . '<span class="no-line-break">' . $product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry(), true) . '</span>';
return '<span class="no-line-break">'.$product->getFormattedPriceWith(true, false, Yard::instance('shopping')->getUserCountry(), true).' €</span>'.'<span class="no-line-break">'.$product->getFormattedPriceCurrencyWith(true, false, Yard::instance('shopping')->getUserCountry(), true).'</span>';
})
->addColumn('action', function (Product $product) {
return '<button class="btn btn-default btn-sm icon-btn md-btn-flat product-tooltip" title="details" data-modal="modal-lg"
@ -642,7 +671,7 @@ class OrderController extends Controller
data-action="user-order-show-product" data-view="customer"><i class="ion ion-md-eye"></i></button>';
})
->filterColumn('product', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->where('name', 'LIKE', '%'.$keyword.'%');
}
})
@ -669,7 +698,8 @@ class OrderController extends Controller
public function performRequest()
{
if (! Request::ajax()) {
Log::channel(self::LOG_CHANNEL)->warning("Non-AJAX request to performRequest method");
Log::channel(self::LOG_CHANNEL)->warning('Non-AJAX request to performRequest method');
return response()->json(['response' => false, 'message' => 'Only AJAX requests are allowed']);
}
@ -678,9 +708,9 @@ class OrderController extends Controller
$data['for'] = $is_for;
$data['comp_products'] = Shop::getCompProducts($is_for);
Log::channel(self::LOG_CHANNEL)->info("Performing cart action", [
Log::channel(self::LOG_CHANNEL)->info('Performing cart action', [
'action' => $data['action'] ?? 'unknown',
'is_for' => $is_for
'is_for' => $is_for,
]);
if ($data['action'] === 'updateCart' && isset($data['product_id'])) {
@ -689,6 +719,7 @@ class OrderController extends Controller
if ($data['action'] === 'clearCart') {
Yard::instance('shopping')->destroy();
return response()->json(['response' => true, 'data' => Yard::instance('shopping')->count(), 'html_card' => '', 'html_comp' => '']);
}
@ -700,7 +731,8 @@ class OrderController extends Controller
return $this->handleUpdateCompProduct($data, $is_for);
}
Log::channel(self::LOG_CHANNEL)->warning("Unknown action in performRequest", ['action' => $data['action'] ?? 'not set']);
Log::channel(self::LOG_CHANNEL)->warning('Unknown action in performRequest', ['action' => $data['action'] ?? 'not set']);
return response()->json(['response' => false, 'data' => $data]);
}
@ -711,11 +743,12 @@ class OrderController extends Controller
{
$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']]);
Log::channel(self::LOG_CHANNEL)->warning('Product not found for cart update', ['product_id' => $data['product_id']]);
return response()->json(['response' => false, 'message' => 'Product not found']);
}
$image = "";
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
@ -730,7 +763,7 @@ class OrderController extends Controller
round($product->getPriceWith(Yard::instance('shopping')->getUserTaxFree(), false, Yard::instance('shopping')->getUserCountry()), 1),
false,
false,
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
} else {
$cartItem = Yard::instance('shopping')
@ -741,7 +774,7 @@ class OrderController extends Controller
$product->getPriceWith(Yard::instance('shopping')->getUserTaxFree(), true, Yard::instance('shopping')->getUserCountry()),
false,
false,
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
}
@ -761,8 +794,8 @@ class OrderController extends Controller
Yard::instance('shopping')->reCalculateShippingPrice();
$this->checkCompProduct(Yard::instance('shopping')->getNumComp());
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -778,14 +811,14 @@ class OrderController extends Controller
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country->id, $is_for);
$this->checkCompProduct(Yard::instance('shopping')->getNumComp());
} else {
Log::channel(self::LOG_CHANNEL)->warning("Shipping country not found", [
'shipping_country_id' => $data['shipping_country_id']
Log::channel(self::LOG_CHANNEL)->warning('Shipping country not found', [
'shipping_country_id' => $data['shipping_country_id'],
]);
}
}
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -798,8 +831,8 @@ class OrderController extends Controller
$this->updateCompProduct($data);
Yard::instance('shopping')->reCalculateShippingPrice();
$html_card = view("user.order.yard_view_form", $data)->render();
$html_comp = view("user.order.comp_product", $data)->render();
$html_card = view('user.order.yard_view_form', $data)->render();
$html_comp = view('user.order.comp_product', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html_card' => $html_card, 'html_comp' => $html_comp]);
}
@ -836,7 +869,7 @@ class OrderController extends Controller
if (isset($data['comp_product_id'])) {
$product = Product::find($data['comp_product_id']);
if ($product) {
$image = "";
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
@ -853,14 +886,14 @@ class OrderController extends Controller
'weight' => 0,
'points' => 0,
'comp' => intval($data['comp_num']),
'product_id' => $product->id
'product_id' => $product->id,
]
);
Yard::setTax($cartItem->rowId, 0);
} else {
Log::channel(self::LOG_CHANNEL)->warning("Compensation product not found", [
'comp_product_id' => $data['comp_product_id']
Log::channel(self::LOG_CHANNEL)->warning('Compensation product not found', [
'comp_product_id' => $data['comp_product_id'],
]);
}
}
@ -873,9 +906,10 @@ class OrderController extends Controller
{
try {
$data = OrderPaymentService::getCustomPayment($identifier);
return view('user.order.payment.custom_payment', $data);
} catch (\Exception $e) {
Log::channel(self::LOG_CHANNEL)->error("Error accessing custom payment: " . $e->getMessage(), ['identifier' => $identifier]);
Log::channel(self::LOG_CHANNEL)->error('Error accessing custom payment: '.$e->getMessage(), ['identifier' => $identifier]);
abort(404, 'Custom payment not found');
}
}
@ -889,14 +923,14 @@ class OrderController extends Controller
$shopping_instance = ShoppingInstance::where('identifier', $identifier)->first();
if (! $shopping_instance) {
Log::channel(self::LOG_CHANNEL)->error("Shopping instance not found for email", ['identifier' => $identifier]);
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']]);
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'));
}

View file

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

View file

@ -1,13 +1,12 @@
<?php
namespace App\Http\Controllers\User;
use App\Exports\UserTeamExport;
use App\Http\Controllers\Controller;
use App\Models\UserBusiness;
use App\Models\UserLevel;
use App\Models\UserSalesVolume;
use App\Services\AboHelper;
use App\Services\BusinessPlan\ExportBot;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
@ -17,10 +16,6 @@ use App\Services\LevelReportService;
use App\Services\NextLevelBadgeHelper;
use App\Services\TranslationHelper;
use App\User;
use Auth;
use Carbon\Carbon;
use function Ramsey\Uuid\v1;
use Maatwebsite\Excel\Facades\Excel;
use Request;
@ -36,9 +31,13 @@ use Request;
class TeamController extends Controller
{
private $filter_active = [1 => '', 2 => '', 3 => '']; // Wird in getFilterActive() übersetzt
private $filter_next_level = [0 => '', 1 => '', 2 => '', 3 => '']; // Wird in getFilterNextLevel() übersetzt
private $month;
private $year;
private $forceLiveCalculation;
public function __construct()
@ -46,8 +45,6 @@ class TeamController extends Controller
$this->middleware('active.account');
}
/**
* Zeigt die Team-Übersicht mit optimierter TreeCalcBotOptimized-Datenverarbeitung
* Lädt Team-Daten für DataTable-Anzeige
@ -68,7 +65,7 @@ class TeamController extends Controller
$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"));
($forceLiveCalculation === true ? ' with forced live calculation' : 'not live calculation'));
// Verwende TreeCalcBotOptimized für bessere Performance
// $TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
@ -79,7 +76,7 @@ class TeamController extends Controller
$executionTime = round(($endTime - $startTime) * 1000, 2);
$memoryUsed = $this->formatBytes($endMemory - $startMemory);
$calculationType = $forceLiveCalculation ? " (LIVE)" : " (CACHE)";
$calculationType = $forceLiveCalculation ? ' (LIVE)' : ' (CACHE)';
\Log::info("TeamController: Optimized team overview built in {$executionTime}ms, Memory: {$memoryUsed}{$calculationType}");
$data = [
@ -95,11 +92,12 @@ class TeamController extends Controller
'user_id' => $user->id,
'user_count' => 0, // $TreeCalcBot->getTotalUserCount(),
'version' => 'Optimized',
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache'
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache',
],
'optimized' => true,
'forceLiveCalculation' => $forceLiveCalculation,
];
return view('user.team.show', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error in optimized show for user {$user->id}: ".$e->getMessage());
@ -119,7 +117,7 @@ class TeamController extends Controller
'execution_time' => $executionTime,
'memory_used' => 'N/A',
'version' => 'Fallback',
'calculation_type' => 'Error'
'calculation_type' => 'Error',
],
'optimized' => false,
];
@ -175,8 +173,8 @@ class TeamController extends Controller
$executionTime = round(($endTime - $startTime) * 1000, 2);
$memoryUsed = $this->formatBytes($endMemory - $startMemory);
$versionInfo = ($optimizedUsed ? "OPTIMIZED" : "STANDARD") .
($forceLiveCalculation ? " + LIVE" : " + CACHE");
$versionInfo = ($optimizedUsed ? 'OPTIMIZED' : 'STANDARD').
($forceLiveCalculation ? ' + LIVE' : ' + CACHE');
\Log::info("TeamController: Structure built for user {$user->id} in {$executionTime}ms, Memory: {$memoryUsed} ({$versionInfo})");
@ -191,7 +189,7 @@ class TeamController extends Controller
? $TreeCalcBot->getTotalUserCount()
: '-',
'version' => $optimizedUsed ? 'Optimized' : 'Standard',
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache'
'calculation_type' => $forceLiveCalculation ? 'Live' : 'Cache',
],
'optimized' => $optimizedUsed,
'forceLiveCalculation' => $forceLiveCalculation,
@ -218,7 +216,7 @@ class TeamController extends Controller
'memory_used' => 'N/A',
'user_count' => '-',
'version' => 'Fallback',
'calculation_type' => $forceLiveCalculation ? __('team.live_not_supported_fallback') : __('team.cache')
'calculation_type' => $forceLiveCalculation ? __('team.live_not_supported_fallback') : __('team.cache'),
],
'optimized' => false,
'forceLiveCalculation' => $forceLiveCalculation,
@ -227,6 +225,7 @@ class TeamController extends Controller
return view('user.team.structure', $data);
}
}
public function structureOld()
{
abort(403, 'This page is removed');
@ -244,10 +243,10 @@ class TeamController extends Controller
'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
@ -266,7 +265,7 @@ class TeamController extends Controller
$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" : ""));
($forceLiveCalculation == true ? ' with forced live calculation' : ''));
// Lade TreeCalcBotOptimized-Daten
$TreeCalcBot = new TreeCalcBotOptimized($this->month, $this->year, 'member', $forceLiveCalculation);
@ -277,12 +276,12 @@ class TeamController extends Controller
// KRITISCH: Bereinige die Objekte für DataTables (entferne zirkuläre Referenzen)
$teamUsers = collect($this->cleanBusinessUserItemsForDataTable($teamUsersRaw));
\Log::info("TeamController: TeamUsers cleaned for DataTable: " . $teamUsers->count());
\Log::info('TeamController: TeamUsers cleaned for DataTable: '.$teamUsers->count());
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
$this->forceLiveCalculation = $forceLiveCalculation;
\Log::info("TeamController: Optimized datatable data prepared in {$executionTime}ms for " . $teamUsers->count() . " users");
\Log::info("TeamController: Optimized datatable data prepared in {$executionTime}ms for ".$teamUsers->count().' users');
return \DataTables::of($teamUsers)
->addColumn('id', function ($teamUser) {
@ -300,7 +299,13 @@ class TeamController extends Controller
return $teamUser->m_account;
})
->addColumn('email', function ($teamUser) {
return e($teamUser->email);
$button = '<a href="#" class="text-black" data-toggle="modal" data-target="#modals-load-content" '.
'data-id="'.$teamUser->user_id.'" data-action="business-user-show" data-back="" '.
'data-modal="modal-md" data-init_from="member" data-route="'.route('modal_load').'">'.
'<span class="mr-1 ion ion-ios-contact"></span> '.
'</a>';
return $button.e($teamUser->email);
})
->addColumn('first_name', function ($teamUser) {
return e($teamUser->first_name);
@ -313,6 +318,7 @@ class TeamController extends Controller
})
->addColumn('is_qual_kp', function ($teamUser) {
$user = User::find($teamUser->user_id);
return TreeHelperOptimized::generateQualKPBadgeForUser($user, $this->month, $this->year);
})
->addColumn('sales_volume_KP_points', function ($teamUser) {
@ -331,18 +337,19 @@ class TeamController extends Controller
if ($userBusiness) {
return NextLevelBadgeHelper::generateBadgeFromUserBusiness($userBusiness);
}
return NextLevelBadgeHelper::renderNoDataBadge();
})
->addColumn('active_account', function ($teamUser) {
return get_active_badge($teamUser->active_account);
})
->addColumn('payment_account_date', function ($teamUser) {
return $teamUser->active_date ? formatDate($teamUser->active_date) : "-";
return $teamUser->active_date ? formatDate($teamUser->active_date) : '-';
})
->rawColumns(['id', 'next_level_qualified', 'active_account', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total'])
->rawColumns(['id', 'email', 'next_level_qualified', 'active_account', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total'])
->make(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error in optimized datatable: " . $e->getMessage());
\Log::error('TeamController: Error in optimized datatable: '.$e->getMessage());
// Fallback zur Standard-DataTable
return $this->datatable();
@ -384,6 +391,7 @@ class TeamController extends Controller
$pointsSum = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_KP_sum');
$isQual = $pointsSum >= $qualKP;
$badgeClass = $isQual ? 'badge-outline-success' : 'badge-outline-warning-dark';
return '<span class="badge '.$badgeClass.'"> KU '.$qualKP.'</span>';
})
->addColumn('sales_volume_KP_points', function (User $teamUser) {
@ -392,6 +400,7 @@ class TeamController extends Controller
$total = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_KP_sum');
$individual = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_KP_points');
$shop = (int) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_points_shop');
return '<div class="no-line-break">'.$total.'</div>'.
'<span class="small no-line-break">E: '.$individual.' | S: '.$shop.'</span>';
})
@ -401,6 +410,7 @@ class TeamController extends Controller
$total = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total_sum');
$individual = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total');
$shop = (float) $teamUser->getUserSalesVolumeBy($month, $year, 'sales_volume_total_shop');
return '<div class="no-line-break">'.formatNumber($total).' &euro;</div>'.
'<span class="small no-line-break">E: '.formatNumber($individual).' | S: '.formatNumber($shop).' &euro;</span>';
})
@ -425,13 +435,14 @@ class TeamController extends Controller
$html .= ' | '.e($sponsor->account->m_account);
$html .= '</span>';
}
return $html;
})
->addColumn('active_account', function (User $teamUser) {
return get_active_badge($teamUser->isActiveAccount());
})
->addColumn('payment_account_date', function (User $teamUser) {
return $teamUser->payment_account ? $teamUser->getPaymentAccountDateFormat(false) : "-";
return $teamUser->payment_account ? $teamUser->getPaymentAccountDateFormat(false) : '-';
})
->addColumn('next_level_qualified', function (User $teamUser) {
// Verwende bereits berechnete UserBusiness-Daten für bessere Performance
@ -450,28 +461,28 @@ class TeamController extends Controller
return NextLevelBadgeHelper::renderNoDataBadge();
})
->filterColumn('m_account', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('m_account', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('first_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('first_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('last_name', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->whereHas('account', function ($q) use ($keyword) {
$q->where('last_name', 'LIKE', '%'.$keyword.'%');
});
}
})
->filterColumn('email', function ($query, $keyword) {
if ($keyword != "") {
if ($keyword != '') {
$query->where('email', 'LIKE', '%'.$keyword.'%');
}
})
@ -484,10 +495,10 @@ class TeamController extends Controller
->rawColumns(['id', 'is_qual_kp', 'sales_volume_KP_points', 'sales_volume_total', 'sponsor', 'active_account', 'next_level_qualified'])
->make(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error in userDatatable: " . $e->getMessage());
\Log::error('TeamController: Error in userDatatable: '.$e->getMessage());
return response()->json([
'error' => 'Team-Datatable konnte nicht geladen werden: ' . $e->getMessage()
'error' => 'Team-Datatable konnte nicht geladen werden: '.$e->getMessage(),
], 500);
}
}
@ -519,7 +530,7 @@ class TeamController extends Controller
$treeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
// Lade Level-Reports für Team
$levelReportService = new LevelReportService();
$levelReportService = new LevelReportService;
$filters = ['only_not_updated' => $onlyNotUpdated];
$promotions = $levelReportService->getTeamLevelPromotions($treeCalcBot, $month, $year, $filters);
$statistics = $levelReportService->getStatistics($promotions);
@ -527,7 +538,7 @@ class TeamController extends Controller
$endTime = microtime(true);
$executionTime = round(($endTime - $startTime) * 1000, 2);
\Log::info("TeamController: Level reports loaded for user {$user->id} in {$executionTime}ms - " . $promotions->count() . " promotions found");
\Log::info("TeamController: Level reports loaded for user {$user->id} in {$executionTime}ms - ".$promotions->count().' promotions found');
$availableYears = range(date('Y'), date('Y') - 5);
$availableMonths = [
@ -542,7 +553,7 @@ class TeamController extends Controller
9 => __('cal.months.September'),
10 => __('cal.months.October'),
11 => __('cal.months.November'),
12 => __('cal.months.December')
12 => __('cal.months.December'),
];
$data = [
@ -551,19 +562,19 @@ class TeamController extends Controller
'filters' => [
'month' => $month,
'year' => $year,
'only_not_updated' => $onlyNotUpdated
'only_not_updated' => $onlyNotUpdated,
],
'availableYears' => $availableYears,
'availableMonths' => $availableMonths,
'performance' => [
'execution_time' => $executionTime,
'user_id' => $user->id
]
'user_id' => $user->id,
],
];
return view('user.team.level-reports', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error loading level reports: " . $e->getMessage());
\Log::error('TeamController: Error loading level reports: '.$e->getMessage());
return view('user.team.level-reports', [
'error' => 'Fehler beim Laden der Level-Reports: '.$e->getMessage(),
@ -583,8 +594,8 @@ class TeamController extends Controller
9 => __('cal.months.September'),
10 => __('cal.months.October'),
11 => __('cal.months.November'),
12 => __('cal.months.December')
]
12 => __('cal.months.December'),
],
]);
}
}
@ -608,7 +619,7 @@ class TeamController extends Controller
$treeCalcBot->initStructureUser($user->id, $forceLiveCalculation);
// Lade Level-Reports
$levelReportService = new LevelReportService();
$levelReportService = new LevelReportService;
$filters = ['only_not_updated' => $onlyNotUpdated];
$promotions = $levelReportService->getTeamLevelPromotions($treeCalcBot, $month, $year, $filters);
@ -622,7 +633,8 @@ class TeamController extends Controller
return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\Exception $e) {
\Log::error("TeamController: Error exporting level reports: " . $e->getMessage());
\Log::error('TeamController: Error exporting level reports: '.$e->getMessage());
return redirect()->back()->with('error', 'Fehler beim Export: '.$e->getMessage());
}
}
@ -654,19 +666,19 @@ class TeamController extends Controller
'currentUser' => $user,
'currentLevel' => $currentLevel,
'performance' => [
'execution_time' => $executionTime
]
'execution_time' => $executionTime,
],
];
return view('user.team.marketingplan', $data);
} catch (\Exception $e) {
\Log::error("TeamController: Error loading marketingplan: " . $e->getMessage());
\Log::error('TeamController: Error loading marketingplan: '.$e->getMessage());
return view('user.team.marketingplan', [
'error' => __('marketingplan.loading_error').' '.$e->getMessage(),
'userLevels' => collect(),
'currentUser' => null,
'currentLevel' => null
'currentLevel' => null,
]);
}
}
@ -678,14 +690,15 @@ class TeamController extends Controller
{
$user = User::find(\Auth::user()->id);
if ($user->isActiveShop() && $user->shop) {
$shop_register_link = $user->shop->getSubdomain(false) . "/reg";
$shop_register_link = $user->shop->getSubdomain(false).'/reg';
} else {
$member_id = 'm'.($user->id + config('mivita.add_number_id'));
$shop_register_link = config('app.protocol').config('app.domain').config('app.tld_care').'/reg/'.$member_id;
}
$data = [
'shop_register_link' => $shop_register_link
'shop_register_link' => $shop_register_link,
];
return view('user.team.members', $data);
}
@ -697,24 +710,8 @@ class TeamController extends Controller
$user = User::find(\Auth::user()->id);
$this->setFilterVars();
// Nutze TreeCalcBotOptimized um das Team zu bekommen
$month = session('team_user_filter_month');
$year = session('team_user_filter_year');
// Lade Team-Struktur
$TreeCalcBot = new TreeCalcBotOptimized($month, $year, 'member', false);
$TreeCalcBot->initStructureUser($user->id, false);
// Hole flache Liste aller Team-Mitglieder
$teamUsersRaw = $this->getTeamUsersFromStructure($TreeCalcBot);
// Sammle User-IDs für Abo-Abfrage
$teamUserIds = [];
foreach ($teamUsersRaw as $teamUser) {
if ($teamUser->user_id && $teamUser->user_id != $user->id) {
$teamUserIds[] = $teamUser->user_id;
}
}
// Hole Team-Mitglieder-IDs effizient via Sponsor-Hierarchie
$teamUserIds = AboHelper::getTeamUserIds($user->id);
// Hole Abos der Team-Mitglieder
$abos = \App\Models\UserAbo::whereIn('user_id', $teamUserIds)
@ -740,24 +737,8 @@ class TeamController extends Controller
$user = User::find(\Auth::user()->id);
$user_abo = \App\Models\UserAbo::findOrFail($id);
// Prüfe ob das Abo zu einem Team-Mitglied gehört
$this->setFilterVars();
$month = session('team_user_filter_month');
$year = session('team_user_filter_year');
$TreeCalcBot = new TreeCalcBotOptimized($month, $year, 'member', false);
$TreeCalcBot->initStructureUser($user->id, false);
$teamUsersRaw = $this->getTeamUsersFromStructure($TreeCalcBot);
$teamUserIds = [];
foreach ($teamUsersRaw as $teamUser) {
if ($teamUser->user_id) {
$teamUserIds[] = $teamUser->user_id;
}
}
// Prüfe Berechtigung
if (!in_array($user_abo->user_id, $teamUserIds)) {
// Prüfe ob das Abo zu einem Team-Mitglied gehört (effizient via Sponsor-Kette)
if (! AboHelper::isUserInTeam($user->id, $user_abo->user_id)) {
abort(403, 'Unauthorized action. This subscription does not belong to your team.');
}
@ -819,6 +800,7 @@ class TeamController extends Controller
'filter_months' => HTMLHelper::getTransMonths(),
'filter_years' => HTMLHelper::getYearRange(2022),
];
return view('user.team.points', $data);
}
@ -834,19 +816,20 @@ class TeamController extends Controller
$data = [
'ExportBot' => $ExportBot,
];
return view('user.team.export', $data);
}
public function userTeamExport()
{
if (Request::get('action') === "export") {
if (Request::get('action') === 'export') {
$user = User::find(\Auth::user()->id);
$ExportBot = new ExportBot('member');
$ExportBot->initStructureUser($user, 'list'); // tree or list
$columns = [];
$filename = __('team.filename_export').date('Y-m-d-H-i-s');
$headers = array(
$headers = [
__('tables.line'),
__('tables.level'),
__('tables.email'),
@ -864,10 +847,10 @@ class TeamController extends Controller
__('tables.account'),
__('tables.account_to'),
__('tables.sponsor'),
);
];
if (isset($ExportBot->user_list->childs)) {
foreach ($ExportBot->user_list->childs as $child) {
$columns[] = array(
$columns[] = [
__('tables.line') => $child->line,
__('tables.level') => $child->level_name,
__('tables.email') => $child->email,
@ -885,9 +868,10 @@ class TeamController extends Controller
__('tables.account') => ($child->active_account == 1 ? __('yes') : __('no')),
__('tables.account_to') => $child->payment_account_date,
__('tables.sponsor') => $child->sponsor_name,
);
];
}
}
return Excel::download(new UserTeamExport($columns, $headers), $filename.'.xls');
}
}
@ -964,11 +948,11 @@ class TeamController extends Controller
return $query;
}
public function datatablePoints()
{
$query = $this->initSearchPoints();
return \DataTables::eloquent($query)
->addColumn('order', function (UserSalesVolume $UserSalesVolume) {
@ -980,6 +964,7 @@ class TeamController extends Controller
return '<a href="'.route('user_shop_order_detail', [$UserSalesVolume->shopping_order->id]).'" class="btn btn-xs btn-secondary">'.$UserSalesVolume->shopping_order->id.'</a>';
}
}
return '';
})
->addColumn('total_net', function (UserSalesVolume $UserSalesVolume) {
@ -1018,6 +1003,7 @@ class TeamController extends Controller
'userSalesVolume' => $userSalesVolume,
];
$html = view('user.team._points_sum', $data)->render();
return response()->json(['response' => true, 'data' => $data, 'html' => $html]);
}
@ -1026,7 +1012,7 @@ class TeamController extends Controller
*/
private function formatBytes(int $bytes, int $precision = 2): string
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
$bytes /= 1024;
@ -1058,7 +1044,7 @@ class TeamController extends Controller
return [
1 => __('team.filter_active'),
2 => __('team.filter_not_active'),
3 => __('team.filter_all')
3 => __('team.filter_all'),
];
}
@ -1071,7 +1057,7 @@ class TeamController extends Controller
0 => __('team.all_status'),
1 => __('team.qualified_green'),
2 => __('team.in_progress_yellow'),
3 => __('team.no_level_red')
3 => __('team.no_level_red'),
];
}
@ -1089,14 +1075,14 @@ class TeamController extends Controller
// Debug: Prüfe TreeCalcBot-Inhalt
$businessUsers = $treeCalcBot->getItems();
\Log::info("TeamController: TreeCalcBot root items count: " . count($businessUsers));
\Log::info('TeamController: TreeCalcBot root items count: '.count($businessUsers));
// Sammle alle Root-User UND deren verschachtelte businessUserItems
foreach ($businessUsers as $businessUser) {
// WICHTIG: user_id korrekt über b_user abrufen (Magic Method Problem mit isset())
$userId = $businessUser->user_id; // Über __get() Method
\Log::debug("TeamController: Processing root businessUser", [
\Log::debug('TeamController: Processing root businessUser', [
'user_id' => $userId,
'businessUserItems_count' => count($businessUser->businessUserItems ?? []),
]);
@ -1134,17 +1120,17 @@ class TeamController extends Controller
\Log::debug("TeamController: Parentless-User übersprungen: {$userId} (bereits verarbeitet)");
}
} else {
\Log::warning("TeamController: Parentless BusinessUser ohne user_id übersprungen");
\Log::warning('TeamController: Parentless BusinessUser ohne user_id übersprungen');
}
}
}
}
}
\Log::info("TeamController: AllUsers before filtering: " . count($allUsers));
\Log::info('TeamController: AllUsers before filtering: '.count($allUsers));
// Filter anwenden
$filteredUsers = $this->applyTeamFiltersToBusinessUsers($allUsers);
\Log::info("TeamController: AllUsers after filtering: " . count($filteredUsers));
\Log::info('TeamController: AllUsers after filtering: '.count($filteredUsers));
return $filteredUsers;
}
@ -1163,7 +1149,7 @@ class TeamController extends Controller
// Debug: Zeige verfügbare Eigenschaften des ersten BusinessUsers
if (! empty($businessUsers)) {
$firstUser = $businessUsers[0];
\Log::debug("TeamController: First BusinessUser properties", [
\Log::debug('TeamController: First BusinessUser properties', [
'user_id' => $firstUser->user_id ?? 'not set',
'active_account' => $firstUser->active_account ?? 'not set',
'm_level_id' => $firstUser->m_level_id ?? 'not set',
@ -1233,6 +1219,7 @@ class TeamController extends Controller
$maxDepth = 20;
if ($depth > $maxDepth) {
\Log::warning("TeamController: Maximale Sammlungstiefe ({$maxDepth}) erreicht bei Tiefe {$depth}");
return;
}
@ -1244,6 +1231,7 @@ class TeamController extends Controller
// KRITISCHER SCHUTZ: Prüfe ob User bereits gesammelt wurde
if (isset($processedIds[$userId])) {
\Log::debug("TeamController: Überspringe bereits gesammelten User {$userId} (Duplikat verhindert)");
continue;
}
@ -1256,7 +1244,7 @@ class TeamController extends Controller
// 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}");
\Log::debug('TeamController: Sammle '.count($businessUserItem->businessUserItems)." verschachtelte Items von User {$userId}");
$this->collectAllBusinessUserItemsFlat($businessUserItem->businessUserItems, $allUsers, $processedIds, $depth + 1);
}
} else {
@ -1276,11 +1264,12 @@ class TeamController extends Controller
$maxDepth = 20;
if ($deep > $maxDepth) {
\Log::warning("TeamController: Maximale Sammlungstiefe ({$maxDepth}) erreicht");
return;
}
if (isset($businessUser->businessUserItems) && is_array($businessUser->businessUserItems)) {
\Log::debug("TeamController: Collecting from businessUser with " . count($businessUser->businessUserItems) . " sub-items at depth {$deep}");
\Log::debug('TeamController: Collecting from businessUser with '.count($businessUser->businessUserItems)." sub-items at depth {$deep}");
foreach ($businessUser->businessUserItems as $subBusinessUser) {
if ($subBusinessUser) {
@ -1291,6 +1280,7 @@ class TeamController extends Controller
// KRITISCHER BUGFIX: Prüfe ob User bereits gesammelt wurde
if (isset($processedIds[$userId])) {
\Log::debug("TeamController: Überspringe bereits gesammelten User {$userId} (zirkuläre Referenz verhindert)");
continue;
}
@ -1326,7 +1316,7 @@ class TeamController extends Controller
try {
// Extrahiere nur die Properties, die für DataTable benötigt werden
$cleanedUser = new \stdClass();
$cleanedUser = new \stdClass;
// Basis Properties (direkt über Magic Method __get)
$cleanedUser->user_id = $businessUserItem->user_id;
@ -1354,13 +1344,14 @@ class TeamController extends Controller
\Log::debug("TeamController: Cleaned user {$cleanedUser->user_id} for DataTable");
} catch (\Exception $e) {
\Log::error("TeamController: Error cleaning BusinessUserItem for DataTable: " . $e->getMessage());
\Log::error('TeamController: Error cleaning BusinessUserItem for DataTable: '.$e->getMessage());
// Skip diesen User, statt alles abzubrechen
continue;
}
}
\Log::info("TeamController: Cleaned " . count($cleanedUsers) . " users for DataTable (from " . count($businessUserItems) . " raw items)");
\Log::info('TeamController: Cleaned '.count($cleanedUsers).' users for DataTable (from '.count($businessUserItems).' raw items)');
return $cleanedUsers;
}

View file

@ -11,7 +11,6 @@ use App\Models\ShoppingUser;
use App\Repositories\CheckoutRepository;
use App\Services\AboHelper;
use App\Services\CustomerPriority;
use App\Services\OrderPaymentService;
use App\Services\Payment;
use App\Services\Shop;
use App\Services\Util;
@ -24,6 +23,7 @@ use Yard;
class CheckoutController extends Controller
{
private $checkoutRepo;
private $instance = 'checkout';
/**
@ -97,20 +97,18 @@ class CheckoutController extends Controller
'is_checkout' => true,
'yard_instance' => $this->instance,
];
return view('web.templates.checkout', $data);
}
/**
* Bereitet die ShoppingUser-Daten vor
*
* @param ShoppingUser $shopping_user
* @return void
*/
private function prepareShoppingUserData(ShoppingUser $shopping_user)
{
if ($shopping_user->same_as_billing === NULL) {
if ($shopping_user->same_as_billing === null) {
$shopping_user->same_as_billing = false;
}
if (! $shopping_user->billing_country_id) {
@ -220,7 +218,7 @@ class CheckoutController extends Controller
'shipping_address' => 'required',
'shipping_zipcode' => 'required',
'shipping_city' => 'required',
'shipping_salutation' => 'required'
'shipping_salutation' => 'required',
]);
}
@ -257,7 +255,7 @@ class CheckoutController extends Controller
}
// Zahlung vorbereiten
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$reference = $pay->setPrePayment($payment_method, $amount, 'EUR', $result);
@ -277,7 +275,7 @@ class CheckoutController extends Controller
*/
private function checkCreditCard($data, $shopping_user, $shopping_order)
{
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$ret['cc'] = $pay->checkCreditCard($data);
@ -285,9 +283,11 @@ class CheckoutController extends Controller
Session::flash('cc-error', 1);
Session::flash('errormessage', $ret['cc']['errormessage']);
Session::flash('customermessage', $ret['cc']['customermessage']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
$ret['returnstatus'] = 'VALID';
return $ret;
}
@ -302,7 +302,7 @@ class CheckoutController extends Controller
private function checkSepaAccount($data, $shopping_user, $shopping_order)
{
if (is_null(Request::get('mandate_identification'))) {
$pay = new PayoneController();
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$ret['elv'] = $pay->checkBankAccount($data, $amount, 'EUR', $shopping_user);
@ -311,14 +311,16 @@ class CheckoutController extends Controller
Session::flash('elv-error', 1);
Session::flash('errormessage', $ret['elv']['errormessage']);
Session::flash('customermessage', $ret['elv']['customermessage']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
if ($ret['elv']['status'] === 'APPROVED' && $ret['elv']['mandate_status'] !== "active") {
if ($ret['elv']['status'] === 'APPROVED' && $ret['elv']['mandate_status'] !== 'active') {
Session::flash('elv-managemandate', 1);
Session::flash('elv-mandate_identification', $ret['elv']['mandate_identification']);
Session::flash('elv-mandate_text', $ret['elv']['mandate_text']);
Session::flash('elv-creditor_identifier', $ret['elv']['creditor_identifier']);
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
@ -329,12 +331,13 @@ class CheckoutController extends Controller
'creditor_identifier' => Request::get('creditor_identifier'),
'iban' => $data['elv_iban'],
'bic' => $data['elv_bic'],
'bankaccountholder' => $data['elv_bankaccountholder']
'bankaccountholder' => $data['elv_bankaccountholder'],
];
$this->storeUserPaymentsData($shopping_user, $ret);
}
$ret['returnstatus'] = 'VALID';
return $ret;
}
@ -354,6 +357,19 @@ class CheckoutController extends Controller
return view('web.templates.checkout-is-final', $data);
}
/**
* Verarbeitet den Transaktionsstatus (POST-Anfragen)
* Einige Zahlungsanbieter senden POST-Anfragen zurück
*
* @param string $status
* @param string $reference
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
*/
public function transactionStatusPost($status, $reference)
{
return $this->transactionStatus($status, $reference);
}
/**
* Verarbeitet den Transaktionsstatus
*
@ -363,37 +379,76 @@ class CheckoutController extends Controller
*/
public function transactionStatus($status, $reference)
{
$shopping_order_id = $this->checkoutRepo->getSessionPayments('shopping_order_id');
$ShoppingPayment = ShoppingPayment::where('shopping_order_id', $shopping_order_id)
->where('reference', $reference)
->first();
// Suche ShoppingPayment nur über reference (nicht Session-abhängig)
// Dies ist wichtig, da die Session bei Redirect-Zahlungen verloren gehen kann
$ShoppingPayment = ShoppingPayment::where('reference', $reference)->first();
if (! $ShoppingPayment) {
Util::setUserHistoryValue(['status' => 21]);
Session::flash('checkout-error', 'Der Zahlungsvorgang konnte nicht abgeschlossen werden, die Zahlung wurde nicht gefunden: ' . $reference);
return redirect(route('checkout.checkout_card'));
\Log::warning('CheckoutController::transactionStatus - ShoppingPayment nicht gefunden', [
'reference' => $reference,
'status' => $status,
]);
// Zeige eine dedizierte Fehlerseite anstatt zur Hauptseite weiterzuleiten
return $this->showTransactionError(
__('payment.payment_not_found'),
__('payment.payment_not_found_description', ['reference' => $reference])
);
}
$ShoppingPayment->status = $status;
$ShoppingPayment->save();
if ($status === "success") {
if ($status === 'success') {
return $this->handleSuccessfulTransaction($ShoppingPayment, $reference);
}
if ($status === "cancel") {
if ($status === 'cancel') {
Util::setUserHistoryValue(['status' => 22]);
Util::setInstanceStatus(5); // link_canceled
Session::flash('checkout-error', 'Der Zahlungsvorgang wurde abgebrochen, die Bestellung konnte nicht ausgeführt werden.');
return redirect(route('checkout.checkout_card'));
Util::setInstanceStatusByPayment($ShoppingPayment, 6); // link_canceled
return $this->showTransactionError(
__('payment.payment_canceled'),
__('payment.payment_canceled_description')
);
}
if ($status === "error") {
if ($status === 'error') {
Util::setUserHistoryValue(['status' => 23]);
Util::setInstanceStatus(6); // link_failed
Session::flash('checkout-error', 'Der Zahlungsvorgang wurde abgebrochen, die Bestellung konnte nicht ausgeführt werden.');
return redirect(route('checkout.checkout_card'));
Util::setInstanceStatusByPayment($ShoppingPayment, 5); // link_failed
return $this->showTransactionError(
__('payment.payment_error'),
__('payment.payment_error_description')
);
}
// Fallback für unbekannte Status
return $this->showTransactionError(
__('payment.payment_unknown_status'),
__('payment.payment_unknown_status_description')
);
}
/**
* Zeigt eine Transaktionsfehlerseite an
*
* @param string $title
* @param string $message
* @return \Illuminate\View\View
*/
private function showTransactionError($title, $message)
{
$data = [
'user_shop' => Util::getUserShop(),
'is_checkout' => true,
'yard_instance' => $this->instance,
'error_title' => $title,
'error_message' => $message,
];
return view('web.templates.checkout-error', $data);
}
/**
@ -487,7 +542,6 @@ class CheckoutController extends Controller
/**
* Verarbeitet den direkten Zahlungsstatus (Rechnung MIV)
*
* @param PaymentTransaction $payt
* @return void
*/
private function directPaymentStatus(PaymentTransaction $payt)
@ -534,6 +588,7 @@ class CheckoutController extends Controller
$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;
}
@ -544,6 +599,7 @@ class CheckoutController extends Controller
// 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);
}

View file

@ -2,34 +2,32 @@
namespace App\Http\Controllers;
use Auth;
use Hash;
use Yard;
use Request;
use App\User;
use Validator;
use App\Mail\MailAccountActive;
use App\Mail\MailAutoReleaseAccount;
use App\Mail\MailReleaseAccount;
use App\Models\File;
use App\Services\Util;
use App\Models\Product;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use App\Models\UserAccount;
use App\Models\UserHistory;
use App\Services\UserService;
use App\Mail\MailAccountActive;
use App\Models\ShippingCountry;
use App\Mail\MailReleaseAccount;
use App\Models\ShoppingInstance;
use App\Mail\MailAutoReleaseAccount;
use App\Repositories\ContractPDFRepository;
use App\Repositories\FileRepository;
use App\Repositories\UserRepository;
use App\Services\UserService;
use App\Services\Util;
use App\User;
use Auth;
use Hash;
use Illuminate\Support\Facades\Mail;
use App\Repositories\ContractPDFRepository;
use Request;
use Validator;
use Yard;
class WizardController extends Controller
{
protected $fileRepo;
/**
* Create a new controller instance.
*
@ -51,6 +49,7 @@ class WizardController extends Controller
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_create'));
}
@ -64,8 +63,12 @@ class WizardController extends Controller
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
'userHistoryWizardPayment' => $userHistoryWizardPayment,
];
@ -87,6 +90,7 @@ class WizardController extends Controller
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_register'));
}
@ -99,14 +103,19 @@ class WizardController extends Controller
$data = [
'user' => Auth::user(),
'step' => $step,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
];
if ($step == 5) {
if ($user->active) {
$user->active = false;
$user->save();
}
return view('user.wizard.register_release', $data);
}
@ -124,6 +133,7 @@ class WizardController extends Controller
$account = UserAccount::create([]);
$user->account_id = $account->id;
$user->save();
return redirect(route('wizard_payment'));
}
@ -141,13 +151,16 @@ class WizardController extends Controller
$data = [
'user' => Auth::user(),
'step' => 0,
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
'products' => Product::where('active', true)->where(function ($q) {
$q->whereJsonContains('show_on', '7')
->orWhereJsonContains('show_on', '8')
->orWhereJsonContains('show_on', '9');
})->orderBy('pos', 'ASC')->get(),
'products_on_board' => collect(),
'userHistoryWizardPayment' => $userHistoryWizardPayment,
'yard_info' => UserService::getYardInfo(),
];
if ($user->wizard == 20) {
return view('user.wizard.register_payment', $data);
}
@ -169,6 +182,7 @@ class WizardController extends Controller
return $shipping_country->id;
}
}
return false;
}
@ -180,22 +194,22 @@ class WizardController extends Controller
}
$user = User::findOrFail(Auth::user()->id);
if (! $user->account) {
$user->account = new UserAccount();
$user->account = new UserAccount;
}
$data = Request::all();
if ($step == 7 && Request::get('user_country_id')) {
$user->account->country_id = Request::get('user_country_id');
$user->account->save();
return redirect(route('wizard_register', [1]));
}
if ($step == 0) {
$rules = array(
$rules = [
'accepted_data_protection' => 'required',
'accepted_active' => 'required',
'accepted_contract' => 'required'
);
'accepted_contract' => 'required',
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
@ -206,6 +220,7 @@ class WizardController extends Controller
];
$user->wizard = 0;
$user->save();
return view('user.wizard.register', $data)->withErrors($validator);
}
$account = $user->account;
@ -222,26 +237,29 @@ class WizardController extends Controller
$user->wizard = 1;
$user->save();
return redirect(route('wizard_register'));
}
if ($step == 1) {
$data = Request::all();
if (isset($data['action']) && $data['action'] == "reverse_charge_validate") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate') {
$user->wizard = 1;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_validate($data, $user, route('wizard_register', [0]));
}
if (isset($data['action']) && $data['action'] == "reverse_charge_delete") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete') {
$user->wizard = 1;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_delete($data, $user, route('wizard_register', [0]));
}
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -255,7 +273,7 @@ class WizardController extends Controller
'bank_owner' => 'required',
'bank_iban' => 'required',
'bank_bic' => 'required',
);
];
if (! Request::get('same_as_billing')) {
$rules = array_merge($rules, [
@ -272,12 +290,14 @@ class WizardController extends Controller
if ($validator->fails()) {
$user->wizard = 1;
$user->save();
return redirect(route('wizard_register', [1]))->withErrors($validator)->withInput(Request::all());
}
$data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
$data['same_as_billing'] = Request::get('same_as_billing') == null ? 0 : 1;
$user->account->fill($data)->save();
$user->wizard = 2;
$user->save();
return redirect(route('wizard_register'));
}
@ -288,16 +308,19 @@ class WizardController extends Controller
$validator->errors()->add('field', __('msg.no_id_card_deposited_please_upload_first'));
$user->wizard = 2;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
}
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'));
}
$this->fileRepo->_set('disk', 'user');
$this->fileRepo->_set('dir', '/'.$user->id.'/verification/');
$this->fileRepo->_set('user_id', $user->id);
$this->fileRepo->_set('identifier', 'id_card');
return $this->fileRepo->uploadFile(Request::all());
}
@ -305,23 +328,25 @@ class WizardController extends Controller
if (Request::get('submit') === 'do') {
$data = Request::all();
if ($data['business_license_choose'] === "now") {
if ($data['business_license_choose'] === 'now') {
if (File::whereUserId($user->id)->whereIdentifier('business_license')->count() == 0) {
$validator = Validator::make(Request::all(), []);
$validator->errors()->add('field', __('msg.no_trade_licence_deposited_please_upload_first'));
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
}
}
if ($data['business_license_choose'] === "later") {
if ($data['business_license_choose'] === 'later') {
}
if ($data['business_license_choose'] === "non") {
if (!$data['non_business_license_reason'] || $data['non_business_license_reason'] == "") {
if ($data['business_license_choose'] === 'non') {
if (! $data['non_business_license_reason'] || $data['non_business_license_reason'] == '') {
$validator = Validator::make(Request::all(), []);
$validator->errors()->add('field', __('msg.please_enter_reason_why_you_not_need_trade_licence'));
$user->wizard = 3;
$user->save();
return redirect(route('wizard_register'))->withErrors($validator)->withInput(Request::all());
} else {
$user->account->setNotice('business_license_reason', $data['non_business_license_reason']);
@ -338,6 +363,7 @@ class WizardController extends Controller
$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());
}
@ -402,6 +428,7 @@ class WizardController extends Controller
Mail::to($user->email)->locale($user->getLocale())->send(new MailAccountActive($user));
UserHistory::create(['user_id' => $user->id, 'action' => 'released_completed', 'status' => 0]);
\Session()->flash('alert-success', __('msg.account_released'));
return redirect(route('wizard_payment'));
}
@ -414,14 +441,14 @@ class WizardController extends Controller
$user = User::findOrFail(Auth::user()->id);
if (! $user->account) {
$user->account = new UserAccount();
$user->account = new UserAccount;
}
if ($step == 10) {
$rules = array(
$rules = [
'accepted_data_protection' => 'required',
'accepted_active' => 'required',
);
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
@ -432,6 +459,7 @@ class WizardController extends Controller
];
$user->wizard = 10;
$user->save();
return view('user.wizard.create', $data)->withErrors($validator);
}
$account = $user->account;
@ -455,11 +483,12 @@ class WizardController extends Controller
if ($user->isPasswort()) {
$user->wizard = 12;
$user->save();
return redirect(route('wizard_create', [12]));
}
$rules = array(
$rules = [
'password' => 'required|string|min:6|confirmed',
);
];
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
$data = [
@ -468,37 +497,40 @@ class WizardController extends Controller
'products' => Product::where('active', true)->whereJsonContains('show_on', ['7', '8'])->orderBy('pos', 'ASC')->get(),
'products_on_board' => Product::where('active', true)->whereJsonContains('show_on', '9')->orderBy('pos', 'ASC')->get(),
];
return view('user.wizard.create', $data)->withErrors($validator);
}
$user->fill([
'password' => Hash::make(Request::get('password'))
'password' => Hash::make(Request::get('password')),
])->save();
$user->wizard = 12;
$user->save();
return redirect(route('wizard_create', [12]));
}
if ($step == 12) {
$data = Request::all();
if (isset($data['action']) && $data['action'] == "reverse_charge_validate") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate') {
$user->wizard = 12;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_validate($data, $user, route('wizard_create', [12]));
}
if (isset($data['action']) && $data['action'] == "reverse_charge_delete") {
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete') {
$user->wizard = 12;
$user->save();
$userRepo = new UserRepository($user);
return $userRepo->reverse_charge_delete($data, $user, route('wizard_create', [12]));
}
$rules = array(
$rules = [
'salutation' => 'required',
'first_name' => 'required',
'last_name' => 'required',
@ -509,7 +541,7 @@ class WizardController extends Controller
'mobil' => 'required_without:phone',
'country_id' => 'required|integer|min:1',
'birthday' => 'required',
);
];
if (! Request::get('same_as_billing')) {
$rules = array_merge($rules, [
@ -518,7 +550,7 @@ class WizardController extends Controller
'shipping_address' => 'required',
'shipping_zipcode' => 'required',
'shipping_city' => 'required',
'shipping_salutation' => 'required'
'shipping_salutation' => 'required',
]);
}
@ -528,7 +560,7 @@ class WizardController extends Controller
}
$data = Request::all();
$data['same_as_billing'] = Request::get('same_as_billing') == NULL ? 0 : 1;
$data['same_as_billing'] = Request::get('same_as_billing') == null ? 0 : 1;
$user->account->fill($data)->save();
$user->wizard = 13;
@ -538,11 +570,11 @@ class WizardController extends Controller
$user->confirmation_code_to = null;
$user->confirmation_code_remider = 0;
$user->save();
return redirect(route('wizard_create', [13]));
}
}
public function storePayment($step = 0)
{
@ -566,37 +598,19 @@ class WizardController extends Controller
Yard::instance('shopping')->setUserPriceInfos(UserService::getYardInfo());
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id);
if ($product && $product->active) {
// set membership product
$image = "";
$image = '';
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]);
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'free_shipping_consultant' => $product->free_shipping_consultant, 'show_on' => $product->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith(\App\Services\UserService::$user_country));
}
//set onboarding products
if (Request::get('products_on_board')) {
foreach (Request::get('products_on_board') as $product_on_board_id) {
$product_on_board = Product::find($product_on_board_id);
$image = "";
if ($product_on_board->images->count()) {
$image = $product_on_board->images->first()->slug;
}
$cartItem = Yard::instance('shopping')->add($product_on_board->id, $product_on_board->getLang('name'), 1, $product_on_board->getPriceWith(\App\Services\UserService::getTaxFree(), false, \App\Services\UserService::$user_country), false, false, ['image' => $image, 'slug' => $product_on_board->slug, 'weight' => $product_on_board->weight, 'points' => $product_on_board->points, 'no_commission' => $product_on_board->no_commission, 'show_on' => $product_on_board->show_on]);
if (\App\Services\UserService::getTaxFree()) {
Yard::setTax($cartItem->rowId, 0);
} else {
Yard::setTax($cartItem->rowId, $product->getTaxWith(\App\Services\UserService::$user_country));
}
}
}
do {
$identifier = Util::getToken();
} while (ShoppingInstance::where('identifier', $identifier)->count());
@ -622,11 +636,13 @@ class WizardController extends Controller
// 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");
\Session()->flash('alert-error', 'Fehler beim Produkt');
return back();
}
@ -641,6 +657,7 @@ class WizardController extends Controller
$file->delete();
\Session()->flash('alert-success', __('msg.file_deleted'));
}
return back();
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,6 +18,7 @@ use Illuminate\Database\Eloquent\Model;
* @property \Illuminate\Support\Carbon|null $display_date
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
*
* @mixin \Eloquent
*/
class DashboardNews extends Model
@ -58,6 +59,7 @@ class DashboardNews extends Model
if (! $trans || $trans == '') {
return $this->{$key};
}
return $trans;
}
@ -70,25 +72,40 @@ class DashboardNews extends Model
if (! empty($this->{$transKey}[$lang])) {
return $this->{$transKey}[$lang];
}
return "";
return '';
}
/**
* Get active news
*/
public static function getActiveNews()
public static function getActiveNews(): ?self
{
return self::where('active', true)
->orderBy('created_at', 'DESC')
->first();
}
/**
* Get all archived (non-active) news ordered by display date descending
*
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function getArchiveNews(): \Illuminate\Database\Eloquent\Collection
{
return self::where('active', false)
->orderBy('display_date', 'DESC')
->orderBy('created_at', 'DESC')
->get();
}
/**
* Get formatted display date or created_at as fallback
*/
public function getDisplayDateFormatted()
{
$date = $this->display_date ?: $this->created_at;
return $date ? $date->format('d.m.Y') : '';
}
@ -115,6 +132,7 @@ class DashboardNews extends Model
];
}
}
return null;
})->filter()->values();
}

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -6,11 +6,11 @@
namespace App\Models;
use App\Services\Util;
use App\User;
use Carbon\Carbon;
use App\Services\Util;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
@ -34,7 +34,6 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property Carbon|null $user_deleted_at
* @property User $user
* @property Collection|UserAboOrder[] $user_abo_orders
* @package App\Models
* @property int|null $member_id
* @property int $shopping_user_id
* @property string|null $email
@ -48,6 +47,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property-read Collection<int, \App\Models\UserAboItem> $user_abo_items
* @property-read int|null $user_abo_items_count
* @property-read int|null $user_abo_orders_count
*
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo onlyTrashed()
@ -76,11 +76,13 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo whereWallettype($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withTrashed()
* @method static \Illuminate\Database\Eloquent\Builder|UserAbo withoutTrashed()
*
* @mixin \Eloquent
*/
class UserAbo extends Model
{
use SoftDeletes;
protected $table = 'user_abos';
protected $casts = [
@ -97,7 +99,7 @@ class UserAbo extends Model
'next_date' => 'datetime',
'cancel_date' => 'datetime',
'user_deleted_at' => 'datetime',
'carddata' => 'array'
'carddata' => 'array',
];
@ -119,7 +121,7 @@ class UserAbo extends Model
'last_date',
'next_date',
'cancel_date',
'user_deleted_at'
'user_deleted_at',
];
public static $aboDeliveryDays = [5, 10, 20, 25];
@ -132,7 +134,7 @@ class UserAbo extends Model
4 => 'abo_cancel',
5 => 'abo_finish',
6 => 'abo_inactive',
7 => 'abo_grace'
7 => 'abo_grace',
];
public static $statusColors = [
@ -143,11 +145,9 @@ class UserAbo extends Model
4 => 'danger',
5 => 'info',
6 => 'warning',
7 => 'danger'
7 => 'danger',
];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
@ -173,6 +173,37 @@ class UserAbo extends Model
return $this->hasMany(UserAboItem::class);
}
public function user_abo_item_histories()
{
return $this->hasMany(UserAboItemHistory::class);
}
public function getInitialItems()
{
return $this->user_abo_item_histories()
->where('is_initial', true)
->where('comp', 0)
->orderBy('created_at')
->get();
}
public function getInitialCompItems()
{
return $this->user_abo_item_histories()
->where('is_initial', true)
->where('comp', '>', 0)
->orderBy('comp')
->get();
}
public function getChangeHistory()
{
return $this->user_abo_item_histories()
->where('is_initial', false)
->orderByDesc('created_at')
->get();
}
public function getCountOrders()
{
// sind bezahlte Bestellungen
@ -187,8 +218,9 @@ class UserAbo extends Model
public function setStartDateAttribute($value)
{
$this->attributes['start_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['start_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getStartDateAttribute()
{
return $this->attributes['start_date'] ? Carbon::parse($this->attributes['start_date'])->format(\Util::formatDateDB()) : '';
@ -196,8 +228,9 @@ class UserAbo extends Model
public function setLastDateAttribute($value)
{
$this->attributes['last_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['last_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getLastDateAttribute()
{
return $this->attributes['last_date'] ? Carbon::parse($this->attributes['last_date'])->format(\Util::formatDateDB()) : '';
@ -205,8 +238,9 @@ class UserAbo extends Model
public function setNextDateAttribute($value)
{
$this->attributes['next_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['next_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getNextDateAttribute()
{
return $this->attributes['next_date'] ? Carbon::parse($this->attributes['next_date'])->format(\Util::formatDateDB()) : '';
@ -214,8 +248,9 @@ class UserAbo extends Model
public function setCancelDateAttribute($value)
{
$this->attributes['cancel_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['cancel_date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getCancelDateAttribute()
{
return $this->attributes['cancel_date'] ? Carbon::parse($this->attributes['cancel_date'])->format(\Util::formatDateDB()) : '';
@ -223,8 +258,9 @@ class UserAbo extends Model
public function getFormattedAmount()
{
return isset($this->attributes['amount']) ? Util::formatNumber($this->attributes['amount'] / 100) : "";
return isset($this->attributes['amount']) ? Util::formatNumber($this->attributes['amount'] / 100) : '';
}
public function getIsForFormated()
{
return $this->attributes['is_for'] === 'me' ? '<span class="badge badge-outline-warning-dark">'.__('tables.adviser').'</span>' : '<span class="badge badge-outline-info">'.__('tables.customer').'</span>';
@ -237,12 +273,12 @@ class UserAbo extends Model
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('abo.' . self::$statusTypes[$this->status]) : "";
return isset(self::$statusTypes[$this->status]) ? __('abo.'.self::$statusTypes[$this->status]) : '';
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getPaymentType()

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -6,10 +6,9 @@
namespace App\Models;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use App\Models\ShoppingOrder;
use App\User;
/**
* Class UserSalesVolume
@ -32,11 +31,11 @@ use App\User;
* @property Carbon|null $updated_at
* @property ShoppingOrder|null $shopping_order
* @property User $user
* @package App\Models
* @property int|null $user_invoice_id
* @property int|null $month_shop_points
* @property float|null $month_shop_total_net
* @property-read \App\Models\UserInvoice|null $user_invoice
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume query()
@ -57,16 +56,23 @@ use App\User;
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereUserInvoiceId($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereYear($value)
*
* @property array|null $syslog
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereSyslog($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereInfo($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereStatusPoints($value)
*
* @property int|null $month_KP_points
* @property int|null $month_TP_points
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereMonthKPPoints($value)
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereMonthTPPoints($value)
*
* @property int|null $status_turnover
*
* @method static \Illuminate\Database\Eloquent\Builder|UserSalesVolume whereStatusTurnover($value)
*
* @mixin \Eloquent
*/
class UserSalesVolume extends Model
@ -89,11 +95,11 @@ class UserSalesVolume extends Model
'month_total_net' => 'float',
'month_shop_total_net' => 'float',
'status' => 'int',
'syslog' => 'array'
'syslog' => 'array',
];
protected $dates = [
'date'
'date',
];
protected $fillable = [
@ -115,10 +121,9 @@ class UserSalesVolume extends Model
'message',
'info',
'status',
'syslog'
'syslog',
];
public static $statusPointsTypes = [
1 => 'KU + TP', // Eigene + Team
2 => 'KU', // nur Eigene nicht Team
@ -136,6 +141,7 @@ class UserSalesVolume extends Model
3 => 'shoporder_pending', // hinzugefügt aus
4 => 'credit', // hinzugefügt aus
5 => 'registration', // hinzugefügt aus
6 => 'cancelled', // Stornorechnung
// 10 => ''
];
@ -146,6 +152,7 @@ class UserSalesVolume extends Model
3 => 'warning',
4 => 'info',
5 => 'info',
6 => 'danger',
10 => 'danger',
];
@ -168,13 +175,15 @@ class UserSalesVolume extends Model
{
return $this->attributes['date'] ? Carbon::parse($this->attributes['date'])->format(\Util::formatDateDB()) : '';
}
public function setDateAttribute($value)
{
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : NULL;
$this->attributes['date'] = isset($value) ? (new Carbon($value))->format('Y-m-d') : null;
}
public function getDateRaw()
{
return isset($this->attributes['date']) ? $this->attributes['date'] : NULL;
return isset($this->attributes['date']) ? $this->attributes['date'] : null;
}
// Points Setter/Getter für deutsches Zahlenformat
@ -200,7 +209,7 @@ class UserSalesVolume extends Model
public function getFormattedPoints()
{
return isset($this->attributes['points']) ? \Util::formatNumber($this->attributes['points']) : "";
return isset($this->attributes['points']) ? \Util::formatNumber($this->attributes['points']) : '';
}
public function getFormattedMonthKPPoints()
@ -222,6 +231,7 @@ class UserSalesVolume extends Model
{
return $this->month_KP_points + $this->month_shop_points; // only KP für SUM - KP is for User
}
public function getPointsTPSum()
{
return $this->month_TP_points + $this->month_shop_points; // only TP für SUM - TP is only for Payline
@ -234,7 +244,7 @@ class UserSalesVolume extends Model
public function getStatusType()
{
return isset(self::$statusTypes[$this->status]) ? __('payment.' . self::$statusTypes[$this->status]) : "";
return isset(self::$statusTypes[$this->status]) ? __('payment.'.self::$statusTypes[$this->status]) : '';
}
public static function getTransStatusType()
@ -243,6 +253,7 @@ class UserSalesVolume extends Model
foreach (self::$statusTypes as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
@ -252,21 +263,23 @@ class UserSalesVolume extends Model
foreach (self::$statusTurnoverTypes as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
public function getStatusColor()
{
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : "default";
return isset(self::$statusColors[$this->status]) ? self::$statusColors[$this->status] : 'default';
}
public function getStatusPointsType()
{
return isset(self::$statusPointsTypes[$this->status_points]) ? self::$statusPointsTypes[$this->status_points] : "";
return isset(self::$statusPointsTypes[$this->status_points]) ? self::$statusPointsTypes[$this->status_points] : '';
}
public function getStatusPointsColor()
{
return isset(self::$statusColors[$this->status_points]) ? self::$statusColors[$this->status_points] : "default";
return isset(self::$statusColors[$this->status_points]) ? self::$statusColors[$this->status_points] : 'default';
}
public function getStatusTurnoverType()
@ -285,12 +298,13 @@ class UserSalesVolume extends Model
case 5: // Registrierung
return 'E';
}
return "";
return '';
}
public function getStatusTurnoverColor()
{
switch ($this->status) {
case 1: // Bestellung Berater
return 'success';
@ -305,12 +319,13 @@ class UserSalesVolume extends Model
case 5: // Registrierung
return 'success';
}
return "default";
return 'default';
}
public function getFormatedMonthYear()
{
return str_pad($this->month, 2, "0", STR_PAD_LEFT) . "/" . $this->year;
return str_pad($this->month, 2, '0', STR_PAD_LEFT).'/'.$this->year;
}
public function isCurrentMonthYear()
@ -318,6 +333,7 @@ class UserSalesVolume extends Model
if ($this->month === intval(date('m')) && $this->year === intval(date('Y'))) {
return true;
}
return false;
}
@ -326,6 +342,7 @@ class UserSalesVolume extends Model
if ($this->total_net > 0 && $margin > 0) {
return $this->total_net / 100 * $margin;
}
return 0;
}
}

View file

@ -2,20 +2,16 @@
namespace App\Repositories;
use Carbon;
use App\Models\UserAbo;
use App\Services\AboHelper;
class AboRepository extends BaseRepository
{
public function __construct()
{
// $this->model = $model;
}
public function setModel(UserAbo $model)
{
$this->model = $model;
@ -31,11 +27,14 @@ class AboRepository extends BaseRepository
$this->model->next_date = AboHelper::setNextDate(now(), $data['abo_interval']);
$this->model->save();
\Session()->flash('alert-success', 'Einstellungen gespeichert');
return true;
}
return false;
}
}
return false;
}
@ -50,6 +49,7 @@ class AboRepository extends BaseRepository
$this->model->active = false;
$this->model->cancel_date = now();
$this->model->save();
return;
}
@ -70,32 +70,36 @@ class AboRepository extends BaseRepository
}
}
$this->model->active = $active;
return;
}
private function validate($data)
{
if ($data['view'] !== 'admin') {
if ($data['view'] !== 'admin' && $data['view'] !== 'portal') {
if ($this->model->is_for === 'me' && $this->model->user_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($this->model->is_for === 'ot' && $this->model->member_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($data['view'] === 'me' && $this->model->is_for !== 'me') {
\Session()->flash('alert-error', 'Unauthorized action. Is not for me');
return false;
}
if ($data['view'] === 'ot' && $this->model->is_for !== 'ot') {
\Session()->flash('alert-error', 'Unauthorized action. Is not your customer');
return false;
}
}
if (! in_array($data['abo_interval'], \App\Models\UserAbo::$aboDeliveryDays)) {
// to check if user is not admin
\Session()->flash('alert-error', __('abo.error_abo_interval'));
return false;
}
@ -106,6 +110,7 @@ class AboRepository extends BaseRepository
if (! $executedThisMonth && $data['abo_interval'] <= now()->day) {
\Session()->flash('alert-error', __('abo.error_abo_interval_in_the_past'));
return false;
}

View file

@ -2,24 +2,22 @@
namespace App\Repositories;
use Yard;
use App\Services\Util;
use App\Models\ShoppingUser;
use App\Models\Homeparty;
use App\Models\ShoppingCollectOrder;
use App\Models\PaymentMethod;
use App\Models\ShoppingCollectOrder;
use App\Models\ShoppingOrder;
use Illuminate\Session\SessionManager;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Services\Util;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Collection;
use Yard;
class CheckoutRepository extends BaseRepository
{
private $session;
private $instance;
private $instance;
public function __construct(SessionManager $session)
{
@ -153,9 +151,11 @@ class CheckoutRepository extends BaseRepository
$data['product_id'] = null;
}
$model->fill($data)->save();
return false;
}
}
return $model->delete();
});
foreach ($items as $item) {
@ -177,7 +177,7 @@ class CheckoutRepository extends BaseRepository
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
'slug' => $item->options->slug,
];
if ($shopping_user->is_from === 'homeparty') {
@ -200,8 +200,10 @@ class CheckoutRepository extends BaseRepository
} else {
$shopping_order->makeTaxSplit();
}
return $shopping_order;
}
public function makeShoppingUser($data)
{
@ -240,6 +242,7 @@ class CheckoutRepository extends BaseRepository
} else {
$payment_methods['active'] = \App\Models\PaymentMethod::where('active', true)->get()->pluck('id', 'short')->toArray();
}
return $payment_methods;
}
@ -259,7 +262,7 @@ class CheckoutRepository extends BaseRepository
public function makeCustomerShoppingUser($shopping_data, $is_for, $is_from)
{
// $shopping_user = ShoppingUser::findOrFail($shopping_data['shopping_user_id']);
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->fill($shopping_data);
$shopping_user->faker_mail = false;
$shopping_user->auth_user_id = null;
@ -271,12 +274,13 @@ class CheckoutRepository extends BaseRepository
$shopping_user->is_from = $is_from;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
return $shopping_user;
}
public function initShoppingUser($is_for, $is_from, $homeparty_id = null)
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->homeparty_id = $homeparty_id;
$shopping_user->language = \App::getLocale();
// eingeloggter Kunde
@ -290,6 +294,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->mode = 'prev';
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
return $shopping_user;
}
@ -305,7 +310,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->shipping_country_id = null;
}
} else {
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
}
@ -315,7 +320,7 @@ class CheckoutRepository extends BaseRepository
public function shoppingUserByAuthUser(\App\User $user, $is_from, $is_for)
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
$shopping_user->billing_salutation = $user->account->salutation;
@ -331,10 +336,10 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
// Lieferadresse
$shopping_user->same_as_billing = $user->account->same_as_billing ? false : true;
$shopping_user->shipping_salutation = $user->account->shipping_salutation;
@ -349,7 +354,6 @@ class CheckoutRepository extends BaseRepository
$shopping_user->shipping_phone = $user->account->shipping_phone;
$shopping_user->shipping_postnumber = $user->account->shipping_postnumber;
return $shopping_user;
}
@ -357,7 +361,7 @@ class CheckoutRepository extends BaseRepository
{
$user = Util::getAuthUser();
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->auth_user_id = $user->id;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
@ -375,6 +379,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
@ -449,6 +454,7 @@ class CheckoutRepository extends BaseRepository
if ($content->has($key)) {
return $content->get($key);
}
return false;
}
@ -469,6 +475,7 @@ class CheckoutRepository extends BaseRepository
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
}

View file

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

View file

@ -2,21 +2,22 @@
namespace App\Repositories;
use PDF;
use Storage;
use App\User;
use App\Services\Credit;
use App\Models\UserCredit;
use Response;
use App\Libraries\CreditDetailsPDF;
use App\Libraries\MyPDFMerger;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Models\UserSalesVolume;
use App\Libraries\CreditDetailsPDF;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\Credit;
use App\User;
use PDF;
use Response;
use Storage;
class CreditRepository extends BaseRepository {
class CreditRepository extends BaseRepository
{
private $user_credit;
public function __construct(User $model)
{
$this->model = $model;
@ -26,11 +27,11 @@ class CreditRepository extends BaseRepository {
{
// need invoice $data
$number = Credit::getCreditNumber();
$credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format("d.m.Y");
$credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format('d.m.Y');
$credit_send_mail = isset($request['credit_send_mail']) ? true : false;
$credit_number = Credit::createCreditNumber($number, $credit_date);
$this->user_credit = new UserCredit();
$this->user_credit = new UserCredit;
$user_credit_items = $this->makeUserCredit();
if (! count($user_credit_items)) {
return false;
@ -42,8 +43,6 @@ class CreditRepository extends BaseRepository {
'user_credits' => $this->user_credit,
'user_credit_items' => $user_credit_items,
];
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$dir = Credit::getCreditStorageDir($credit_date);
if (! Storage::disk('public')->exists($dir)) {
@ -51,15 +50,26 @@ class CreditRepository extends BaseRepository {
}
$path = Storage::disk('public')->path('');
// Benutzersprache ermitteln
$userLocale = $this->model->account ? $this->model->account->getLocale() : 'de';
$originalLocale = \App::getLocale();
// Deutsches Original-Dateiname (wird in DB gespeichert)
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
// 1. IMMER deutsches Original erstellen (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createCreditPDF($data, $path, $dir, $filename, 'de', false);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
Storage::disk('public')->put($dir.$filename, $file);
// 2. Wenn Benutzersprache != DE, Kopie in Benutzersprache erstellen
if ($userLocale && $userLocale !== 'de') {
\App::setLocale($userLocale);
$localizedFilename = Credit::makeCreditFilenameLocale($credit_number, $userLocale);
$this->createCreditPDF($data, $path, $dir, $localizedFilename, $userLocale, true);
}
// Locale zurücksetzen
\App::setLocale($originalLocale);
$this->user_credit->user_id = $this->model->id;
$this->user_credit->year = \Carbon::parse($credit_date)->format('Y');
@ -76,10 +86,51 @@ class CreditRepository extends BaseRepository {
Credit::sendCreditMail($this->user_credit);
}
$this->finishUserCredit($this->user_credit->id, $user_credit_items);
return true;
}
private function finishUserCredit($user_credit_id, $user_credit_items){
/**
* Erstellt eine Gutschrift-PDF-Datei.
*
* @param string $locale Sprachcode für das Template (de, en, es, fr)
* @param bool $is_copy Ob es sich um eine Kopie handelt (nicht das Original)
*/
private function createCreditPDF(array $data, string $path, string $dir, string $filename, string $locale = 'de', bool $is_copy = false)
{
// Kopie-Flag an Template übergeben
$data['is_copy'] = $is_copy;
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);
// Template basierend auf Locale
$template = $this->getTemplateForLocale($locale);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, $template);
Storage::disk('public')->put($dir.$filename, $file);
}
/**
* Gibt das PDF-Template für die angegebene Locale zurück.
* Verfügbare Templates werden aus config/localization.php geladen.
*/
private function getTemplateForLocale(string $locale): string
{
$availableTemplates = config('localization.availableTemplates', ['de']);
if (in_array($locale, $availableTemplates)) {
return 'template_invoice_'.$locale;
}
return 'template_invoice_de';
}
private function finishUserCredit($user_credit_id, $user_credit_items)
{
// next credits
Credit::makeNextCreditNumber();
// mark as payed
@ -91,14 +142,14 @@ class CreditRepository extends BaseRepository {
}
}
private function makeUserCredit(){
private function makeUserCredit()
{
$this->user_credit->net = 0;
$this->user_credit->infos = [];
$infos = [];
$user_credit_items = [];
$UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach ($UserCreditItems as $userCreditItem) {
$user_credit_items[] = $userCreditItem;
@ -119,7 +170,6 @@ class CreditRepository extends BaseRepository {
$this->user_credit->tax_rate = config('app.main_tax_rate');
$this->user_credit->total = round($this->user_credit->net * config('app.main_tax'), 2);
$this->user_credit->tax = $this->user_credit->total - $this->user_credit->net;
} else {
$this->user_credit->tax_rate = 0;
$this->user_credit->total = $this->user_credit->net;
@ -127,6 +177,7 @@ class CreditRepository extends BaseRepository {
}
}
$this->user_credit->infos = $infos;
return $user_credit_items;
}
@ -138,7 +189,7 @@ class CreditRepository extends BaseRepository {
public function create_report(UserCredit $user_credit, $do = 'html')
{
// collect all data
$collection = new \stdClass();
$collection = new \stdClass;
$collection->calc_bot = [];
$collection->commission_shop = [];
$collection->commission_payline = [];
@ -147,7 +198,6 @@ class CreditRepository extends BaseRepository {
$collection->commission_registration = [];
$collection->commission_credit = [];
$dates = [];
/* für jede Postion aus der Gutschrift nach Status */
foreach ($user_credit->user_credit_items as $user_credit_item) {
@ -186,9 +236,7 @@ class CreditRepository extends BaseRepository {
->where('status', 2) // 'shoporder', //hinzugefügt aus
->orderBy('id', 'DESC')->first();
$obj = new \stdClass();
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->user_sales_volumes_total = $user_sales_volumes_total;
$obj->user_credit_item = $user_credit_item;
@ -209,8 +257,6 @@ class CreditRepository extends BaseRepository {
$collection->commission_credit[$date] = $user_sales_volumes_credit;
}
/*
status === 2 commission_payline
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
@ -222,8 +268,6 @@ class CreditRepository extends BaseRepository {
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
}
/*
@ -255,7 +299,7 @@ class CreditRepository extends BaseRepository {
->sum('points'); // sum('points');
if ($user_sales_volumes->count() > 0) {
$obj = new \stdClass();
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
@ -288,17 +332,14 @@ class CreditRepository extends BaseRepository {
->sum('points'); // sum('points');
if ($user_sales_volumes->count() > 0) {
$obj = new \stdClass();
$obj = new \stdClass;
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->commission_registration[$date] = $obj;
}
}
/*
//need this?
$user_credit_item->status = 3; //credit_added
@ -316,7 +357,6 @@ class CreditRepository extends BaseRepository {
if ($do === 'pdf') {
$dir = Credit::getCreditDetailStorageDir($user_credit->date);
if (! Storage::disk('public')->exists($dir)) {
Storage::disk('public')->makeDirectory($dir); // creates directory
@ -329,12 +369,11 @@ class CreditRepository extends BaseRepository {
$pdf->create($data, $filename, 'save', $path.$dir);
/*$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);*/
$pdfMerger = new MyPDFMerger();
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_report_de');
Storage::disk('public')->put($dir.$filename, $file);
@ -343,10 +382,9 @@ class CreditRepository extends BaseRepository {
$mime = Storage::disk('public')->mimeType($path);
return Response::make($file, 200)
->header("Content-Type", $mime)
->header('Content-Type', $mime)
->header('Content-disposition', 'inline; filename="'.$filename.'"');
// return $dir.$filename;
/*
$dir = Credit::getCreditStorageDir($credit_date);

View file

@ -2,18 +2,14 @@
namespace App\Repositories\DC;
use Request;
use App\Models\DcTag;
use App\Models\DcCategory;
use App\Models\DcTag;
use App\Repositories\BaseRepository;
use Request;
class TagRepository extends BaseRepository {
public function __construct()
class TagRepository extends BaseRepository
{
}
public function __construct() {}
public function storeItem($obj, $data)
{
@ -23,6 +19,7 @@ class TagRepository extends BaseRepository {
$category->pos = 0;
$category->save();
\Session()->flash('alert-success', 'Kategorie erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
@ -33,6 +30,7 @@ class TagRepository extends BaseRepository {
$tag->pos = 0;
$tag->save();
\Session()->flash('alert-success', 'Tag erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if ($obj === 'structure' && isset($data['nestable'])) {
@ -40,7 +38,7 @@ class TagRepository extends BaseRepository {
if (Request::ajax()) {
return response()->json([
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true])
'redirect' => route('admin_downloadcenter_tags', ['flash' => true]),
]);
}
}
@ -54,24 +52,28 @@ class TagRepository extends BaseRepository {
]);
}
}
return true;
}
protected function updateAjax($data){
protected function updateAjax($data)
{
if ($data['action'] == 'update-tag-active' && isset($data['id'])) {
$tag = DcTag::findOrFail($data['id']);
$tag->active = $tag->active ? 0 : 1;
$tag->save();
return $tag->active;
return $tag->active;
}
if ($data['action'] == 'update-category-active' && isset($data['id'])) {
$category = DcCategory::findOrFail($data['id']);
$category->active = $category->active ? 0 : 1;
$category->save();
return $category->active;
}
return false;
}
@ -83,31 +85,40 @@ class TagRepository extends BaseRepository {
$tags = DcTag::all();
foreach ($tags as $value) {
$value->category_id = null;
$value->pos = NULL;
$value->pos = null;
$value->save();
}
$this->saveStructureLevel($data['nestable']);
return true;
}
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false){
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false)
{
foreach ($nestable as $key => $value) {
if ($value['id'] == 0) {
continue;
}
if ($deep == 0) {
$cat = DcCategory::findOrFail($value['id']);
$cat = DcCategory::find($value['id']);
if (! $cat) {
// Kategorie existiert nicht mehr, überspringen
continue;
}
$cat->pos = $key;
$cat->save();
}
if ($deep == 1) {
$tag = DcTag::findOrFail($value['id']);
$tag = DcTag::find($value['id']);
if (! $tag) {
// Tag existiert nicht mehr, überspringen
continue;
}
$tag->category_id = $category_id;
$tag->pos = $key;
$tag->save();
}
if (! empty($value['children'])) {
$this->saveStructureLevel($value['children'], $deep + 1, $value['id']);
@ -115,7 +126,8 @@ class TagRepository extends BaseRepository {
}
}
public function deleteItem($obj, $id){
public function deleteItem($obj, $id)
{
if ($obj == 'category') {
$this->deleteCategory($id);
}
@ -124,7 +136,8 @@ class TagRepository extends BaseRepository {
}
}
public function deleteCategory($id){
public function deleteCategory($id)
{
$cat = DcCategory::findOrFail($id);
$tags = DcTag::where('category_id', $cat->id)->get();
foreach ($tags as $tag) {
@ -133,9 +146,9 @@ class TagRepository extends BaseRepository {
$cat->delete();
}
public function deleteTag($id){
public function deleteTag($id)
{
$tag = DcTag::findOrFail($id);
$tag->delete();
}
}

View file

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

View file

@ -27,6 +27,8 @@ class ProductRepository extends BaseRepository
$data['shipping_addon'] = isset($data['shipping_addon']) ? 1 : 0;
$data['no_commission'] = isset($data['no_commission']) ? 1 : 0;
$data['no_free_shipping'] = isset($data['no_free_shipping']) ? 1 : 0;
$data['free_shipping_consultant'] = isset($data['free_shipping_consultant']) ? 1 : 0;
$data['is_membership_only'] = isset($data['is_membership_only']) ? 1 : 0;
$data['buying_restriction'] = isset($data['buying_restriction']) ? 1 : 0;
$data['sponsor_buying_points'] = isset($data['sponsor_buying_points']) ? 1 : 0;
$data['show_on'] = isset($data['show_on']) ? $data['show_on'] : null;

View file

@ -3,20 +3,17 @@
namespace App\Services;
use App\Models\Product;
use Yard;
use App\User;
use Carbon\Carbon;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserAboOrder;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserAboOrder;
use App\User;
use Carbon\Carbon;
class AboHelper
{
public static $txaction_filter_text = [
'paid' => 'paymend_paid',
'appointed' => 'paymend_open',
@ -29,10 +26,10 @@ class AboHelper
'NULL' => 'no_payment',
];
public static function userHasAbo(User $user)
{
$user = $user ? $user : \Auth::user();
return UserAbo::where('user_id', $user->id)->where('is_for', 'me')->where('status', '>', 1)->first() === null ? false : true;
}
@ -41,6 +38,7 @@ class AboHelper
if (! $shopping_user) {
return false;
}
return UserAbo::where('email', $shopping_user->billing_email)->where('is_for', 'ot')->where('status', '>', 1)->first() === null ? false : true;
}
@ -57,6 +55,7 @@ class AboHelper
}
UserAboOrder::where('user_abo_id', $user_abo->id)->where('shopping_order_id', $shopping_order->id)->update(['status' => $status, 'paid' => $paid]);
}
public static function setAboActive(ShoppingOrder $shopping_order, $status, $paid = false)
{
self::setAboStatus($shopping_order, $status, $paid);
@ -80,14 +79,29 @@ class AboHelper
return true;
}
$paidOrdersCount = $user_abo->getCountPaidOrders();
return $paidOrdersCount >= (int) $minDuration;
}
public static function isAddOnlyMode(UserAbo $user_abo, $view = 'user'): bool
{
if ($view === 'admin') {
return false;
}
return ! self::canCancelAbo($user_abo, $view);
}
public static function canEditAbo($user_abo, $view = 'user')
{
if ($view !== 'admin' && ($user_abo->user_id != \Auth::user()->id && $user_abo->member_id != \Auth::user()->id)) {
if ($view === 'portal') {
return true;
}
$user = \Auth::user();
if ($view !== 'admin' && (! $user || ($user_abo->user_id != $user->id && $user_abo->member_id != $user->id))) {
return false;
}
return true;
}
@ -100,8 +114,10 @@ class AboHelper
}
}
}
return false;
}
public static function getAboShowOn(Product $product)
{
$show_on = $product->show_on;
@ -111,8 +127,10 @@ class AboHelper
if (in_array('13', $show_on)) {
return 'upgrade';
}
return false;
}
public static function getAboTypeBadge($abo_type)
{
if ($abo_type === 'base') {
@ -121,6 +139,7 @@ class AboHelper
if ($abo_type === 'upgrade') {
return '<span class="badge badge-pill badge-info"><i class="far fa-star"></i> '.__('abo.'.$abo_type).'</span></a>';
}
return '';
}
@ -128,6 +147,7 @@ class AboHelper
{
$nextDate = Carbon::parse($date)->firstOfMonth();
$nextDate->addDays($abo_interval - 1);
return $nextDate->gt($date) ? $nextDate : $nextDate->addMonth(1);
}
@ -135,6 +155,7 @@ class AboHelper
{
$nextDate = Carbon::parse($date)->firstOfMonth()->addMonth(1);
$nextDate->addDays($abo_interval - 1);
return $nextDate->gt($date) ? $nextDate : $nextDate->addMonth(1);
}
@ -188,8 +209,10 @@ class AboHelper
'status' => 1,
]);
}
}
$user_abo->load('user_abo_items');
AboItemHistoryService::logInitialCreation($user_abo, 'system');
}
public static function getTransStatusFilterText()
{
@ -197,6 +220,71 @@ class AboHelper
foreach (self::$txaction_filter_text as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
/**
* Prüft effizient, ob ein User im Team eines anderen Users ist (Downline).
* Traversiert die Sponsor-Hierarchie rekursiv (m_sponsor) statt die komplette
* TreeCalcBot-Struktur aufzubauen.
*
* @param int $teamOwnerId ID des Team-Users (Berechtigter)
* @param int $userToCheckId ID des zu prüfenden Users (z.B. Abo-Besitzer)
* @param int $maxDepth Max. Tiefe (Schutz vor zirkulären Referenzen)
* @return bool True wenn userToCheckId im Team von teamOwnerId ist
*/
public static function isUserInTeam(int $teamOwnerId, int $userToCheckId, int $maxDepth = 100): bool
{
if ($teamOwnerId === $userToCheckId) {
return true;
}
$currentId = $userToCheckId;
$depth = 0;
while ($depth < $maxDepth) {
$currentUser = User::where('id', $currentId)->select('m_sponsor')->first();
if (! $currentUser || ! $currentUser->m_sponsor) {
return false;
}
if ($currentUser->m_sponsor === $teamOwnerId) {
return true;
}
$currentId = $currentUser->m_sponsor;
$depth++;
}
return false;
}
/**
* Liefert alle User-IDs im Team (Downline) eines Users.
* Traversiert die Sponsor-Hierarchie rekursiv nach unten statt TreeCalcBot.
*
* @param int $teamOwnerId ID des Team-Users
* @param int $maxDepth Max. Tiefe (Schutz vor Endlosschleifen)
* @return int[]
*/
public static function getTeamUserIds(int $teamOwnerId, int $maxDepth = 50): array
{
$teamUserIds = [];
$toProcess = [$teamOwnerId];
$depth = 0;
while (! empty($toProcess) && $depth < $maxDepth) {
$children = User::whereIn('m_sponsor', $toProcess)
->whereNull('deleted_at')
->pluck('id')
->toArray();
$teamUserIds = array_merge($teamUserIds, $children);
$toProcess = $children;
$depth++;
}
return array_values(array_unique($teamUserIds));
}
}

View file

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

View file

@ -2,24 +2,20 @@
namespace App\Services;
use Yard;
use App\User;
use Carbon\Carbon;
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\ShoppingUser;
use App\Models\UserAboOrder;
use App\Models\ShoppingOrder;
use App\Models\ShippingCountry;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserAboItem;
use App\User;
use Yard;
class AboOrderCart
{
private static $user_abo;
private static $is_for;
private static $customer_detail;
private static $is_for;
private static $customer_detail;
public static function initYard($user_abo)
{
@ -37,12 +33,12 @@ class AboOrderCart
\Log::info('AboOrderCart::initYard: Yard geleert', [
'abo_id' => $user_abo->id,
'items_vor_destroy' => $itemsBeforeDestroy
'items_vor_destroy' => $itemsBeforeDestroy,
]);
$itemsAfterDestroy = $yard->content()->count();
\Log::info('AboOrderCart::initYard: Yard geleert', [
'abo_id' => $user_abo->id,
'items_after_destroy' => $itemsAfterDestroy
'items_after_destroy' => $itemsAfterDestroy,
]);
self::$customer_detail = self::makeCustomerDetail($user_abo);
@ -56,6 +52,7 @@ class AboOrderCart
if ($country_id && $shipping_country = ShippingCountry::whereCountryId($country_id)->first()) {
if ($shipping_country->shipping && $shipping_country->shipping->active) {
UserService::initUserYard($user_abo->user, $shipping_country->id, 'abo-me');
return true;
}
}
@ -64,6 +61,7 @@ class AboOrderCart
if ($user_abo->is_for === 'ot') {
self::$is_for = 'abo-ot-customer';
UserService::initCustomerYard(self::$customer_detail, 'abo-ot-customer');
return true;
}
@ -90,7 +88,7 @@ class AboOrderCart
if ($itemsBefore > 0) {
\Log::warning('AboOrderCart::makeOrderYard: Yard war nicht leer vor makeOrderYard und wurde geleert', [
'abo_id' => $user_abo->id,
'items_before' => $itemsBefore
'items_before' => $itemsBefore,
]);
}
@ -105,9 +103,9 @@ class AboOrderCart
'id' => $item->id,
'product_id' => $item->product_id,
'qty' => $item->qty,
'comp' => $item->comp
'comp' => $item->comp,
];
})->toArray()
})->toArray(),
]);
foreach ($abo_items as $abo_item) {
@ -141,10 +139,11 @@ class AboOrderCart
'weight' => 0,
'points' => 0,
'comp' => $item->comp,
'product_id' => $product->id
'product_id' => $product->id,
]
);
Yard::setTax($cartItem->rowId, 0);
return true;
}
if (self::$is_for === 'ot-customer' || self::$is_for === 'abo-ot-customer') {
@ -156,7 +155,7 @@ class AboOrderCart
round($product->getPriceWith($tax_free, false, $user_country, false, self::$user_abo->user), 1),
false,
false,
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
} else {
$cartItem = Yard::instance('shopping')
@ -167,7 +166,7 @@ class AboOrderCart
$product->getPriceWith($tax_free, true, $user_country, false, self::$user_abo->user),
false,
false,
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'show_on' => $product->show_on]
['image' => '', 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points, 'no_commission' => $product->no_commission, 'no_free_shipping' => $product->no_free_shipping, 'show_on' => $product->show_on]
);
}
if ($tax_free) {
@ -200,6 +199,7 @@ class AboOrderCart
'qty' => 1,
'status' => 1,
]);
AboItemHistoryService::logSystemCompAdded($user_abo, $UserAboItem);
self::addProductToCart($UserAboItem);
}
}
@ -207,6 +207,7 @@ class AboOrderCart
if (count($UserAboItems) > $needNumComp) {
foreach ($UserAboItems as $UserAboItem) {
if ($UserAboItem->comp > $needNumComp) {
AboItemHistoryService::logSystemCompRemoved($user_abo, $UserAboItem);
$UserAboItem->delete();
}
}
@ -239,10 +240,10 @@ class AboOrderCart
$shopping_user = $user_abo->shopping_user->replicate();
\Log::info('AboOrderCart::makeCustomerDetail: ShoppingUser repliziert für Abo ID: '.$user_abo->id, [
'abo_id' => $user_abo->id,
'original_shopping_user_id' => $user_abo->shopping_user->id
'original_shopping_user_id' => $user_abo->shopping_user->id,
]);
} else {
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
\Log::info('AboOrderCart::makeCustomerDetail: Neuer ShoppingUser erstellt für Abo ID: '.$user_abo->id);
}
@ -258,6 +259,7 @@ class AboOrderCart
$shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email ?? null;
$shopping_user->language = $user->account->getLocale();
// Auth User ID setzen falls noch nicht gesetzt
if (! $shopping_user->auth_user_id) {
@ -296,6 +298,7 @@ class AboOrderCart
// look for the primary user of this abo
$shopping_user = $user_abo->shopping_user->replicate();
}
return $shopping_user;
}
}

View file

@ -100,6 +100,17 @@ class SalesPointsVolume
case 5: // Registrierung
$month_points = self::add_KP_TP_Points($userSalesVolume, $month_points);
$month_total_net += $userSalesVolume->total_net;
break;
case 6: // Storno - negative Punkte und Beträge
$month_points = self::add_KP_TP_Points($userSalesVolume, $month_points);
if ($userSalesVolume->status_turnover === 2) {
$month_shop_points += $userSalesVolume->points; // bereits negativ
$month_shop_total_net += $userSalesVolume->total_net; // bereits negativ
} else {
$month_total_net += $userSalesVolume->total_net; // bereits negativ
}
break;
}
$userSalesVolume->month_shop_points = $month_shop_points;
@ -255,4 +266,61 @@ class SalesPointsVolume
\Session()->flash('alert-success', 'Points hinzugefügt');
}
/**
* Erstellt einen Storno-Eintrag für eine stornierte Rechnung
* Negative Punkte werden dem aktuellen Monat zugeordnet
*
* @param UserSalesVolume $original_sales_volume Der ursprüngliche Sales Volume Eintrag
* @param int $cancellation_invoice_id Die ID der Stornorechnung
* @return UserSalesVolume
*/
public static function cancelSalesPointsVolume(UserSalesVolume $original_sales_volume, $cancellation_invoice_id)
{
$month = date('m');
$year = date('Y');
$date = date('d.m.Y');
$syslog = [
date('d.m.Y H:i:s') => 'Stornorechnung erstellt - Punkte korrigiert (Original Invoice: #'.$original_sales_volume->user_invoice_id.')',
];
// Negativen Eintrag erstellen (alle Werte negativ)
$cancellation_sales_volume = UserSalesVolume::create([
'user_id' => $original_sales_volume->user_id,
'shopping_order_id' => $original_sales_volume->shopping_order_id,
'user_invoice_id' => $cancellation_invoice_id,
'month' => $month,
'year' => $year,
'date' => $date,
'points' => -$original_sales_volume->points, // Negativ!
'month_points' => 0, // Wird durch reCalculate gesetzt
'month_KP_points' => 0,
'month_TP_points' => 0,
'month_shop_points' => 0,
'total_net' => -$original_sales_volume->total_net, // Negativ!
'month_total_net' => 0,
'status' => 6, // Status 6 = cancelled/storniert
'status_points' => $original_sales_volume->status_points,
'status_turnover' => $original_sales_volume->status_turnover,
'message' => 'Storniert am '.date('d.m.Y'),
'info' => 'Storno für Invoice #'.$original_sales_volume->user_invoice_id,
'syslog' => $syslog,
]);
// Neuberechnung für aktuellen Monat
self::reCalculateSalesPointsVolume($original_sales_volume->user_id, $month, $year);
\Log::info('Punktekorrektur für Stornorechnung durchgeführt', [
'original_invoice_id' => $original_sales_volume->user_invoice_id,
'cancellation_invoice_id' => $cancellation_invoice_id,
'original_points' => $original_sales_volume->points,
'cancellation_points' => $cancellation_sales_volume->points,
'user_id' => $original_sales_volume->user_id,
'month' => $month,
'year' => $year,
]);
return $cancellation_sales_volume;
}
}

View file

@ -1,53 +1,78 @@
<?php
namespace App\Services;
use App\Services\Util;
use App\Models\Setting;
use App\Mail\MailCredit;
use App\Models\Setting;
use App\Models\UserCredit;
use Illuminate\Support\Facades\Mail;
class Credit
{
public static function getCreditNumber(){
public static function getCreditNumber()
{
// return (int) Setting::getContentBySlug('credit-number');
return (int) Setting::getContentBySlug('invoice-number');
}
public static function makeNextCreditNumber(){
public static function makeNextCreditNumber()
{
$credit_number = self::getCreditNumber();
$credit_number = $credit_number + 1;
// Setting::setContentBySlug('credit-number', $credit_number, 'int');
Setting::setContentBySlug('invoice-number', $credit_number, 'int');
return $credit_number;
}
public static function createCreditNumber($credit_number, $credit_date){
public static function createCreditNumber($credit_number, $credit_date)
{
$prefix = "GS".\Carbon::parse($credit_date)->format('Y');
$prefix = 'GS'.\Carbon::parse($credit_date)->format('Y');
$credit_number = str_pad($credit_number, 5, '0', STR_PAD_LEFT);
return $prefix.$credit_number;
}
public static function getCreditStorageDir($credit_date){
return "/credit/".\Carbon::parse($credit_date)->format('Y/m/');
public static function getCreditStorageDir($credit_date)
{
return '/credit/'.\Carbon::parse($credit_date)->format('Y/m/');
}
public static function getCreditDetailStorageDir($credit_date){
return "/credit_details/".\Carbon::parse($credit_date)->format('Y/m/');
public static function getCreditDetailStorageDir($credit_date)
{
return '/credit_details/'.\Carbon::parse($credit_date)->format('Y/m/');
}
public static function makeCreditFilename($credit_number){
return $credit_number."-MIVITA-Gutschrift.pdf";
public static function makeCreditFilename($credit_number)
{
return $credit_number.'-MIVITA-Gutschrift.pdf';
}
public static function makeCreditDetailFilename($credit_number){
return $credit_number."-MIVITA-Report.pdf";
public static function makeCreditDetailFilename($credit_number)
{
return $credit_number.'-MIVITA-Report.pdf';
}
public static function isCredit(UserCredit $user_credit){
/**
* Erstellt den Dateinamen für eine lokalisierte Gutschrift.
* Deutsch (de) ist das Original ohne Suffix.
*
* @param string $credit_number
* @param string $locale
* @return string
*/
public static function makeCreditFilenameLocale($credit_number, $locale)
{
if ($locale === 'de' || ! $locale) {
return self::makeCreditFilename($credit_number);
}
return $credit_number.'-MIVITA-Gutschrift-'.$locale.'.pdf';
}
public static function isCredit(UserCredit $user_credit)
{
return $user_credit->isCredit();
}
@ -73,7 +98,8 @@ class Credit
return \Storage::disk('public')->path($dir.$filename);
}*/
public static function sendCreditMail(UserCredit $user_credit){
public static function sendCreditMail(UserCredit $user_credit)
{
$bcc = [];
$email = $user_credit->user->email;
if (! $email) {

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

@ -2,13 +2,12 @@
namespace App\Services;
use App\Models\ShoppingUser;
use App\Models\ShoppingInstance;
use App\Models\ShoppingUser;
use Yard;
class OrderPaymentService
{
public static function deleteInstance($identifier)
{
@ -42,6 +41,7 @@ class OrderPaymentService
if (! $shopping_instance) {
return false;
}
return $shopping_instance->getStatus();
}
@ -54,22 +54,28 @@ class OrderPaymentService
if ($isFor === 'ot-customer') {
return ' <span class="badge badge-pill badge-secondary">'.__('order.order').'</span>';
}
return "";
return '';
}
public static function getStatusBadgeClasses()
{
return [
'link_sent' => 'default',
'link_openly' => 'info',
'link_check' => 'warning',
'link_pending' => 'warning',
'link_appointed' => 'warning',
'link_paid' => 'secondary',
'link_failed' => 'danger',
'link_canceled' => 'danger',
];
}
public static function getStatusBadge(ShoppingInstance $shoppingInstance)
{
$status = $shoppingInstance->getStatus();
$badgeClasses = [
'link_sent' => 'info',
'link_openly' => 'info',
'link_paid' => 'secondary',
'link_check' => 'warning',
'link_pending' => 'warning',
'link_appointed' => 'warning',
'link_failed' => 'danger',
'link_canceled' => 'danger'
];
$badgeClasses = self::getStatusBadgeClasses();
if (isset($badgeClasses[$status])) {
return sprintf(
@ -130,6 +136,7 @@ class OrderPaymentService
'is_for' => $shopping_instance->shopping_data['is_for'] ?? false,
'backlink' => false,
];
return $data;
}
@ -145,7 +152,6 @@ class OrderPaymentService
Yard::instance('shopping')->setUserPriceInfos($shopping_instance->shopping_data['user_price_infos']);
Yard::instance('shopping')->setShippingCountryWithPrice($shopping_instance->country_id, $is_for);
$rows = Yard::instance('shopping')->getContentByOrder();
$ret = [];
$ret['items'] = [];
@ -154,12 +160,12 @@ class OrderPaymentService
foreach ($rows as $row) {
$product = \App\Models\Product::find($row->id);
$item = new \stdClass();
$item = new \stdClass;
$item->image = $row->options->has('image') ? $row->options->image : null;
$item->price_net = (float) Yard::instance('shopping')->rowPriceNet($row, 3, '.', '');
$item->price_net_total = (float) Yard::instance('shopping')->rowSubtotalNet($row, 2, '.', '');
$item->price_currency = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('rowPriceNetCurrency', $row, 3) . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency_total = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('rowSubtotalCurrency', $row, 3) . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('rowPriceNetCurrency', $row, 3).' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price_currency_total = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('rowSubtotalCurrency', $row, 3).' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$item->price = $row->price;
$item->price_total = ($row->qty * $row->price);
$item->qty = $row->qty;
@ -174,16 +180,16 @@ class OrderPaymentService
$ret['tax_free'] = $tax_free;
$ret['total']['subtotal'] = Yard::instance('shopping')->subtotal();
$ret['total']['subtotal_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('subtotal') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotal_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('subtotal').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['shippingCountryName'] = Yard::instance('shopping')->getShippingCountryName();
$ret['total']['shippingNet'] = Yard::instance('shopping')->shippingNet();
$ret['total']['shippingNet currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('shippingNet') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['shippingNet currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('shippingNet').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotalWithShipping'] = Yard::instance('shopping')->subtotalWithShipping();
$ret['total']['subtotalWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('subtotalWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['subtotalWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('subtotalWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['taxWithShipping'] = Yard::instance('shopping')->taxWithShipping();
$ret['total']['taxWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('taxWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['taxWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('taxWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['totalWithShipping'] = Yard::instance('shopping')->totalWithShipping();
$ret['total']['totalWithShipping_currency'] = $is_currency ? "~" . Yard::instance('shopping')->getCurrencyByKey('totalWithShipping') . " " . Yard::instance('shopping')->getPriceCurrencyUnit() : null;
$ret['total']['totalWithShipping_currency'] = $is_currency ? '~'.Yard::instance('shopping')->getCurrencyByKey('totalWithShipping').' '.Yard::instance('shopping')->getPriceCurrencyUnit() : null;
return $ret;
}

View file

@ -2,7 +2,6 @@
namespace App\Services;
use App\Mail\MailCheckout;
use App\Models\ProductBuying;
use App\Models\ShoppingOrder;
@ -10,17 +9,12 @@ use App\Models\ShoppingPayment;
use App\Models\UserCreditItem;
use App\Models\UserLevel;
use App\Repositories\InvoiceRepository;
use App\Services\AboHelper;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\ShopApiOrderCart;
use App\Services\UserUtil;
use App\Services\Util;
use App\User;
use Illuminate\Support\Facades\Mail;
class Payment
{
public static $txaction_text = [
'paid' => 'paid',
'appointed' => 'open',
@ -30,6 +24,7 @@ class Payment
'invoice_open' => 'open',
'invoice_paid' => 'paid',
'invoice_non' => 'no_payment',
'cancelled' => 'cancelled',
'NULL' => 'no_payment',
];
@ -42,6 +37,7 @@ class Payment
'invoice_open' => 'invoice_open',
'invoice_paid' => 'invoice_paid',
'invoice_non' => 'invoice_no_payment',
'cancelled' => 'cancelled',
'NULL' => 'no_payment',
];
@ -60,14 +56,15 @@ class Payment
'invoice_open' => 'warning',
'invoice_paid' => 'success',
'invoice_non' => 'failed',
'cancelled' => 'danger',
];
public static function getFormattedTxaction($txaction)
{
if ($txaction && isset(self::$txaction_text[$txaction])) {
return __('payment.'.self::$txaction_text[$txaction]);
}
return __('payment.'.self::$txaction_text['NULL']);
}
@ -76,7 +73,8 @@ class Payment
if ($txaction && isset(self::$txaction_color[$txaction])) {
return self::$txaction_color[$txaction];
}
return "warning";
return 'warning';
}
public static function getTransTxactionFilterText()
@ -85,6 +83,7 @@ class Payment
foreach (self::$txaction_filter_text as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
@ -94,6 +93,7 @@ class Payment
foreach (self::$txaction_invoice as $key => $val) {
$ret[$key] = trans('payment.'.$val);
}
return $ret;
}
@ -106,6 +106,7 @@ class Payment
if ($shopping_order->mode === 'dev') {
return '<span class="badge badge-pill badge-info">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_order->txaction).'">'.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
@ -115,6 +116,7 @@ class Payment
if ($shopping_order->is_abo) {
$abo = ' <span class="badge badge-pill badge-success">'.__('abo.abo').'</span>';
}
return '<span class="badge badge-pill badge-'.$shopping_order->getPaymentForColor().'">'.$shopping_order->getPaymentForType().'</span>'.$abo;
}
@ -123,6 +125,7 @@ class Payment
if ($shopping_payment->mode === 'test') {
return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_payment->mode).' - '.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
}
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_payment->txaction).'">'.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
}
@ -143,7 +146,7 @@ class Payment
ProductBuying::create([
'user_id' => $user->id,
'product_id' => $product_id,
'amount' => 1
'amount' => 1,
]);
}
@ -157,7 +160,7 @@ class Payment
'points' => $product->sponsor_buying_points_amount,
'info' => 'VP: '.$user->getFullName(false).' | '.$product->name,
'status_points' => 2,
'status' => 5
'status' => 5,
];
SalesPointsVolume::addSalesPointsVolume($data);
}
@ -210,8 +213,10 @@ class Payment
$date = \Carbon::parse($user->payment_account)->modify('1 year');
}
foreach ($shopping_order_item->product->action as $do) {
// bzw. product_id 34 = 0 => payment_for_account => payment_order_id = 35 = 0 => payment_for_account, 1 => payment_for_shop, 2 => payment_for_shop_upgrade
// 0 => payment_for_account, 1 => payment_for_shop, 2 => payment_for_shop_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_account') {
$user->payment_order_id = $shopping_order_item->product->id; //34
$user->payment_order_id = $shopping_order_item->product->id;
$user->payment_account = $date;
$user->wizard = 100;
// only date is > now and acount is deactive.
@ -224,12 +229,14 @@ class Payment
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 1 => payment_for_shop
if ($shopping_order_item->product->getActionName($do) === 'payment_for_shop') {
$user->payment_order_id = $shopping_order_item->product->id; // 35
$user->payment_shop = $date;
$user->wizard = 100;
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 2 => payment_for_shop_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_shop_upgrade') {
if ($shopping_order_item->product->upgrade_to_id) {
$user->payment_order_id = $shopping_order_item->product->upgrade_to_id;
@ -237,6 +244,7 @@ class Payment
$user->payment_shop = $user->payment_account; // same Date, is upgrade
$shopping_order->setUserHistoryValue(['status' => 9]);
}
// 4 => payment_for_lead_upgrade
if ($shopping_order_item->product->getActionName($do) === 'payment_for_lead_upgrade') {
if ($shopping_order_item->product->upgrade_to_id) {
self::updateUserLevel($user, $shopping_order_item->product->upgrade_to_id);
@ -259,20 +267,26 @@ class Payment
$shopping_order->setUserHistoryValue(['status' => 9]);
ShopApiOrderCart::finishOrder($shopping_order->shopping_collect_order);
}
//the Order is Pay, so we can set the Status in the Abo
if ($shopping_order->is_abo) {
// Set payment link status to paid for all orders
if ($shopping_payment) {
Util::setInstanceStatusByPayment($shopping_payment, 10); // link_paid
$shopping_payment->identifier = null;
$shopping_payment->save();
}
// the Order is Pay, so we can set the Status in the Abo
if ($shopping_order->is_abo) {
AboHelper::setAboActive($shopping_order, 2, true);
}
// make Invoice is not exist and is live
if ($shopping_order->mode === 'live' || Util::isTestSystem(true)) {
$invoice_repo = new InvoiceRepository($shopping_order);
// Reload the shopping order to check for invoice again (defense against race conditions)
$shopping_order->refresh();
if (! $shopping_order->isInvoice()) {
$invoice_repo = new InvoiceRepository($shopping_order);
$invoice_repo->createAndSalesVolume();
}
}
@ -295,7 +309,7 @@ class Payment
}
}
if (! filter_var($billing_email, FILTER_VALIDATE_EMAIL)) {
\Log::channel('payment')->error("Invalid billing email at shopping_order " . $shopping_order->id, ['billing_email' => $billing_email]);
\Log::channel('payment')->error('Invalid billing email at shopping_order '.$shopping_order->id, ['billing_email' => $billing_email]);
$billing_email = config('app.checkout_mail');
}

View file

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

View file

@ -2,7 +2,6 @@
namespace App\Services;
use App\Http\Controllers\Api\KasController;
use App\Models\ShoppingUser;
use App\Models\ShoppingUserMemberLog;
@ -12,8 +11,6 @@ use App\User;
class UserUtil
{
public static function setShoppingUserToNewMember($pre_member_id, $new_member_id)
{
$ShoppingUsers = ShoppingUser::where('member_id', $pre_member_id)->get();
@ -21,7 +18,7 @@ class UserUtil
ShoppingUserMemberLog::create([
'pre_member_id' => $shopping_user->member_id,
'shopping_user_id' => $shopping_user->id,
'new_member_id' => $new_member_id
'new_member_id' => $new_member_id,
]);
$shopping_user->member_id = $new_member_id;
$shopping_user->save();
@ -72,10 +69,22 @@ class UserUtil
{
$user = User::find($user_id);
if ($user) {
if (! $user) {
\Log::channel('cleanup')->error('setUserToClient: User not found, user_id: '.$user_id);
return false;
}
if (! $user->account) {
\Log::channel('cleanup')->error('setUserToClient: User has no account data, user_id: '.$user_id);
return false;
}
try {
$data = [
'member_id' => $sponsor_id,
'language' => $user->lang ? $user->lang : 'de',
'language' => $user->lang ?? 'de',
'billing_salutation' => $user->account->salutation,
'billing_company' => $user->account->company,
'billing_firstname' => $user->account->first_name,
@ -87,6 +96,7 @@ class UserUtil
'billing_country_id' => $user->account->country_id,
'billing_phone' => $user->account->getPhoneNumber(),
'billing_email' => $user->email,
'language' => $user->account->getLocale(),
'same_as_billing' => $user->account->same_as_billing,
'shipping_salutation' => $user->account->shipping_salutation,
'shipping_company' => $user->account->shipping_company,
@ -100,10 +110,16 @@ class UserUtil
'shipping_phone' => $user->account->getShippingPhoneFull(),
'shipping_postnumber' => $user->account->shipping_postnumber,
];
ShoppingUser::create($data);
}
}
ShoppingUser::create($data);
return true;
} catch (\Exception $e) {
\Log::channel('cleanup')->error('setUserToClient failed for user_id: '.$user_id.' | Error: '.$e->getMessage());
return false;
}
}
/*
find next activ sponsor on user id
@ -126,6 +142,7 @@ class UserUtil
if ($user->pre_sponsor) { // hat der User einen pre_sponsor - schon inaktiv
return self::findNextActiveSponsor($user->pre_sponsor);
}
// dump('not sponsor');
return $user;
}
@ -155,8 +172,8 @@ class UserUtil
// shop wird gelöscht
if ($user->shop) {
// $subdomain_name = $user->shop->slug . '.mivita.care';
$user->shop->name = "delete" . $user->shop->id;
$user->shop->slug = "delete" . $user->shop->id;
$user->shop->name = 'delete'.$user->shop->id;
$user->shop->slug = 'delete'.$user->shop->id;
$user->shop->save();
$user->shop->delete();
// isset KAS - delete Subdomain
@ -170,11 +187,11 @@ class UserUtil
}
// user soll nicht komplett gelöscht werden
$user->email = "delete-" . $user->email;
$user->email = 'delete-'.$user->email;
// password wird gelöscht
$user->password = "delete" . time();
$user->password = 'delete'.time();
$user->confirmed = 0;
$user->confirmation_code = "delete" . time();
$user->confirmation_code = 'delete'.time();
$user->confirmation_date = null;
$user->confirmation_code_to = null;
$user->confirmation_code_remider = 2;
@ -187,7 +204,7 @@ class UserUtil
$user->pre_deleted_at = now();
// user soll komplett gelöscht werden
if ($complete) {
$user->email = "delete-" . time() . "-" . rand(1000, 9999);
$user->email = 'delete-'.time().'-'.rand(1000, 9999);
if ($user->account) {
$user->account->delete();
}
@ -198,14 +215,16 @@ class UserUtil
return true;
}
public static function checkEmailExists($user)
{
$email = str_replace("delete-", "", $user->email);
$email = str_replace('delete-', '', $user->email);
$user = User::where('email', $email)->first();
if ($user) {
return 'Der Account kann nicht wieder hergestellt werden, da die E-Mail-Adresse <b>'.$email.'</b> bereits in Verwendung ist.';
}
return null;
}
@ -217,7 +236,7 @@ class UserUtil
$user->pre_sponsor = null;
}
$user->email = str_replace("delete-", "", $user->email);
$user->email = str_replace('delete-', '', $user->email);
$user->confirmed = 1;
$user->confirmation_date = now();
$user->confirmation_code = null;
@ -242,13 +261,13 @@ class UserUtil
}
}
public static function reactiveUserResetChilds($user_id, $info = '')
{
$user = User::find($user_id);
if (! $user) {
\Log::channel('cleanup')->error('reactiveUserResetChilds find no user by user_id:'.$user_id);
return 0;
}
$data = [
@ -270,6 +289,7 @@ class UserUtil
$user = User::find($user_id);
if (! $user) {
\Log::channel('cleanup')->error('deactiveUserNewSponsorChilds find no user by user_id:'.$user_id);
return 0;
}
$data = [

View file

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

12
boost.json Normal file
View file

@ -0,0 +1,12 @@
{
"agents": [
"claude_code",
"cursor"
],
"editors": [
"claude_code",
"cursor"
],
"guidelines": [],
"sail": true
}

9
bootstrap/cache/events.php vendored Normal file
View file

@ -0,0 +1,9 @@
<?php return array (
'App\\Providers\\EventServiceProvider' =>
array (
'App\\Events\\Event' =>
array (
0 => 'App\\Listeners\\EventListener',
),
),
);

View file

@ -66,6 +66,13 @@
0 => 'Laracasts\\Flash\\FlashServiceProvider',
),
),
'laravel/boost' =>
array (
'providers' =>
array (
0 => 'Laravel\\Boost\\BoostServiceProvider',
),
),
'laravel/horizon' =>
array (
'aliases' =>
@ -84,6 +91,17 @@
0 => 'Illuminate\\Database\\Eloquent\\LegacyFactoryServiceProvider',
),
),
'laravel/mcp' =>
array (
'aliases' =>
array (
'Mcp' => 'Laravel\\Mcp\\Server\\Facades\\Mcp',
),
'providers' =>
array (
0 => 'Laravel\\Mcp\\Server\\McpServiceProvider',
),
),
'laravel/passport' =>
array (
'providers' =>
@ -91,6 +109,13 @@
0 => 'Laravel\\Passport\\PassportServiceProvider',
),
),
'laravel/roster' =>
array (
'providers' =>
array (
0 => 'Laravel\\Roster\\RosterServiceProvider',
),
),
'laravel/sail' =>
array (
'providers' =>

View file

@ -31,32 +31,35 @@
27 => 'JoeDixon\\Translation\\TranslationServiceProvider',
28 => 'JoeDixon\\Translation\\TranslationBindingsServiceProvider',
29 => 'Laracasts\\Flash\\FlashServiceProvider',
30 => 'Laravel\\Horizon\\HorizonServiceProvider',
31 => 'Illuminate\\Database\\Eloquent\\LegacyFactoryServiceProvider',
32 => 'Laravel\\Passport\\PassportServiceProvider',
33 => 'Laravel\\Sail\\SailServiceProvider',
34 => 'Laravel\\Tinker\\TinkerServiceProvider',
35 => 'Laravel\\Ui\\UiServiceProvider',
36 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
37 => 'Carbon\\Laravel\\ServiceProvider',
38 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
39 => 'Termwind\\Laravel\\TermwindServiceProvider',
40 => 'Pest\\Laravel\\PestServiceProvider',
41 => 'Spatie\\Html\\HtmlServiceProvider',
42 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
43 => 'Yajra\\DataTables\\DataTablesServiceProvider',
44 => 'Laravel\\Tinker\\TinkerServiceProvider',
45 => 'Acme\\Dhl\\DhlServiceProvider',
46 => 'App\\Providers\\AppServiceProvider',
47 => 'App\\Providers\\AuthServiceProvider',
48 => 'App\\Providers\\EventServiceProvider',
49 => 'App\\Providers\\HorizonServiceProvider',
50 => 'App\\Providers\\RouteServiceProvider',
51 => 'Jenssegers\\Date\\DateServiceProvider',
52 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
53 => 'Yajra\\DataTables\\DataTablesServiceProvider',
54 => 'App\\Providers\\YardServiceProvider',
55 => 'Alban\\LaravelCollectiveSpatieHtmlParser\\ServiceProvider',
30 => 'Laravel\\Boost\\BoostServiceProvider',
31 => 'Laravel\\Horizon\\HorizonServiceProvider',
32 => 'Illuminate\\Database\\Eloquent\\LegacyFactoryServiceProvider',
33 => 'Laravel\\Mcp\\Server\\McpServiceProvider',
34 => 'Laravel\\Passport\\PassportServiceProvider',
35 => 'Laravel\\Roster\\RosterServiceProvider',
36 => 'Laravel\\Sail\\SailServiceProvider',
37 => 'Laravel\\Tinker\\TinkerServiceProvider',
38 => 'Laravel\\Ui\\UiServiceProvider',
39 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
40 => 'Carbon\\Laravel\\ServiceProvider',
41 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
42 => 'Termwind\\Laravel\\TermwindServiceProvider',
43 => 'Pest\\Laravel\\PestServiceProvider',
44 => 'Spatie\\Html\\HtmlServiceProvider',
45 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
46 => 'Yajra\\DataTables\\DataTablesServiceProvider',
47 => 'Laravel\\Tinker\\TinkerServiceProvider',
48 => 'Acme\\Dhl\\DhlServiceProvider',
49 => 'App\\Providers\\AppServiceProvider',
50 => 'App\\Providers\\AuthServiceProvider',
51 => 'App\\Providers\\EventServiceProvider',
52 => 'App\\Providers\\HorizonServiceProvider',
53 => 'App\\Providers\\RouteServiceProvider',
54 => 'Jenssegers\\Date\\DateServiceProvider',
55 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
56 => 'Yajra\\DataTables\\DataTablesServiceProvider',
57 => 'App\\Providers\\YardServiceProvider',
58 => 'Alban\\LaravelCollectiveSpatieHtmlParser\\ServiceProvider',
),
'eager' =>
array (
@ -76,29 +79,32 @@
13 => 'Jenssegers\\Date\\DateServiceProvider',
14 => 'JoeDixon\\Translation\\TranslationServiceProvider',
15 => 'Laracasts\\Flash\\FlashServiceProvider',
16 => 'Laravel\\Horizon\\HorizonServiceProvider',
17 => 'Illuminate\\Database\\Eloquent\\LegacyFactoryServiceProvider',
18 => 'Laravel\\Passport\\PassportServiceProvider',
19 => 'Laravel\\Ui\\UiServiceProvider',
20 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
21 => 'Carbon\\Laravel\\ServiceProvider',
22 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
23 => 'Termwind\\Laravel\\TermwindServiceProvider',
24 => 'Pest\\Laravel\\PestServiceProvider',
25 => 'Spatie\\Html\\HtmlServiceProvider',
26 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
27 => 'Yajra\\DataTables\\DataTablesServiceProvider',
28 => 'Acme\\Dhl\\DhlServiceProvider',
29 => 'App\\Providers\\AppServiceProvider',
30 => 'App\\Providers\\AuthServiceProvider',
31 => 'App\\Providers\\EventServiceProvider',
32 => 'App\\Providers\\HorizonServiceProvider',
33 => 'App\\Providers\\RouteServiceProvider',
34 => 'Jenssegers\\Date\\DateServiceProvider',
35 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
36 => 'Yajra\\DataTables\\DataTablesServiceProvider',
37 => 'App\\Providers\\YardServiceProvider',
38 => 'Alban\\LaravelCollectiveSpatieHtmlParser\\ServiceProvider',
16 => 'Laravel\\Boost\\BoostServiceProvider',
17 => 'Laravel\\Horizon\\HorizonServiceProvider',
18 => 'Illuminate\\Database\\Eloquent\\LegacyFactoryServiceProvider',
19 => 'Laravel\\Mcp\\Server\\McpServiceProvider',
20 => 'Laravel\\Passport\\PassportServiceProvider',
21 => 'Laravel\\Roster\\RosterServiceProvider',
22 => 'Laravel\\Ui\\UiServiceProvider',
23 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
24 => 'Carbon\\Laravel\\ServiceProvider',
25 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
26 => 'Termwind\\Laravel\\TermwindServiceProvider',
27 => 'Pest\\Laravel\\PestServiceProvider',
28 => 'Spatie\\Html\\HtmlServiceProvider',
29 => 'Spatie\\LaravelIgnition\\IgnitionServiceProvider',
30 => 'Yajra\\DataTables\\DataTablesServiceProvider',
31 => 'Acme\\Dhl\\DhlServiceProvider',
32 => 'App\\Providers\\AppServiceProvider',
33 => 'App\\Providers\\AuthServiceProvider',
34 => 'App\\Providers\\EventServiceProvider',
35 => 'App\\Providers\\HorizonServiceProvider',
36 => 'App\\Providers\\RouteServiceProvider',
37 => 'Jenssegers\\Date\\DateServiceProvider',
38 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
39 => 'Yajra\\DataTables\\DataTablesServiceProvider',
40 => 'App\\Providers\\YardServiceProvider',
41 => 'Alban\\LaravelCollectiveSpatieHtmlParser\\ServiceProvider',
),
'deferred' =>
array (

View file

@ -33,6 +33,7 @@
"barryvdh/laravel-debugbar": "^3.13",
"barryvdh/laravel-ide-helper": "^3.6",
"fakerphp/faker": "^1.23",
"laravel/boost": "^1.8",
"laravel/pint": "^1.0",
"laravel/sail": "^1.44",
"mockery/mockery": "^1.6.2",

249
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "925483d8104ae55ae4bf5fd0ada18726",
"content-hash": "90b6546de8df440433d5fe91b858d196",
"packages": [
{
"name": "barryvdh/laravel-dompdf",
@ -9605,6 +9605,53 @@
},
"time": "2025-04-30T06:54:44+00:00"
},
{
"name": "illuminate/json-schema",
"version": "v12.52.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/json-schema.git",
"reference": "d161f398dab36f08cf131997362bc2e3ecb0309a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/json-schema/zipball/d161f398dab36f08cf131997362bc2e3ecb0309a",
"reference": "d161f398dab36f08cf131997362bc2e3ecb0309a",
"shasum": ""
},
"require": {
"illuminate/contracts": "^10.50.0|^11.47.0|^12.40.2",
"php": "^8.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
}
},
"autoload": {
"psr-4": {
"Illuminate\\JsonSchema\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "The Illuminate Json Schema package.",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2025-11-28T18:45:48+00:00"
},
{
"name": "jean85/pretty-package-versions",
"version": "2.1.1",
@ -9665,6 +9712,145 @@
},
"time": "2025-03-19T14:43:43+00:00"
},
{
"name": "laravel/boost",
"version": "v1.8.11",
"source": {
"type": "git",
"url": "https://github.com/laravel/boost.git",
"reference": "485dd7c834bde865a8a174249fc6ffc56e79e63c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/boost/zipball/485dd7c834bde865a8a174249fc6ffc56e79e63c",
"reference": "485dd7c834bde865a8a174249fc6ffc56e79e63c",
"shasum": ""
},
"require": {
"guzzlehttp/guzzle": "^7.9",
"illuminate/console": "^10.49.0|^11.45.3|^12.41.1",
"illuminate/contracts": "^10.49.0|^11.45.3|^12.41.1",
"illuminate/routing": "^10.49.0|^11.45.3|^12.41.1",
"illuminate/support": "^10.49.0|^11.45.3|^12.41.1",
"laravel/mcp": "^0.5.1",
"laravel/prompts": "0.1.25|^0.3.6",
"laravel/roster": "^0.2.9",
"php": "^8.1"
},
"require-dev": {
"laravel/pint": "^1.20.0",
"mockery/mockery": "^1.6.12",
"orchestra/testbench": "^8.36.0|^9.15.0|^10.6",
"pestphp/pest": "^2.36.0|^3.8.4|^4.1.5",
"phpstan/phpstan": "^2.1.27",
"rector/rector": "^2.1"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Laravel\\Boost\\BoostServiceProvider"
]
},
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"Laravel\\Boost\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.",
"homepage": "https://github.com/laravel/boost",
"keywords": [
"ai",
"dev",
"laravel"
],
"support": {
"issues": "https://github.com/laravel/boost/issues",
"source": "https://github.com/laravel/boost"
},
"time": "2026-02-20T07:28:22+00:00"
},
{
"name": "laravel/mcp",
"version": "v0.5.9",
"source": {
"type": "git",
"url": "https://github.com/laravel/mcp.git",
"reference": "39e8da60eb7bce4737c5d868d35a3fe78938c129"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/mcp/zipball/39e8da60eb7bce4737c5d868d35a3fe78938c129",
"reference": "39e8da60eb7bce4737c5d868d35a3fe78938c129",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-mbstring": "*",
"illuminate/console": "^11.45.3|^12.41.1|^13.0",
"illuminate/container": "^11.45.3|^12.41.1|^13.0",
"illuminate/contracts": "^11.45.3|^12.41.1|^13.0",
"illuminate/http": "^11.45.3|^12.41.1|^13.0",
"illuminate/json-schema": "^12.41.1|^13.0",
"illuminate/routing": "^11.45.3|^12.41.1|^13.0",
"illuminate/support": "^11.45.3|^12.41.1|^13.0",
"illuminate/validation": "^11.45.3|^12.41.1|^13.0",
"php": "^8.2"
},
"require-dev": {
"laravel/pint": "^1.20",
"orchestra/testbench": "^9.15|^10.8|^11.0",
"pestphp/pest": "^3.8.5|^4.3.2",
"phpstan/phpstan": "^2.1.27",
"rector/rector": "^2.2.4"
},
"type": "library",
"extra": {
"laravel": {
"aliases": {
"Mcp": "Laravel\\Mcp\\Server\\Facades\\Mcp"
},
"providers": [
"Laravel\\Mcp\\Server\\McpServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Laravel\\Mcp\\": "src/",
"Laravel\\Mcp\\Server\\": "src/Server/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "Rapidly build MCP servers for your Laravel applications.",
"homepage": "https://github.com/laravel/mcp",
"keywords": [
"laravel",
"mcp"
],
"support": {
"issues": "https://github.com/laravel/mcp/issues",
"source": "https://github.com/laravel/mcp"
},
"time": "2026-02-17T19:05:53+00:00"
},
{
"name": "laravel/pint",
"version": "v1.27.0",
@ -9732,6 +9918,67 @@
},
"time": "2026-01-05T16:49:17+00:00"
},
{
"name": "laravel/roster",
"version": "v0.2.9",
"source": {
"type": "git",
"url": "https://github.com/laravel/roster.git",
"reference": "82bbd0e2de614906811aebdf16b4305956816fa6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/roster/zipball/82bbd0e2de614906811aebdf16b4305956816fa6",
"reference": "82bbd0e2de614906811aebdf16b4305956816fa6",
"shasum": ""
},
"require": {
"illuminate/console": "^10.0|^11.0|^12.0",
"illuminate/contracts": "^10.0|^11.0|^12.0",
"illuminate/routing": "^10.0|^11.0|^12.0",
"illuminate/support": "^10.0|^11.0|^12.0",
"php": "^8.1|^8.2",
"symfony/yaml": "^6.4|^7.2"
},
"require-dev": {
"laravel/pint": "^1.14",
"mockery/mockery": "^1.6",
"orchestra/testbench": "^8.22.0|^9.0|^10.0",
"pestphp/pest": "^2.0|^3.0",
"phpstan/phpstan": "^2.0"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Laravel\\Roster\\RosterServiceProvider"
]
},
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"Laravel\\Roster\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Detect packages & approaches in use within a Laravel project",
"homepage": "https://github.com/laravel/roster",
"keywords": [
"dev",
"laravel"
],
"support": {
"issues": "https://github.com/laravel/roster/issues",
"source": "https://github.com/laravel/roster"
},
"time": "2025-10-20T09:56:46+00:00"
},
{
"name": "laravel/sail",
"version": "v1.52.0",

141
config/datev.php Normal file
View file

@ -0,0 +1,141 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| DATEV EXTF Export Konfiguration
|--------------------------------------------------------------------------
|
| Zentrale Konfiguration für den DATEV-Buchungsstapel-Export im EXTF-Format.
| Header-Daten, Konten-Mappings, Steuerschlüssel und Gegenkonten.
|
*/
// DATEV Header-Daten
'berater_nr' => env('DATEV_BERATER_NR', ''),
'mandant_nr' => env('DATEV_MANDANT_NR', ''),
'format_version' => 700,
'format_category' => 21, // 21 = Buchungsstapel
'format_name' => 'Buchungsstapel',
'currency' => 'EUR',
// Datenquelle (wird im Header geschrieben)
'source' => 'ERP',
'source_name' => env('DATEV_SOURCE_NAME', 'MIVITA'),
// Sachkontenlänge (DATEV-Standard: 4)
'sachkontenlaenge' => 4,
/*
|--------------------------------------------------------------------------
| Sammelkonten (Phase 1)
|--------------------------------------------------------------------------
*/
'sammeldebitor' => env('DATEV_SAMMELDEBITOR', '10000'),
'sammelkreditor' => env('DATEV_SAMMELKREDITOR', '70000'),
/*
|--------------------------------------------------------------------------
| Umsatzerlöse: Steuerfall -> [konto, bu_schluessel]
|--------------------------------------------------------------------------
|
| Mapping basierend auf Steuersatz und Lieferland-Typ:
| - domestic_19: Inland 19% USt
| - domestic_7: Inland 7% USt
| - eu_exempt: Steuerfreie innergemeinschaftliche Lieferung §4 Nr. 1b UStG
| - third_country_exempt: Steuerfreie Drittland-Lieferung §4 Nr. 1a UStG
|
*/
'revenue_accounts' => [
'domestic_19' => ['konto' => 8400, 'bu' => 9],
'domestic_7' => ['konto' => 8300, 'bu' => 8],
'eu_exempt' => ['konto' => 8125, 'bu' => 1],
'third_country_exempt' => ['konto' => 8120, 'bu' => 11],
],
/*
|--------------------------------------------------------------------------
| Provisionen: Typ -> Sachkonto
|--------------------------------------------------------------------------
|
| Mapping basierend auf UserCreditItem.status:
| - 1 (commission_shop) + 5 (commission_growth_bonus) -> 4760 Verkaufsprovision
| - 2 (commission_payline) -> 4764 Payline-Provision
|
*/
'commission_accounts' => [
'shop' => 4760, // commission_shop (status=1)
'growth_bonus' => 4760, // commission_growth_bonus (status=5)
'payline' => 4764, // commission_payline (status=2)
],
// Mapping: UserCreditItem.status -> commission_type key
'credit_item_status_map' => [
1 => 'shop', // commission_shop
2 => 'payline', // commission_payline
5 => 'growth_bonus', // commission_growth_bonus
],
/*
|--------------------------------------------------------------------------
| Provisions-Steuerschlüssel
|--------------------------------------------------------------------------
|
| Basierend auf dem Steuerstatus des Beraters (UserAccount):
| - normal: USt-pflichtig (taxable_sales=1) -> BU 9
| - kleinunternehmer: Nicht USt-pflichtig DE (taxable_sales=2) -> BU 50
| - reverse_charge: Reverse Charge Verfahren (reverse_charge=true) -> BU 94
|
*/
'commission_tax_keys' => [
'normal' => 9, // 19% USt
'kleinunternehmer' => 50, // Kleinunternehmer
'reverse_charge' => 94, // Reverse Charge
],
/*
|--------------------------------------------------------------------------
| Gegenkonto-Mapping nach Zahlungsart
|--------------------------------------------------------------------------
|
| Bestimmt das Gegenkonto (Debitor) basierend auf der Zahlungsart
| (ShoppingPayment.clearingtype + wallettype).
| Format: "{clearingtype}_{wallettype}" => Gegenkonto
| Fallback: Sammeldebitor
|
*/
'counteraccount_map' => [
'wlt_PPE' => 1230, // PayPal
// Alle anderen Zahlungsarten -> Sammeldebitor (Fallback)
],
/*
|--------------------------------------------------------------------------
| Deutschland Country-ID
|--------------------------------------------------------------------------
|
| Die ID von Deutschland in der countries-Tabelle.
| Wird verwendet um Inland vs. Ausland zu unterscheiden.
|
*/
'germany_country_id' => 1,
/*
|--------------------------------------------------------------------------
| Storage-Einstellungen
|--------------------------------------------------------------------------
*/
'storage_disk' => 'local',
'storage_path' => 'datev',
/*
|--------------------------------------------------------------------------
| CSV-Format-Einstellungen
|--------------------------------------------------------------------------
*/
'delimiter' => ';',
'encoding' => 'UTF-8', // UTF-8 mit BOM für neuere DATEV-Versionen
'line_ending' => "\r\n", // CRLF
];

View file

@ -13,6 +13,20 @@
*/
return [
/*
|--------------------------------------------------------------------------
| Configuration Source Priority
|--------------------------------------------------------------------------
|
| Determines which configuration source has priority:
| - 'database': Settings from database override .env values (default)
| - 'env': Environment/Config values override database settings
|
| Useful for test servers where you want to use .env values
| without modifying database settings
*/
'config_source' => env('DHL_CONFIG_SOURCE', 'database'),
/*
|--------------------------------------------------------------------------
| DHL API Settings
@ -51,7 +65,7 @@ return [
'webhook' => [
'enabled' => env('DHL_WEBHOOK_ENABLED', false),
'secret' => env('DHL_WEBHOOK_SECRET'),
'route' => env('DHL_WEBHOOK_ROUTE', 'dhl/webhooks/tracking')
'route' => env('DHL_WEBHOOK_ROUTE', 'dhl/webhooks/tracking'),
],
/*
@ -85,11 +99,11 @@ return [
],
'dimensions' => [
'default' => ['length' => 120, 'width' => 60, 'height' => 60,],
'V01PAK' => ['length' => 120, 'width' => 60, 'height' => 60,], // DHL Paket National
'V62WP' => ['length' => 35, 'width' => 25, 'height' => 8,], // Warenpost National
'V53PAK' => ['length' => 120, 'width' => 60, 'height' => 60,], // DHL Paket International
'V07PAK' => ['length' => 120, 'width' => 60, 'height' => 60,], // DHL Retoure Online
'default' => ['length' => 120, 'width' => 60, 'height' => 60],
'V01PAK' => ['length' => 120, 'width' => 60, 'height' => 60], // DHL Paket National
'V62WP' => ['length' => 35, 'width' => 25, 'height' => 8], // Warenpost National
'V53PAK' => ['length' => 120, 'width' => 60, 'height' => 60], // DHL Paket International
'V07PAK' => ['length' => 120, 'width' => 60, 'height' => 60], // DHL Retoure Online
],
/*

View file

@ -1,7 +1,7 @@
<?php
return [
'availableTemplates' => ['de', 'en', 'es', 'fr'],
// Uncomment the languages that your site supports - or add new ones.
// These are sorted by the native name, which is the order you might show them in a language selector.
// Regional languages are sorted by their base language, so "British English" sorts as "English, British"
@ -295,6 +295,6 @@ return [
// 'vai' => ['name' => 'Vai (Vai)', 'script' => 'Vaii', 'native' => 'ꕙꔤ', 'regional' => ''],
// 'jv-Java' => ['name' => 'Javanese (Javanese)', 'script' => 'Java', 'native' => 'ꦧꦱꦗꦮ', 'regional' => ''],
// 'ko' => ['name' => 'Korean', 'script' => 'Hang', 'native' => '한국어', 'regional' => 'ko_KR'],
]
],
];

0
database.db Normal file
View file

View file

@ -1,8 +1,8 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
@ -25,7 +25,6 @@ class CreateProductsTable extends Migration
$table->decimal('tax', 5, 2)->nullable();
$table->decimal('price_old', 8, 2)->nullable(); // streichpreis
$table->unsignedInteger('points')->nullable()->default(0);
$table->unsignedInteger('weight')->nullable()->default(0);
@ -63,7 +62,7 @@ class CreateProductsTable extends Migration
$table->unsignedTinyInteger('buying_restriction_amount')->nullable();
$table->boolean('sponsor_buying_points')->default(false);
$table->unsignedTinyInteger('sponsor_buying_points_amount')->nullable();
$table->unsignedSmallInteger('sponsor_buying_points_amount')->nullable();
$table->string('identifier', 20)->nullable();
$table->string('action')->nullable();
@ -74,9 +73,6 @@ class CreateProductsTable extends Migration
$table->timestamps();
$table->softDeletes();
});
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
/**
* Run the migrations.
*
* Fügt ein Sprachfeld für Benutzer hinzu, um deren bevorzugte Sprache
* für Rechnungen, Provisionsabrechnungen und Lieferscheine zu speichern.
*/
public function up(): void
{
Schema::table('user_accounts', function (Blueprint $table) {
$table->string('language', 5)->nullable()->default('de')->after('notice');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('user_accounts', function (Blueprint $table) {
$table->dropColumn('language');
});
}
};

View file

@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* Ändert den Default von 'de' auf NULL, damit die App-Locale
* als Fallback verwendet wird wenn keine Sprache gesetzt ist.
*/
public function up(): void
{
// Default auf NULL ändern
Schema::table('user_accounts', function (Blueprint $table) {
$table->string('language', 5)->nullable()->default(null)->change();
});
// Alle bestehenden 'de' Werte auf NULL setzen,
// damit die App-Locale als Fallback greift
\DB::table('user_accounts')
->where('language', 'de')
->update(['language' => null]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('user_accounts', function (Blueprint $table) {
$table->string('language', 5)->nullable()->default('de')->change();
});
\DB::table('user_accounts')
->whereNull('language')
->update(['language' => 'de']);
}
};

View file

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('datev_exports', function (Blueprint $table) {
$table->id();
// Abrechnungszeitraum
$table->date('period_from');
$table->date('period_to');
$table->unsignedTinyInteger('month');
$table->unsignedSmallInteger('year');
// Status: 0=draft, 1=generated, 2=downloaded, 3=locked
$table->unsignedTinyInteger('status')->default(0);
// DATEV Header-Daten
$table->string('berater_nr', 10)->nullable();
$table->string('mandant_nr', 10)->nullable();
// Statistik
$table->unsignedInteger('invoice_count')->default(0);
$table->unsignedInteger('credit_count')->default(0);
$table->unsignedInteger('cancellation_count')->default(0);
$table->decimal('total_revenue', 15, 2)->default(0);
$table->decimal('total_commissions', 15, 2)->default(0);
// Datei
$table->string('filename')->nullable();
$table->string('file_path')->nullable();
$table->string('file_hash', 64)->nullable();
// Admin der den Export erstellt hat
$table->unsignedBigInteger('created_by')->nullable();
// Validierungs-Zusammenfassung
$table->unsignedInteger('warning_count')->default(0);
$table->unsignedInteger('error_count')->default(0);
$table->json('validation_summary')->nullable();
$table->timestamps();
$table->softDeletes();
// Indices
$table->index(['month', 'year']);
$table->index('status');
});
}
public function down(): void
{
Schema::dropIfExists('datev_exports');
}
};

View file

@ -0,0 +1,56 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('datev_export_lines', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('datev_export_id');
$table->foreign('datev_export_id')
->references('id')
->on('datev_exports')
->onDelete('cascade');
// Quell-Referenz
$table->string('source_type', 30); // invoice, credit, cancellation
$table->unsignedBigInteger('source_id');
// Zeilennummer im CSV
$table->unsignedInteger('line_number')->default(0);
// DATEV-Buchungsfelder
$table->decimal('amount_gross', 13, 2); // Spalte A: Umsatz (Brutto)
$table->char('soll_haben', 1); // Spalte B: H oder S
$table->unsignedInteger('konto'); // Spalte G: Sachkonto
$table->unsignedInteger('gegenkonto'); // Spalte H: Gegenkonto
$table->unsignedSmallInteger('bu_schluessel'); // BU-Schlüssel (Steuerschlüssel)
$table->date('belegdatum'); // Spalte J: Belegdatum
$table->string('belegfeld1', 36); // Spalte K: Rechnungs-/Gutschriftsnummer
$table->string('buchungstext', 60); // Spalte N: Buchungstext (max 60 Zeichen DATEV)
// EU/USt Felder
$table->string('eu_ustid', 20)->nullable(); // Spalte AN: USt-ID
$table->char('eu_land', 2)->nullable(); // EU-Ländercode
// Fertig gerenderte CSV-Zeile (für exakte Reproduzierbarkeit)
$table->text('row_csv')->nullable();
$table->timestamps();
// Indices
$table->index(['datev_export_id', 'line_number']);
$table->index(['source_type', 'source_id']);
});
}
public function down(): void
{
Schema::dropIfExists('datev_export_lines');
}
};

View file

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('dhl_package_shipments', function (Blueprint $table) {
$table->timestamp('tracking_completed_at')->nullable()->after('last_tracked_at');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('dhl_package_shipments', function (Blueprint $table) {
$table->dropColumn('tracking_completed_at');
});
}
};

View file

@ -0,0 +1,62 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('user_abo_item_histories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_abo_id');
$table->foreign('user_abo_id')
->references('id')
->on('user_abos')
->onDelete('cascade');
$table->unsignedInteger('user_abo_item_id')->nullable();
$table->unsignedInteger('product_id');
$table->foreign('product_id')
->references('id')
->on('products');
$table->string('action', 30);
$table->string('product_name', 255);
$table->string('product_number', 50)->nullable();
$table->decimal('unit_price', 10, 2);
$table->decimal('total_price', 10, 2);
$table->unsignedInteger('qty_before')->nullable();
$table->unsignedInteger('qty_after')->nullable();
$table->unsignedInteger('old_product_id')->nullable();
$table->string('old_product_name', 255)->nullable();
$table->unsignedTinyInteger('comp')->default(0);
$table->unsignedInteger('changed_by_user_id')->nullable();
$table->string('changed_by_name', 255)->nullable();
$table->string('channel', 30);
$table->uuid('batch_id')->nullable()->index();
$table->boolean('is_initial')->default(false);
$table->timestamps();
$table->index(['user_abo_id', 'created_at']);
$table->index(['user_abo_id', 'is_initial']);
});
}
public function down(): void
{
Schema::dropIfExists('user_abo_item_histories');
}
};

View file

@ -0,0 +1,63 @@
<?php
use App\Models\UserAbo;
use App\Models\UserAboItemHistory;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Str;
return new class extends Migration
{
public function up(): void
{
$userAbos = UserAbo::with('user_abo_items.product')
->where('status', '>', 0)
->get();
foreach ($userAbos as $userAbo) {
// Nur seeden wenn noch keine History existiert
if (UserAboItemHistory::where('user_abo_id', $userAbo->id)->exists()) {
continue;
}
$batchId = Str::uuid()->toString();
foreach ($userAbo->user_abo_items as $item) {
if (! $item->product) {
continue;
}
// is_for=me: Berater kauft netto mit UserFactor
// is_for=ot: Kunde kauft brutto
$isMe = $userAbo->is_for === 'me';
$unitPrice = (float) $item->product->getPriceWith($isMe, $isMe);
UserAboItemHistory::create([
'user_abo_id' => $userAbo->id,
'user_abo_item_id' => $item->id,
'product_id' => $item->product_id,
'action' => UserAboItemHistory::ACTION_INITIAL,
'product_name' => $item->product->getLang('name'),
'product_number' => $item->product->number ?? null,
'unit_price' => $unitPrice,
'total_price' => $unitPrice * $item->qty,
'qty_before' => null,
'qty_after' => $item->qty,
'comp' => $item->comp ?? 0,
'changed_by_user_id' => null,
'changed_by_name' => 'System (Migration)',
'channel' => UserAboItemHistory::CHANNEL_SYSTEM,
'batch_id' => $batchId,
'is_initial' => true,
'created_at' => $userAbo->created_at ?? now(),
'updated_at' => $userAbo->created_at ?? now(),
]);
}
}
}
public function down(): void
{
// Nur die durch Migration erstellten Einträge löschen
UserAboItemHistory::where('changed_by_name', 'System (Migration)')->delete();
}
};

View file

@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->boolean('free_shipping_consultant')->default(false)->after('no_free_shipping');
});
}
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('free_shipping_consultant');
});
}
};

View file

@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->boolean('is_membership_only')->default(false)->after('free_shipping_consultant');
});
}
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('is_membership_only');
});
}
};

Some files were not shown because too many files have changed in this diff Show more