|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Odiseo\SyliusReferralsPlugin\Controller\Shop; |
|
6
|
|
|
|
|
7
|
|
|
use Odiseo\SyliusReferralsPlugin\Entity\AffiliateInterface; |
|
8
|
|
|
use Odiseo\SyliusReferralsPlugin\Repository\AffiliateReferralViewRepositoryInterface; |
|
9
|
|
|
use Odiseo\SyliusReferralsPlugin\Repository\OrderRepositoryInterface; |
|
10
|
|
|
use Sylius\Component\Core\Model\CustomerInterface; |
|
11
|
|
|
use Sylius\Component\Customer\Context\CustomerContextInterface; |
|
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
14
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpException; |
|
15
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
|
16
|
|
|
use Twig\Environment; |
|
17
|
|
|
|
|
18
|
|
|
final class StatisticsAffiliateReferralAction |
|
19
|
|
|
{ |
|
20
|
|
|
public function __construct( |
|
21
|
|
|
private CustomerContextInterface $customerContext, |
|
22
|
|
|
private OrderRepositoryInterface $orderRepository, |
|
23
|
|
|
private AffiliateReferralViewRepositoryInterface $affiliateReferralViewRepository, |
|
24
|
|
|
private Environment $twig, |
|
25
|
|
|
) { |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function __invoke(Request $request): Response |
|
29
|
|
|
{ |
|
30
|
|
|
/** @var CustomerInterface|null $customer */ |
|
31
|
|
|
$customer = $this->customerContext->getCustomer(); |
|
32
|
|
|
if (null === $customer) { |
|
33
|
|
|
throw new HttpException(Response::HTTP_UNAUTHORIZED); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if (!$customer instanceof AffiliateInterface) { |
|
37
|
|
|
throw new NotFoundHttpException(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
$sales = $this->orderRepository->countSalesByAffiliate($customer); |
|
41
|
|
|
$visits = $this->affiliateReferralViewRepository->countViewsByAffiliate($customer); |
|
42
|
|
|
$average = $this->getAverage($sales, $visits); |
|
43
|
|
|
|
|
44
|
|
|
$data = [ |
|
45
|
|
|
'sales' => $sales, |
|
46
|
|
|
'visits' => $visits, |
|
47
|
|
|
'average' => $average, |
|
48
|
|
|
]; |
|
49
|
|
|
|
|
50
|
|
|
$content = $this->twig->render( |
|
51
|
|
|
'@OdiseoSyliusReferralsPlugin/Shop/Account/AffiliateReferral/Index/Statistics/_template.html.twig', |
|
52
|
|
|
$data, |
|
53
|
|
|
); |
|
54
|
|
|
|
|
55
|
|
|
return new Response($content); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function getAverage(int $sales, int $visits): int |
|
59
|
|
|
{ |
|
60
|
|
|
if ($sales == 0 || $visits == 0) { |
|
61
|
|
|
return 0; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return (int) (($sales / $visits) * 100); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|