mivita/tests/Feature/BackofficeStatisticsDrilldownTest.php
Kevin d65922adfe Statistiken: Kundenfeedback 2026-08-19 komplett (N1-N8) + Review-Fixes + VP-/Incentive-Repair gehärtet
Statistik-Änderungen 2026-08-19 (dev/2026-07-22/entwicklungsplan-2026-08-19.md, alle 8 Pakete gemäß beantworteten F-Fragen):
- N1 Monatsstatistik: Team-Cluster (Firstlines klickbar -> neue Seite user_team_firstlines, Teampartner gesamt/Payline [nur aktive], Abos Payline mit +N) + Level-Kachel (Quali-Stufe, fehlende Payline-/persönliche Punkte, Karriere-Level); LiveCommissionService-Snapshot v3 reicht Level-/Quali-Daten durch
- N2 Abo-Kacheln auf Home monatsbezogen (aboStockCount-Rückrechnung über cancel/deleted/Status-Historie; VIP-Statistik bleibt tagesaktuell)
- N3 VIP-Statistik 'Recruiter des Monats' (Neupartner-Definition wie KPI, rekursives Ketten-Volumen als Gesamtpunkte inkl. Starterpaket) + Drilldown/CSV-Spalte 'Punkte gesamt'
- N4 Prognose-Block 'Level & Provision laut Prognose (Stand 25.)' mit unverbindlich-Kennzeichnung (ebenengenaue offene Abo-Punkte + TP-Laufstände)
- N5 Checkout-Herkunft: Dropdown raus, Pflicht-Freitext (lokalisierte Fehlermeldung)
- N6 Berater-Profilfoto (user_accounts.profile_image, Einwilligung als Sprachkey-Platzhalter, DSGVO-Löschung) + teaminterne Top-3-Karte (TopResultsService, Scope-Schalter)
- N7 USt-Optionen: 'nicht umsatzsteuerpflichtig' zuerst + '§ 19 UStG'-Textfix
- N8 Jahresgebühr-Nachfassliste je Berater (AnnualFeeDueService, überfällig/1-3 Monate, Sidenav)

Kontroll-Review (8 Perspektiven) angewendet: next-Level-Fallback im Steady-State (resolveNextLevel — sonst 'Höchstes Level erreicht' für Normalfälle), _calculated-Punktebasis bei mehr Paylines, keine Wiederbelebung deaktivierter Abos in der Monatsrückrechnung, Payline-Abo-Kachel monatskonsistent, Top-3-Nachrücker; Performance: BackofficeDashboardService als Singleton mit lineBuckets-Memo (+flushLineBucketsMemo), level_forecast 6h-Cache; Reuse: User-Scopes firstlinesOf/newPartnerIn, SalesVolumePoints::totalPointsByUser, Slim::storeCroppedImage (3 Upload-Kopien vereinigt), activeAbo-Scope statt Inline-Prädikate, Form::open-Konvention, Return-Types

Repair-Härtung (Kundenentscheide): VP-Nachtrepair dedupliziert über shopping_order_id (Live-Pfad schreibt sie jetzt mit), zählende Alt-Zeilen-Erkennung, Vormonats-Scan für Monatswechsel, Firmenaccount-Buchungen (config mivita.company_user_id) werden automatisch auf den Berater umgebucht (in place bzw. per Gegenbuchung bei geschlossenem Monat; Echtfall Anna Schall Order 58797 -> Christina Schuder), Berater-zu-Berater nur Warnung; Incentive-Repair: m_sponsor=NULL löscht nicht mehr, FK-Repair vor Stale-Bereinigung, gebatchte Lookups, zentrales Incentive::qualificationWindow(); .env aus dem Git-Tracking entfernt (Pflege per SFTP)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 10:44:44 +00:00

257 lines
9.2 KiB
PHP

<?php
use App\Models\Product;
use App\Models\UserAbo;
use App\Models\UserAboItem;
use App\Models\UserSalesVolume;
use App\Services\Abo\TeamAboOverviewService;
use App\Services\Backoffice\BackofficeDashboardService;
use App\Services\Backoffice\BackofficeDrilldownService;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\URL;
use Tests\TestCase;
uses(TestCase::class, RefreshDatabase::class);
beforeEach(function () {
if (! Schema::connection('sqlite')->hasColumn('products', 'slug')) {
Schema::connection('sqlite')->table('products', function ($table) {
$table->string('slug')->nullable();
});
}
});
function boMakeUser(?int $sponsorId = null, ?string $activeDate = null, ?string $paymentAccount = null): User
{
return User::forceCreate([
'email' => 'bo-'.uniqid('', true).'@example.com',
'password' => bcrypt('secret'),
'lang' => 'de',
'm_level' => 1,
'm_sponsor' => $sponsorId,
'active_date' => $activeDate,
'payment_account' => $paymentAccount ?? now()->addYear(),
]);
}
function boMakeAbo(int $memberId, string $isFor, string $startDate, int $points = 0): UserAbo
{
$abo = UserAbo::create([
'user_id' => $memberId,
'member_id' => $memberId,
'shopping_user_id' => 0,
'email' => 'a-'.uniqid('', true).'@example.com',
'is_for' => $isFor,
'payone_userid' => 0,
'clearingtype' => 'cc',
'amount' => 5000,
'active' => true,
'status' => 2,
'abo_interval' => 5,
'start_date' => $startDate,
'last_date' => $startDate,
'next_date' => '2026-12-10',
]);
if ($points > 0) {
$product = Product::forceCreate([
'name' => 'P-'.uniqid('', true),
'title' => 'Test',
'price' => 10.0,
'tax' => 19.0,
'active' => true,
'pos' => 1,
'weight' => 100,
'points' => $points,
'slug' => 'p-'.uniqid('', true),
]);
UserAboItem::create([
'user_abo_id' => $abo->id,
'product_id' => $product->id,
'comp' => 0,
'qty' => 1,
'status' => 1,
]);
}
return $abo->fresh();
}
function boMakeSalesVolume(int $userId, int $month, int $year, float $points, int $status): UserSalesVolume
{
return UserSalesVolume::forceCreate([
'user_id' => $userId,
'month' => $month,
'year' => $year,
'points' => $points,
'status' => $status,
]);
}
it('gruppiert Teamkundenabos pro Teampartner mit Punkten je Abo und gesamt', function (): void {
$root = boMakeUser();
$anna = boMakeUser($root->id);
$lena = boMakeUser($root->id);
// Anna: 2 Kundenabos (20 + 30 Punkte), Lena: 1 Kundenabo (15 Punkte)
boMakeAbo($anna->id, 'ot', '2026-06-10', 20);
boMakeAbo($anna->id, 'ot', '2026-05-10', 30);
boMakeAbo($lena->id, 'ot', '2026-06-12', 15);
$details = app(BackofficeDrilldownService::class)->details($root, 0, 'team_customer_abos', 6, 2026);
expect($details['rows'])->toHaveCount(2);
// Nach Gesamtpunkten absteigend: Anna (50) vor Lena (15)
$first = $details['rows'][0];
expect($first['type'])->toBe('customer_abo_group')
->and($first['consultant_id'])->toBe($anna->id)
->and($first['abo_count'])->toBe(2)
->and($first['points'])->toBe(50.0)
->and($first['abos'])->toHaveCount(2);
expect($details['summary']['abo_count'])->toBe(3)
->and($details['summary']['points'])->toBe(65.0);
});
it('markiert im Teamkundenabo-Drilldown die im Monat neuen Abos', function (): void {
$root = boMakeUser();
$anna = boMakeUser($root->id);
boMakeAbo($anna->id, 'ot', '2026-06-10', 20); // neu im Juni
boMakeAbo($anna->id, 'ot', '2026-05-10', 30); // nicht neu
$details = app(BackofficeDrilldownService::class)->details($root, 0, 'team_customer_abos', 6, 2026);
$abos = collect($details['rows'][0]['abos']);
expect($abos->where('is_new_this_month', true))->toHaveCount(1)
->and($abos->where('is_new_this_month', false))->toHaveCount(1);
});
it('zaehlt Neupartner nur fuer den gewaehlten Monat mit aktivem Account', function (): void {
$root = boMakeUser();
$newInJune = boMakeUser($root->id, '2026-06-15');
$newInMay = boMakeUser($root->id, '2026-05-15');
$expiredAccount = boMakeUser($root->id, '2026-06-20', now()->subDay());
$service = app(BackofficeDashboardService::class);
$teamIds = $service->teamUserIds($root->id);
expect($service->newPartnersCount($teamIds, 6, 2026))->toBe(1)
->and($service->newPartnersCount($teamIds, 5, 2026))->toBe(1);
});
it('rendert die kombinierte Monatsstatistik-Card mit Abo- und Neupartner-Kennzahlen', function (): void {
URL::resolveMissingNamedRoutesUsing(fn (string $name, $parameters = []) => '/'.$name);
$html = view('dashboard._statistics', [
'monthlyStats' => [
'month' => 6,
'year' => 2026,
'customer_points' => 1200.0,
'team_payline_points' => 3400.0,
'payline_is_live' => true,
'direct_new_partners' => 2,
'team_total_abos' => 5,
'team_partner_abos' => 3,
'team_partner_abos_new' => 1,
'team_customer_abos' => 2,
'team_customer_abos_new' => 1,
'shop_1000' => 1,
'new_partners' => 4,
'own_abos' => 1,
'own_abos_new' => 0,
'own_customer_abos' => 2,
'own_customer_abos_new' => 1,
],
])->render();
expect($html)
->toContain(__('home.monthly_statistics'))
->toContain(__('home.team_customer_subscriptions'))
->toContain(__('abo.shop_1000'))
->toContain(__('home.team_new_partners'))
->toContain('user_abos_team_show')
->toContain('+1'); // "+neu"-Badge im gewählten Monat
});
it('zeigt im Neupartner-Drilldown Sponsor und tagesaktuelle Kundenpunkte', function (): void {
$root = boMakeUser();
$sponsor = boMakeUser($root->id);
$partner = boMakeUser($sponsor->id, '2026-06-15');
boMakeSalesVolume($partner->id, 6, 2026, 250, 2); // Kundenpunkte (Shop)
boMakeSalesVolume($partner->id, 6, 2026, 100, 1); // Eigenpunkte zaehlen nicht als Kundenpunkte
$details = app(BackofficeDrilldownService::class)->details($root, 0, 'new_partners', 6, 2026);
expect($details['rows'])->toHaveCount(1)
->and($details['rows'][0]['sponsor'])->toBe($sponsor->email)
->and($details['rows'][0]['customer_points'])->toBe(250.0)
->and($details['summary']['customer_points'])->toBe(250.0);
});
it('zaehlt den Betrachter selbst beim 1000-Punkte-Shop mit', function (): void {
$root = boMakeUser();
$partner = boMakeUser($root->id);
boMakeSalesVolume($root->id, 6, 2026, 1200, 2);
boMakeSalesVolume($partner->id, 6, 2026, 1500, 2);
$details = app(BackofficeDrilldownService::class)->details($root, 0, 'shop_1000', 6, 2026);
expect($details['rows'])->toHaveCount(2);
$selfRow = collect($details['rows'])->firstWhere('user_id', $root->id);
expect($selfRow['name'])->toContain('(ich)');
$overview = app(BackofficeDashboardService::class)->overview($root, 6, 2026);
expect($overview['totals']['shop_1000'])->toBe(2)
->and($overview['lines'][1]['shop_1000'])->toBe(1);
});
it('zaehlt den Berater selbst bei den Dashboard-KPIs zum 1000-Punkte-Shop mit', function (): void {
$root = boMakeUser();
boMakeSalesVolume($root->id, 6, 2026, 1100, 2);
// auch ganz ohne Team zaehlt der eigene 1000-Punkte-Shop
$kpis = app(TeamAboOverviewService::class)->teamKpis($root, 6, 2026);
expect($kpis['shop_1000'])->toBe(1);
$partner = boMakeUser($root->id);
boMakeSalesVolume($partner->id, 6, 2026, 1300, 2);
app(BackofficeDashboardService::class)->flushLineBucketsMemo(); // Struktur hat sich im selben Prozess geändert
$kpis = app(TeamAboOverviewService::class)->teamKpis($root->fresh(), 6, 2026);
expect($kpis['shop_1000'])->toBe(2);
});
it('filtert Abo-Drilldowns mit only_new auf die im Monat neuen Abos', function (): void {
$root = boMakeUser();
$anna = boMakeUser($root->id);
$lena = boMakeUser($root->id);
boMakeAbo($anna->id, 'me', '2026-06-10', 20); // neu im Juni
boMakeAbo($lena->id, 'me', '2026-05-10', 30); // Bestand
$service = app(BackofficeDrilldownService::class);
$all = $service->details($root, 0, 'team_partner_abos', 6, 2026);
$onlyNew = $service->details($root, 0, 'team_partner_abos', 6, 2026, true);
expect($all['rows'])->toHaveCount(2)
->and($all['only_new'])->toBeFalse()
->and($onlyNew['rows'])->toHaveCount(1)
->and($onlyNew['rows'][0]['user_id'])->toBe($anna->id)
->and($onlyNew['only_new'])->toBeTrue()
->and($onlyNew['metric_label'])->toContain('nur neue');
boMakeAbo($anna->id, 'ot', '2026-06-12', 10); // neues Kundenabo
boMakeAbo($anna->id, 'ot', '2026-04-01', 10); // Bestand
$onlyNewCustomers = $service->details($root, 0, 'team_customer_abos', 6, 2026, true);
expect($onlyNewCustomers['rows'])->toHaveCount(1)
->and($onlyNewCustomers['rows'][0]['abo_count'])->toBe(1);
});