mivita/app/Services/GdprDeletionService.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

357 lines
13 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\GdprDeletionException;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Models\UserAccount;
use App\Models\UserBusiness;
use App\Models\UserShop;
use App\Models\UserUpdateEmail;
use App\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
/**
* DSGVO-Löschung (Art. 17 DSGVO) für Berater (User) und Endkunden (ShoppingUser).
*
* Personenbezogene Daten werden unwiderruflich anonymisiert. Daten, die unter
* gesetzliche Aufbewahrungspflichten fallen (Rechnungen, Gutschriften,
* DATEV-Exporte, Provisionsabrechnungen, Bestellungen mit Beleg), bleiben
* gemäß Art. 17 Abs. 3 lit. b DSGVO erhalten:
* - Rechnungs-/Gutschrift-PDFs und deren DB-Zeilen werden nicht verändert.
* - Bei Kunden-Datensätzen (shopping_users) mit Bestellungen bleiben Name und
* Rechnungsadresse erhalten (Buchungsbeleg), Kontaktdaten werden entfernt.
* - Provisions-Snapshots (user_businesses) behalten die Zahlen, die
* denormalisierten Personendaten werden anonymisiert.
*/
class GdprDeletionService
{
public const ANONYMIZED_FIRSTNAME = 'Gelöscht';
public const ANONYMIZED_LASTNAME = 'DSGVO';
/**
* Berater (User) DSGVO-konform löschen.
*
* @return array<string, int|string> Zusammenfassung der ausgeführten Schritte
*
* @throws GdprDeletionException wenn Sperrgründe vorliegen (Admin-Account, aktives Abo)
*/
public function deleteUser(User $user, ?int $executedByUserId = null): array
{
if ($user->admin >= 2) {
throw new GdprDeletionException(__('msg.gdpr_error_is_admin'));
}
$activeAbos = UserAbo::where('user_id', $user->id)->where('active', true)->count();
if ($activeAbos > 0) {
throw new GdprDeletionException(__('msg.gdpr_error_active_abo'));
}
$originalEmail = $user->email;
$summary = DB::transaction(function () use ($user) {
$summary = ['user_id' => $user->id];
// MLM-Struktur erhalten: Downline und Kunden auf den nächsten aktiven Sponsor
// übertragen. Bewusst beim Sponsor starten, nicht beim User selbst — ein noch
// aktiver User würde sonst sich selbst als neuen Sponsor erhalten.
$active_sponsor = UserUtil::findNextActiveSponsor($user->m_sponsor ?: $user->pre_sponsor);
if ($active_sponsor && $active_sponsor->id !== $user->id) {
UserUtil::setNewSponsorToChilds($user->id, $active_sponsor->id);
UserUtil::setShoppingUserToNewMember($user->id, $active_sponsor->id);
$summary['new_sponsor_id'] = $active_sponsor->id;
}
// Bestehende Komplett-Löschung: E-Mail randomisieren, Zugangsdaten entwerten,
// Account + Shop soft-deleten
UserUtil::deleteUser($user, true);
$this->anonymizeUserRow($user);
$this->anonymizeUserAccount($user);
$this->anonymizeUserShop($user);
$summary['files_deleted'] = $this->deleteUserFiles($user);
$summary['update_emails_deleted'] = UserUpdateEmail::where('user_id', $user->id)->delete();
$summary['abos_anonymized'] = $this->anonymizeUserAbos('user_id', $user->id);
$summary['business_rows_anonymized'] = $this->anonymizeUserBusinessRows($user);
$summary['shopping_users_anonymized'] = $this->anonymizeShoppingUserRows(
ShoppingUser::withTrashed()->where('auth_user_id', $user->id)->get()
);
return $summary;
});
$this->logDeletion('gdpr-delete-user', $user->id, User::class, $executedByUserId, $originalEmail, $summary);
return $summary;
}
/**
* Endkunden (ShoppingUser) DSGVO-konform löschen.
*
* Anonymisiert alle Datensätze des Kunden (Einträge mit gleicher Kundennummer).
*
* @return array<string, int|string>
*
* @throws GdprDeletionException wenn der Datensatz zu einem Berater gehört oder ein aktives Abo besteht
*/
public function deleteShoppingUser(ShoppingUser $shoppingUser, ?int $executedByUserId = null): array
{
if ($shoppingUser->auth_user_id) {
throw new GdprDeletionException(__('msg.gdpr_error_customer_is_member'));
}
$rows = $this->getCustomerRows($shoppingUser);
$activeAbos = UserAbo::whereIn('shopping_user_id', $rows->pluck('id'))->where('active', true)->count();
if ($activeAbos > 0) {
throw new GdprDeletionException(__('msg.gdpr_error_active_abo'));
}
$originalEmail = $shoppingUser->billing_email;
$summary = DB::transaction(function () use ($shoppingUser, $rows) {
$summary = ['shopping_user_id' => $shoppingUser->id];
$summary['abos_anonymized'] = 0;
foreach ($rows as $row) {
$summary['abos_anonymized'] += $this->anonymizeUserAbos('shopping_user_id', $row->id);
}
$summary['shopping_users_anonymized'] = $this->anonymizeShoppingUserRows($rows);
return $summary;
});
$this->logDeletion('gdpr-delete-customer', $shoppingUser->id, ShoppingUser::class, $executedByUserId, $originalEmail, $summary);
return $summary;
}
/**
* Alle Datensätze eines Endkunden (gleiche Kundennummer), inkl. soft-deleted.
*
* @return \Illuminate\Database\Eloquent\Collection<int, ShoppingUser>
*/
public function getCustomerRows(ShoppingUser $shoppingUser)
{
if ($shoppingUser->number > 0) {
return ShoppingUser::withTrashed()->where('number', $shoppingUser->number)->get();
}
return ShoppingUser::withTrashed()->where('id', $shoppingUser->id)->get();
}
protected function anonymizeUserRow(User $user): void
{
$user->notes = null;
$user->settings = null;
$user->payment_methods = null;
$user->last_login = null;
$user->save();
}
protected function anonymizeUserAccount(User $user): void
{
if (! $user->account_id) {
return;
}
$account = UserAccount::withTrashed()->find($user->account_id);
if (! $account) {
return;
}
$account->m_salutation = null;
$account->m_first_name = self::ANONYMIZED_FIRSTNAME;
$account->m_last_name = self::ANONYMIZED_LASTNAME;
$account->m_notes = null;
$account->company = null;
$account->salutation = null;
$account->first_name = self::ANONYMIZED_FIRSTNAME;
$account->last_name = self::ANONYMIZED_LASTNAME;
$account->address = null;
$account->address_2 = null;
$account->zipcode = null;
$account->city = null;
$account->pre_phone_id = null;
$account->phone = null;
$account->pre_mobil_id = null;
$account->mobil = null;
$account->tax_number = null;
$account->tax_identification_number = null;
$account->shipping_salutation = null;
$account->shipping_company = null;
$account->shipping_firstname = null;
$account->shipping_lastname = null;
$account->shipping_address = null;
$account->shipping_address_2 = null;
$account->shipping_zipcode = null;
$account->shipping_city = null;
$account->shipping_pre_phone_id = null;
$account->shipping_phone = null;
$account->shipping_postnumber = null;
$account->birthday = null;
$account->website = null;
$account->facebook = null;
$account->facebook_fanpage = null;
$account->instagram = null;
$account->bank_owner = null;
$account->bank_iban = null;
$account->bank_bic = null;
$account->payment_data = null;
$account->notice = null;
if ($account->profile_image) {
Storage::disk('public')->delete('images/profile/'.$account->profile_image);
}
$account->profile_image = null;
$account->save();
}
protected function anonymizeUserShop(User $user): void
{
$shop = UserShop::withTrashed()->where('user_id', $user->id)->first();
if (! $shop) {
return;
}
if ($shop->filename) {
Storage::disk('public')->delete('images/shop/'.$shop->filename);
}
$shop->title = null;
$shop->contact = null;
$shop->accessibility = null;
$shop->about = null;
$shop->trans = null;
$shop->filename = null;
$shop->originalname = null;
$shop->ext = null;
$shop->mine = null;
$shop->size = null;
$shop->save();
}
protected function deleteUserFiles(User $user): int
{
$count = 0;
foreach ($user->files()->get() as $file) {
Storage::disk('user')->delete($file->dir.$file->filename);
$file->delete();
$count++;
}
return $count;
}
/**
* Zahlungs-Tokens und Kontaktdaten aller Abos entfernen (auch soft-deleted).
*/
protected function anonymizeUserAbos(string $column, int $id): int
{
$count = 0;
$abos = UserAbo::withTrashed()->where($column, $id)->get();
foreach ($abos as $abo) {
$abo->email = null;
$abo->carddata = null;
$abo->payone_userid = 0;
$abo->stripe_customer_id = null;
$abo->stripe_payment_method_id = null;
$abo->active = false;
$abo->save();
$count++;
}
return $count;
}
/**
* Denormalisierte Personendaten in den monatlichen Provisions-Snapshots
* anonymisieren; die Finanzdaten (Umsätze, Provisionen) bleiben erhalten.
*/
protected function anonymizeUserBusinessRows(User $user): int
{
return UserBusiness::where('user_id', $user->id)->update([
'email' => null,
'first_name' => self::ANONYMIZED_FIRSTNAME,
'last_name' => self::ANONYMIZED_LASTNAME,
'user_birthday' => null,
'user_phone' => null,
]);
}
/**
* Kunden-Datensätze anonymisieren. Datensätze mit Bestellungen behalten
* Name und Rechnungsadresse (Aufbewahrungspflicht Buchungsbeleg),
* verlieren aber alle Kontaktdaten. Datensätze ohne Bestellung werden
* vollständig anonymisiert.
*
* @param Collection<int, ShoppingUser> $rows
*/
protected function anonymizeShoppingUserRows($rows): int
{
$count = 0;
foreach ($rows as $row) {
$hasOrders = $row->shopping_orders()->withTrashed()->count() > 0;
if ($hasOrders) {
$this->anonymizeShoppingUserContactData($row);
} else {
$this->anonymizeShoppingUserComplete($row);
}
$count++;
}
return $count;
}
protected function anonymizeShoppingUserContactData(ShoppingUser $row): void
{
$row->billing_phone = null;
$row->billing_email = 'geloescht_'.$row->id.'@dsgvo.invalid';
$row->shipping_phone = null;
$row->shipping_email = null;
$row->remarks = '';
$row->notice = [];
$row->subscribed = false;
$row->faker_mail = true;
$row->save();
}
protected function anonymizeShoppingUserComplete(ShoppingUser $row): void
{
$row->billing_salutation = null;
$row->billing_company = null;
$row->billing_firstname = self::ANONYMIZED_FIRSTNAME;
$row->billing_lastname = self::ANONYMIZED_LASTNAME;
$row->billing_address = null;
$row->billing_address_2 = null;
$row->billing_zipcode = null;
$row->billing_city = null;
$row->shipping_salutation = null;
$row->shipping_company = null;
$row->shipping_firstname = null;
$row->shipping_lastname = null;
$row->shipping_address = null;
$row->shipping_address_2 = null;
$row->shipping_zipcode = null;
$row->shipping_city = null;
$row->shipping_postnumber = null;
$this->anonymizeShoppingUserContactData($row);
}
/**
* Nachweis der Löschung (Art. 5 Abs. 2 DSGVO) ohne personenbezogene Daten.
*
* @param array<string, int|string> $summary
*/
protected function logDeletion(string $action, int $modelId, string $modelClass, ?int $executedByUserId, ?string $originalEmail, array $summary): void
{
SysLog::action($action, 'gdpr', 4)
->setUserId($executedByUserId)
->setModel($modelId, $modelClass)
->setMessage('DSGVO-Löschung ausgeführt. Umfang: '.json_encode($summary))
->save();
Log::channel('cleanup')->info($action.' id:'.$modelId.' email-hash:'.hash('sha256', (string) $originalEmail).' summary:'.json_encode($summary));
}
}