<?php
namespace App\Subscriber\Balance;
use App\Dictionary\BalanceType;
use App\Dictionary\PaymentType;
use App\Event\Payment\PaymentCreatedEvent;
use App\Service\Amateur\BalanceAmateurService;
use App\Service\Payment\PaymentService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SettlementProvisionSubscriber implements EventSubscriberInterface
{
protected BalanceAmateurService $balanceAmateurService;
protected PaymentService $paymentService;
/**
* ChargebackProvisionSubscriber constructor.
*/
public function __construct(BalanceAmateurService $balanceAmateurService, PaymentService $paymentService)
{
$this->balanceAmateurService = $balanceAmateurService;
$this->paymentService = $paymentService;
}
public static function getSubscribedEvents(): array
{
return [
PaymentCreatedEvent::class => [
['settleAmateurProvision', 0],
],
];
}
protected function getBalanceAmateurService(): BalanceAmateurService
{
return $this->balanceAmateurService;
}
protected function getPaymentService(): PaymentService
{
return $this->paymentService;
}
/**
* @throws \App\Exception\Commission\NotAnAmateurException
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function settleAmateurProvision(PaymentCreatedEvent $event)
{
$payment = $event->getPayment();
if (PaymentType::SETTLEMENT !== $payment->getType()) {
return;
}
$paymentService = $this->getPaymentService();
// Bei Teilzahlungen nach Chargebacks keine Provision, erst bei komplettem Ausgleich
if (0 == $paymentService->getOpenBookingAmountByPayment($payment)) {
// @TODO assignAmateurProvisionByPurchase
// search for the chargeback of the initial payment
$chargeback = $paymentService->getOriginalPaymentOfType($payment, PaymentType::CHARGEBACK);
if (!$chargeback) {
return;
}
$balanceService = $this->getBalanceAmateurService();
// $chargebackBalances are the (negative) amateur provisions for the original chargeback
$chargebackBalances = $balanceService->getAmateurBalancesOfTypeByPayment($chargeback, BalanceType::CHARGEBACK);
foreach ($chargebackBalances as $balanceAmateur) {
$member = $balanceAmateur->getMember();
$balance = $balanceService->createProvisionByAmateur($member, BalanceType::SETTLEMENT);
$balance->setAmount($balanceAmateur->getAmount() * -1); // negate the previous provision
$balance->setBalanceDetail($balanceAmateur->getBalanceDetail());
$balance->setPayment($payment); // the settlement from the event
$balanceService->storeBalanceAmateur($balance);
}
}
}
}