From 841d87e1611a77cbf7a6772cea2e7dceee03a4a2 Mon Sep 17 00:00:00 2001 From: Kevin Date: Wed, 12 Aug 2026 10:28:06 +0000 Subject: [PATCH] Incentive: Ticket-Fixes 2026-08-12 + Team-Struktur nach active_date sortiert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- app/Console/Commands/IncentiveCalculate.php | 3 + app/Models/IncentiveParticipant.php | 28 +- .../BusinessPlan/BusinessUserItem.php | 2 + .../BusinessUserItemOptimized.php | 5 +- .../BusinessPlan/TreeHtmlRenderer.php | 33 ++- .../IncentivePointsLogRepairService.php | 56 +++- app/Services/Incentive/IncentiveTracker.php | 8 +- dev/2026-08-12-intensiv-tickets/README.md | 130 +++++++++ .../TreeCalcBotIntegrationTest.php | 103 ++++--- ...ncentivePartnerRepairSponsorChangeTest.php | 268 ++++++++++++++++++ .../BusinessPlan/TreeHtmlRendererTest.php | 168 +++++++---- 11 files changed, 689 insertions(+), 115 deletions(-) create mode 100644 dev/2026-08-12-intensiv-tickets/README.md create mode 100644 tests/Feature/Incentive/IncentivePartnerRepairSponsorChangeTest.php diff --git a/app/Console/Commands/IncentiveCalculate.php b/app/Console/Commands/IncentiveCalculate.php index 4c8cd0db..c80b77f0 100644 --- a/app/Console/Commands/IncentiveCalculate.php +++ b/app/Console/Commands/IncentiveCalculate.php @@ -95,6 +95,7 @@ class IncentiveCalculate extends Command 'with_partners' => 0, 'with_abos' => 0, 'tracking_partner_added' => 0, + 'tracking_partner_removed' => 0, 'tracking_abo_added' => 0, 'repair_partner_fk' => 0, 'repair_abo_fk' => 0, @@ -119,6 +120,7 @@ class IncentiveCalculate extends Command $participant->rebuildFromSourceTables()->save(); } else { if (! $skipRepair) { + $stats['tracking_partner_removed'] += $repairService->removeStaleSponsorTrackings($participant); $stats['tracking_partner_added'] += $repairService->syncMissingTrackingPartners($participant); $stats['tracking_abo_added'] += $repairService->syncMissingTrackingAbos($participant); $r = $repairService->repairForeignKeys($participant); @@ -179,6 +181,7 @@ class IncentiveCalculate extends Command if (! $force) { $tableRows[] = ['Neupartner-Trackings nachgezogen', (string) $stats['tracking_partner_added']]; + $tableRows[] = ['Neupartner-Trackings entfernt (Sponsorwechsel)', (string) $stats['tracking_partner_removed']]; $tableRows[] = ['Neuabo-Trackings nachgezogen', (string) $stats['tracking_abo_added']]; $tableRows[] = ['FK Partner (akkum.) repariert', (string) $stats['repair_partner_fk']]; $tableRows[] = ['FK Abo (akkum.) repariert', (string) $stats['repair_abo_fk']]; diff --git a/app/Models/IncentiveParticipant.php b/app/Models/IncentiveParticipant.php index 62d7aa2f..015294d9 100644 --- a/app/Models/IncentiveParticipant.php +++ b/app/Models/IncentiveParticipant.php @@ -265,22 +265,30 @@ class IncentiveParticipant extends Model $this->newAbos()->delete(); $this->pointsLog()->delete(); - // A. Neupartner: direkt gesponserte User im Qualifikationszeitraum mit bezahltem Starterpaket + // A. Neupartner: direkt gesponserte User mit im Qualifikationszeitraum bezahltem Starterpaket + // (Bestelldatum zaehlt, wie Live-Tracking - nicht das User-Registrierungsdatum) + $partnerWindowStart = $incentive->qualification_start->copy()->startOfDay(); + $partnerWindowEnd = $incentive->qualification_end->copy()->endOfDay(); + $new_partners = User::where('m_sponsor', $this->user_id) - ->whereBetween('created_at', [ - $incentive->qualification_start, - $incentive->qualification_end->copy()->endOfDay(), - ]) - ->whereHas('shopping_orders', function ($q) { - $q->wherePaidRegistrationIncludesStarterKit(); + ->whereHas('shopping_orders', function ($q) use ($partnerWindowStart, $partnerWindowEnd) { + $q->wherePaidRegistrationIncludesStarterKit() + ->whereBetween('created_at', [$partnerWindowStart, $partnerWindowEnd]); }) ->get(); foreach ($new_partners as $partner) { + $starterOrderDate = $partner->shopping_orders() + ->wherePaidRegistrationIncludesStarterKit() + ->whereBetween('created_at', [$partnerWindowStart, $partnerWindowEnd]) + ->orderBy('id') + ->value('created_at'); + $registeredAt = $starterOrderDate ? Carbon::parse($starterOrderDate) : $partner->created_at; + $newPartner = IncentiveNewPartner::create([ 'participant_id' => $this->id, 'user_id' => $partner->id, - 'registered_at' => $partner->created_at, + 'registered_at' => $registeredAt, ]); IncentivePointsLog::create([ @@ -289,8 +297,8 @@ class IncentiveParticipant extends Model 'source_type' => User::class, 'source_id' => $partner->id, 'source_label' => $partner->getFullName() ?: $partner->email ?: ('User #'.$partner->id), - 'month' => $partner->created_at->month, - 'year' => $partner->created_at->year, + 'month' => $registeredAt->month, + 'year' => $registeredAt->year, 'points_onetime' => $incentive->points_partner_onetime, 'points_accumulated' => 0, 'incentive_new_partner_id' => $newPartner->id, diff --git a/app/Services/BusinessPlan/BusinessUserItem.php b/app/Services/BusinessPlan/BusinessUserItem.php index 2e1e1b80..f8fd8d85 100644 --- a/app/Services/BusinessPlan/BusinessUserItem.php +++ b/app/Services/BusinessPlan/BusinessUserItem.php @@ -325,6 +325,8 @@ class BusinessUserItem ->where('users.m_sponsor', '=', $this->b_user->user_id) // <- need the id for parents / sponsors ->where('users.payment_account', '!=', null) ->where('users.active_date', '<=', $this->date->end_date) // wurde in dem Monat freigeschaltet + ->orderBy('users.active_date') + ->orderBy('users.id') ->get(); if ($users) { diff --git a/app/Services/BusinessPlan/BusinessUserItemOptimized.php b/app/Services/BusinessPlan/BusinessUserItemOptimized.php index 37f8c82b..79d949a7 100644 --- a/app/Services/BusinessPlan/BusinessUserItemOptimized.php +++ b/app/Services/BusinessPlan/BusinessUserItemOptimized.php @@ -5,6 +5,7 @@ namespace App\Services\BusinessPlan; use App\Models\UserAccount; use App\Models\UserBusiness; use App\Models\UserLevel; +use App\Models\UserSalesVolume; use App\User; use Carbon\Carbon; use Illuminate\Support\Facades\Log; @@ -393,7 +394,7 @@ class BusinessUserItemOptimized \Log::info("BusinessUserItem: No UserSalesVolume found for user {$user->id} in {$this->date->month}/{$this->date->year}"); // Prüfe neueste verfügbare Daten - $latestVolume = \App\Models\UserSalesVolume::where('user_id', $user->id) + $latestVolume = UserSalesVolume::where('user_id', $user->id) ->orderBy('year', 'desc') ->orderBy('month', 'desc') ->first(); @@ -1086,6 +1087,8 @@ class BusinessUserItemOptimized ->where('users.m_sponsor', '=', $this->b_user->user_id) ->where('users.payment_account', '!=', null) ->where('users.active_date', '<=', $this->date->end_date) + ->orderBy('users.active_date') + ->orderBy('users.id') ->get(); if ($users->isNotEmpty()) { diff --git a/app/Services/BusinessPlan/TreeHtmlRenderer.php b/app/Services/BusinessPlan/TreeHtmlRenderer.php index 35601a3f..718e3a15 100644 --- a/app/Services/BusinessPlan/TreeHtmlRenderer.php +++ b/app/Services/BusinessPlan/TreeHtmlRenderer.php @@ -41,7 +41,7 @@ class TreeHtmlRenderer $this->loadAboBadges($this->collectUserIds($businessUsers)); $html = '
    '; - foreach ($businessUsers as $businessUser) { + foreach (self::sortByActivation($businessUsers) as $businessUser) { $html .= $this->renderUserItem($businessUser, 0); } $html .= '
'; @@ -49,6 +49,35 @@ class TreeHtmlRenderer return $html; } + /** + * Sortiert Business-User-Items nach Partner-Aktivierung (active_date, dann user_id). + * + * Die Loader liefern die Downline in users.id-Reihenfolge (= Konto-Registrierung); + * gespeicherte Monats-Snapshots konservieren diese Reihenfolge zusaetzlich. + * Bestandskunden, die erst spaeter zum Berater upgraden, stuenden damit mitten in + * der Liste statt am Ende - deshalb wird hier zentral beim Rendern sortiert. + * + * Achtung: kein `$item->active_date ?? null` verwenden - BusinessUserItem(Optimized) + * hat __get ohne __isset, damit liefert `??` immer null. + * + * @param array $items + * @return array + */ + public static function sortByActivation(array $items): array + { + usort($items, function ($a, $b): int { + $aDate = $a->active_date; + $bDate = $b->active_date; + + $aKey = $aDate ? strtotime((string) $aDate) : PHP_INT_MAX; + $bKey = $bDate ? strtotime((string) $bDate) : PHP_INT_MAX; + + return $aKey <=> $bKey ?: ((int) $a->user_id <=> (int) $b->user_id); + }); + + return $items; + } + /** * Rendert parentlose User als HTML */ @@ -221,7 +250,7 @@ class TreeHtmlRenderer $childrenHtml = ''; if ($item->businessUserItems && count($item->businessUserItems) > 0) { $childrenHtml = '
    '; - foreach ($item->businessUserItems as $child) { + foreach (self::sortByActivation($item->businessUserItems) as $child) { $childrenHtml .= $this->renderUserItem($child, $deep + 1); } $childrenHtml .= '
'; diff --git a/app/Services/Incentive/IncentivePointsLogRepairService.php b/app/Services/Incentive/IncentivePointsLogRepairService.php index b32af225..6a85623c 100644 --- a/app/Services/Incentive/IncentivePointsLogRepairService.php +++ b/app/Services/Incentive/IncentivePointsLogRepairService.php @@ -18,6 +18,10 @@ class IncentivePointsLogRepairService * Fehlende Neupartner-Tracking-Zeilen anlegen (Starterpaket / gleiche Regeln wie Neuaufbau A). * Nutzt IncentiveTracker::trackNewPartner, wenn eine qualifizierte Bestellung existiert. * + * Neupartner = Starterpaket im Qualifikationszeitraum bezahlt (Bestelldatum, wie Live-Tracking). + * Das User-Registrierungsdatum ist bewusst irrelevant: auch Bestandskunden, die im Zeitraum + * zum Berater upgraden, zaehlen. + * * @return int Anzahl nachgezogener Partner-Trackings fuer diesen Teilnehmer */ public function syncMissingTrackingPartners(IncentiveParticipant $participant): int @@ -29,14 +33,14 @@ class IncentivePointsLogRepairService $added = 0; + $windowStart = $incentive->qualification_start->copy()->startOfDay(); + $windowEnd = $incentive->qualification_end->copy()->endOfDay(); + $candidates = User::query() ->where('m_sponsor', $participant->user_id) - ->whereBetween('created_at', [ - $incentive->qualification_start, - $incentive->qualification_end->copy()->endOfDay(), - ]) - ->whereHas('shopping_orders', function ($q) { - $q->wherePaidRegistrationIncludesStarterKit(); + ->whereHas('shopping_orders', function ($q) use ($windowStart, $windowEnd) { + $q->wherePaidRegistrationIncludesStarterKit() + ->whereBetween('created_at', [$windowStart, $windowEnd]); }) ->get(); @@ -51,6 +55,7 @@ class IncentivePointsLogRepairService $order = ShoppingOrder::query() ->where('auth_user_id', $partner->id) ->wherePaidRegistrationIncludesStarterKit() + ->whereBetween('created_at', [$windowStart, $windowEnd]) ->orderBy('id') ->first(); @@ -62,10 +67,12 @@ class IncentivePointsLogRepairService ->where('participant_id', $participant->id) ->where('user_id', $partner->id) ->exists()) { + $registeredAt = $order?->created_at ?? $partner->created_at; + $newPartner = IncentiveNewPartner::create([ 'participant_id' => $participant->id, 'user_id' => $partner->id, - 'registered_at' => $partner->created_at, + 'registered_at' => $registeredAt, ]); IncentivePointsLog::create([ @@ -74,8 +81,8 @@ class IncentivePointsLogRepairService 'source_type' => User::class, 'source_id' => $partner->id, 'source_label' => $partner->getFullName() ?: $partner->email ?: ('User #'.$partner->id), - 'month' => $partner->created_at->month, - 'year' => $partner->created_at->year, + 'month' => $registeredAt->month, + 'year' => $registeredAt->year, 'points_onetime' => $incentive->points_partner_onetime, 'points_accumulated' => 0, 'incentive_new_partner_id' => $newPartner->id, @@ -93,6 +100,37 @@ class IncentivePointsLogRepairService return $added; } + /** + * Entfernt Neupartner-Trackings, deren Partner inzwischen einen anderen Sponsor hat + * (z. B. nach Umhaengen in der Teamstruktur). Die zugehoerigen Log-Zeilen (Einmalpunkte + * und akkumulierte Umsatzpunkte) werden mitgeloescht; beim aktuellen Sponsor legt + * {@see syncMissingTrackingPartners} + {@see syncMissingSalesVolumeLogs} im selben + * Lauf alles neu an. Geloeschte User bleiben unangetastet. + * + * @return int Anzahl entfernter Partner-Trackings fuer diesen Teilnehmer + */ + public function removeStaleSponsorTrackings(IncentiveParticipant $participant): int + { + $removed = 0; + + foreach ($participant->newPartners()->get() as $tracking) { + $partner = User::find($tracking->user_id); + if (! $partner) { + continue; + } + + if ((int) $partner->m_sponsor === (int) $participant->user_id) { + continue; + } + + IncentivePointsLog::where('incentive_new_partner_id', $tracking->id)->delete(); + $tracking->delete(); + $removed++; + } + + return $removed; + } + /** * Fehlende Abo-Tracking-Zeilen anlegen (Kundenabo ot / Eigenabo me, wie IncentiveTracker). * Zuerst trackAboActivated ueber Erstbestellung; ohne UserAboOrder manuell wie Neuaufbau B. diff --git a/app/Services/Incentive/IncentiveTracker.php b/app/Services/Incentive/IncentiveTracker.php index 803e067c..a640a8b1 100644 --- a/app/Services/Incentive/IncentiveTracker.php +++ b/app/Services/Incentive/IncentiveTracker.php @@ -37,8 +37,8 @@ class IncentiveTracker $incentives = Incentive::query() ->active() - ->where('qualification_start', '<=', $registration_date) - ->where('qualification_end', '>=', $registration_date) + ->whereDate('qualification_start', '<=', $registration_date) + ->whereDate('qualification_end', '>=', $registration_date) ->get(); foreach ($incentives as $incentive) { @@ -106,8 +106,8 @@ class IncentiveTracker $incentives = Incentive::query() ->active() - ->where('qualification_start', '<=', $activation_date) - ->where('qualification_end', '>=', $activation_date) + ->whereDate('qualification_start', '<=', $activation_date) + ->whereDate('qualification_end', '>=', $activation_date) ->get(); foreach ($incentives as $incentive) { diff --git a/dev/2026-08-12-intensiv-tickets/README.md b/dev/2026-08-12-intensiv-tickets/README.md new file mode 100644 index 00000000..408e9e17 --- /dev/null +++ b/dev/2026-08-12-intensiv-tickets/README.md @@ -0,0 +1,130 @@ +# 2026-08-12 – Incentive („Intensiv"): Ticket-Analyse, Fixes & Team-Struktur-Sortierung + +Analyse von 4 Kundentickets zum Montenegro Incentive 2026 (ID 2, Qualifikation 01.04.–31.08.2026) +plus Prüfung der Tracking-Lücke durch die verspätete Zeitraum-Verlängerung. + +## Kontext: Verspätete Verlängerung (Anfang August) + +Das Incentive endete ursprünglich am 31.07.2026 und wurde erst am **03.08.2026 16:57** +auf den 31.08.2026 verlängert. Ereignisse vom 01.–03.08. wurden live nicht getrackt. + +**Ergebnis der Prüfung: Die Lücke hat sich selbst geheilt.** Der Nacht-Cron +`incentive:calculate` (täglich 05:00, siehe `app/Console/Kernel.php`) nutzt den +`IncentivePointsLogRepairService`, der fehlende Trackings anhand des *aktuellen* +Qualifikationszeitraums idempotent nachzieht. Am 04.08. um 05:00–05:01 wurden alle +10 fehlenden Abos + 1 Neupartner aus dem Lücken-Fenster nachgetragen (verifizierbar an +`incentive_new_abos.created_at`). Ein separates Ausgleichs-Command war nicht nötig. + +## Die 4 Tickets + +### 1. Steffi Karrer – „Dino Portaro fehlt im Incentive" → Bug, gefixt + +Dino Portaro (User 1045) registrierte sein Konto bereits im **Okt. 2024** (als Kunde) +und bezahlte das Starterpaket erst am **31.07.2026 11:05** (Order 59302). Er fehlte aus +zwei unabhängigen Gründen: + +1. **Datums-Randfall im Live-Tracker:** `incentives.qualification_end` ist eine + DATE-Spalte. Der Vergleich `qualification_end >= '2026-07-31 11:05:52'` schlägt fehl, + weil MySQL das Datum als Mitternacht interpretiert. Bestellungen am letzten Tag des + Zeitraums gingen verloren. → Fix: `whereDate()` in `IncentiveTracker`. +2. **Falsche Neupartner-Definition im Repair/Rebuild:** `syncMissingTrackingPartners` + und `rebuildFromSourceTables` filterten auf `users.created_at` im Zeitraum. Der + Live-Tracker zählt aber nach **Bestelldatum des Starterpakets**. Bestandskunden, die + im Zeitraum zum Berater upgraden, waren damit nie reparierbar. + → Fix: Kandidaten über das Bestelldatum des bezahlten Starterpakets im Zeitraum; + `registered_at`/Log-Monat = Bestelldatum. + +Ergebnis nach `incentive:calculate 2`: Steffi 10.022 → 10.822 Punkte, 3 Partner. + +### 2. Monika Kunz – „Mai-Punkte für Bockhacker (24) und Dannenhauer (54) fehlen" → kein Bug + +Die Mai-Abbuchungen beider Kundenabos (Abo 197 Bockhacker, Abo 198 Dannenhauer) +**schlugen fehl** (`shopping_orders.txaction = 'prev'`). Die Nachzahlung gelang am +17.06.; die 24 P bzw. 54 P wurden korrekt für **Juni** gutgeschrieben und zählen im +Incentive. Regel: Punkte entstehen im Monat der erfolgreichen Zahlung, nicht im +Fälligkeitsmonat. + +Nebenbefund: Dannenhauers Abo 198 wurde am 06.07. gelöscht (Status 3, kein Ersatz) – +die Kundin hat aktuell kein aktives Abo. Bockhacker bekam am 10.07. ein Ersatz-Abo (496). + +### 3. Christina Schuder – „Anna Schall fehlt" → Bug, gefixt + +Anna Schall (User 1426, Konto seit Dez. 2025, Starterpaket 22.07.2026) war getrackt, +aber beim **Firmenkonto** (User 6, mivita care gmbh): Beim verspäteten Zahlungs-Callback +am 24.07. stand ihr `m_sponsor` noch auf 6; sie wurde erst danach zu Christina (1241) +umgehängt. Der Repair konnte das nicht korrigieren (gleiche `users.created_at`-Falle wie +bei Ticket 1, plus fehlende Bereinigung veralteter Trackings). + +→ Fix: Neue Methode `IncentivePointsLogRepairService::removeStaleSponsorTrackings()` – +entfernt Partner-Trackings (+ zugehörige Log-Zeilen), wenn der Partner laut `m_sponsor` +inzwischen woanders hängt; der reguläre Sync legt sie im selben Lauf beim aktuellen +Sponsor neu an. Im `incentive:calculate` eingebunden (Statistik-Zeile +„Neupartner-Trackings entfernt (Sponsorwechsel)"). + +Ergebnis: Christina 7.165 → 7.965 Punkte, 2 Partner; Firmenkonto von 800 auf 0 Punkte +(alle 4 dort hängenden Fremd-Trackings zum jeweils richtigen Sponsor verschoben). + +### 4. Jasmin Grund – „Madeleine Schrade fehlt" → hatte sich bereits selbst geheilt + +Madeleine (User 1600) registrierte + bezahlte am 09.08.; der Nacht-Cron zog sie am +11.08. 05:00 nach (600 P, August). Das Ticket entstand in den ~1,5 Tagen dazwischen. +Ursache für das fehlende Live-Tracking: `IncentiveTracker::trackNewPartner` feuert nur +über `Payment::paymentStatusPaidAction`; Zahlungswege daran vorbei fängt erst der +Nacht-Cron ab (by design). + +### 1b. Steffi Karrer – „Dino steht mitten in der Team-Struktur" → Sortierung umgestellt + +`/user/team/structure` listete die Downline in `users.id`-Reihenfolge +(= Konto-Registrierung), weil die Lade-Queries kein `orderBy` hatten. Dino (Konto Okt. +2024, Partner erst Juli 2026) stand deshalb zwischen Margarete Fislage und Renate +Hofrichter statt am Ende. + +→ Umgestellt auf Sortierung nach **`active_date`** (Partner-Aktivierung), Tiebreaker `users.id`: + +- Zentral beim Rendern: `TreeHtmlRenderer::sortByActivation()` (wirkt sofort, auch für + bereits gespeicherte Monats-Snapshots, die die alte Reihenfolge konservieren). +- Zusätzlich `orderBy` in beiden Downline-Queries + (`BusinessUserItemOptimized::readParentsBusinessUsers`, + `BusinessUserItem::readParentsBusinessUsers`), damit künftige Snapshots und der + Standard-Bot-Fallback konsistent sind. + +Stolperfalle dabei: `BusinessUserItem(Optimized)` hat `__get` ohne `__isset` – +`$item->active_date ?? null` liefert dort **immer** null. Deshalb direkter +Property-Zugriff in `sortByActivation()`. + +## Geänderte Dateien + +| Datei | Änderung | +|---|---| +| `app/Services/Incentive/IncentiveTracker.php` | `whereDate()` für Zeitraum-Vergleiche (DATE-Spalte vs. Datetime) | +| `app/Services/Incentive/IncentivePointsLogRepairService.php` | Neupartner per Starterpaket-Bestelldatum; neu: `removeStaleSponsorTrackings()` | +| `app/Models/IncentiveParticipant.php` | Force-Rebuild nutzt dieselbe Bestelldatum-Definition | +| `app/Console/Commands/IncentiveCalculate.php` | Sponsorwechsel-Bereinigung eingebunden + Statistik | +| `app/Services/BusinessPlan/TreeHtmlRenderer.php` | `sortByActivation()`; Sortierung in `renderTree`/`renderUserItem` | +| `app/Services/BusinessPlan/BusinessUserItemOptimized.php` | `orderBy(active_date, id)` in Downline-Query | +| `app/Services/BusinessPlan/BusinessUserItem.php` | dito (Standard-Bot-Fallback) | + +## Tests + +- `tests/Feature/Incentive/IncentivePartnerRepairSponsorChangeTest.php` (neu, 5 Tests): + Bestandskunden-Upgrade zählt, Zeitraum-Grenzen, letzter-Tag-Randfall, + Sponsorwechsel-Verschiebung, korrekte Trackings bleiben unangetastet. +- `tests/Unit/BusinessPlan/TreeHtmlRendererTest.php` (+2): Sortierlogik inkl. + `__get`-ohne-`__isset`-Falle. +- `tests/Feature/BusinessPlan/TreeCalcBotIntegrationTest.php` (+1): Downline-Query-Reihenfolge. + +Vorbestehende Fehlschläge (nicht durch diese Änderungen): `IncentiveTeaserPageTest` +(fehlendes Galeriebild) sowie die Legacy-Tests in `tests/Unit/BusinessPlan/` und +`tests/Feature/BusinessPlan/` (fehlende Factories, `route()`/DB in Unit-Kontext). + +## Deployment-Hinweise + +1. Nach dem Deploy korrigiert der nächste 05:00-Lauf von `incentive:calculate` die + Incentive-Daten automatisch (Dino → Steffi, Anna Schall → Christina). Sofort: + `php artisan incentive:calculate 2`. +2. Die neue Struktur-Sortierung wirkt in der Ansicht sofort (Renderer-Sortierung), + unabhängig vom Monats-Snapshot. +3. Achtung: Durch die neue Neupartner-Definition (Bestelldatum statt Registrierung) + können beim ersten Lauf weitere, bisher fehlende Bestandskunden-Upgrades + nachgetragen werden – das ist gewollt und entspricht dem Live-Tracking. Auf dem + Teststand (Live-Dump 12.08.) waren es genau die zwei Ticket-Fälle. diff --git a/tests/Feature/BusinessPlan/TreeCalcBotIntegrationTest.php b/tests/Feature/BusinessPlan/TreeCalcBotIntegrationTest.php index 87677dfe..049562fe 100644 --- a/tests/Feature/BusinessPlan/TreeCalcBotIntegrationTest.php +++ b/tests/Feature/BusinessPlan/TreeCalcBotIntegrationTest.php @@ -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')); } -} \ No newline at end of file +} diff --git a/tests/Feature/Incentive/IncentivePartnerRepairSponsorChangeTest.php b/tests/Feature/Incentive/IncentivePartnerRepairSponsorChangeTest.php new file mode 100644 index 00000000..82437e85 --- /dev/null +++ b/tests/Feature/Incentive/IncentivePartnerRepairSponsorChangeTest.php @@ -0,0 +1,268 @@ + '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(); +}); diff --git a/tests/Unit/BusinessPlan/TreeHtmlRendererTest.php b/tests/Unit/BusinessPlan/TreeHtmlRendererTest.php index 2abd330d..24dcbdf1 100644 --- a/tests/Unit/BusinessPlan/TreeHtmlRendererTest.php +++ b/tests/Unit/BusinessPlan/TreeHtmlRendererTest.php @@ -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('
    ', $result); $this->assertStringContainsString('
', $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('
    ', $result); } @@ -205,33 +206,88 @@ class TreeHtmlRendererTest extends TestCase public function html_output_is_properly_escaped() { $businessUsers = [ - $this->createMockBusinessUser(1, 'John