Incentive: Ticket-Fixes 2026-08-12 + Team-Struktur nach active_date sortiert

Incentive (Montenegro 2026):
- Live-Tracker: whereDate() für Zeitraum-Vergleiche – Bestellungen am letzten
  Tag des Qualifikationszeitraums gingen verloren (DATE-Spalte vs. Datetime)
- Repair/Rebuild: Neupartner-Definition auf Starterpaket-Bestelldatum im
  Zeitraum umgestellt (statt users.created_at) – Bestandskunden-Upgrades
  zählen jetzt wie im Live-Tracking (Fall Dino Portaro → Steffi Karrer)
- Neu: removeStaleSponsorTrackings() – Partner-Trackings wandern nach
  Sponsorwechsel zum aktuellen Sponsor (Fall Anna Schall lag beim Firmenkonto)
- incentive:calculate: Sponsorwechsel-Bereinigung eingebunden + Statistik

Team-Struktur (/user/team/structure):
- Downline sortiert nach active_date (Partner-Aktivierung) statt users.id:
  zentral in TreeHtmlRenderer::sortByActivation() (wirkt sofort, auch für
  gespeicherte Monats-Snapshots) + orderBy in beiden Downline-Queries

Doku: dev/2026-08-12-intensiv-tickets/README.md (4 Kundentickets analysiert,
Lücke durch verspätete Zeitraum-Verlängerung hatte sich per Nacht-Cron geheilt)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Kevin 2026-08-12 10:28:06 +00:00
parent ac3bd6e8ea
commit 841d87e161
11 changed files with 689 additions and 115 deletions

View file

@ -2,15 +2,13 @@
namespace Tests\Feature\BusinessPlan;
use Tests\TestCase;
use App\User;
use App\Models\UserAccount;
use App\Models\UserLevel;
use App\Models\UserBusiness;
use App\Models\UserBusinessStructure;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\BusinessPlan\TreeCalcBotOptimized;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class TreeCalcBotIntegrationTest extends TestCase
{
@ -24,20 +22,20 @@ class TreeCalcBotIntegrationTest extends TestCase
'm_sponsor' => null,
'm_level' => 1,
'payment_account' => '2024-01-15',
'active_date' => '2024-01-01'
'active_date' => '2024-01-01',
]);
UserAccount::factory()->create([
'user_id' => $user->id,
'first_name' => 'Test',
'last_name' => 'User',
'm_account' => 'TEST123'
'm_account' => 'TEST123',
]);
UserLevel::factory()->create([
'id' => 1,
'name' => 'Bronze',
'pos' => 1
'pos' => 1,
]);
// Test original version
@ -52,10 +50,10 @@ class TreeCalcBotIntegrationTest extends TestCase
// Both should return same number of items
$this->assertEquals(count($originalItems), count($optimizedItems));
// Both should have same basic functionality
$this->assertEquals($originalBot->isParentless(), $optimizedBot->isParentless());
// HTML output should be generated (length > 0)
$this->assertGreaterThan(0, strlen($originalBot->makeHtmlTree()));
$this->assertGreaterThan(0, strlen($optimizedBot->makeHtmlTree()));
@ -71,30 +69,30 @@ class TreeCalcBotIntegrationTest extends TestCase
'm_sponsor' => null,
'm_level' => 1,
'payment_account' => '2024-01-15',
'active_date' => '2024-01-01'
'active_date' => '2024-01-01',
]);
UserAccount::factory()->create([
'user_id' => $user->id,
'first_name' => 'User',
'last_name' => $i,
'm_account' => 'TEST' . $i
'm_account' => 'TEST'.$i,
]);
$users[] = $user;
}
$startMemory = memory_get_usage();
$optimizedBot = new TreeCalcBotOptimized(1, 2024, 'admin');
$optimizedBot->initStructureAdmin(false);
$endMemory = memory_get_usage();
$memoryUsed = $endMemory - $startMemory;
// Memory usage should be reasonable (less than 5MB for 5 users)
$this->assertLessThan(5 * 1024 * 1024, $memoryUsed);
// Should still function correctly
$this->assertEquals(5, count($optimizedBot->getItems()));
}
@ -103,7 +101,7 @@ class TreeCalcBotIntegrationTest extends TestCase
public function optimized_version_maintains_backward_compatibility()
{
$optimizedBot = new TreeCalcBotOptimized(1, 2024, 'admin');
// Test all public methods exist and are callable
$this->assertTrue(method_exists($optimizedBot, 'initStructureAdmin'));
$this->assertTrue(method_exists($optimizedBot, 'initStructureUser'));
@ -114,11 +112,11 @@ class TreeCalcBotIntegrationTest extends TestCase
$this->assertTrue(method_exists($optimizedBot, 'isParentless'));
$this->assertTrue(method_exists($optimizedBot, 'getGrowthBonus'));
$this->assertTrue(method_exists($optimizedBot, 'getKeybyLine'));
// Test static methods
$this->assertTrue(method_exists($optimizedBot, 'isFromStored'));
$this->assertTrue(method_exists($optimizedBot, 'addUserID'));
// Test magic methods for property access
$date = $optimizedBot->__get('date');
$this->assertNotNull($date);
@ -134,13 +132,13 @@ class TreeCalcBotIntegrationTest extends TestCase
'm_sponsor' => null,
'm_level' => 1,
'payment_account' => '2024-01-15',
'active_date' => '2024-01-01'
'active_date' => '2024-01-01',
]);
UserAccount::factory()->create([
'user_id' => $user->id,
'first_name' => 'Test',
'last_name' => 'User'
'last_name' => 'User',
]);
$optimizedBot = new TreeCalcBotOptimized(1, 2024, 'admin');
@ -155,30 +153,69 @@ class TreeCalcBotIntegrationTest extends TestCase
$this->assertIsString($treeHtml);
$this->assertIsString($parentlessHtml);
$this->assertIsString($sponsorHtml);
// Tree HTML should contain user data when users exist
if (count($optimizedBot->getItems()) > 0) {
$this->assertStringContainsString('Test User', $treeHtml);
}
// HTML should be properly formed (basic check)
$this->assertStringNotContainsString('><', $treeHtml . $parentlessHtml . $sponsorHtml);
$this->assertStringNotContainsString('><', $treeHtml.$parentlessHtml.$sponsorHtml);
}
/** @test */
public function structure_children_are_ordered_by_active_date_not_by_user_id()
{
$makeUser = function (?int $sponsorId, string $activeDate): User {
return User::forceCreate([
'email' => 'tree-'.uniqid('', true).'@example.com',
'password' => bcrypt('secret'),
'lang' => 'de',
'm_sponsor' => $sponsorId,
'm_level' => 1,
'admin' => 0,
'payment_account' => $activeDate,
'active_date' => $activeDate,
]);
};
$sponsor = $makeUser(null, '2023-01-01');
// Kinder in ID-Reihenfolge angelegt, aber active_date bewusst durcheinander:
// Bestandskunde (frühe Registrierung/ID) wird erst spät Partner
$lateUpgrader = $makeUser($sponsor->id, '2024-01-10');
$earlyPartner = $makeUser($sponsor->id, '2023-05-01');
$midPartner = $makeUser($sponsor->id, '2024-01-05');
$bot = new TreeCalcBotOptimized(1, 2024, 'member');
$bot->initStructureUser($sponsor->id);
$items = $bot->getItems();
$this->assertCount(1, $items);
$childIds = array_map(fn ($item) => $item->user_id, $items[0]->businessUserItems);
$this->assertEquals(
[$earlyPartner->id, $midPartner->id, $lateUpgrader->id],
$childIds,
'Downline muss nach active_date sortiert sein, nicht nach users.id'
);
}
/** @test */
public function optimized_version_error_handling_works()
{
$optimizedBot = new TreeCalcBotOptimized(1, 2024, 'admin');
// Should handle non-existent user gracefully
$optimizedBot->initStructureUser(999999);
// Should return empty results but not crash
$this->assertEquals([], $optimizedBot->getItems());
$this->assertFalse($optimizedBot->isParentless());
// Should handle method calls on empty state
$this->assertEquals([], $optimizedBot->getGrowthBonus());
$this->assertEquals(0, $optimizedBot->getKeybyLine(1, 'points'));
}
}
}

View file

@ -0,0 +1,268 @@
<?php
use App\Models\Country;
use App\Models\Incentive;
use App\Models\IncentiveNewPartner;
use App\Models\IncentiveParticipant;
use App\Models\IncentivePointsLog;
use App\Models\Product;
use App\Models\Shipping;
use App\Models\ShippingCountry;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Models\UserShop;
use App\Services\Incentive\IncentivePointsLogRepairService;
use App\Services\Incentive\IncentiveTracker;
use App\User;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
beforeEach(function () {
Carbon::setTestNow(Carbon::parse('2026-05-15 12:00:00'));
});
afterEach(function () {
Carbon::setTestNow();
});
function repairTestCreateUser(?int $sponsorId = null, ?string $createdAt = null): User
{
$user = User::forceCreate([
'email' => 'u-'.uniqid('', true).'@example.com',
'password' => bcrypt('secret'),
'lang' => 'de',
'm_sponsor' => $sponsorId,
]);
if ($createdAt) {
$user->created_at = Carbon::parse($createdAt);
$user->save();
}
return $user->fresh();
}
function repairTestCreateStarterKitOrder(User $registrant, User $shopOwner, ?string $orderCreatedAt = null): ShoppingOrder
{
$country = Country::firstOrCreate(['code' => 'DE'], [
'phone' => '49',
'en' => 'Germany',
'de' => 'Deutschland',
'es' => 'Alemania',
'fr' => 'Allemagne',
'it' => 'Germania',
'ru' => 'Германия',
]);
$shipping = Shipping::create(['name' => 'S', 'active' => true]);
$shippingCountry = ShippingCountry::create(['shipping_id' => $shipping->id, 'country_id' => $country->id]);
$userShop = UserShop::create([
'user_id' => $shopOwner->id,
'name' => 'T'.substr(uniqid('', true), 0, 6),
'slug' => 't-'.uniqid(),
'active' => true,
]);
$shoppingUser = ShoppingUser::create([
'auth_user_id' => $registrant->id,
'member_id' => $shopOwner->id,
'billing_country_id' => $country->id,
'shipping_country_id' => $country->id,
'billing_email' => 'su-'.uniqid('', true).'@example.com',
'is_from' => 'wizard',
]);
$order = ShoppingOrder::create([
'shopping_user_id' => $shoppingUser->id,
'auth_user_id' => $registrant->id,
'country_id' => $shippingCountry->id,
'user_shop_id' => $userShop->id,
'payment_for' => 1,
'paid' => true,
'txaction' => 'paid',
'mode' => 'test',
'total' => 100,
'subtotal' => 90,
]);
$productId = DB::table('products')->insertGetId([
'name' => 'Starter '.uniqid(),
'title' => 'T',
'is_membership_only' => false,
'active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
ShoppingOrderItem::create([
'shopping_order_id' => $order->id,
'product_id' => Product::findOrFail($productId)->id,
'qty' => 1,
'price' => 50,
]);
if ($orderCreatedAt) {
$order->created_at = Carbon::parse($orderCreatedAt);
$order->save();
}
return $order->fresh(['shopping_order_items.product']);
}
function repairTestCreateIncentive(): Incentive
{
return Incentive::factory()->create([
'qualification_start' => '2026-04-01',
'qualification_end' => '2026-07-31',
'calculation_end' => '2026-08-31',
'points_partner_onetime' => 600,
'points_abo_onetime' => 400,
'status' => 1,
]);
}
it('syncMissingTrackingPartners zaehlt Bestandskunden, die im Zeitraum zum Berater upgraden (Bestelldatum zaehlt)', function () {
$incentive = repairTestCreateIncentive();
$sponsor = repairTestCreateUser();
$participant = IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $sponsor->id,
]);
// User lange vor dem Qualifikationszeitraum registriert, Starterpaket aber im Zeitraum bezahlt
$partner = repairTestCreateUser($sponsor->id, '2024-10-28 16:48:05');
repairTestCreateStarterKitOrder($partner, $sponsor, '2026-05-10 11:05:52');
$added = app(IncentivePointsLogRepairService::class)->syncMissingTrackingPartners($participant);
expect($added)->toBe(1);
expect(IncentiveNewPartner::where('participant_id', $participant->id)->where('user_id', $partner->id)->exists())->toBeTrue();
$log = IncentivePointsLog::where('participant_id', $participant->id)
->where('type', 'partner')
->where('source_id', $partner->id)
->where('is_storno', false)
->first();
expect($log)->not->toBeNull();
expect((int) $log->points_onetime)->toBe(600);
expect((int) $log->month)->toBe(5);
});
it('syncMissingTrackingPartners ignoriert Starterpakete ausserhalb des Qualifikationszeitraums', function () {
$incentive = repairTestCreateIncentive();
$sponsor = repairTestCreateUser();
$participant = IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $sponsor->id,
]);
$partner = repairTestCreateUser($sponsor->id, '2026-05-01 10:00:00');
repairTestCreateStarterKitOrder($partner, $sponsor, '2026-03-15 11:00:00');
$added = app(IncentivePointsLogRepairService::class)->syncMissingTrackingPartners($participant);
expect($added)->toBe(0);
expect(IncentiveNewPartner::where('user_id', $partner->id)->exists())->toBeFalse();
});
it('trackNewPartner zaehlt Bestellungen am letzten Tag des Qualifikationszeitraums (Datums-Randfall)', function () {
Carbon::setTestNow(Carbon::parse('2026-07-31 11:05:52'));
$incentive = repairTestCreateIncentive();
$sponsor = repairTestCreateUser();
IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $sponsor->id,
]);
$partner = repairTestCreateUser($sponsor->id);
$order = repairTestCreateStarterKitOrder($partner, $sponsor, '2026-07-31 11:05:52');
IncentiveTracker::trackNewPartner($order);
expect(IncentiveNewPartner::where('user_id', $partner->id)->exists())->toBeTrue();
});
it('removeStaleSponsorTrackings verschiebt Partner nach Sponsorwechsel zum aktuellen Sponsor', function () {
$incentive = repairTestCreateIncentive();
$oldSponsor = repairTestCreateUser();
$newSponsor = repairTestCreateUser();
$participantOld = IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $oldSponsor->id,
]);
$participantNew = IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $newSponsor->id,
]);
// Partner wurde unter dem alten Sponsor getrackt, haengt inzwischen aber unter dem neuen
$partner = repairTestCreateUser($newSponsor->id);
repairTestCreateStarterKitOrder($partner, $newSponsor, '2026-05-10 09:00:00');
$staleTracking = IncentiveNewPartner::create([
'participant_id' => $participantOld->id,
'user_id' => $partner->id,
'registered_at' => Carbon::parse('2026-05-10 09:00:00'),
]);
IncentivePointsLog::create([
'participant_id' => $participantOld->id,
'type' => 'partner',
'source_type' => User::class,
'source_id' => $partner->id,
'source_label' => 'Partner',
'month' => 5,
'year' => 2026,
'points_onetime' => 600,
'points_accumulated' => 0,
'incentive_new_partner_id' => $staleTracking->id,
]);
$participantOld->recalculateFromTrackingTables()->save();
expect((int) $participantOld->fresh()->total_points)->toBe(600);
$repair = app(IncentivePointsLogRepairService::class);
$removed = $repair->removeStaleSponsorTrackings($participantOld);
expect($removed)->toBe(1);
expect(IncentiveNewPartner::where('participant_id', $participantOld->id)->exists())->toBeFalse();
expect(IncentivePointsLog::where('participant_id', $participantOld->id)->exists())->toBeFalse();
$participantOld->recalculateFromTrackingTables()->save();
expect((int) $participantOld->fresh()->total_points)->toBe(0);
// Beim aktuellen Sponsor zieht der Repair den Partner nach
$added = $repair->syncMissingTrackingPartners($participantNew);
expect($added)->toBe(1);
$participantNew->recalculateFromTrackingTables()->save();
expect((int) $participantNew->fresh()->total_points)->toBe(600);
expect((int) $participantNew->fresh()->qualified_partners)->toBe(1);
});
it('removeStaleSponsorTrackings laesst korrekte Trackings unangetastet', function () {
$incentive = repairTestCreateIncentive();
$sponsor = repairTestCreateUser();
$participant = IncentiveParticipant::factory()->create([
'incentive_id' => $incentive->id,
'user_id' => $sponsor->id,
]);
$partner = repairTestCreateUser($sponsor->id);
IncentiveNewPartner::create([
'participant_id' => $participant->id,
'user_id' => $partner->id,
'registered_at' => now(),
]);
$removed = app(IncentivePointsLogRepairService::class)->removeStaleSponsorTrackings($participant);
expect($removed)->toBe(0);
expect(IncentiveNewPartner::where('participant_id', $participant->id)->exists())->toBeTrue();
});

View file

@ -2,23 +2,24 @@
namespace Tests\Unit\BusinessPlan;
use Tests\TestCase;
use App\Services\BusinessPlan\TreeHtmlRenderer;
use App\Services\BusinessPlan\BusinessUserItemOptimized;
use App\Services\BusinessPlan\TreeHtmlRenderer;
use stdClass;
use Tests\TestCase;
class TreeHtmlRendererTest extends TestCase
{
private $renderer;
private $dateObj;
protected function setUp(): void
{
parent::setUp();
$this->renderer = new TreeHtmlRenderer('admin');
$this->dateObj = new stdClass();
$this->dateObj = new stdClass;
$this->dateObj->month = 1;
$this->dateObj->year = 2024;
$this->dateObj->start_date = '2024-01-01 00:00:00';
@ -30,43 +31,43 @@ class TreeHtmlRendererTest extends TestCase
{
$adminRenderer = new TreeHtmlRenderer('admin');
$memberRenderer = new TreeHtmlRenderer('member');
$defaultRenderer = new TreeHtmlRenderer();
$defaultRenderer = new TreeHtmlRenderer;
// Using reflection to access private property
$reflection = new \ReflectionClass(TreeHtmlRenderer::class);
$property = $reflection->getProperty('initFrom');
$property->setAccessible(true);
$this->assertEquals('admin', $property->getValue($adminRenderer));
$this->assertEquals('member', $property->getValue($memberRenderer));
$this->assertEquals('member', $property->getValue($defaultRenderer));
}
/** @test */
public function renderTree_returns_info_message_for_empty_array()
public function render_tree_returns_info_message_for_empty_array()
{
$result = $this->renderer->renderTree([]);
$this->assertStringContainsString('Keine Business-User gefunden', $result);
$this->assertStringContainsString('alert-info', $result);
}
/** @test */
public function renderTree_generates_html_structure_for_business_users()
public function render_tree_generates_html_structure_for_business_users()
{
// Create mock business user items
$businessUsers = [
$this->createMockBusinessUser(1, 'John', 'Doe', 'john@example.com', true),
$this->createMockBusinessUser(2, 'Jane', 'Smith', 'jane@example.com', false)
$this->createMockBusinessUser(2, 'Jane', 'Smith', 'jane@example.com', false),
];
$result = $this->renderer->renderTree($businessUsers);
// Check basic HTML structure
$this->assertStringContainsString('<ol class="dd-list">', $result);
$this->assertStringContainsString('</ol>', $result);
$this->assertStringContainsString('dd-item', $result);
// Check user data is included
$this->assertStringContainsString('John Doe', $result);
$this->assertStringContainsString('Jane Smith', $result);
@ -75,44 +76,44 @@ class TreeHtmlRendererTest extends TestCase
}
/** @test */
public function renderTree_includes_admin_buttons_for_admin_init()
public function render_tree_includes_admin_buttons_for_admin_init()
{
$adminRenderer = new TreeHtmlRenderer('admin');
$businessUsers = [
$this->createMockBusinessUser(1, 'John', 'Doe', 'john@example.com', true)
$this->createMockBusinessUser(1, 'John', 'Doe', 'john@example.com', true),
];
$result = $adminRenderer->renderTree($businessUsers);
// Should include calculator button for admin
$this->assertStringContainsString('fa-calculator', $result);
$this->assertStringContainsString('business-user-detail', $result);
}
/** @test */
public function renderTree_excludes_admin_buttons_for_member_init()
public function render_tree_excludes_admin_buttons_for_member_init()
{
$memberRenderer = new TreeHtmlRenderer('member');
$businessUsers = [
$this->createMockBusinessUser(1, 'John', 'Doe', 'john@example.com', true)
$this->createMockBusinessUser(1, 'John', 'Doe', 'john@example.com', true),
];
$result = $memberRenderer->renderTree($businessUsers);
// Should not include calculator button for regular members
$this->assertStringNotContainsString('fa-calculator', $result);
}
/** @test */
public function renderTree_handles_inactive_accounts_correctly()
public function render_tree_handles_inactive_accounts_correctly()
{
$businessUsers = [
$this->createMockBusinessUser(1, 'Active', 'User', 'active@example.com', true),
$this->createMockBusinessUser(2, 'Inactive', 'User', 'inactive@example.com', false)
$this->createMockBusinessUser(2, 'Inactive', 'User', 'inactive@example.com', false),
];
$result = $this->renderer->renderTree($businessUsers);
// Active user should have primary color icon
$this->assertStringContainsString('text-primary', $result);
// Inactive user should have danger/muted styling
@ -121,82 +122,82 @@ class TreeHtmlRendererTest extends TestCase
}
/** @test */
public function renderParentless_returns_empty_message_for_empty_array()
public function render_parentless_returns_empty_message_for_empty_array()
{
$result = $this->renderer->renderParentless([]);
$this->assertStringContainsString('Keine parentlosen User gefunden', $result);
$this->assertStringContainsString('alert-info', $result);
}
/** @test */
public function renderParentless_generates_list_for_parentless_users()
public function render_parentless_generates_list_for_parentless_users()
{
$parentlessUsers = [
$this->createMockBusinessUser(1, 'Orphan', 'User', 'orphan@example.com', true)
$this->createMockBusinessUser(1, 'Orphan', 'User', 'orphan@example.com', true),
];
$result = $this->renderer->renderParentless($parentlessUsers);
$this->assertStringContainsString('dd-item', $result);
$this->assertStringContainsString('Orphan User', $result);
$this->assertStringContainsString('orphan@example.com', $result);
}
/** @test */
public function renderSponsor_returns_no_sponsor_message_for_null()
public function render_sponsor_returns_no_sponsor_message_for_null()
{
$result = $this->renderer->renderSponsor(null);
$this->assertStringContainsString('alert-warning', $result);
$this->assertStringContainsString('team.no_sponsor_assigned', $result);
}
/** @test */
public function renderSponsor_generates_sponsor_html()
public function render_sponsor_generates_sponsor_html()
{
$sponsor = $this->createMockBusinessUser(1, 'Sponsor', 'User', 'sponsor@example.com', true);
$result = $this->renderer->renderSponsor($sponsor);
$this->assertStringContainsString('dd-item', $result);
$this->assertStringContainsString('Sponsor User', $result);
$this->assertStringContainsString('sponsor@example.com', $result);
}
/** @test */
public function renderSponsor_includes_admin_details_for_admin_init()
public function render_sponsor_includes_admin_details_for_admin_init()
{
$adminRenderer = new TreeHtmlRenderer('admin');
$sponsor = $this->createMockBusinessUser(1, 'Sponsor', 'User', 'sponsor@example.com', true);
// Set some business data
$sponsor->sales_volume_points_KP_sum = 1000;
$sponsor->sales_volume_total_sum = 5000;
$result = $adminRenderer->renderSponsor($sponsor);
$this->assertStringContainsString('1000', $result);
$this->assertStringContainsString('5000', $result);
$this->assertStringContainsString('total_points', $result);
}
/** @test */
public function renderItem_handles_deep_nesting()
public function render_item_handles_deep_nesting()
{
// Create business user with nested children
$parentUser = $this->createMockBusinessUser(1, 'Parent', 'User', 'parent@example.com', true);
$childUser = $this->createMockBusinessUser(2, 'Child', 'User', 'child@example.com', true);
// Set up nesting
$parentUser->businessUserItems = [$childUser];
$result = $this->renderer->renderTree([$parentUser]);
// Should contain both parent and child
$this->assertStringContainsString('Parent User', $result);
$this->assertStringContainsString('Child User', $result);
// Should have nested structure
$this->assertStringContainsString('<ol class="dd-list dd-nodrag">', $result);
}
@ -205,33 +206,88 @@ class TreeHtmlRendererTest extends TestCase
public function html_output_is_properly_escaped()
{
$businessUsers = [
$this->createMockBusinessUser(1, 'John <script>', 'Doe & Co', 'john@example.com', true)
$this->createMockBusinessUser(1, 'John <script>', 'Doe & Co', 'john@example.com', true),
];
$result = $this->renderer->renderTree($businessUsers);
// HTML should be escaped
$this->assertStringNotContainsString('<script>', $result);
$this->assertStringContainsString('&lt;script&gt;', $result);
$this->assertStringContainsString('&amp;', $result);
}
/** @test */
public function sort_by_activation_orders_by_active_date_then_user_id_with_nulls_last()
{
$make = function (int $userId, ?string $activeDate) {
$item = new stdClass;
$item->user_id = $userId;
$item->active_date = $activeDate;
return $item;
};
$items = [
$make(10, '2026-07-31'),
$make(11, '2024-10-07'),
$make(12, null),
$make(13, '2024-10-07'),
$make(14, '2023-01-01'),
];
$sorted = TreeHtmlRenderer::sortByActivation($items);
$this->assertEquals([14, 11, 13, 10, 12], array_column($sorted, 'user_id'));
}
/** @test */
public function sort_by_activation_works_on_business_user_items_despite_get_without_isset()
{
// Bestandskunde (niedrige User-ID = frühe Konto-Registrierung), aber spätes Partner-Upgrade.
// BusinessUserItemOptimized hat __get ohne __isset - die Sortierung muss trotzdem
// an active_date kommen (kein ??-Operator auf dem Item).
$lateUpgrader = $this->createMockBusinessUser(2, 'Dino', 'Portaro', 'dino@example.com', true);
$earlyPartner = $this->createMockBusinessUser(3, 'Renate', 'Hofrichter', 'renate@example.com', true);
$this->setMockActiveDate($lateUpgrader, '2026-07-31');
$this->setMockActiveDate($earlyPartner, '2024-11-07');
$sorted = TreeHtmlRenderer::sortByActivation([$lateUpgrader, $earlyPartner]);
$this->assertEquals(
[3, 2],
array_map(fn ($item) => $item->user_id, $sorted),
'Partnerin mit früherem active_date muss vor dem späten Upgrader stehen'
);
}
/**
* Helper: setzt active_date auf dem gemockten b_user-Objekt
*/
private function setMockActiveDate($businessUser, string $activeDate): void
{
$reflection = new \ReflectionClass($businessUser);
$property = $reflection->getProperty('b_user');
$property->setAccessible(true);
$property->getValue($businessUser)->active_date = $activeDate;
}
/**
* Helper method to create mock business user
*/
private function createMockBusinessUser($id, $firstName, $lastName, $email, $activeAccount)
{
$businessUser = new BusinessUserItemOptimized($this->dateObj);
// Create a mock b_user object
$bUser = new stdClass();
$bUser = new stdClass;
$bUser->user_id = $id;
$bUser->first_name = $firstName;
$bUser->last_name = $lastName;
$bUser->email = $email;
$bUser->active_account = $activeAccount;
$bUser->user_level_name = 'Bronze';
$bUser->m_account = 'TEST' . $id;
$bUser->m_account = 'TEST'.$id;
$bUser->user_birthday = '1990-01-01';
$bUser->user_phone = '+1234567890';
$bUser->sales_volume_points_KP_sum = 100;
@ -242,13 +298,13 @@ class TreeHtmlRendererTest extends TestCase
$bUser->sales_volume_total_shop = 500;
$bUser->payment_account_date = '2024-01-15';
$bUser->businessUserItems = [];
// Use reflection to set private property
$reflection = new \ReflectionClass($businessUser);
$property = $reflection->getProperty('b_user');
$property->setAccessible(true);
$property->setValue($businessUser, $bUser);
return $businessUser;
}
}
}