mivita/app/Repositories/AboRepository.php
Kevin ac3bd6e8ea Statistiken/Abo: Kundenfeedback 2026-07-24 komplett umgesetzt + Steuern: DATEV-Fixes 08+09/2025 (Sammel-Commit Branch-WIP)
Feedback-Umsetzung (dev/2026-07-22/feedback-analyse-2026-07-24.md, alle 10 Punkte):
- VIP-Statistik: eigener Berater ('ich', Linie 0) in Neue-Kundenabos- und beiden Top-10-Listen; Top-10-Umsatz sortiert nach abgerechneten Ist-Punkten + Abo-Anzahl-Spalte; Fußnote nicht-payline-wirksame Punkte (SalesVolumePoints::nonPaylinePoints)
- Führungskräfte-Liste: beide Sichten 'direkt' (an nächster FK abgeschnitten, additiv) und 'gesamt' (komplette Downline), Gesamt-Spalte nach Kundenzählweise
- Team-Abos: je Ebene 'abgerechnet (Monat)' und 'bis zum 25. erwartet'; Payline-Karte mit Teamabo-/Kundenabo-Zählern
- Incentive-Live-Ranking: Qualifizierte zuerst nummeriert (fixt auch isWinner rank<=max_winners)
- Porto: Netto-/Brutto-Kennzeichnung (Berater netto, Endkunden inkl. MwSt., portal_view-Flag; auch CRM-/Shop-Warenkorb + Checkout), Yard::shipping_tax-Fix
- Struktur-Ansicht: Abo-Badges 'A' (eigenes Abo) und '(n)' (Kundenabos) je Teampartner, gebatcht
- Abo-Löschung: Softdelete setzt active=0 (UserAbo deleting-Hook) + Bereinigungs-Migration für gelöschte-aber-aktive Abos
- Doku: technische Analyse + Kundinnen-Feedback-Dokument unter dev/2026-07-22/
- Tests: IncentiveRankingTest, TeamStructureAboBadgesTest, YardShippingTaxTest (neu); BackofficeStatisticsListsTest, TeamAboOverviewTest, PaylineForecastServiceTest, AboAdminDeleteTest, AboOneTimeViewTest erweitert

Außerdem enthalten (Branch-WIP vor dem Feedback): DATEV-Abgleich-Fixes 08+09/2025, USt-ID-Live-Validierung sowie restliche unkommittete Stände (u. a. Abo-Pause-Sprachkeys).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-24 13:56:02 +00:00

346 lines
14 KiB
PHP

<?php
namespace App\Repositories;
use App\Models\Setting;
use App\Models\UserAbo;
use App\Models\UserAboStatusHistory;
use App\Services\AboHelper;
use Carbon\Carbon;
class AboRepository extends BaseRepository
{
private const DEFAULT_LOCK_DAYS_CHANGE = 10;
private const DEFAULT_LOCK_DAYS_PAUSE_CANCEL = 3;
/**
* Sperrfrist (Kalendertage) vor der Ausführung, ab der das Bearbeiten des Abos
* (Intervall/Produkte) blockiert wird. Konfigurierbar über das Setting
* `abo-lock-days-change`; Fallback auf den Default, wenn leer/0.
*/
public static function getLockDaysChange(): int
{
$days = (int) Setting::getContentBySlug('abo-lock-days-change');
return $days > 0 ? $days : self::DEFAULT_LOCK_DAYS_CHANGE;
}
/**
* Sperrfrist (Kalendertage) vor der Ausführung, ab der das Pausieren/Kündigen
* des Abos blockiert wird. Konfigurierbar über das Setting
* `abo-lock-days-pause-cancel`; Fallback auf den Default, wenn leer/0.
*/
public static function getLockDaysPauseCancel(): int
{
$days = (int) Setting::getContentBySlug('abo-lock-days-pause-cancel');
return $days > 0 ? $days : self::DEFAULT_LOCK_DAYS_PAUSE_CANCEL;
}
public function __construct()
{
// $this->model = $model;
}
public function setModel(UserAbo $model)
{
$this->model = $model;
}
public function update($data)
{
if (isset($data['action'])) {
if ($data['action'] === 'abo_update_settings') {
if ($this->validate($data)) {
// Pause ist eine eigenständige Aktion: sie verschiebt nur next_date
// und darf nicht von der anschließenden Liefertag-Neuberechnung
// überschrieben werden.
if (isset($data['abo_pause']) && $data['abo_pause'] == 'true') {
return $this->pauseOneMonth($data);
}
$this->updateStatus($data);
$this->model->abo_interval = (int) $data['abo_interval'];
$nextDate = $this->isAdminUpdate($data)
? $this->calculateAdminNextDate($data)
: $this->calculateNewNextDate((int) $data['abo_interval']);
$this->model->next_date = $nextDate;
$this->model->save();
$daysUntilNext = AboHelper::calendarDaysUntil(now(), $nextDate);
\Session()->flash('alert-warning', __('abo.warning_next_date_info', ['days' => $daysUntilNext, 'date' => $nextDate->format(\Util::formatDateDB())]));
return true;
}
return false;
}
}
return false;
}
public function create($data) {}
private function updateStatus($data)
{
$isAdminUpdate = $this->isAdminUpdate($data);
// Handle cancellation
if (isset($data['abo_cancel']) && $data['abo_cancel'] == 'true') {
// Mindestlaufzeit serverseitig durchsetzen — die UI blendet den Button nur aus
if (! $isAdminUpdate && ! AboHelper::canCancelAbo($this->model, $data['view'] ?? 'user')) {
\Session()->flash('alert-error', __('abo.info_min_duration_orders_left', [
'count' => max(0, (int) AboHelper::getAboMinDuration() - $this->model->getCountPaidOrders()),
]));
return;
}
// Sperre: 3 Tage vor Ausführung kann nicht mehr pausiert/gekündigt werden
if (! $isAdminUpdate && $this->model->next_date) {
$daysUntil = (int) now()->diffInDays(Carbon::parse($this->model->next_date), false);
if ($daysUntil >= 0 && $daysUntil < self::getLockDaysPauseCancel()) {
\Session()->flash('alert-error', __('abo.error_cancel_locked', ['days' => $daysUntil, 'lock' => self::getLockDaysPauseCancel()]));
return;
}
}
// Status 4 = abo_cancel (storniert/gekündigt)
$this->model->status = 4;
$this->model->active = false;
$this->model->cancel_date = now();
$this->model->save();
$this->logStatusHistory(UserAboStatusHistory::ACTION_CANCELLED, $data);
return;
}
$active = (isset($data['abo_is_active']) && $data['abo_is_active']) ? true : false;
// Sperre: 3 Tage vor Ausführung kann nicht mehr pausiert werden
if (! $isAdminUpdate && $this->model->active && ! $active && $this->model->next_date) {
$daysUntil = (int) now()->diffInDays(Carbon::parse($this->model->next_date), false);
if ($daysUntil >= 0 && $daysUntil < self::getLockDaysPauseCancel()) {
\Session()->flash('alert-error', __('abo.error_pause_locked', ['days' => $daysUntil, 'lock' => self::getLockDaysPauseCancel()]));
return;
}
}
// if status is active and active is false, set status to inactive
if ($this->model->active && ! $active) {
if ($this->model->status == 2) { // okay
$this->model->status = 6; // inactive
$this->model->active = false;
$this->model->save();
$this->logStatusHistory(UserAboStatusHistory::ACTION_DEACTIVATED, $data);
}
}
if (! $this->model->active && $active) {
if ($this->model->status == 6) { // inactive
$this->model->status = 2; // okay
$this->model->active = true;
$this->model->save();
$this->logStatusHistory(UserAboStatusHistory::ACTION_REACTIVATED, $data);
}
}
$this->model->active = $active;
}
/**
* Pausiert das Abo um genau einen Ausführungs-Zyklus: next_date wandert auf den
* gleichen Liefertag des Folgemonats, das Abo bleibt aktiv (Status 2).
* Regeln (außer Admin): Sperrfrist vor der Ausführung, Mindestlaufzeit und
* max. 1 Pause pro X Monate ({@see AboHelper::canPauseAbo()}).
*/
private function pauseOneMonth(array $data): bool
{
// Zeilen-Lock + frisches Modell: zwei parallele Pause-Requests dürfen next_date
// nicht beide auf Basis des alten Standes verschieben (Doppel-Pause).
return \DB::transaction(function () use ($data): bool {
$this->model = UserAbo::whereKey($this->model->id)->lockForUpdate()->firstOrFail();
return $this->pauseOneMonthLocked($data);
});
}
private function pauseOneMonthLocked(array $data): bool
{
$isAdminUpdate = $this->isAdminUpdate($data);
if (! $this->model->active || (int) $this->model->status !== 2 || ! $this->model->getRawOriginal('next_date')) {
\Session()->flash('alert-error', __('abo.error_pause_not_active'));
return false;
}
if (! $isAdminUpdate) {
$daysUntil = (int) now()->diffInDays(Carbon::parse($this->model->getRawOriginal('next_date')), false);
if ($daysUntil >= 0 && $daysUntil < self::getLockDaysPauseCancel()) {
\Session()->flash('alert-error', __('abo.error_pause_locked', ['days' => $daysUntil, 'lock' => self::getLockDaysPauseCancel()]));
return false;
}
if (! AboHelper::canCancelAbo($this->model, $data['view'] ?? 'user')) {
\Session()->flash('alert-error', __('abo.info_min_duration_orders_left', ['count' => (int) AboHelper::getAboMinDuration() - $this->model->getCountPaidOrders()]));
return false;
}
if (($nextPossible = AboHelper::nextPossiblePauseDate($this->model)) !== null) {
\Session()->flash('alert-error', __('abo.error_pause_interval', ['months' => AboHelper::getPauseIntervalMonths(), 'date' => $nextPossible->format(\Util::formatDateDB())]));
return false;
}
}
$previousNextDate = Carbon::parse($this->model->getRawOriginal('next_date'));
$newNextDate = AboHelper::setNextDate($previousNextDate, (int) $this->model->abo_interval);
$this->model->next_date = $newNextDate;
$this->model->last_pause_date = now();
$this->model->pause_count = (int) $this->model->pause_count + 1;
$this->model->save();
$this->logStatusHistory(UserAboStatusHistory::ACTION_PAUSED, $data, $previousNextDate, $newNextDate);
\Session()->flash('alert-success', __('abo.pause_success', ['date' => $newNextDate->format(\Util::formatDateDB())]));
return true;
}
private function logStatusHistory(string $action, array $data, ?Carbon $previousNextDate = null, ?Carbon $newNextDate = null): void
{
UserAboStatusHistory::create([
'user_abo_id' => $this->model->id,
'action' => $action,
'view' => $data['view'] ?? null,
'actor_user_id' => \Auth::id(),
'previous_next_date' => $previousNextDate,
'new_next_date' => $newNextDate,
]);
}
private function validate($data)
{
if ($data['view'] !== 'admin' && $data['view'] !== 'portal') {
if ($this->model->is_for === 'me' && $this->model->user_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($this->model->is_for === 'ot' && $this->model->member_id !== \Auth::user()->id) {
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if ($data['view'] === 'me' && $this->model->is_for !== 'me') {
\Session()->flash('alert-error', 'Unauthorized action. Is not for me');
return false;
}
if ($data['view'] === 'ot' && $this->model->is_for !== 'ot') {
\Session()->flash('alert-error', 'Unauthorized action. Is not your customer');
return false;
}
}
if (! isset($data['abo_interval']) || ! in_array((int) $data['abo_interval'], UserAbo::$aboDeliveryDays, true)) {
\Session()->flash('alert-error', __('abo.error_abo_interval'));
return false;
}
if ($this->isAdminUpdate($data)) {
if (! isset($data['abo_next_month']) || ! in_array($data['abo_next_month'], $this->getAdminExecutionMonths(), true)) {
\Session()->flash('alert-error', __('abo.error_next_date'));
return false;
}
if ($this->calculateAdminNextDate($data)->startOfDay()->lt(now()->startOfDay())) {
\Session()->flash('alert-error', __('abo.error_next_date'));
return false;
}
return true;
}
// Die Change-Sperre (Liefertag/Intervall) greift NUR, wenn der Liefertag tatsächlich
// geändert wird. Reines Pausieren/Kündigen (Intervall unverändert) unterliegt
// ausschließlich der eigenen Sperrfrist in updateStatus() + der Mindestlaufzeit.
$intervalChanged = (int) $data['abo_interval'] !== (int) $this->model->abo_interval;
if ($intervalChanged) {
// Sperre: X Tage vor nächster Ausführung kein Liefertag-Wechsel mehr (Pakete werden vorgepackt)
if ($this->model->next_date) {
$daysUntilExecution = (int) now()->diffInDays(Carbon::parse($this->model->next_date), false);
if ($daysUntilExecution >= 0 && $daysUntilExecution < self::getLockDaysChange()) {
\Session()->flash('alert-error', __('abo.error_change_locked', ['days' => $daysUntilExecution, 'lock' => self::getLockDaysChange()]));
return false;
}
}
// Prüfung: Das neue berechnete Ausführungsdatum muss mindestens getLockDaysChange() Tage entfernt sein.
// Falls next_date bereits in einem zukünftigen Monat liegt, wird das neue Datum in diesem Monat berechnet.
$newNextDate = $this->calculateNewNextDate($data['abo_interval']);
$daysUntilNewDate = (int) now()->diffInDays($newNextDate, false);
if ($daysUntilNewDate < self::getLockDaysChange()) {
\Session()->flash('alert-error', __('abo.error_abo_interval_too_soon', ['days' => $daysUntilNewDate, 'lock' => self::getLockDaysChange()]));
return false;
}
}
return true;
}
/**
* Berechnet das neue Ausführungsdatum unter Berücksichtigung des aktuellen next_date.
* Falls next_date bereits in einem zukünftigen Monat liegt, wird der Monatsanfang
* dieses Monats als Referenz verwendet, sodass der neue Tag im selben Monat landet.
*/
private function calculateNewNextDate(int $aboInterval): Carbon
{
$referenceDate = now();
if ($this->model->next_date) {
$currentNextDate = Carbon::parse($this->model->next_date);
if ($currentNextDate->format('Y-m') > now()->format('Y-m')) {
$referenceDate = $currentNextDate->startOfMonth();
}
}
return AboHelper::setNextDate($referenceDate, $aboInterval);
}
private function calculateAdminNextDate(array $data): Carbon
{
return Carbon::createFromFormat('Y-m-d', $data['abo_next_month'].'-01')
->startOfMonth()
->addDays(((int) $data['abo_interval']) - 1);
}
/**
* @return array<int, string>
*/
private function getAdminExecutionMonths(): array
{
return collect(range(0, 3))
->map(fn (int $offset): string => now()->copy()->startOfMonth()->addMonths($offset)->format('Y-m'))
->all();
}
private function isAdminUpdate(array $data): bool
{
return ($data['view'] ?? null) === 'admin';
}
}