<?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 ChargebackProvisionSubscriber 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 => [
['revokeAmateurProvision', 1],
],
];
}
protected function getService(): BalanceAmateurService
{
return $this->balanceAmateurService;
}
/**
* @throws \App\Exception\Commission\NotAnAmateurException
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function revokeAmateurProvision(PaymentCreatedEvent $event)
{
$chargeback = $event->getPayment();
if (PaymentType::CHARGEBACK !== $chargeback->getType()) {
return;
}
// search for the initial booking
$booking = $this->paymentService->getOriginalPaymentOfType($chargeback, PaymentType::BOOKING);
if (!$booking) {
return;
}
$service = $this->getService();
// incomeBalances are the amateur provisions for the original booking
$incomeBalances = $service->getAmateurBalancesOfTypeByPayment($booking, BalanceType::INCOME);
foreach ($incomeBalances as $balanceAmateur) {
$member = $balanceAmateur->getMember();
$balance = $service->createProvisionByAmateur($member, BalanceType::CHARGEBACK);
// negate the previous provision
$balance->setAmount($balanceAmateur->getAmount() * -1);
$balance->setBalanceDetail($balanceAmateur->getBalanceDetail());
$balance->setPayment($chargeback); // the chargeback from the event
$service->storeBalanceAmateur($balance);
}
}
}