src/Controller/Risk/RiskController.php line 83

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Risk;
  3. use App\Builder\RiskModelBuilder;
  4. use App\Constant\BusinessActivityTypes;
  5. use App\Constant\BusinessLinesType;
  6. use App\Constant\CountryListConstant;
  7. use App\Constant\RiskNaturalPerson;
  8. use App\Constant\SourceOfFundsType;
  9. use App\Form\Model\Instance\InstanceFilterModel;
  10. use App\Form\Model\Merchant\MerchantFilterModel;
  11. use App\Form\Model\Risk\Person\PersonRiskLevelModel;
  12. use App\Form\Model\Risk\Person\RiskLevelModel;
  13. use App\Form\Model\Risk\Person\RisksPersonModel;
  14. use App\Form\Type\Risk\Person\PersonRiskLevelType;
  15. use App\RequestManager\Application\BusinessActivityRequestManager;
  16. use App\RequestManager\InstanceRequestManager;
  17. use App\RequestManager\MerchantRequestManager;
  18. use App\RequestManager\RiskRequestManager;
  19. use App\RequestManager\RiskV3RequestManager;
  20. use GuzzleHttp\Exception\GuzzleException;
  21. use JsonException;
  22. use App\Controller\BaseController;
  23. use Paynetics\Exception\ApiException;
  24. use Psr\Cache\CacheItemPoolInterface;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Serializer\Exception\ExceptionInterface;
  29. /**
  30.  * Class DashboardController
  31.  * @package App\Controller
  32.  */
  33. class RiskController extends BaseController
  34. {
  35.     /**
  36.      * @var RiskRequestManager
  37.      * @required
  38.      */
  39.     public RiskRequestManager $riskRequestManager;
  40.     /**
  41.      * @required
  42.      */
  43.     public RiskV3RequestManager $riskV3RequestManager;
  44.     /**
  45.      * @var MerchantRequestManager
  46.      * @required
  47.      */
  48.     public MerchantRequestManager $merchantRequestManager;
  49.     /**
  50.      * @var InstanceRequestManager
  51.      * @required
  52.      */
  53.     public InstanceRequestManager $instanceRequestManager;
  54.     /**
  55.      * @var BusinessActivityRequestManager
  56.      * @required
  57.      */
  58.     public BusinessActivityRequestManager $businessActivityRequestManager;
  59.     /**
  60.      * @var CacheItemPoolInterface
  61.      * @required
  62.      */
  63.     public CacheItemPoolInterface $cache;
  64.     /**
  65.      * @var RiskModelBuilder
  66.      * @required
  67.      */
  68.     public RiskModelBuilder $builder;
  69.     /**
  70.      * @param Request $request
  71.      * @return Response
  72.      */
  73.     public function show(Request $requeststring $code): Response
  74.     {
  75.         $this->isGranted(['ROLE_RISK_MANAGER']);
  76.         $risk $this->riskRequestManager->show($code);
  77.         /**
  78.          * @var object $model
  79.          */
  80.         $model $this->builder->build($code$risk);
  81.         $formFullName str_replace('Model''Type'get_class($model));
  82.         $form $this->createForm($formFullName$model);
  83.         $form->handleRequest($request);
  84.         $instances = [];
  85.         $merchants = [];
  86.         if ($code == 'instance') {
  87.             try {
  88.                 $filter = new InstanceFilterModel();
  89.                 $instances $this->instanceRequestManager->getInstances(11000$filter)['items'];
  90.                 $instances array_column($instances'name''token');
  91.             } catch (GuzzleException|ExceptionInterface|\Exception $e) {
  92.                 $message 'An error occurred. Code: ' $e->getCode();
  93.                 $this->addFlash('error'$message);
  94.                 return $this->redirectToRoute('risk_show'compact('code'));
  95.             }
  96.         } else if ($code == 'merchant') {
  97.             try {
  98.                 $filter = new MerchantFilterModel();
  99.                 $filter->setIsMaster(true);
  100.                 $merchants $this->merchantRequestManager->getMerchants(11000$filter)['items'];
  101.                 $merchants array_column($merchants'name''token');
  102.             } catch (GuzzleException|\Exception $e) {
  103.                 $message 'An error occurred. Code: ' $e->getCode();
  104.                 $this->addFlash('error'$message);
  105.                 return $this->redirectToRoute('risk_show'compact('code'));
  106.             }
  107.         }
  108.         if ($form->isSubmitted() && $form->isValid()) {
  109.             $data $this->builder->build($code$form->getData(), true);
  110.             $this->handleUpdate($data$risk$code);
  111.             return $this->redirectToRoute('risk_show'compact('code'));
  112.         }
  113.         return $this->renderForm("risk/$code.html.twig", ['form' => $form'sourceOfFunds' => SourceOfFundsType::TYPES'countries_list' => CountryListConstant::COUNTRIES_ARRAY_ISO_2'activities' => BusinessActivityTypes::TYPES'lines' => BusinessLinesType::TYPES'instances' => $instances'merchants' => $merchants]);
  114.     }
  115.     /**
  116.      * @param $token
  117.      * @return Response
  118.      * @throws ApiException
  119.      * @throws GuzzleException
  120.      * @throws JsonException
  121.      */
  122.     public function showMerchantDetailsRisk($token): Response
  123.     {
  124.         $risk $this->riskV3RequestManager->loadMerchantScore($token);
  125.         $cacheItem $this->cache->getItem('risk');
  126.         if ($cacheItem->isHit()) {
  127.             $risksArray $cacheItem->get();
  128.         } else {
  129.             $risksArray $this->riskRequestManager->checks();
  130.             $cacheItem->set($risksArray);
  131.             $cacheItem->expiresAfter(7200);
  132.             $this->cache->save($cacheItem);
  133.         }
  134.         $risks array_column($risksArray'description''code');
  135.         $merchant $this->merchantRequestManager->getMerchant($token);
  136.         return $this->render('merchant/risk.html.twig', [
  137.             'merchant' => $merchant,
  138.             'risk' => $risk,
  139.             'risks' => $risks
  140.         ]);
  141.     }
  142.     /**
  143.      * @throws ApiException
  144.      * @throws GuzzleException
  145.      * @throws JsonException
  146.      */
  147.     public function showPersonLevel(Request $request)
  148.     {
  149.         $risk $this->riskRequestManager->showLevels();
  150.         $levels = new PersonRiskLevelModel();
  151.         $result = [];
  152.         foreach ($risk as $riskElement) {
  153.             $model = new RiskLevelModel();
  154.             $model->setId($riskElement['id']);
  155.             $model->setLevel($riskElement['level']);
  156.             $model->setRiskLowValue($riskElement['riskLowValue']);
  157.             $model->setRiskHighValue($riskElement['riskHighValue']);
  158.             $result[] = $model;
  159.         }
  160.         $levels->setLevels($result);
  161.         $form $this->createForm(PersonRiskLevelType::class, $levels);
  162.         $form->handleRequest($request);
  163.         if ($form->isSubmitted() && $form->isValid()) {
  164.             $formData $form->getData();
  165.            $this->riskRequestManager->updateLevels($formData);
  166.             return $this->redirectToRoute('risk_person_level_show');
  167.         }
  168.         return $this->renderForm("risk/person/level.html.twig", ['form' => $form]);
  169.     }
  170.     public function showPerson(Request $request$type)
  171.     {
  172.         $typeId RiskNaturalPerson::TYPES[$type];
  173.         $risk $this->riskRequestManager->showPersonRisk($typeId);
  174.         /**
  175.          * @var object $model
  176.          */
  177.         $model $this->builder->buildPerson($type$risk);
  178.         $formFullName str_replace('Model''Type'get_class($model));
  179.         $form $this->createForm($formFullName$model);
  180.         $form->handleRequest($request);
  181.         if ($form->isSubmitted() && $form->isValid()) {
  182.             $this->handleUpdatePerson($form->getData(), $risk$type);
  183.             return $this->redirectToRoute('risk_person_show'compact('type'));
  184.         }
  185.         return $this->renderForm("risk/person/{$type}.html.twig", ['form' => $form]);
  186.     }
  187.     private function handleUpdate(array $array$originalArray$code null)
  188.     {
  189.         $key = (isset($originalArray['values'][0]['score']) ? 'score' : (isset($originalArray['values'][0]['entity']))) ? 'entity' 'range';
  190.         $keyGeneral = isset($originalArray['general'][0]['range']) ? 'range' 'score';
  191.         $originalValues array_column($originalArray['values'] ?? [], $key'id');
  192.         $formValues array_column($array$key'id');
  193.         $forUpdate array_diff_assoc($formValues$originalValues);
  194.         $arrayCopy $array;
  195.         $hasEntity false;
  196.         $hasScore false;
  197.         $hasRange false;
  198.         foreach ($arrayCopy as $key => $value) {
  199.             if (!isset($value['entity']) && !(isset($value['score']) && isset($value['range']))) {
  200.                 unset($arrayCopy[$key]);
  201.             }
  202.             if (isset($value['entity'])) {
  203.                 $hasEntity true;
  204.             }
  205.             if (isset($value['score']) && !isset($originalArray['general'][0]['score'])) {
  206.                 $hasScore true;
  207.             }
  208.             if (isset($value['range'])) {
  209.                 $hasRange true;
  210.             }
  211.         }
  212.         if ($hasScore) {
  213.             $originalScoreValues array_column($originalArray['values'] ?? [], 'score''id');
  214.             $formScoreValues array_column($array'score''id');
  215.             $forUpdateScores array_diff_assoc($formScoreValues$originalScoreValues);
  216.             $forUpdate += $forUpdateScores;
  217.         }
  218.         if ($hasRange) {
  219.             $originalRangeValues array_column($originalArray['values'] ?? [], 'range''id');
  220.             $formRangeValues array_column($array'range''id');
  221.             $forUpdateScores array_diff_assoc($formRangeValues$originalRangeValues);
  222.             $forUpdate += $forUpdateScores;
  223.         }
  224.         $forDelete = [];
  225.         foreach ($array as $item) {
  226.             if (isset($item['id']) && isset($item['entity']) && (!isset($item['risk']) && !isset($item['score']) && !isset($item['range']))
  227.                 || (isset($item['id'])) && isset($item['risk']) && !isset($item['score']) && !isset($item['entity']) && !isset($item['range'])) {
  228.                 $forDelete[$item['id']] = null;
  229.             }
  230.         }
  231.         $forUpdateNomenclature = [];
  232.         if ($hasEntity) {
  233.             $formValues array_column($arrayCopy'risk''entity');
  234.             $formValues += array_column($arrayCopy'score''entity');
  235.             $originalValues array_column($originalArray['nomenclature'] ?? [], 'risk''entity');
  236.             $forUpdateNomenclature array_diff($formValues$originalValues);
  237.             $forUpdateNomenclature2 array_diff_assoc($formValues$originalValues);
  238.             if (array_diff($forUpdateNomenclature$forUpdateNomenclature2) || array_diff($forUpdateNomenclature2$forUpdateNomenclature)) {
  239.                 $forUpdateNomenclature array_merge($forUpdateNomenclature2$forUpdateNomenclature);
  240.             }
  241.         }
  242.         $forUpdateGeneral = [];
  243.         if (isset($originalArray['general'])) {
  244.             $originalValues array_column($originalArray['general'], $keyGeneral'id');
  245.             $formValues array_column($array$keyGeneral'id');
  246.             $forUpdateGeneral array_diff_assoc($formValues$originalValues);
  247.         }
  248.         $successMessage '';
  249.         foreach ($array as $item) {
  250.             if (isset($item['id'])) {
  251.                 if ((array_key_exists($item['id'], $forUpdate) && $forUpdate[$item['id']] !== null && !isset($item['entity']))//risk is present and changed
  252.                     || (isset($item['entity']) && array_key_exists($item['entity'], $forUpdateNomenclature) && $forUpdateNomenclature[$item['entity']] !== null//nomenclature is present and changed
  253.                     || (array_key_exists($item['id'], $forUpdateNomenclature) && $forUpdateNomenclature[$item['id']] !== null//values is present and changed
  254.                     || (array_key_exists($item['id'], $forUpdateGeneral) && $forUpdateGeneral[$item['id']] !== null)) { //general is present and changed
  255.                     try {
  256.                         $this->riskRequestManager->update($item);
  257.                     } catch (GuzzleException|\Exception $e) {
  258.                         $message 'An error occurred. Code: ' $e->getCode();
  259.                         if ($e->getCode() === 8002) {
  260.                             $message 'This range/token already exists';
  261.                         }
  262.                         $this->addFlash('error'$message);
  263.                         return;
  264.                     }
  265.                     $successMessage 'Successfully Updated!';
  266.                 } else if ((isset($item['risk']) && array_key_exists($item['id'], $forUpdate) && $forUpdate[$item['id']] === null && !isset($item['entity']))
  267.                     || (array_key_exists($item['id'], $forUpdateGeneral) && $forUpdateGeneral[$item['id']] === null)
  268.                     || (isset($item['entity']) && array_key_exists($item['entity'], $forUpdateNomenclature) && $forUpdateNomenclature[$item['entity']] === null)
  269.                     || (array_key_exists($item['id'], $forDelete) && $forDelete[$item['id']] === null)
  270.                 ) {
  271.                     try {
  272.                         $this->riskRequestManager->remove($item['id']);
  273.                     } catch (GuzzleException|\Exception $e) {
  274.                         $message 'An error occurred. Code: ' $e->getCode();
  275.                         $this->addFlash('error'$message);
  276.                         return;
  277.                     }
  278.                     $successMessage 'Successfully Deleted!';
  279.                 }
  280.             } else {//no id set
  281.                 if ((isset($item['score']))
  282.                     || (isset($item['risk']) && (isset($item['entity']) || isset($item['range'])))
  283.                     || (isset($item['entity']) && isset($item['range']))) {//create
  284.                     $item['type'] = $code;
  285.                     try {
  286.                         $this->riskRequestManager->create($item);
  287.                     } catch (GuzzleException|\Exception $e) {
  288.                         $message 'An error occurred. Code: ' $e->getCode();
  289.                         if ($e->getCode() === 8002) {
  290.                             $message 'This range/token already exists';
  291.                         }
  292.                         $this->addFlash('error'$message);
  293.                         return;
  294.                     }
  295.                     $successMessage 'Successfully Created!';
  296.                 }
  297.             }
  298.         }
  299.         if (strlen($successMessage) > 0) {
  300.             $this->addFlash('success'$successMessage);
  301.         }
  302.     }
  303.     private function handleUpdatePerson(RisksPersonModel $array$originalArray$type null)
  304.     {
  305.         foreach ($array->getValues() as $item) {
  306.             if ($item->getId() === null) {
  307.                 $item->setRiskType(RiskNaturalPerson::TYPES[$type]);
  308.                 try {
  309.                     $this->riskRequestManager->createPerson($item);
  310.                 } catch (\Exception $exception) {
  311.                     $message 'An error occurred. Code: ' $exception->getCode();
  312.                     if ($exception->getCode() === 8002) {
  313.                         $message 'This configuration already exists';
  314.                     }
  315.                     $this->addFlash('error'$message);
  316.                     continue;
  317.                 }
  318.                 $successMessage 'Successfully Created!';
  319.                 $this->addFlash('success'$successMessage);
  320.                 continue;
  321.             }
  322.             foreach ($originalArray as $value) {
  323.                 if ($value['id'] == $item->getId()) {
  324.                     if ($item->getRisk() !== null && isset($value['risk']) && $value['risk'] != $item->getRisk()
  325.                         || ($item->getDescription() !== null && isset($value['description']) && $value['description'] != $item->getDescription())
  326.                         || ($item->getCode() !== null && $value['code'] != $item->getCode())) {
  327.                         try {
  328.                             $this->riskRequestManager->updatePerson($item$item->getId());
  329.                         } catch (\Exception $exception) {
  330.                             $message 'An error occurred. Code: ' $exception->getCode();
  331.                             if ($exception->getCode() === 8002) {
  332.                                 $message 'This configuration already exists';
  333.                             }
  334.                             $this->addFlash('error'$message);
  335.                             continue;
  336.                         }
  337.                         $successMessage 'Successfully Updated!';
  338.                         $this->addFlash('success'$successMessage);
  339.                         break;
  340.                     } else if ($item->getCode() === null && $item->getDescription() === null) {
  341.                         try {
  342.                             $this->riskRequestManager->removePerson($item->getId());
  343.                         } catch (\Exception $exception) {
  344.                             $message 'An error occurred. Code: ' $exception->getCode();
  345.                             $this->addFlash('error'$message);
  346.                             continue;
  347.                         }
  348.                         $successMessage 'Successfully Deleted!';
  349.                         $this->addFlash('success'$successMessage);
  350.                         break;
  351.                     }
  352.                 }
  353.             }
  354.         }
  355.         return $this->redirectToRoute('risk_person_show'compact('type'));
  356.     }
  357.     public function delete(string $codeint $id): Response
  358.     {
  359.         $this->isGranted(['ROLE_RISK_MANAGER']);
  360.         try {
  361.             $this->riskRequestManager->remove($id);
  362.         } catch (GuzzleException|ApiException $e) {
  363.             $message 'An error occurred. Code: ' $e->getCode();
  364.             $this->addFlash('error'$message);
  365.             return $this->redirectToRoute('risk_show'compact('code'));
  366.         }
  367.         $this->addFlash('success''Successfully Deleted!');
  368.         return $this->redirectToRoute('risk_show'compact('code'));
  369.     }
  370.     public function deletePerson($type$id): RedirectResponse
  371.     {
  372.         $this->isGranted(['ROLE_RISK_MANAGER']);
  373.         try {
  374.             $this->riskRequestManager->removePerson($id);
  375.         } catch (GuzzleException|ApiException $e) {
  376.             $message 'An error occurred. Code: ' $e->getCode();
  377.             $this->addFlash('error'$message);
  378.             return $this->redirectToRoute('risk_person_show'compact('type'));
  379.         }
  380.         $this->addFlash('success''Successfully Deleted!');
  381.         return $this->redirectToRoute('risk_person_show'compact('type'));
  382.     }
  383. }