← Code-Übersicht

ResolveVendorUseCase.php

Pfad: src/Application/Rechnung/ResolveVendorUseCase.php

Ext: php

Größe: 1875 Bytes

Geändert: 2026-07-16T14:10:57+02:00

Frühere Version vom 2026-07-16T14:10:57+02:00 · zur aktuellen Fassung

<?php
declare(strict_types=1);

namespace Demo\Application\Rechnung;

use Demo\Domain\Rechnung\ExtractedInvoiceData;
use Demo\Domain\Rechnung\InvoiceErrorCode;
use Demo\Domain\Rechnung\InvoiceLoggerPort;
use Demo\Domain\Rechnung\LexofficePort;

/**
 * Use Case: Kontaktabgleich oder Kontakt-Anlage.
 */
final class ResolveVendorUseCase
{
    /**
     * @param LexofficePort    $lexoffice Buha-Adapter.
     * @param InvoiceLoggerPort $logger    Logging.
     */
    public function __construct(
        private LexofficePort $lexoffice,
        private InvoiceLoggerPort $logger
    ) {
    }

    /**
     * @param string             $runId   Lauf-ID.
     * @param ExtractedInvoiceData $data   Extrahierte Daten.
     * @return string Kontakt-ID.
     */
    public function execute(string $runId, ExtractedInvoiceData $data): string
    {
        $matches = $this->lexoffice->findContactByName($data->vendorName);

        if (count($matches) === 1) {
            $this->logger->logStep($runId, 'vendor', 'DONE', ['action' => 'match']);
            return (string) ($matches[0]['id'] ?? '');
        }

        if (count($matches) > 1) {
            throw new InvoiceProcessException(
                InvoiceErrorCode::VENDOR_MATCH,
                'vendor',
                'Mehrdeutiger Kontakt in Buha'
            );
        }

        $this->logger->logStep($runId, 'vendor', 'START', ['action' => 'create']);
        $contactId = $this->lexoffice->createContact($data->vendorName, $data->vendorAddressSignature);
        if ($contactId === '') {
            throw new InvoiceProcessException(
                InvoiceErrorCode::VENDOR_MATCH,
                'vendor',
                'Kontakt konnte nicht angelegt werden'
            );
        }

        $this->logger->logStep($runId, 'vendor', 'DONE', ['action' => 'created']);
        return $contactId;
    }
}