AppExtension.php 20.6 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6
<?php

namespace App\Twig;

use App\Entity\AchatMonnaieAConfirmerAdherent;
use App\Entity\AchatMonnaieAConfirmerPrestataire;
7 8
use App\Entity\AchatMonnaieAdherent;
use App\Entity\AchatMonnaiePrestataire;
Julien Jorry committed
9 10
use App\Entity\Adherent;
use App\Entity\Comptoir;
11 12 13 14 15
use App\Entity\CotisationAdherent;
use App\Entity\CotisationPrestataire;
use App\Entity\Don;
use App\Entity\DonAdherent;
use App\Entity\DonPrestataire;
Julien Jorry committed
16 17 18 19
use App\Entity\Flux;
use App\Entity\GlobalParameter;
use App\Entity\Groupe;
use App\Entity\Groupeprestataire;
20
use App\Entity\HelloAsso;
Julien Jorry committed
21 22 23 24 25 26 27 28 29
use App\Entity\News;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\Siege;
use App\Entity\User;
use App\Enum\CurrencyEnum;
use App\Flux\AccountableInterface;
use App\Utils\CotisationUtils;
use App\Utils\OperationUtils;
30
use App\Utils\TAVCotisationUtils;
Julien Jorry committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Security;
use Twig\Extension\AbstractExtension;
use Twig\TwigTest;

class AppExtension extends AbstractExtension
{
    public $em;
    public $security;
    public $container;
    public $paginator;
    public $session;
    public $operationUtils;
    public $cotisationUtils;
50 51 52 53 54 55 56 57 58 59 60 61
    public $tavCotisationUtils;

    public function __construct(
        ContainerInterface $container,
        Security $security,
        EntityManagerInterface $em,
        PaginatorInterface $paginator,
        SessionInterface $session,
        OperationUtils $operationUtils,
        CotisationUtils $cotisationUtils,
        TAVCotisationUtils $tavCotisationUtils
    ) {
Julien Jorry committed
62 63 64 65 66 67 68
        $this->em = $em;
        $this->security = $security;
        $this->container = $container;
        $this->paginator = $paginator;
        $this->session = $session;
        $this->operationUtils = $operationUtils;
        $this->cotisationUtils = $cotisationUtils;
69
        $this->tavCotisationUtils = $tavCotisationUtils;
Julien Jorry committed
70 71 72 73 74 75 76 77 78 79 80 81
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getMLCPrestataire', [$this, 'getMLCPrestataire']),
            new \Twig_SimpleFunction('showModalGroupChoice', [$this, 'showModalGroupChoice']),
            new \Twig_SimpleFunction('getCurrentRole', [$this, 'getCurrentRole']),
            new \Twig_SimpleFunction('getCurrentComptoir', [$this, 'getCurrentComptoir']),
            new \Twig_SimpleFunction('getCurrentGroupe', [$this, 'getCurrentGroupe']),
            new \Twig_SimpleFunction('getCurrentPrestataire', [$this, 'getCurrentPrestataire']),
            new \Twig_SimpleFunction('isCotisationValid', [$this, 'isCotisationValid']),
82 83
            new \Twig_SimpleFunction('isCotisationValidForPresta', [$this, 'isCotisationValidForPresta']),
            new \Twig_SimpleFunction('isCotisationValidForAdherent', [$this, 'isCotisationValidForAdherent']),
Julien Jorry committed
84 85 86
            new \Twig_SimpleFunction('getSiege', [$this, 'getSiege']),
            new \Twig_SimpleFunction('isDevFixture', [$this, 'isDevFixture']),
            new \Twig_SimpleFunction('getLastNews', [$this, 'getLastNews']),
87
            new \Twig_SimpleFunction('getAllAdherents', [$this, 'getAllAdherents']),
Julien Jorry committed
88 89 90 91 92 93
            new \Twig_SimpleFunction('getAllPrestataires', [$this, 'getAllPrestataires']),
            new \Twig_SimpleFunction('getAllGroupePrestataires', [$this, 'getAllGroupePrestataires']),
            new \Twig_SimpleFunction('getAllComptoirs', [$this, 'getAllComptoirs']),
            new \Twig_SimpleFunction('getAllRubriques', [$this, 'getAllRubriques']),
            new \Twig_SimpleFunction('getAllGroupes', [$this, 'getAllGroupes']),
            new \Twig_SimpleFunction('getAllFlux', [$this, 'getAllFlux']),
94
            new \Twig_SimpleFunction('getValidCotisations', [$this, 'getValidCotisations']),
Julien Jorry committed
95 96 97 98 99 100 101 102 103
            new \Twig_SimpleFunction('isCurrentAccountable', [$this, 'isCurrentAccountable']),
            new \Twig_SimpleFunction('getDemandeAchatMonnaie', [$this, 'getDemandeAchatMonnaie']),
            new \Twig_SimpleFunction('hasDemandeAchatMonnaie', [$this, 'hasDemandeAchatMonnaie']),
            new \Twig_SimpleFunction('getLastOperations', [$this, 'getLastOperations']),
            new \Twig_SimpleFunction('mediaurl', [$this, 'mediaurl']),
            new \Twig_SimpleFunction('getWordpressApiKey', [$this, 'getWordpressApiKey']),
            new \Twig_SimpleFunction('getTotalMonnaieEmise', [$this, 'getTotalMonnaieEmise']),
            new \Twig_SimpleFunction('getStatsMonnaie', [$this, 'getStatsMonnaie']),
            new \Twig_SimpleFunction('getCurrencyName', [$this, 'getCurrencyName']),
104 105
            new \Twig_SimpleFunction('getPaymentReceiptUrlFromFlux', [$this, 'getPaymentReceiptUrlFromFlux']),
            new \Twig_SimpleFunction('getDonType', [$this, 'getDonType']),
106
            new \Twig_SimpleFunction('getLastTavCotisationForAdherent', [$this, 'getLastTavCotisationForAdherent']),
107
            new \Twig_SimpleFunction('getPrestaLastTransactionsExportDate', [$this, 'getPrestaLastTransactionsExportDate']),
Julien Jorry committed
108 109 110 111 112 113
            new \Twig_SimpleFunction('parameter', function ($name) {
                return $this->container->getParameter($name);
            }),
        ];
    }

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    public function getPaymentReceiptUrlFromFlux(Flux $flux): ?string
    {
        $helloasso = $this->em->getRepository(HelloAsso::class)->findOneBy(['flux' => $flux]);
        if (null != $helloasso) {
            return $helloasso->getPaymentReceiptUrl();
        }

        return '';
    }

    public function getDonType($don): ?string
    {
        if ($don instanceof DonAdherent || ($don instanceof Don && Don::TYPE_DON_ADHERENT == $don->getType())) {
            $cotis = $this->em->getRepository(CotisationAdherent::class)->findOneBy(['don' => $don]);
            if (null === $cotis) {
                $achat = $this->em->getRepository(AchatMonnaieAdherent::class)->findOneBy(['don' => $don]);

                return $achat;
            }

            return $cotis;
        } elseif ($don instanceof DonPrestataire || ($don instanceof Don && Don::TYPE_DON_PRESTATAIRE == $don->getType())) {
            $cotis = $this->em->getRepository(CotisationPrestataire::class)->findOneBy(['don' => $don]);
            if (null === $cotis) {
                $achat = $this->em->getRepository(AchatMonnaiePrestataire::class)->findOneBy(['don' => $don]);

                return $achat;
            }

            return $cotis;
        }

        return null;
    }

Julien Jorry committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    public function getCurrencyName(string $currency): string
    {
        if (!in_array($currency, CurrencyEnum::getAvailableTypes())) {
            throw new \Exception('Opération impossible ! Type de currency  ' . $currency . ' inexistant !');
        }
        $symbol = $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::MLC_SYMBOL);
        switch ($currency) {
            case CurrencyEnum::CURRENCY_EMLC:
                return 'e' . $symbol;
            case CurrencyEnum::CURRENCY_MLC:
                return $symbol;
            case CurrencyEnum::CURRENCY_EURO:
                return '€';
            case CurrencyEnum::CURRENCY_MLC_NANTIE:
                return $symbol;
        }

        return '';
    }

    public function getMLCPrestataire(): ?Prestataire
    {
        try {
            $prestaMLC = $this->em->getRepository(Prestataire::class)->getPrestataireMLC();

            return $prestaMLC;
        } catch (\Exception $e) {
            return null;
        }

        return null;
    }

    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('json_decode', [$this, 'jsonDecode']),
            new \Twig_SimpleFilter('safe_email', [$this, 'safeEmailFilter']),
        ];
    }

    public function jsonDecode($string)
    {
        return json_decode($string, true);
    }

    public function getWordpressApiKey()
    {
        $users = $this->em->getRepository(User::class)->findByRole('ROLE_API');
        if (count($users) <= 0) {
            // @TODO :erreur => crée un nouvel utilisateur API si non existant ?
            return '';
        }

        return $users[0]->getApiKey();
    }

    public function showModalGroupChoice()
    {
        if (null != $this->security->getUser()) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            /* Enable display of modal after the first login of a user,
             * the first time there is an enable prestataire associated to the account.
             *
             * The user now realizes that a new role is available and can be picked up.
             *
             * Otherwise, in case prestataire is enabled after first login, user would login automaticaly as
             * adherent again without being noticed that prestataire has been enabled.
             */
            if($this->container->getParameter('presta_self_init_and_eval')) {
                $hasPrestataireEnabled = $this->security->getUser()->getPrestataires() && !$this->security->getUser()->getPrestataires()->isEmpty();
                $nowIsfirstLoginWithPrestaEnabled = $this->security->getUser()->getBeforeFirstLoginWithPrestaEnabled();
                if ($hasPrestataireEnabled && $nowIsfirstLoginWithPrestaEnabled) {
                    $this->security->getUser()->setBeforeFirstLoginWithPrestaEnabled(false);
                    $this->em->flush();
                    return true;
                }
            }
Julien Jorry committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239
            if (count($this->security->getUser()->getPossiblegroups()) > 1 && 0 == count($this->security->getUser()->getGroups())) {
                return true;
            }
        }

        return false;
    }

    public function getCurrentRole()
    {
        $return = $this->security->getUser()->getGroups()[0]->getName();
        $user = $this->security->getUser();
        if (null != $this->session->get('_prestagere') && $user->isGranted('ROLE_PRESTATAIRE')) {
            $presta = $this->session->get('_prestagere');
240
            $presta = $this->em->getRepository(Prestataire::class)->findOneById($presta->getId());
Julien Jorry committed
241 242 243 244 245
            $return .= '<br/>' . $presta->__toString();
        } elseif (null != $user->getAdherent() && $user->isGranted('ROLE_ADHERENT')) {
            $return .= '<br/>' . $user->getAdherent()->__toString();
        } elseif (null != $this->session->get('_comptoirgere') && $user->isGranted('ROLE_COMPTOIR')) {
            $comptoir = $this->session->get('_comptoirgere');
246
            $comptoir = $this->em->getRepository(Comptoir::class)->findOneById($comptoir->getId());
Julien Jorry committed
247 248 249
            $return .= '<br/>' . $comptoir->__toString();
        } elseif (null != $this->session->get('_groupegere') && $user->isGranted('ROLE_GESTION_GROUPE')) {
            $groupe = $this->session->get('_groupegere');
250
            $groupe = $this->em->getRepository(Groupe::class)->findOneById($groupe->getId());
Julien Jorry committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            $return .= '<br/>' . $groupe->__toString();
        }

        return $return;
    }

    public function getCurrentComptoir()
    {
        if (!$this->session->has('_comptoirgere')) {
            return null;
        }

        return $this->em->getRepository(Comptoir::class)->findOneById($this->session->get('_comptoirgere')->getId());
    }

    public function getCurrentGroupe()
    {
        if (!$this->session->has('_groupegere')) {
            return null;
        }

        return $this->em->getRepository(Groupe::class)->findOneById($this->session->get('_groupegere')->getId());
    }

    public function getCurrentPrestataire()
    {
        if (!$this->session->has('_prestagere')) {
            return null;
        }

        return $this->em->getRepository(Prestataire::class)->findOneById($this->session->get('_prestagere')->getId());
    }

284
    /**
285 286 287 288 289
     * isCotisationValid.
     *
     * @param UserInterface|null $user
     *
     * @return bool|date
290 291
     */
    public function isCotisationValid(?UserInterface $user = null)
Julien Jorry committed
292 293 294 295
    {
        return $this->cotisationUtils->isCotisationValid($user);
    }

296
    /**
297 298 299 300 301
     * [isCotisationValidForPresta.
     *
     * @param Prestataire|null $presta
     *
     * @return bool|date
302 303
     */
    public function isCotisationValidForPresta(?Prestataire $presta = null)
304 305 306 307
    {
        return $this->cotisationUtils->isCotisationValidForPresta($presta);
    }

308
    /**
309 310 311 312 313
     * [isCotisationValidForAdherent.
     *
     * @param Adherent|null $adherent
     *
     * @return bool|date
314 315
     */
    public function isCotisationValidForAdherent(?Adherent $adherent = null)
316 317 318 319
    {
        return $this->cotisationUtils->isCotisationValidForAdherent($adherent);
    }

320 321 322 323 324 325 326 327 328 329 330 331
    /**
     * [getLastTavCotisationForAdherent.
     *
     * @param Adherent|null $adherent
     *
     * @return bool|date
     */
    public function getLastTavCotisationForAdherent(?Adherent $adherent = null)
    {
        return $this->tavCotisationUtils->getLastTavCotisationForAdherent($adherent);
    }

Julien Jorry committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    public function isDevFixture(?string $username = null)
    {
        if (null == $username) {
            $user = $this->em->getRepository(User::class)->findBy(['username' => ['user_redacteur', 'user_tresorier', 'user_prestataire', 'user_contact']]);

            return 4 === count($user);
        }

        return null != $this->em->getRepository(User::class)->findOneByUsername($username);
    }

    public function getSiege()
    {
        return $this->em->getRepository(Siege::class)->getTheOne();
    }

    public function getLastNews($limit = 5)
    {
350
        return $this->em->getRepository(News::class)->findLatest($limit)->getResult();
Julien Jorry committed
351 352
    }

353 354 355 356 357
    public function getAllAdherents()
    {
        return $this->em->getRepository(Adherent::class)->findOrderByName();
    }

358
    public function getAllPrestataires($orderBy = 'raison', $direction = 'ASC', $limit = null)
Julien Jorry committed
359
    {
360
        return $this->em->getRepository(Prestataire::class)->findDefault('all', $orderBy, $direction, $limit);
Julien Jorry committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    }

    public function getAllGroupePrestataires($type = '')
    {
        if (!empty($type)) {
            return $this->em->getRepository(Groupeprestataire::class)->findBy(['type' => $type, 'enabled' => true]);
        }

        return $this->em->getRepository(Groupeprestataire::class)->findBy(['enabled' => true]);
    }

    public function getAllComptoirs()
    {
        return $this->em->getRepository(Comptoir::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function getAllRubriques()
    {
        return $this->em->getRepository(Rubrique::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function isCurrentAccountable(User $user, AccountableInterface $object)
    {
        $obj = $this->operationUtils->getCurrentAccountable($user);
        if ($obj->getId() == $object->getId() && get_class($obj) == get_class($object)) {
            return true;
        }

        return false;
    }

    public function getDemandeAchatMonnaie($reconverti = true)
    {
        $obj = $this->operationUtils->getCurrentAccountable($this->security->getUser());
        if ($obj instanceof Prestataire) {
            $q = $this->em->getRepository(AchatMonnaieAConfirmerPrestataire::class)->findBy(['destinataire' => $obj, 'reconverti' => $reconverti], ['createdAt' => 'DESC']);
        } elseif ($obj instanceof Adherent) {
            $q = $this->em->getRepository(AchatMonnaieAConfirmerAdherent::class)->findBy(['destinataire' => $obj, 'reconverti' => $reconverti], ['createdAt' => 'DESC']);
        }

        return $q;
    }

    public function hasDemandeAchatMonnaie($reconverti = true): bool
    {
        $q = $this->getDemandeAchatMonnaie($reconverti);

        return null != $q && count($q) > 0;
    }

    public function getTotalMonnaieEmise(): float
    {
        $return = $this->em->getRepository(Flux::class)->getTotalVenteAchat();
        if (null == $return) {
            return 0;
        }

        return $return;
    }

    public function getStatsMonnaie(string $currency = CurrencyEnum::CURRENCY_EMLC): float
    {
        $siege = $this->em->getRepository(Siege::class)->getTheOne();

        if (!empty($currency)) {
            if (!in_array($currency, [CurrencyEnum::CURRENCY_EMLC, CurrencyEnum::CURRENCY_MLC_NANTIE])) {
                return (float) 0;
            }

430 431 432
            if ($currency == CurrencyEnum::CURRENCY_MLC_NANTIE) {
                return round($siege->getAccountWithCurrency($currency)->getBalance(), 0);
            }
Julien Jorry committed
433 434 435 436 437 438 439 440 441 442
            return $siege->getAccountWithCurrency($currency)->getBalance();
        }

        return $siege->getEmlcAccount()->getBalance();
    }

    public function getLastOperations(Request $request, User $user, string $currency = null, int $limit = 10)
    {
        $query = $this->operationUtils->getUserOperationsByCurrency($request, $currency);

443
        // return $query->getResult();
Julien Jorry committed
444 445 446 447 448 449 450 451 452 453 454 455 456
        if (null != $query) {
            $pagination = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/ ,
                $limit/*limit per page*/
            );

            return $pagination;
        }

        return null;
    }

457 458 459 460 461 462 463 464 465 466 467 468
    public function getValidCotisations(User $user, Request $request)
    {
        $cotisationsValid = [];
        $cotisations = $this->getAllFlux($user, $request, 'cotisation');
        foreach ($cotisations as $keys => $cotisation) {
            if (null != $cotisation->getCotisationInfos() && $cotisation->getCotisationInfos()->isRecu()) {
                $cotisationsValid[] = $cotisation;
            }
        }
        return $cotisationsValid;
    }

Julien Jorry committed
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    public function getAllFlux(User $user, Request $request, $parenttype = null)
    {
        $query = null;
        if (null != $this->session->get('_prestagere')) {
            if ($this->security->isGranted('ROLE_PRESTATAIRE')) {
                $query = $this->em->getRepository(Flux::class)->getQueryByPrestataire($this->session->get('_prestagere'), $parenttype);
            } elseif ($this->security->isGranted('ROLE_CAISSIER')) {
                $query = $this->em->getRepository(Flux::class)->getQueryByCaissier($this->session->get('_prestagere'));
            }
        } elseif (null != $user->getAdherent()) {
            $query = $this->em->getRepository(Flux::class)->getQueryByAdherent($user->getAdherent(), $parenttype);
        } elseif (null != $this->session->get('_comptoirgere')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByComptoir($this->session->get('_comptoirgere'));
        } elseif (null != $this->session->get('_groupegere')) {
            $query = $this->em->getRepository(Flux::class)->getQueryByGroupe($this->session->get('_groupegere'));
        }
        if (null != $query) {
            $pagination = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/ ,
                10/*limit per page*/
            );

            return $pagination;
        }

        return null;
    }

    public function getAllGroupes()
    {
        return $this->em->getRepository(Groupe::class)->findBy(['enabled' => true], ['name' => 'ASC']);
    }

    public function mediaurl($media, $format)
    {
        $provider = $this->container->get($media->getProviderName());

        return $provider->generatePublicUrl($media, $format);
    }

    public function getTests(): array
    {
        return [
            new TwigTest('instanceof', [$this, 'instanceof']),
        ];
    }

    public function instanceof($var, $instance)
    {
        $reflexionClass = new \ReflectionClass($instance);

        return $reflexionClass->isInstance($var);
    }

    /**
     * Protects email address.
     * (inspired by : https://github.com/getgrav/grav/blob/develop/system/src/Grav/Common/Twig/TwigExtension.php ).
     *
     * @param string $str
     *
     * @return string
     */
    public function safeEmailFilter($str)
    {
        $email = '';
        for ($i = 0, $len = strlen($str); $i < $len; ++$i) {
            $j = mt_rand(0, 1);
            if (0 === $j) {
                $email .= '&#' . ord($str[$i]) . ';';
            } elseif (1 === $j) {
                $email .= $str[$i];
            }
        }

        return str_replace('@', '&#64;', $email);
    }
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

    public function getPrestaLastTransactionsExportDate(?Adherent $adherent = null)
    {
        if (!$this->session->has('_prestagere')) {
            return null;
        }

        $presta = $this->em->getRepository(Prestataire::class)->findOneById($this->session->get('_prestagere')->getId());

        $datetime_last_export = $presta->getLastTransactionsExportDatetime();

        $res = "";
        if (null == $datetime_last_export) {
            $res = $presta->getCreatedAt()->format('d/m/Y H\hi');
        } else {
            $res = $datetime_last_export->format('d/m/Y H\hi');
        }

        return $res;
    }
Julien Jorry committed
566
}