<?php
namespace App\Subscriber\Payout;
use App\Dictionary\PayoutArea;
use App\Entity\Billing;
use App\Event\Payment\PayoutCreatedEvent;
use App\Event\Payment\PayoutSealedEvent;
use App\Lib\Payment\Admin\WebmasterPayoutItem;
use App\Service\Payment\BillingService;
use App\Service\Payment\PayoutService;
use App\Service\User\AccountService;
use App\Service\Webmaster\BalanceWebmasterService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class WebmasterPayoutSubscriber implements EventSubscriberInterface
{
/**
* @var BalanceWebmasterService
*/
protected $service;
/**
* @var PayoutService
*/
protected $payoutService;
/**
* @var AccountService
*/
protected $accountService;
/**
* @var BillingService
*/
protected $billingService;
/**
* WebmasterPayoutSubscriber constructor.
*/
public function __construct(BalanceWebmasterService $service, BillingService $billingService,
PayoutService $payoutService, AccountService $accountService)
{
$this->service = $service;
$this->payoutService = $payoutService;
$this->accountService = $accountService;
$this->billingService = $billingService;
}
public static function getSubscribedEvents(): array
{
return [
PayoutCreatedEvent::class => [
['onPayoutCreated', 0],
],
PayoutSealedEvent::class => [
['onPayoutSealed', 0],
],
];
}
public function onPayoutCreated(PayoutCreatedEvent $event)
{
$payout = $event->getPayout();
if (PayoutArea::WEBMASTER !== $payout->getArea()) {
return;
}
$this->service->markBalancesWithPayout($payout);
}
/**
* @throws \Doctrine\DBAL\Exception
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onPayoutSealed(PayoutSealedEvent $event)
{
$payout = $event->getPayout();
if (PayoutArea::WEBMASTER !== $payout->getArea() || !$payout->getIsSealed()) {
return;
}
$payouts = $this->payoutService->getPayoutListWebmaster($payout, 'sum', 'DESC');
$startBillingId = $this->billingService->getMaxBillingId() + 1;
$month = $payout->getBillingMonth();
$month->modify('-1 month');
foreach ($payouts as $item) {
$bill = $this->createBillForPayoutItem($item);
$bill->setPayout($payout);
$bill->setBillingId($startBillingId);
$bill->setInvoiceNumber($month->format('Ym').'.'.$startBillingId);
$this->billingService->storeEntity($bill, false);
++$startBillingId;
}
$this->billingService->delayedFlush();
}
protected function createBillForPayoutItem(WebmasterPayoutItem $item): Billing
{
$bill = new Billing();
$account = $this->accountService->findById($item->getAccountId());
$bill->setWebmaster($account->getWebmaster());
$bill->setPerson($account->getWebmaster()->getPerson());
$bill->setIsGross($item->isGross());
return $bill;
}
}