presseportale/app/Console/Commands/GrandfatherLegacySubscriptions.php
Kevin Adametz a00f9dc79a billing: MAN-Rechnungen fuer Ueberweisungskunden bearbeiten, hold-Altlast bereinigen
Bestandskunden aus dem Altsystem zahlen per Ueberweisung; nach dem 04:30-Lauf
fehlte bisher der gesamte Bearbeitungsweg (kein PDF, keine Mail, kein
Zahlungseingang, kein Bestandsschutz-Ende). Plan und Befund:
dev/lagacy-rechnungen/entwicklungsplan-2026-09-16.md.

Bereinigung (legacy:settle-unpaid, wiederholbar):
- Legacy-Status hold = nie bezahlt, ersatzlos erledigt. 9 daraus abgeleitete
  Bestandsschutz-Buendel werden gekuendigt, MAN-00001/00002 storniert.
  Archivzeilen bleiben erhalten, sind aber in Admin-Archiv und Kundenkonto
  standardmaessig ausgeblendet.
- pending/reminder (recurring) = offene Vorgaenge: Periode auf den
  Leistungsbeginn der unbezahlten Rechnung zurueckgedreht und als MAN-Rechnung
  neu ausgestellt (Archiv-Status superseded, replaces_legacy_invoice_number).
- pending/reminder (single) = abgeschrieben (uncollectible).
- legacy:grandfather-subscriptions wertet den Zahlungsstatus jetzt selbst aus.

Workflow in /admin/payments (ManualInvoiceDunningService, je Aktion mit
Eintrag im Aktivitaets-Verlauf):
- Rechnung senden: Mail mit PDF-Anhang, Bankverbindung aus billing.issuer,
  Hinweis auf Bestandsschutz-Ende; Zahlungsziel zaehlt ab Versand.
- Erinnerung: gleiche Mail im Mahn-Ton, Nachfrist bei verstrichener Frist.
- Bezahlt: Zahlungseingang laut Kontoauszug verbuchen.
- Bestandsschutz beenden: Rechnung storniert (nie geloescht), Buendel
  gekuendigt, weitere offene MAN-Rechnungen des Kunden storniert, optionale
  Kundenmail.
- Panel "Blockierte Vereinbarungen": faellige Posten ohne Rechnung (meist
  fehlende Rechnungsadresse) mit "Jetzt abrechnen" oder "Entfernen".

Schema: invoices bekommt user_payment_option_id, sent_at, reminded_at,
reminder_count, voided_at, void_reason, replaces_legacy_invoice_number
(inkl. Backfill der bestehenden MAN-Rechnungen). PDF-Primitiven des
Archiv-Renderers in den Trait DrawsPdf ausgelagert; MAN-PDF on-demand ueber
admin.invoices.pdf / me.invoices.manual-pdf (InvoicePolicy).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 10:56:29 +00:00

332 lines
14 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\UserPaymentOptionStatus;
use App\Models\LegacyInvoice;
use App\Models\PaymentOption;
use App\Models\UserPaymentOption;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
/**
* Leitet die noch aktiven, jährlich wiederkehrenden Legacy-Zahlungs-
* vereinbarungen aus dem Rechnungsarchiv ab und migriert sie als
* `grandfathered` in `user_payment_options` (D-13, Kriterien 12.06.2026).
*
* Quelle ist ausschließlich das read-only Archiv `legacy_invoices` (D-12):
* Pro (Portal, Legacy-Vereinbarung) zählt die jüngste Rechnung. Aktiv ist,
* was dort `payment_option.type = recurring`, `user_payment_option.status
* = active` und eine nicht zu weit zurückliegende `next_due_date` trägt.
* Alle anderen Rechnungen bleiben unangetastet im Archiv.
*
* Zahlungsstatus der jüngsten Rechnung (Einordnung 16.09.2026):
* - `paid` → Bestandsschutz mit der laufenden Periode.
* - `pending`/`reminder` → Bestandsschutz, aber die Rechnung ist offen: die
* Periode wird auf den Leistungsbeginn dieser Rechnung gesetzt, sodass der
* MAN-Kreis sie neu ausstellt (`legacy_conditions.open_legacy_invoice`).
* - `hold` → nie bezahlt, kein Bestandsschutz (übersprungen).
*
* Die migrierte Vereinbarung trägt `current_period_end = next_due_date` —
* damit stellt `billing:generate-manual-invoices` (MAN-Kreis) die nächste
* Rechnung zum gewohnten Rhythmus mit den Beträgen der letzten
* Legacy-Rechnung aus.
*
* Wiederholbar (D-18): Re-Runs aktualisieren bestehende Einträge anhand
* der Legacy-IDs in `legacy_conditions`, statt Duplikate anzulegen —
* die Kern-Migration läuft kurz vor dem Relaunch erneut.
*
* Verwendung:
* php artisan legacy:grandfather-subscriptions --dry-run
* php artisan legacy:grandfather-subscriptions --as-of=2026-06-12
* php artisan legacy:grandfather-subscriptions
*/
class GrandfatherLegacySubscriptions extends Command
{
protected $signature = 'legacy:grandfather-subscriptions
{--dry-run : Nur anzeigen, nichts schreiben}
{--as-of= : Stichtag für die Aktiv-Prüfung (Default: heute)}
{--grace-months=12 : Wie lange eine überfällige next_due_date noch als aktiv gilt}
{--no-report : Keinen JSON-Report schreiben}';
protected $description = 'Migriert aktive wiederkehrende Legacy-Zahlungen aus dem Rechnungsarchiv nach user_payment_options (grandfathered).';
private const CHUNK_SIZE = 200;
public function handle(): int
{
$isDryRun = (bool) $this->option('dry-run');
$asOf = $this->option('as-of') ? Carbon::parse($this->option('as-of'))->startOfDay() : today();
$graceMonths = max(0, (int) $this->option('grace-months'));
$staleBefore = $asOf->copy()->subMonths($graceMonths);
if ($isDryRun) {
$this->warn('[DRY-RUN] Kein tatsächlicher Schreibvorgang.');
}
$candidates = $this->collectLatestRecurringAgreements();
$report = [
'generated_at' => now()->toIso8601String(),
'as_of' => $asOf->toDateString(),
'grace_months' => $graceMonths,
'dry_run' => $isDryRun,
'created' => [],
'updated' => [],
'stale_skipped' => [],
'unpaid_skipped' => [],
'reopened_unpaid' => [],
'immediately_due' => [],
];
foreach ($candidates as $candidate) {
$nextDue = $candidate['next_due_date'];
if ($candidate['source_status'] === LegacyInvoice::STATUS_HOLD) {
$report['unpaid_skipped'][] = $this->describe($candidate);
continue;
}
if ($candidate['open_legacy_invoice'] !== null) {
$report['reopened_unpaid'][] = $this->describe($candidate);
}
if ($nextDue->lessThan($staleBefore)) {
$report['stale_skipped'][] = $this->describe($candidate);
continue;
}
if ($nextDue->lessThanOrEqualTo($asOf)) {
$report['immediately_due'][] = $this->describe($candidate);
}
if ($isDryRun) {
$this->line(sprintf('[dry-run] %s', $this->describe($candidate)));
continue;
}
$paymentOption = $this->resolveCatalogOption($candidate);
$existing = $this->findExisting($candidate);
$attributes = [
'user_id' => $candidate['user_id'],
'payment_option_id' => $paymentOption->id,
'status' => UserPaymentOptionStatus::Grandfathered->value,
'grandfathered_until' => $candidate['valid_until_date']?->toDateString(),
'current_period_start' => $candidate['period_start']->toDateString(),
'current_period_end' => $nextDue->toDateString(),
'stripe_subscription_id' => null,
'legacy_conditions' => $candidate['legacy_conditions'],
];
if ($existing) {
$existing->update($attributes);
$report['updated'][] = $this->describe($candidate);
} else {
UserPaymentOption::query()->create($attributes);
$report['created'][] = $this->describe($candidate);
}
}
$this->table(
['Ergebnis', 'Anzahl'],
[
['Kandidaten (aktiv, recurring)', count($candidates)],
['Neu angelegt', count($report['created'])],
['Aktualisiert (Re-Run)', count($report['updated'])],
['Übersprungen (stale)', count($report['stale_skipped'])],
['Übersprungen (hold, nie bezahlt)', count($report['unpaid_skipped'])],
['Offene Alt-Rechnung → MAN neu', count($report['reopened_unpaid'])],
['Davon sofort fällig', count($report['immediately_due'])],
],
);
foreach ($report['immediately_due'] as $line) {
$this->warn('Sofort fällig (MAN-Lauf rechnet beim nächsten Lauf ab): '.$line);
}
if (! $this->option('no-report')) {
$path = sprintf('migration/grandfather-subscriptions-%s.json', now()->format('Ymd-His'));
Storage::put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$this->info("Report: storage/app/{$path}");
}
return self::SUCCESS;
}
/**
* Jüngste Archiv-Rechnung pro (Portal, Legacy-Vereinbarung) mit
* aktiver wiederkehrender Zahlungsoption.
*
* @return array<int, array<string, mixed>>
*/
private function collectLatestRecurringAgreements(): array
{
$latest = [];
LegacyInvoice::query()
->whereNotNull('user_id')
->whereNotNull('pdf_payload')
->orderBy('id')
->chunk(self::CHUNK_SIZE, function ($invoices) use (&$latest): void {
foreach ($invoices as $invoice) {
$payload = $invoice->pdf_payload;
$upo = $payload['user_payment_option'] ?? null;
$option = $payload['payment_option'] ?? null;
if (! $upo || ! $option) {
continue;
}
if (($option['type'] ?? null) !== 'recurring' || ($upo['status'] ?? null) !== 'active') {
continue;
}
$key = $invoice->legacy_portal->value.'#'.$upo['id'];
$current = $latest[$key] ?? null;
if ($current && $current->invoice_date->greaterThanOrEqualTo($invoice->invoice_date)) {
continue;
}
$latest[$key] = $invoice;
}
});
return array_values(array_map(fn (LegacyInvoice $invoice): array => $this->toCandidate($invoice), $latest));
}
/**
* @return array<string, mixed>
*/
private function toCandidate(LegacyInvoice $invoice): array
{
$payload = $invoice->pdf_payload;
$snapshot = $invoice->raw_snapshot ?? [];
$upo = $payload['user_payment_option'];
$option = $payload['payment_option'];
$nextDue = isset($upo['next_due_date'])
? Carbon::parse($upo['next_due_date'])->startOfDay()
: Carbon::parse($snapshot['service_period_end_date'] ?? $invoice->invoice_date)->startOfDay();
$periodStart = isset($snapshot['service_period_begin_date'])
? Carbon::parse($snapshot['service_period_begin_date'])->startOfDay()
: $nextDue->copy()->subYear();
$openLegacyInvoice = null;
// Offene Rechnung: Die zuletzt fakturierte Periode ist noch nicht
// bezahlt → Fälligkeit auf deren Leistungsbeginn setzen, damit der
// MAN-Kreis genau diese Periode neu ausstellt.
if (in_array($invoice->status, [LegacyInvoice::STATUS_PENDING, LegacyInvoice::STATUS_REMINDER], true)) {
$openLegacyInvoice = [
'id' => $invoice->id,
'number' => $invoice->number,
'invoice_date' => $invoice->invoice_date->toDateString(),
'total_cents' => $invoice->total_cents,
];
$nextDue = $periodStart->copy();
$periodStart = $nextDue->copy()->subYear();
}
return [
'user_id' => $invoice->user_id,
'legacy_portal' => $invoice->legacy_portal->value,
'legacy_upo_id' => (int) $upo['id'],
'article_number' => (string) ($option['article_number'] ?? 'UNBEKANNT'),
'next_due_date' => $nextDue,
'period_start' => $periodStart,
'valid_until_date' => isset($upo['valid_until_date']) && $upo['valid_until_date']
? Carbon::parse($upo['valid_until_date'])->startOfDay()
: null,
'source_status' => $invoice->status,
'open_legacy_invoice' => $openLegacyInvoice,
'legacy_conditions' => [
'legacy_portal' => $invoice->legacy_portal->value,
'legacy_user_payment_option_id' => (int) $upo['id'],
'legacy_payment_option_id' => (int) ($option['id'] ?? 0),
'article_number' => $option['article_number'] ?? null,
'name' => $payload['payment_option_translation']['name'] ?? null,
'interval' => 'yearly',
'net_cents' => $this->deriveNetCents($invoice),
'last_total_cents' => $invoice->total_cents,
'last_is_netto' => (bool) ($snapshot['is_netto'] ?? false),
'source_invoice_number' => $invoice->number,
'source_invoice_date' => $invoice->invoice_date->toDateString(),
...($openLegacyInvoice ? ['open_legacy_invoice' => $openLegacyInvoice] : []),
],
];
}
/**
* Netto-Vertragsbasis aus der letzten Legacy-Rechnung. Legacy fakturierte
* brutto (Steuer inkludiert, z. B. 199,00 €); steuerbefreite Kunden
* erhielten den Netto-Ausweis (`is_netto`, z. B. 167,23 €). Die neue
* Rechnungsstellung arbeitet immer auf Netto-Basis — die Steuer wird
* pro Rechnung über den VatResolver bestimmt.
*/
private function deriveNetCents(LegacyInvoice $invoice): int
{
$isNetto = (bool) (($invoice->raw_snapshot ?? [])['is_netto'] ?? false);
if ($isNetto) {
return $invoice->total_cents;
}
$vatRate = (float) config('billing.vat_rate', 0.19);
return (int) round($invoice->total_cents / (1 + $vatRate));
}
/**
* Versteckter Katalog-Eintrag pro (Portal, Legacy-Artikel) — die
* verbindlichen Beträge pro Vereinbarung liegen in legacy_conditions.
*/
private function resolveCatalogOption(array $candidate): PaymentOption
{
$portalShort = $candidate['legacy_portal'] === 'presseecho' ? 'PE' : 'BP';
$articleNumber = sprintf('LEGACY-%s-%s', $portalShort, $candidate['article_number']);
return PaymentOption::query()->firstOrCreate(
['article_number' => $articleNumber],
[
'type' => 'recurring',
// Katalogpreise sind netto (Entscheidung 12.06.2026).
'price_cents' => $candidate['legacy_conditions']['net_cents'],
'currency' => config('billing.default_currency'),
'interval' => 'yearly',
'is_hidden' => true,
],
);
}
private function findExisting(array $candidate): ?UserPaymentOption
{
return UserPaymentOption::query()
->where('user_id', $candidate['user_id'])
->get()
->first(function (UserPaymentOption $option) use ($candidate): bool {
$conditions = $option->legacy_conditions ?? [];
return ($conditions['legacy_portal'] ?? null) === $candidate['legacy_portal']
&& (int) ($conditions['legacy_user_payment_option_id'] ?? 0) === $candidate['legacy_upo_id'];
});
}
private function describe(array $candidate): string
{
return sprintf(
'User #%d · %s · Legacy-UPO #%d · fällig %s · netto %s €',
$candidate['user_id'],
$candidate['legacy_portal'],
$candidate['legacy_upo_id'],
$candidate['next_due_date']->toDateString(),
number_format($candidate['legacy_conditions']['net_cents'] / 100, 2, ',', '.'),
);
}
}