src/Controller/WS/GiftCardPointController.php line 816

Open in your IDE?
  1. <?php
  2. namespace App\Controller\WS;
  3. use Symfony\Component\Console\Input\ArrayInput;
  4. use Symfony\Component\Console\Output\BufferedOutput;
  5. use Symfony\Bundle\FrameworkBundle\Console\Application;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use App\Util\Util as Utilx;
  10. use App\Util\WS\Util;
  11. use App\Util\NewUtil;
  12. use App\Util\WS\PointsUtilPorcessor;
  13. use App\Entity\AccountLicense;
  14. use App\Entity\PointAcount;
  15. use App\Entity\PtsAdquiRedemRules;
  16. use App\Entity\TypePoint;
  17. use App\Entity\TypePointAcount;
  18. use App\Entity\OmtClient;
  19. use App\Entity\WebService;
  20. use App\Entity\PointRelatedRequest;
  21. use App\Entity\RabbitRelatedGenericEntity;
  22. use App\Entity\TypePtsGenericDefinitionRules;
  23. use App\Entity\RestaurantLoyaltyConfiguration;
  24. use App\Entity\ActionHistory;
  25. use App\Util\Paginator;
  26. use App\Util\UUIDGeneratorUtil;
  27. use App\Transformer\LicensorGenericTransformer;
  28. use App\Controller\Application\Service\ArmorService;
  29. use App\Controller\Application\Service\Log\Log;
  30. use App\Controller\Application\Service\Util\Encryptor;
  31. use App\Controller\WS\ClientController;
  32. use App\Form\RestaurantLoyaltyConfig;
  33. use App\Form\PointsAdquiRedemRules;
  34. use App\Structure\Dashboard;
  35. use App\Structure\Configuracion;
  36. use App\Structure\RegistActions;
  37. use App\Structure\ConfRangedelivery;
  38. use App\Structure\ValorEpiMerchant;
  39. use App\Form\MerchantAccountType;
  40. use App\Structure\ConfGeneralDelivery;
  41. use App\Structure\ConfMerchantAccount;
  42. use App\Util\WS\ForcedAsynchronousCommandsUtil;
  43. use App\Util\WS\Util as WsUtilx;
  44. use App\Structure\LoyaltyHistory;
  45. use App\Structure\MesaPedido;
  46. use DateTime;
  47. class GiftCardPointController extends ApiController {
  48.     /**
  49.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  50.      * @return Response Json con la informacion de respuesta
  51.     */
  52.     public function createOmtClientRecord(Request $request) {
  53.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  54.             $data json_decode($request->getContent(), true);
  55.             if (!isset($data['uid'])) {
  56.                 return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  57.             }
  58.             $em $this->getDoctrine()->getManager();
  59.             $nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
  60.             $accountLicData $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
  61.             if (empty($accountLicData)) {
  62.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  63.                                 ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  64.             }
  65.             if ($accountLicData[0]->getDeviceUid() != $data['uid']) {
  66.                 $emLev Util::emLicenseConnection($this->realContainer$em$accountLicData[0]);
  67.                 $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
  68.                 if (empty($registeredClientsByUID)) {
  69.                     $emLev->close();
  70.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  71.                                     ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  72.                 } else {
  73.                     $emLev->close();
  74.                 }
  75.             }
  76.             if (strlen($data['id']) != 36) {
  77.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  78.                                 ->respondWithError('Invalid Id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  79.             }
  80.             if ($accountLicData[0]->getAlAccountLicense()->getDeleted()) {
  81.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  82.                                 ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  83.             }
  84.             if ($accountLicData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  85.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  86.                                 ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  87.             }
  88.             $clientOmt $em->getRepository('App\Entity\OmtClient')->find($data['id']);
  89.             $nicknameClientSearch = ['username' => $data['username']];
  90.             $nicknameCliData $em->getRepository('App\Entity\OmtClient')->findBy($nicknameClientSearch);
  91.             $responseArr['status'] = WebService::CODE_SUCCESS;
  92.             $responseArr['msg'] = 'Omt User update successfully!';
  93.             $responseArr['url'] = '';
  94.             if (!$clientOmt) {
  95.                 if ($nicknameCliData) {
  96.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  97.                                     ->respondWithError('Username invalid'WebService::CODE_ACCOUNT_SUSPENDED);
  98.                 }
  99.                 $clientOmt = new OmtClient();
  100.                 $clientOmt->setId($data['id']);
  101.                 $responseArr['msg'] = 'Omt User created successfully!';
  102.             }
  103.             if ($nicknameCliData && $clientOmt->getId() != $nicknameCliData[0]->getId()) {
  104.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  105.                                 ->respondWithError('Username  invalid'WebService::CODE_ACCOUNT_SUSPENDED);
  106.             }
  107.             if (!checkdnsrr($data['email'], "MX")) {
  108.                 return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  109.                     ->respondWithError("The email "$data['email'] ." is not a valid"WebService::HTTP_CODE_BAD_REQUEST);
  110.             }
  111.             $clientOmt->setName($data['name']);
  112.             $clientOmt->setLastname($data['lastname']);
  113.             $clientOmt->setEmail($data['email']);
  114.             $clientOmt->setUsername($data['username']);
  115.             $clientOmt->setBirthdate(new \DateTime($data['birthdate']));
  116.             $clientOmt->setPhone(Utilx::clearEspecialCharactersFromPhone($data['phone']));
  117.             $clientOmt->setLangCode($data['langCode']);
  118.             $em->persist($clientOmt);
  119.             $em->flush();
  120.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  121.             $xxArray $theUrlTrSt->transform();
  122.             $jsonContent json_encode($xxArray);
  123.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  124.         }
  125.     }
  126.     /**
  127.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  128.      * @return Response Json con la informacion de respuesta
  129.     */
  130.     public function createPointAccountRecord(Request $request) {
  131.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  132.             $data json_decode($request->getContent(), true);
  133.             if (strlen($data['omtClientId']) != 36) {
  134.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  135.                                 ->respondWithError('Invalid omtClientId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  136.             }
  137.             if (strlen($data['id']) != 36) {
  138.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  139.                                 ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  140.             }
  141.             $em $this->getDoctrine()->getManager();
  142.             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($data['id']);
  143.             $clientOmt $em->getRepository('App\Entity\OmtClient')->find($data['omtClientId']);
  144.             if (!$clientOmt) {
  145.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  146.                                 ->respondWithError('Omt client not found'WebService::CODE_COULD_NOT_AUTHENTICATE);
  147.             }
  148.             $clientPointSearch = ['omtClient' => $data['omtClientId']];
  149.             $clientPointAccount $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
  150.             $basePointSearch = ['basePointacount' => $data['basePointacount']];
  151.             $basePointAccount $em->getRepository('App\Entity\PointAcount')->findBy($basePointSearch);
  152.             if ($basePointAccount && $basePointAccount[0]->getId() != $data['id']) {
  153.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  154.                                 ->respondWithError('Invalid account token'WebService::CODE_COULD_NOT_AUTHENTICATE);
  155.             }
  156.             $responseArr['status'] = WebService::CODE_SUCCESS;
  157.             $responseArr['msg'] = 'Point account update successfully!';
  158.             if (!$pointAccountData) {
  159.                 $pointAccountData = new PointAcount();
  160.                 $pointAccountData->setId($data['id']);
  161.                 $responseArr['msg'] = 'Point account created successfully!';
  162.             }
  163.             
  164.             $pointAccountData->setOmtClient($clientOmt->getId());
  165.             $pointAccountData->setBasePointacount($data['basePointacount']);
  166.             $pointAccountData->setActivationDate(new \DateTime($data['activationDate']));
  167.             $em->persist($pointAccountData);
  168.             $em->flush();
  169.             if ($clientPointAccount) {
  170.                 $responseArr['msg'] .= ' User already has point account!';
  171.             }
  172.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  173.             $xxArray $theUrlTrSt->transform();
  174.             $jsonContent json_encode($xxArray);
  175.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  176.         }
  177.     }
  178.     /**
  179.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  180.      * @return Response Json con la informacion de respuesta
  181.     */
  182.     public function createTypePointAccountRecord(Request $request) {
  183.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  184.             $data json_decode($request->getContent(), true);
  185.             if (strlen($data['typePoinId']) != 36) {
  186.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  187.                                 ->respondWithError('Invalid typePoinId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  188.             }
  189.             if (strlen($data['pointAccountId']) != 36) {
  190.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  191.                                 ->respondWithError('Invalid pointAccountId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  192.             }
  193.             if (strlen($data['id']) != 36) {
  194.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  195.                                 ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  196.             }
  197.             $em $this->getDoctrine()->getManager();
  198.             $typePointAccountData $em->getRepository('App\Entity\TypePointAcount')->find($data['id']);
  199.             $accountTokenSearch = ['acountToken' => $data['accountToken']];
  200.             $accountTokenData $em->getRepository('App\Entity\TypePointAcount')->findBy($accountTokenSearch);
  201.             if ($accountTokenData && $accountTokenData[0]->getId() != $data['id']) {
  202.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  203.                                 ->respondWithError('Invalid acountToken'WebService::CODE_COULD_NOT_AUTHENTICATE);
  204.             }
  205.             $typePointData $em->getRepository('App\Entity\TypePoint')->find($data['typePoinId']);
  206.             $countrySearch = ['coVal' => $data['countryCode']];
  207.             $countryData $em->getRepository('App\Entity\Country')->findBy($countrySearch);
  208.             if ($countryData) {
  209.                 $countryData $em->getRepository('App\Entity\Country')->find($countryData[0]->getCoId());
  210.             }
  211.             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($data['pointAccountId']);
  212.             if (isset($pointAccountData) && $pointAccountData == []) {
  213.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  214.                                 ->respondWithError('pointAccountId not found'WebService::CODE_COULD_NOT_AUTHENTICATE);
  215.             }
  216.             $responseArr['status'] = WebService::CODE_SUCCESS;
  217.             $responseArr['msg'] = 'Type Point account update successfully!';
  218.             if (!$typePointAccountData) {
  219.                 $typePointAccountData = new TypePointAcount();
  220.                 $typePointAccountData->setId($data['id']);
  221.                 $responseArr['msg'] = 'Type Point account created successfully!';
  222.             }
  223.             $typePointAccountData->setTypePoint($typePointData);
  224.             $typePointAccountData->setPointAcount($pointAccountData);
  225.             $typePointAccountData->setCountryId($countryData);
  226.             $typePointAccountData->setAmount($data['ptAmount']);
  227.             $typePointAccountData->setPointArmAcount($data['pointArmAccount']);
  228.             $typePointAccountData->setStartingDate(new \DateTime($data['startingDate']));
  229.             $typePointAccountData->setAcountToken($data['accountToken']);
  230.             $em->persist($typePointAccountData);
  231.             $em->flush();
  232.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  233.             $xxArray $theUrlTrSt->transform();
  234.             $jsonContent json_encode($xxArray);
  235.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  236.         }
  237.     }
  238.     /**
  239.      * Obtener los puntos acumulados por clientes
  240.      * @param Request $request
  241.      * @return type
  242.     */
  243.     public function getPointAccountByClient(Request $requestArmorService $armorLog $log) {
  244.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  245.             $em $this->getDoctrine()->getManager();
  246.             $path Util::getValidActiveLogByBaseName($this->realContainer'getPointAccountByClient''getPointAccountByClient0.txt');
  247.             $this->createFileJson($path"\r" 'Hello Points: ' $request->getContent() . "\r");
  248.             $indexSearch = ['idClient''nickname'];
  249.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  250.             $order Paginator::filterPaginatorParameters([], $requesttrue);
  251.             $log->createChannel('getPointAccountByClient');
  252.             if (!isset($search['nickname'])) {
  253.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  254.             
  255.             }
  256.             if (!isset($search['idClient'])) {
  257.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid idClient'WebService::CODE_COULD_NOT_AUTHENTICATE);
  258.             
  259.             }
  260.             if (strlen($search['idClient']) != 36) {
  261.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid idClient'WebService::CODE_COULD_NOT_AUTHENTICATE);
  262.            
  263.             }
  264.             $search['client'] = $search['idClient'];
  265.             if (isset($search['nickname'])) {
  266.                 $dataNicknameSearch = ['alLicenseUsername' => $search['nickname']];
  267.                 $accountLicByNicknameData $em->getRepository('App\Entity\AccountLicense')->findBy($dataNicknameSearch);
  268.                 if (!isset($accountLicByNicknameData[0])) {
  269.                     
  270.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname 2'WebService::CODE_COULD_NOT_AUTHENTICATE);
  271.                 
  272.                 } else {
  273.                     $search['restaurant'] = $accountLicByNicknameData[0];
  274.                 }
  275.             }
  276.             $loyaltyConfiguration $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $accountLicByNicknameData[0]->getId()]);
  277.             
  278.             if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
  279.                 
  280.                 $this->createFileJson($path'Loyalty functions not configured yet o.O' "\r");
  281.                 
  282.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  283.                                 ->respondWithError('Loyalty functions not configured yet'WebService::CODE_ACCOUNT_SUSPENDED);
  284.             } elseif (!isset($loyaltyConfiguration[0])) {
  285.                 
  286.                 $this->createFileJson($path'Loyalty functions configuration record not found o.O' "\r");
  287.                 
  288.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  289.                                 ->respondWithError('Loyalty functions configuration record not found!'WebService::CODE_ACCOUNT_SUSPENDED);
  290.             }
  291.             $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  292.             $pointAccountByClient $pointAccountByClientRepository->findTypePointAccountByRestaurant($request$this->realContainer$search$order$loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $accountLicByNicknameData[0], $armor$log$path);
  293.             if (isset($pointAccountByClient['accounts'][0])) {
  294.                 $responseArr['msg'] = 'List of points by client';
  295.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  296.                 $responseArr['client'] = $pointAccountByClient['accounts'][0];
  297.                 $responseArr['bigbag'] = true;
  298.             } else {
  299.                 $responseArr['msg'] = 'No client found with the given data';
  300.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  301.             }
  302.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  303.             
  304.             $xxArray $theUrlTrSt->transform();
  305.             $jsonContent json_encode($xxArray);
  306.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  307.         }
  308.     }
  309.     
  310.     /**
  311.     * funcion encargada de obtener los puntos de una orden en OMT
  312.     * @param Request $request
  313.     * @return array - se retorna arreglo con los puntos obtenidos
  314.     **/
  315.     public function getPointsByOrder(Request $request) {
  316.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  317.             $em $this->getDoctrine()->getManager();
  318.             $params json_decode($request->getContent(), true);
  319.             $response_array $data_response = [];
  320.             if (isset($params['order_id']) && $params['order_id']) {
  321.                 // Se obtienen los datos mediante el order_id
  322.                 $points_data $em->getRepository('App\Entity\PointDeal')->findOneBy([ 'order' => $params['order_id'] ]);
  323.                 if ($points_data) {
  324.                     
  325.                     $data_response = [
  326.                         "earned" => $points_data->getDealPtsAmount()
  327.                     ];
  328.                 }
  329.                 // Respuesta
  330.                 $response_array['msg'] = 'List of points by order';
  331.                 $response_array['status'] = WebService::CODE_SUCCESS;
  332.                 $response_array['data'] = $data_response;
  333.                 $response_array['bigbag'] = true;
  334.             } else {
  335.                 $response_array['msg'] = 'Invalid Params';
  336.                 $response_array['status'] = WebService::CODE_WRONG_ARGUMENTS;
  337.                 $response_array['data'] = false;
  338.                 $response_array['bigbag'] = false;
  339.             }
  340.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$response_array);
  341.             $transform_fnc $theUrlTrSt->transform();
  342.             $json_content_data json_encode($transform_fnc);
  343.             return $this->respondWithItem($json_content_data$theUrlTrSt);
  344.         } else {
  345.             $response_array['msg'] = 'METHOD '$request->getMethod() .' NOT ALLOWED';
  346.             $response_array['status'] = WebService::CODE_NOT_ALLOWED_METHOD;
  347.             $response_array['data'] = null;
  348.             $response_array['false'] = false;
  349.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$response_array);
  350.             $transform_fnc $theUrlTrSt->transform();
  351.             $json_content_data json_encode($transform_fnc);
  352.             return $this->respondWithItem($json_content_data$theUrlTrSt);
  353.         }
  354.     }
  355.     /**
  356.      * @param Request $request
  357.      * @return type
  358.      */
  359.     public function createPtsAdquiRedemRules(Request $request) {
  360.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  361.             $data json_decode($request->getContent(), true);
  362.             if (strlen($data['id']) != 36) {
  363.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  364.                                 ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  365.             }
  366.             $em $this->getDoctrine()->getManager();
  367.             $nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
  368.             $accountLicData $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
  369.             if (empty($accountLicData)) {
  370.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  371.                                 ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  372.             }
  373.             if ($accountLicData[0]->getDeviceUid() != $data['uid']) {
  374.                 $emLev Util::emLicenseConnection($this->realContainer$em$accountLicData[0]);
  375.                 $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
  376.                 if (empty($registeredClientsByUID)) {
  377.                     $emLev->close();
  378.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  379.                                     ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  380.                 } else {
  381.                     $emLev->close();
  382.                 }
  383.             }
  384.             $typePointData $em->getRepository('App\Entity\TypePoint')->find($data['PointType']);
  385.             if (!$typePointData) {
  386.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  387.                                 ->respondWithError('Invalid PointType'WebService::CODE_COULD_NOT_AUTHENTICATE);
  388.             }
  389.             $basicDefinitionData $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->find($data['BasicDefinition']);
  390.             if (!$basicDefinitionData) {
  391.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  392.                                 ->respondWithError('Invalid BasicDefinition'WebService::CODE_COULD_NOT_AUTHENTICATE);
  393.             }
  394.             $ptsAdquiRedemRulesData $em->getRepository('App\Entity\PtsAdquiRedemRules')->find($data['id']);
  395.             $responseArr['status'] = WebService::CODE_SUCCESS;
  396.             $responseArr['msg'] = 'Pts Adqui Redem Rules  update successfully!';
  397.             if (!$ptsAdquiRedemRulesData) {
  398.                 $ptsAdquiRedemRulesData = new PtsAdquiRedemRules;
  399.                 $ptsAdquiRedemRulesData->setId($data['id']);
  400.                 $responseArr['msg'] = 'Pts Adqui Redem Rules created successfully!';
  401.             }
  402.             if ($data['minimumPurchase'] == "") {
  403.                 $data['minimumPurchase'] = null;
  404.             }
  405.             if ($data['QuantityPurchase'] == "") {
  406.                 $data['QuantityPurchase'] = null;
  407.             }
  408.             $ptsAdquiRedemRulesData->setName($data['Name']);
  409.             $ptsAdquiRedemRulesData->setPtsRate($data['PtsRate']);
  410.             $ptsAdquiRedemRulesData->setBasicDefinition($basicDefinitionData);
  411.             $ptsAdquiRedemRulesData->setPointType($typePointData);
  412.             $ptsAdquiRedemRulesData->setCreationDate(new \DateTime($data['CreationDate']));
  413.             $ptsAdquiRedemRulesData->setInitialActivationDate(new \DateTime($data['InitialActivationDate']));
  414.             $ptsAdquiRedemRulesData->setJustClaimOnce($data['JustClaimOnce']);
  415.             $ptsAdquiRedemRulesData->setApplyToSpecificRecord($data['ApplyToSpecificRecord']);
  416.             $ptsAdquiRedemRulesData->setWatchableObject($data['WatchableObject']);
  417.             $ptsAdquiRedemRulesData->setLicense($data['License']);
  418.             $ptsAdquiRedemRulesData->setMinimumPurchase($data['minimumPurchase']);
  419.             $ptsAdquiRedemRulesData->setMinimumQuantityPurchase($data['QuantityPurchase']);
  420.             $em->persist($ptsAdquiRedemRulesData);
  421.             $em->flush();
  422.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  423.             $xxArray $theUrlTrSt->transform();
  424.             $jsonContent json_encode($xxArray);
  425.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  426.         }
  427.     }
  428.     /**
  429.      * @param Request $request
  430.      * @return type
  431.      */
  432.     public function listTypePoint(Request $request) {
  433.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  434.             $em $this->getDoctrine()->getManager();
  435.             $indexSearch = ['typePoint'];
  436.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  437.             if ($search) {
  438.                 $dataSearch = ['type' => $search['typePoint']];
  439.                 $typePointData $em->getRepository('App\Entity\TypePoint')->findBy($dataSearch);
  440.             } else {
  441.                 $typePointData $em->getRepository('App\Entity\TypePoint')->findAll();
  442.             }
  443.             $arrayTypePoint = [];
  444.             foreach ($typePointData as $datos) {
  445.                 $tpData $datos->showEverything();
  446.                 array_push($arrayTypePoint$tpData);
  447.             }
  448.             $responseArr['msg'] = 'List of points types';
  449.             $responseArr['status'] = WebService::CODE_SUCCESS;
  450.             $responseArr['listTypePoint'] = $arrayTypePoint;
  451.             $responseArr['bigbag'] = true;
  452.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  453.             $xxArray $theUrlTrSt->transform();
  454.             $jsonContent json_encode($xxArray);
  455.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  456.         }
  457.     }
  458.     /**
  459.      * @param Request $request
  460.      * @return type
  461.      */
  462.     public function listTypePtsGenericRules(Request $request) {
  463.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  464.             $em $this->getDoctrine()->getManager();
  465.             $indexSearch = ['BasicType''Type'];
  466.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  467.             if (isset($search['BasicType']) && !isset($search['Type'])) {
  468.                 $dataSearch = ['basicType' => $search['BasicType']];
  469.                 $ptsGenericRule $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->findBy($dataSearch);
  470.             }
  471.             if (isset($search['Type']) && !isset($search['BasicType'])) {
  472.                 $dataSearch = ['type' => $search['Type']];
  473.                 $ptsGenericRule $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->findBy($dataSearch);
  474.             }
  475.             if (isset($search['Type']) && isset($search['BasicType'])) {
  476.                 $ptsGenericRule $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->listPtsgenericDefinitionRules($search);
  477.             }
  478.             $arrayPtsGenericRule = [];
  479.             if (isset($ptsGenericRule)) {
  480.                 foreach ($ptsGenericRule as $datos) {
  481.                     if (is_object($datos)) {
  482.                         $pgrData $datos->showEverything();
  483.                         array_push($arrayPtsGenericRule$pgrData);
  484.                     } else {
  485.                         array_push($arrayPtsGenericRule$datos);
  486.                     }
  487.                 }
  488.             }
  489.             $responseArr['msg'] = 'List of point types with generic rules';
  490.             $responseArr['status'] = WebService::CODE_SUCCESS;
  491.             $responseArr['listTypePoint'] = $arrayPtsGenericRule;
  492.             $responseArr['bigbag'] = true;
  493.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  494.             $xxArray $theUrlTrSt->transform();
  495.             $jsonContent json_encode($xxArray);
  496.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  497.         }
  498.     }
  499.     /**
  500.      * @param Request $request
  501.      * @return type
  502.      */
  503.     public function listProductRestaurant(Request $request) {
  504.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  505.             $em $this->getDoctrine()->getManager();
  506.             $indexSearch = ['uid''nickname''type'];
  507.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  508.             if (!isset($search['uid'])) {
  509.                 return $this->errorWrongArgs('Uid undefined!'WebService::CODE_WRONG_ARGUMENTS);
  510.             }
  511.             if (!isset($search['nickname'])) {
  512.                 return $this->errorWrongArgs('Nickname undefined!'WebService::CODE_WRONG_ARGUMENTS);
  513.             }
  514.             if (!isset($search['type'])) {
  515.                 return $this->errorWrongArgs('type undefined!'WebService::CODE_WRONG_ARGUMENTS);
  516.             }
  517.             $dataSearch = ['alLicenseUsername' => $search['nickname']];
  518.             $accountLicByUidData $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
  519.             if (!$accountLicByUidData) {
  520.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  521.                                 ->respondWithError('Invalid Nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  522.             }
  523.             if ($accountLicByUidData[0]->getAlAccountLicense()->getDeleted()) {
  524.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  525.                                 ->respondWithError('Account is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  526.             }
  527.             if ($accountLicByUidData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
  528.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  529.                                 ->respondWithError('License is inactive'WebService::CODE_ACCOUNT_SUSPENDED);
  530.             }
  531.             if ($accountLicByUidData[0]->getDeviceUid() != $search['uid']) {
  532.                 $emLev Util::emLicenseConnection($this->realContainer$em$accountLicByUidData[0]);
  533.                 $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $search['uid']]);
  534.                 if (empty($registeredClientsByUID)) {
  535.                     $emLev->close();
  536.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  537.                                     ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  538.                 } else {
  539.                     $emLev->close();
  540.                 }
  541.             }
  542.             if ($search['type'] == "category" || $search['type'] == "product" || $search['type'] == "product_modifier_map") {
  543.                 $repository Util::getStructureEntityDir($search['type']);
  544.             } else {
  545.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  546.                                 ->respondWithError('Invalid type'WebService::CODE_COULD_NOT_AUTHENTICATE);
  547.             }
  548.             $arrayListCategory = [];
  549.             if (isset($repository)) {
  550.                 $auxLevEm Util::emLicenseConnection($this->realContainer$em$accountLicByUidData[0]);
  551.                 $configuracionForAll $auxLevEm->getRepository($repository)->findAll();
  552.                 foreach ($configuracionForAll as $datos) {
  553.                     if (is_object($datos)) {
  554.                         $pgrData $datos->showEverything();
  555.                         array_push($arrayListCategory$pgrData);
  556.                     } else {
  557.                         array_push($arrayListCategory$datos);
  558.                     }
  559.                 }
  560.             }
  561.             if ($search['type'] == 'product_modifier_map') {
  562.                 $search['type'] = "'product modifier'";
  563.             } else if ($search['type'] == 'product') {
  564.                 $search['type'] = "'product'";
  565.             } else if ($search['type'] == 'category') {
  566.                 $search['type'] = "'category'";
  567.             }
  568.             $responseArr['msg'] = 'List of ' $search['type'] . ' of the restaurant: ' $accountLicByUidData[0]->getAlRestaurantName();
  569.             $responseArr['status'] = WebService::CODE_SUCCESS;
  570.             $responseArr['dataList'] = $arrayListCategory;
  571.             $responseArr['bigbag'] = true;
  572.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  573.             $xxArray $theUrlTrSt->transform();
  574.             $jsonContent json_encode($xxArray);
  575.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  576.         }
  577.     }
  578.     /**
  579.      * @param Request $request
  580.      * @return type
  581.      */
  582.     public function pointDealTransition(Request $request) {
  583.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  584.             $em $this->getDoctrine()->getManager();
  585.             $indexSearch = ['idClient'];
  586.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  587.             if (isset($search['idClient'])) {
  588.                 $client $em->getRepository('App\Entity\OmtClient')->find($search['idClient']);
  589.                 if (!$client) {
  590.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  591.                                     ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  592.                 }
  593.                 $responseArr['dataList']['id'] = $client->getId();
  594.                 $responseArr['dataList']['name'] = $client->getName();
  595.                 $responseArr['dataList']['lastname'] = $client->getLastname();
  596.                 $responseArr['dataList']['phone'] = $client->getPhone();
  597.             }
  598.             $listRules $em->getRepository('App\Entity\PointDeal')->listOfPointDeal($search);
  599.             $responseArr['msg'] = 'List of rules';
  600.             $responseArr['status'] = WebService::CODE_SUCCESS;
  601.             $responseArr['dataList']['pointDeal'] = $listRules;
  602.             $responseArr['bigbag'] = true;
  603.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  604.             $xxArray $theUrlTrSt->transform();
  605.             $jsonContent json_encode($xxArray);
  606.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  607.         }
  608.     }
  609.     /**
  610.      * WS generico para que el servidor andorid responda una pregunta realizada en un push
  611.      * @author Aealan Z <lrobledo@kijho.com> 15/06/16
  612.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  613.      * @return Response Json con la informacion de respuesta
  614.      */
  615.     public function evaluateCustomerPurchaseForPointsOrElse(Request $requestArmorService $armorLog $log) {
  616.         
  617.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST && $request->getMethod() !== WebService::REQUEST_METHOD_OPTIONS) {
  618.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  619.         }
  620.         
  621.         if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
  622.             $responseArrayAux1['status'] = WebService::CODE_SUCCESS;
  623.             $responseArrayAux1['msg'] = 'OPTIONS detected, good to go!';
  624.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrayAux1);
  625.             $jsonTransform $theUrlTrSt->transform();
  626.             $jsonContent json_encode($jsonTransform);
  627.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  628.         }
  629.         if (== !strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) && == !strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  630.             return $this->errorWrongArgs('Wrong content'WebService::CODE_WRONG_ARGUMENTS);
  631.         }
  632.         $path Util::getValidActiveLogByBaseName($this->realContainer'evaluateCustomerPurchaseForPointsOrElse''evaluateCustomerPurchaseForPointsOrElse0.txt');
  633.         $this->createFileJson($path"\r" 'Hello Points: ' $request->getContent() . "\r");
  634.         // try {
  635.             $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  636.             $params json_decode($arrayEncryptResult['data'], true);
  637.             $this->createFileJson($path'Decode params: ' $arrayEncryptResult['data'] . "\r");
  638.             $customerId="";
  639.             $flagAndroid false;
  640.             if(isset($params['requestFrom'])){
  641.                 if (!isset($params['nickname']) || !isset($params['dealType']) || !isset($params['omtCustomerId']) || !isset($params['totalAmount'])) {
  642.                     $this->createFileJson($path"\r" 'Wrong arguments!' WebService::CODE_WRONG_ARGUMENTS "\r");
  643.                     return $this->errorWrongArgs('Wrong arguments!'WebService::CODE_WRONG_ARGUMENTS);
  644.                 } else {
  645.                     $customerId $params['omtCustomerId'];
  646.                 }
  647.             } elseif (!isset($params['nickname']) || !isset($params['uid']) || !isset($params['dealType']) || !isset($params['customerId']) || !isset($params['totalAmount'])) {
  648.                 $this->createFileJson($path"\r" 'Wrong arguments!' WebService::CODE_WRONG_ARGUMENTS "\r");
  649.                 return $this->errorWrongArgs('Wrong arguments!'WebService::CODE_WRONG_ARGUMENTS);
  650.             } else {
  651.                 $customerId $params['customerId'];
  652.                 $flagAndroid true;
  653.             }
  654.             $em $this->getDoctrine()->getManager();
  655.             $data = ['alLicenseUsername' => $params['nickname']];
  656.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  657.             $countResult count($accountLicenseData);
  658.             $validate $this->validateLicense($countResult$path$accountLicenseData);
  659.             if (!$validate["status"]) {
  660.                 $this->createFileJson($path'licencia no eliminada logicamente' "\r");
  661.                 return $this->setStatusCode($validate["status"])->respondWithError($validate["message"], $validate["code"]);
  662.             }
  663.             $clientReposiroty $em->getRepository('App\Entity\OmtClient');
  664.             if($flagAndroid){
  665.                 $this->createFileJson($path"\r" 'Request Android' "\r");
  666.                 if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
  667.                     $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  668.                     
  669.                     $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
  670.                     
  671.                     if (empty($registeredClientsByUID)) {
  672.                         $emLev->close();
  673.                         $this->createFileJson($path'UID diferente! o.O' "\r");
  674.                         return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  675.                     
  676.                     } else {
  677.                         $emLev->close();
  678.                     }
  679.                 }
  680.                 
  681.                 $clientToGetPoint $clientReposiroty->find($customerId);
  682.             }else{
  683.                 $clientToGetPoint $clientReposiroty->findOneBy(["omtUserId"=>$customerId]);
  684.                 $params['customerId'] = !is_null($clientToGetPoint) && is_object($clientToGetPoint) ? $clientToGetPoint->getId() : null;
  685.             }
  686.             
  687.             if (!$clientToGetPoint) {
  688.                 $this->createFileJson($path'Unknown customer' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  689.                 
  690.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  691.                                 ->respondWithError('Unknown customer'WebService::CODE_ACCOUNT_SUSPENDED);
  692.             }
  693.             
  694.             $log->createChannel('gift_card');
  695.             $armorPack = [
  696.                 'request' => $request,
  697.                 'service' => $armor,
  698.                 'log' => $log
  699.             ];
  700.             if (isset($params['debug']) && $params['debug']) {
  701.                 dump("Parametros de entrada",$params);
  702.             }
  703.             if ($params['totalAmount'] > 0) {
  704.                 if (isset($params['debug']) && $params['debug']) {
  705.                     dump('Total amount'$params['totalAmount']);
  706.                 }
  707.                 
  708.                 $this->createFileJson($path'Points evaluation' "\r");
  709.                 $pointEvaluationResult PointsUtilPorcessor::analyzePointTransaction($this->realContainer$em$accountLicenseData[0], $params$armorPack);
  710.             
  711.                 if (isset($params['debug']) && $params['debug']) {
  712.                     dump("Point evaluation result"$pointEvaluationResult);
  713.                 }
  714.                 
  715.                 if (empty($pointEvaluationResult) && isset($params['omtCustomerId'])) {
  716.                     $this->createFileJson($path'create automatic' "\r");
  717.                     $typePointAccountData $this->saveNewTypePointAccount($em$clientToGetPoint,$params$path);
  718.                     
  719.                     $aux = ($typePointAccountData instanceof TypePointAcount) ? 'YES' 'NO';
  720.                     $this->createFileJson($path'$typePointAccountData is TypePointAcount ' .$aux"\r");
  721.                     
  722.                     $aux gettype($typePointAccountData);
  723.                     $this->createFileJson($path'$typePointAccountData is ' .$aux"\r");
  724.                      //  save on armor 
  725.                     if (isset($params['debug']) && $params['debug']) {
  726.                         dump("Create typePointAccount"$typePointAccountData);die;
  727.                     }
  728.                     if ($typePointAccountData instanceof TypePointAcount){
  729.                         $arrayTypePointAccountTokenToArmor PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData$typePointAccountData->getAmount(), $path);
  730.                         $encodeBase Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
  731.                         
  732.                         $request $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
  733.                         $pointEvaluationResult PointsUtilPorcessor::analyzePointTransaction($this->realContainer$em$accountLicenseData[0], $params$armorPack);
  734.                     }
  735.                 }
  736.             } else {
  737.                 if (isset($params['debug']) && $params['debug']) {
  738.                     dump('No es mayor que 0? o.O!');
  739.                     dump($params['totalAmount'] > 0);
  740.                 }
  741.                 $pointEvaluationResult = [];
  742.             }
  743.             $responseArrayAux1['status'] = WebService::CODE_SUCCESS;
  744.             $responseArrayAux1['msg'] = 'Point transactions processed successfully!';
  745.             $responseArrayAux1['bigbag'] = true;
  746.             $responseArrayAux2 $this->processEvaluatedTransactionResponse($pointEvaluationResult$params);  
  747.             $responseArray array_merge($responseArrayAux1$responseArrayAux2);
  748.             if (isset($params['debug']) && $params['debug']) {
  749.                 dump("Response",$responseArray);die;
  750.             }
  751.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArray);
  752.             $jsonTransform $theUrlTrSt->transform();
  753.             
  754.             $jsonContent json_encode($jsonTransform);
  755.             
  756.             $this->createFileJson($path'Response' .$jsonContent"\r");
  757.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  758.         // } catch (\Throwable $th) {
  759.         //     $err = json_encode(['Error Message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trace' => $th->getTrace()]);
  760.         //     $this->createFileJson($path, "\r Alert Error => $err \r");
  761.         //     return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)->respondWithError($err, WebService::HTTP_CODE_INTERNAL_ERROR);
  762.         // }
  763.     }
  764.     /**
  765.      * @param type $em
  766.      * @param type $userTypePointAccount
  767.      */
  768.     public function markAsNoOtherTransactionInProgress($em$userTypePointAccount) {
  769.         $userTypePointAccount $em->getRepository('App\Entity\PointAcount')->find($userTypePointAccount->getId());
  770.         $userTypePointAccount->setIsBlockedByOtherTransaction(false);
  771.         $em->persist($userTypePointAccount);
  772.         $em->flush();
  773.     }
  774.     /**
  775.      * @param type $em
  776.      * @param type $userTypePointAccount
  777.      * @return type
  778.      */
  779.     public function vaidateIfAnotherTransactionIsInProgress($em$userTypePointAccount$params) {
  780.         if (!isset($userTypePointAccount[0])) {
  781.             return 'No point account found for customer!';
  782.         } else {
  783.             $userTypePointAccount $userTypePointAccount[0];
  784.         }
  785.         if ($userTypePointAccount->getIsBlockedByOtherTransaction()) {
  786.             $responseArray['status'] = WebService::CODE_SUCCESS;
  787.             $responseArray['msg'] = '';
  788.             $processedArrayResponse $this->processEvaluatedTransactionResponse('other point transaction is being processed for this account, please wait a few minutes..'$params);
  789.             $responseArray array_merge($responseArray$processedArrayResponse);
  790.             return $responseArray;
  791.         } else {
  792.             $userTypePointAccount->setIsBlockedByOtherTransaction(true);
  793.             $em->persist($userTypePointAccount);
  794.             $em->flush();
  795.         }
  796.         return $userTypePointAccount;
  797.     }
  798.     /**
  799.      * @param PointRelatedRequest $pointCreatedResult
  800.      * @return type
  801.      */
  802.     public function startAllTheCommandToRabbitTransactionProcess($pointCreatedResult$path) {
  803.         if ($pointCreatedResult instanceof PointRelatedRequest) {
  804.             $kernel $this->get('real_kernel');
  805.             $application = new Application($kernel);
  806.             $application->setAutoExit(false);
  807.             $input = new ArrayInput([
  808.                 'command' => 'level:duce:point_transaction',
  809.                 'pointRequestId' => $pointCreatedResult->getId()
  810.             ]);
  811.             // You can use NullOutput() if you don't need the output
  812.             $output = new BufferedOutput();
  813.             $application->run($input$output);
  814.             // return the output, don't use if you used NullOutput()
  815.             $content $output->fetch();
  816.             $this->createFileJson($path'Producer command response: ' $content "\r");
  817.             sleep(1);
  818.             $input2 = new ArrayInput([
  819.                 'command' => 'level:nsume:point_transaction',
  820.                 'pointRequestId' => $pointCreatedResult->getId()
  821.             ]);
  822.             // You can use NullOutput() if you don't need the output
  823.             $output2 = new BufferedOutput();
  824.             $application->run($input2$output2);
  825.             // return the output, don't use if you used NullOutput()
  826.             $content2 $output->fetch();
  827.             $this->createFileJson($path'Consumer command response: ' $content2 "\r");
  828.         } else {
  829.             return $pointCreatedResult;
  830.         }
  831.         return true;
  832.     }
  833.     /**
  834.      * @param type $em
  835.      * @param type $theTransactionToCheck
  836.      * @param type $path
  837.      * @return boolean
  838.      */
  839.     public function pollingAskingIfPointTransactionWasProcessed($em$theTransactionToCheck$path) {
  840.         $responseToPolling = [];
  841.         $auxCounter 0;
  842.         $keepInWhile true;
  843.         $this->createFileJson($path'Checking if point transaction was concluded....' "\r");
  844.         $this->createFileJson($path'Checking -> ' $theTransactionToCheck->getId() . "\r");
  845.         do {
  846.             sleep(4);
  847.             ++$auxCounter;
  848.             $theTransactionToCheck $em->getRepository('App\Entity\PointRelatedRequest')->find($theTransactionToCheck->getId());
  849.             $responseToPolling['theTransaction'] = $theTransactionToCheck;
  850.             if ($theTransactionToCheck->getStatus() == RabbitRelatedGenericEntity::STATUS_PROCCESSED) {
  851.                 $keepInWhile false;
  852.                 $responseToPolling['msg'] = 'Transaction processed.. going forward whith the delivery!';
  853.                 $this->createFileJson($path'Transaction processed.. going forward whith the delivery!' "\r");
  854.                 
  855.                 $responseToPolling['wasProcessed'] = true;
  856.             } elseif ($auxCounter 7) {
  857.                 $keepInWhile false;
  858.                 if ($theTransactionToCheck->getStatus() < RabbitRelatedGenericEntity::STATUS_PROCCESSED) {
  859.                     $responseToPolling['msg'] = 'Maximum waiting reached for a processed point transaction, aborting!';
  860.                     $this->createFileJson($path'Maximum waiting reached for a processed point transaction, aborting!' "\r");
  861.                     $responseToPolling['wasProcessed'] = false;
  862.                 }
  863.             } else {
  864.                 
  865.                 $responseToPolling['msg'] = 'Waiting for transaction to be processed..';
  866.                 $responseToPolling['wasProcessed'] = false;
  867.                 $this->createFileJson($path"$auxCounter try, asking again..." "\r");
  868.             }
  869.         } while ($keepInWhile);
  870.         return $responseToPolling;
  871.     }
  872.     /**
  873.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  874.      * @return Response Json con la informacion de respuesta
  875.      */
  876.     public function createOmtClientAndPointsAccountsRecord(Request $requestArmorService $armorLog $log) { 
  877.         if (!== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
  878.             if (!== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
  879.                 return $this->errorWrongArgs('Wrong content');
  880.             }
  881.         }
  882.         $path Util::getValidActiveLogByBaseName($this->realContainer'omtClientAndPointsAccountsRecord''omtClientAndPointsAccountsRecord0.txt');
  883.         $this->createFileJson($path"\r" 'omtClient Ask: ' $request->getContent() . "\r");
  884.         $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  885.         $params json_decode($arrayEncryptResult['data'], true);
  886.         $this->createFileJson($path'Push Responded decode params: ' $arrayEncryptResult['data'] . "\r");
  887.         if (!isset($params['nickname']) || !isset($params['uid']) || !isset($params['countryCode'])) {
  888.             $this->createFileJson($path'posiblement falte parametro nickname, uid o countryCode' "\r");
  889.             return $this->errorWrongArgs('Wrong Arguments');
  890.         }
  891.         $em $this->getDoctrine()->getManager();
  892.         $countryData $em->getRepository('App\Entity\Country')->findBy(['coVal' => $params['countryCode']]);
  893.         
  894.         if (!isset($countryData[0])) {
  895.             $this->createFileJson($path'Contry code not found!' "\r");
  896.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  897.                             ->respondWithError('Contry code not found!'WebService::CODE_ACCOUNT_SUSPENDED);
  898.         } else {
  899.             $this->createFileJson($path'Contry code exist!' "\r");
  900.             $countryData $countryData[0];
  901.         }
  902.         $data = ['alLicenseUsername' => $params['nickname']];
  903.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  904.         $countResult count($accountLicenseData);
  905.         $this->createFileJson($path'busqueda del restaurante por nickname' "\r");
  906.         $validate $this->validateLicense($countResult$path$accountLicenseData);
  907.         if(!$validate["status"]) {
  908.             
  909.             $this->createFileJson($path'licencia no eliminada logicamente' "\r");
  910.             return $this->setStatusCode($validate["status"])
  911.                             ->respondWithError($validate["message"], $validate["code"]);
  912.         }
  913.         $this->createFileJson($path'licencia activa' "\r");
  914.         if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
  915.             $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  916.             $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
  917.             if (empty($registeredClientsByUID)) {
  918.                 $emLev->close();
  919.                 $this->createFileJson($path'UID diferente! o.O' "\r");
  920.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  921.                                 ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  922.             
  923.             } else {
  924.                 $emLev->close();
  925.             }
  926.         }
  927.         if(isset($params['phone'])){
  928.             $this->createFileJson($path'special characters removed in phone' "\r");
  929.             $tmpPhoneClient preg_replace('/[^0-9]/'""$params['phone']);
  930.             $tmpPhoneClient Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
  931.             $this->createFileJson($path'before ' .$params['phone']. ' ,after '.$tmpPhoneClient"\r");
  932.             
  933.             $params['phone'] = $tmpPhoneClient;
  934.         }
  935.         $this->createFileJson($path'validacion metodo put' "\r");
  936.         if ($request->getMethod() === WebService::REQUEST_METHOD_PUT) {
  937.             $params['alLicenseUsername'] = $params['nickname'];
  938.             return $this->updateDataOmtClient($params$path);
  939.         }
  940.         $this->createFileJson($path'ya termino... sigue ..' "\r");
  941.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  942.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  943.         }
  944.         $uniqueValidationArray = [];
  945.         $this->createFileJson($path'consulta en RestaurantLoyaltyConfiguration' "\r");
  946.         $loyaltyConfiguration $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findOneBy(['license' => $accountLicenseData[0]->getId()]);
  947.         
  948.         if (is_null($loyaltyConfiguration)) {
  949.             $loyaltyConfiguration = new RestaurantLoyaltyConfiguration();
  950.             $loyaltyConfiguration->setDateCreated(new \DateTime('now'));
  951.             $loyaltyConfiguration->setUseLocalPoints(false);
  952.             $loyaltyConfiguration->setUseGlobalPoints(false);
  953.             $loyaltyConfiguration->setMinimumPointAmountToExchange(1);
  954.             $loyaltyConfiguration->setLicense($accountLicenseData[0]);
  955.             $em->persist($loyaltyConfiguration);
  956.             $em->flush();
  957.         }
  958.         $this->createFileJson($path'Entering into the pit...1 o.O!' "\r");
  959.         if (isset($params['lastFour'])) {
  960.             $requiredFields = [
  961.                 "nameOnCard",
  962.                 "franchise",
  963.                 "lastFour"
  964.             ];
  965.             $fieldValidations $this->validateParams($request$requiredFields);
  966.             $params $this->getContentInRequest($request);
  967.             if(isset($params['phone'])){
  968.                 $this->createFileJson($path'special characters removed ' "\r");
  969.     
  970.                 $tmpPhoneClient preg_replace('/[^0-9]/'""$params['phone']);
  971.                 $tmpPhoneClient Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
  972.                 $this->createFileJson($path'before ' .$params['phone']. ' ,after '.$tmpPhoneClient"\r");
  973.                 
  974.                 $params['phone'] = $tmpPhoneClient;
  975.             }
  976.             
  977.             // Validamos que se envien lios campos requeridos
  978.             if ($fieldValidations !== true) {
  979.                 return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  980.                 ->respondWithError($fieldValidationsWebService::CODE_WRONG_ARGUMENTS);
  981.             }
  982.             $perhapsUniqueUserName str_replace(' ''_'strtolower(explode(' '$params['nameOnCard'])[0] . '_' $params['franchise'] . '_' $params['lastFour']));
  983.             $uniqueValidationArray = ['username'];
  984.             $params['username'] = $perhapsUniqueUserName;
  985.         } else {
  986.             $requiredFields = [
  987.                 "phone"
  988.             ];
  989.             $fieldValidations $this->validateParams($request$requiredFields);
  990.             $params $this->getContentInRequest($request);
  991.             if(isset($params['phone'])){
  992.                 $this->createFileJson($path'special characters removed ' "\r");
  993.     
  994.                 $tmpPhoneClient preg_replace('/[^0-9]/'""$params['phone']);
  995.                 $tmpPhoneClient Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
  996.                 $this->createFileJson($path'before ' .$params['phone']. ' ,after '.$tmpPhoneClient"\r");
  997.                 
  998.                 $params['phone'] = $tmpPhoneClient;
  999.             }
  1000.             /**
  1001.              * Validamos que se envien lios campos requeridos
  1002.              */
  1003.             if ($fieldValidations !== true) {
  1004.                 return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  1005.                                 ->respondWithError($fieldValidations
  1006.                                         WebService::CODE_WRONG_ARGUMENTS);
  1007.             }
  1008.             $uniqueValidationArray = ['username''email''phone'];
  1009.             if (!isset($params['username'])) {
  1010.                 if (isset($params['name'])) {
  1011.                     // se reemplaza los espacios en blanco del nombre por guion bajo
  1012.                     $usernamesufix str_replace(' ''_'$params['name']) . '_' Utilx::randomPassword(3);
  1013.                 
  1014.                 } else {
  1015.                     $usernamesufix 'NoName_' Utilx::randomPassword(5);
  1016.                 }
  1017.                 $params['username'] = $usernamesufix;
  1018.             }
  1019.         }
  1020.         $this->createFileJson($path'Entering into the pit...2 o.O!' "\r");
  1021.         $clientController = new ClientController($this->realContainer);
  1022.     
  1023.         $nickUsername Utilx::replaceCharactersEspecials($params['name']);
  1024.         $nickUsername strtolower(substr($nickUsername08) . '_');
  1025.         $repositoryClients $em->getRepository('App\Entity\OmtClient');
  1026.         $countClients $repositoryClients->counting();
  1027.         $this->createFileJson($path'number of OMTClient records ' .$countClients"\r");
  1028.         $nickUsername .= uniqid() ."_"$countClients;
  1029.         $lastParamsNotSend $params;
  1030.         if (!isset($params['lastname']) || $params['lastname'] == '') {
  1031.             $params['lastname'] = "(temporal lastname)";
  1032.         }
  1033.         if (!isset($params['username']) || $params['username'] == '') {
  1034.             $params['username'] = $nickUsername;
  1035.         }
  1036.         if (!isset($params['email']) || $params['email'] == '') {
  1037.             $email NewUtil::generateEmailGeneric($params['name'], $repositoryClients$path);
  1038.             // $nickUsername . "@gmail.com";
  1039.             $params['email'] = $email
  1040.             $lastParamsNotSend['email'] = $email;
  1041.         }
  1042.         
  1043.         unset($params['uid'], $params['countryCode']);
  1044.         
  1045.         if (isset($params['clientId'])) {
  1046.             $auxOmtClient $em->getRepository('App\Entity\OmtClient')->find($params['clientId']);
  1047.             if($auxOmtClient && $auxOmtClient->getOmtUserId()){
  1048.                 $params['omtClientId'] = $auxOmtClient->getOmtUserId();
  1049.             }
  1050.         }
  1051.         // debido a que dos funciones que crean usuario loyalty se agregan parametros para que haya igualdad en el body de ambos webservices
  1052.         $params['alLicenseUsername'] = $params['nickname'];
  1053.         $params['companyName'] = 'omt';
  1054.         $params['phone_2'] = '';
  1055.         $params['fromLicensor'] = true;
  1056.         unset($params['clientId']);
  1057.         unset($params['nickname']);
  1058.         unset($params['langCode']);
  1059.         // se valida que el teléfono y el email no este utilizados por un cliente en OMTWS
  1060.         $this->createFileJson($path"\r" 'parameters to send to isPhoneAndEmailUsingAtOMT => ' json_encode(['phone' => $params['phone'], 'email' => $params['email']]) . "\r");
  1061.         $tmpValidOMT $clientController->isPhoneAndEmailUsingAtOMT($this->realContainer$params['phone'], $params['email']);
  1062.         $this->createFileJson($path"\r" 'isPhoneAndEmailUsingAtOMT => ' json_encode($tmpValidOMT) . "\r");
  1063.         if (isset($tmpValidOMT['data']['message'])){
  1064.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1065.                         ->respondWithError($tmpValidOMT['data']['message'], WebService::CODE_COULD_NOT_AUTHENTICATE);
  1066.         }
  1067.         // se envia la peticion para crear el usuario a OMTWS
  1068.         $responseCreationUserOmt $clientController->createNewUserLoyaltyInOmtWsFromAndroid($this->realContainer$params);
  1069.         
  1070.         $this->createFileJson($path'Creation from omtws, response => 'json_encode($responseCreationUserOmt) . "\r");
  1071.         $existErrorCreationUserOmt $clientController->existErrorsWhenCreateUserLoyaltyInOmtWs($responseCreationUserOmt);
  1072.         
  1073.         if (isset($existErrorCreationUserOmt['error']) && $existErrorCreationUserOmt['error']){
  1074.             return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  1075.             ->respondWithError($existErrorCreationUserOmt['message'], WebService::HTTP_CODE_BAD_REQUEST);
  1076.         }
  1077.         $params $lastParamsNotSend;
  1078.         $clientOmt null;
  1079.         $omtClientRepo $em->getRepository('App\Entity\OmtClient');
  1080.         $clientToUpdateDirect null;
  1081.         if (isset($params['clientId'])) {
  1082.             $clientToUpdateDirect $omtClientRepo->find($params['clientId']);
  1083.         }
  1084.         if (is_null($clientToUpdateDirect) && isset($params['email']) && $params['email'] != '') {
  1085.             $clientToUpdateDirect $omtClientRepo->findOneBy(['email' => $params['email']]);
  1086.         }
  1087.         $this->createFileJson($path'Entering into the pit...3 o.O!' "\r");
  1088.         $nicknameCliData null;
  1089.         foreach ($uniqueValidationArray as $uniqueFieldToValidate) {
  1090.             if (isset($params[$uniqueFieldToValidate])) {
  1091.                 $nicknameClientSearch = [$uniqueFieldToValidate => $params[$uniqueFieldToValidate]];
  1092.                 $nicknameCliData $omtClientRepo->findBy($nicknameClientSearch);
  1093.                 $this->createFileJson($path'checking if user exists ' .json_encode($nicknameClientSearch). "\r");
  1094.                 if (isset($nicknameCliData[0])) {
  1095.                     $clientOmt $nicknameCliData[0];
  1096.                     $this->createFileJson($path'yes, the customer exists with the ID '$clientOmt->getId().' ' .$clientOmt"\r");
  1097.                     break;
  1098.                 }
  1099.             }
  1100.         }
  1101.         $unexpectedEditFlag false;
  1102.         /**
  1103.          * Esta condicion permite validar si el cliente que va a ser creado 
  1104.          * tiene el  email y el telefono valido lo deja crear de lo contrario
  1105.          * le retorna un mensaje con su respectivo error
  1106.          */
  1107.         if ((!isset($params['clientId']) || (isset($params['clientId']) && $params['clientId'] == "" ) ) && ((isset($params['email']) && $params['email'] !== null && $params['email'] !== "") || (isset($params['phone']) && $params['phone'] !== null && $params['phone'] !== ""))) {
  1108.             if (isset($params['email'])) {
  1109.                 $existClientByEmail $omtClientRepo->findBy(['email' => $params['email']]);
  1110.             }
  1111.             if (isset($params['phone'])) {
  1112.                 $existClientByPhone $omtClientRepo->findBy(['phone' => $params['phone']]);
  1113.             }
  1114.             
  1115.             if (isset($existClientByEmail[0]) && $existClientByEmail[0]->getLastname() == 'Default GiftCard Customer') {
  1116.                 $this->createFileJson($path'Invalid email' "\r");
  1117.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1118.                             ->respondWithError('Invalid email'WebService::CODE_ERR_CONFLICT);
  1119.             }
  1120.             
  1121.             if (isset($existClientByPhone[0]) && $existClientByPhone[0]->getLastname() == 'Default GiftCard Customer') {
  1122.                 $this->createFileJson($path'Invalid phone number' "\r");
  1123.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1124.                             ->respondWithError('Invalid phone number'WebService::CODE_ERR_CONFLICT);
  1125.             }
  1126.             if (isset($existClientByEmail[0]) && isset($existClientByPhone[0]) && $existClientByPhone[0]->getId() != $existClientByEmail[0]->getId()) {
  1127.                 unset($params['email']);
  1128.             }
  1129.             if (isset($existClientByPhone[0])) {
  1130.                 $typePointAccountByClient $em->getRepository('App\Entity\TypePointAcount')->findUserPtAccount($existClientByPhone[0]->getId(), TypePoint::WORK_AS_LOCAL$accountLicenseData[0]->getId());
  1131.                 if (!$clientOmt) {
  1132.                     $clientOmt $existClientByPhone[0];
  1133.                 }
  1134.                 if (!isset($typePointAccountByClient[0])) {
  1135.                     $unexpectedEditFlag true;
  1136.                 } else {
  1137.                     if (isset($existClientByEmail[0])) {
  1138.                         $responseArr['status'] = WebService::CODE_WRONG_ARGUMENTS;
  1139.                         if (isset($existClientByEmail[0]) && isset($params['omtUserId']) && $existClientByEmail[0]->getOmtUserId() == $params['omtUserId'] && isset($params['omtUserUsername']) && $existClientByEmail[0]->getOmtUserUsername() == null) {
  1140.                             
  1141.                             $existClientByEmail[0]->setOmtUserUsername($params['omtUserUsername']);
  1142.                             
  1143.                             $em->persist($existClientByEmail[0]);
  1144.                             $em->flush();
  1145.                         }
  1146.                         $responseArr['msg'] = 'Email is already in use!';
  1147.                         $this->createFileJson($path'Email is already in use!' "\r");
  1148.                         $responseArr['idClient'] = $existClientByEmail[0]->getId();
  1149.                     } elseif (isset($existClientByPhone[0])) {
  1150.                         if (isset($existClientByPhone[0]) && isset($params['omtUserId']) && $existClientByPhone[0]->getOmtUserId() == $params['omtUserId'] && isset($params['omtUserUsername']) && $existClientByPhone[0]->getOmtUserUsername() == null) {
  1151.                             
  1152.                             $existClientByPhone[0]->setOmtUserUsername($params['omtUserUsername']);
  1153.                             $em->persist($existClientByPhone[0]);
  1154.                             $em->flush();
  1155.                         }
  1156.                         $responseArr['status'] = WebService::CODE_ERR_CONFLICT;
  1157.                         $responseArr['msg'] = 'The user could not be created!';
  1158.                         $this->createFileJson($path'The user could not be created!' "\r");
  1159.                         return $this->setStatusCode($responseArr['status'])
  1160.                         ->respondWithError($responseArr['msg'], WebService::CODE_ERR_CONFLICT);
  1161.                     }
  1162.                     if (isset($existClientByEmail) && $existClientByEmail !== []) {
  1163.                         $responseArr['bigbag'] = true;
  1164.                         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1165.                         
  1166.                         $xxArray $theUrlTrSt->transform();
  1167.                         $jsonContent json_encode($xxArray);
  1168.                         return $this->respondWithItem($jsonContent$theUrlTrSt);
  1169.                     }
  1170.                 }
  1171.             } else {
  1172.                 if (isset($existClientByEmail[0])) {
  1173.                     $responseArr['status'] = WebService::CODE_WRONG_ARGUMENTS;
  1174.                     $responseArr['msg'] = 'Email is already in use!';
  1175.                     $this->createFileJson($path'Email is already in use!' "\r");
  1176.                     $responseArr['idClient'] = $existClientByEmail[0]->getId();
  1177.                 }
  1178.                 if (isset($existClientByEmail) && $existClientByEmail !== []) {
  1179.                     $responseArr['bigbag'] = true;
  1180.                     $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1181.                     
  1182.                     $xxArray $theUrlTrSt->transform();
  1183.                     $jsonContent json_encode($xxArray);
  1184.                     
  1185.                     return $this->respondWithItem($jsonContent$theUrlTrSt);
  1186.                 }
  1187.             }
  1188.         }
  1189.         $copyLoyaltyUserIntoOMT false;
  1190.         $this->createFileJson($path'!$clientOmt'. !$clientOmt "\r");
  1191.         if (!$clientOmt) {
  1192.             if ($nicknameCliData) {
  1193.                 $this->createFileJson($path'Username invalid' "\r");
  1194.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1195.                 ->respondWithError('Username invalid'WebService::CODE_ACCOUNT_SUSPENDED);
  1196.             }
  1197.             $copyLoyaltyUserIntoOMT true;
  1198.             $clientOmt = new OmtClient();
  1199.             
  1200.             //$params['id'] = UUIDGeneratorUtil::getUUIDv4();
  1201.             // se le asigna la llave primaria del usuario de omtws
  1202.             $params['id'] = $responseCreationUserOmt['data']['id'];
  1203.             $this->createFileJson($path'UUID generated!: ' .$params['id']. "\r");
  1204.             
  1205.             $clientOmt->setId($params['id']);
  1206.             if (isset($params['omtUserId'])) {
  1207.                 $clientOmt->setOmtUserId($params['omtUserId']);
  1208.             }
  1209.             if (isset($params['omtUserUsername'])) {
  1210.                 $clientOmt->setOmtUserUsername($params['omtUserUsername']);
  1211.             }
  1212.             $responseArr['msg'] = 'Omt User created successfully!';
  1213.             $this->createFileJson($path'Omt User created successfully!' "\r");
  1214.         } else {
  1215.             $this->createFileJson($path'the customer already exists debuger'"\r");
  1216.             if ($unexpectedEditFlag) {
  1217.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  1218.                 $responseArr['msg'] = 'Omt client created for restaurant successfully!';
  1219.                 $this->createFileJson($path'Omt client created for restaurant successfully!' "\r");
  1220.             } else {
  1221.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  1222.                 $responseArr['msg'] = 'Omt client update successfully!';
  1223.                 $this->createFileJson($path'Omt client update successfully!' "\r");
  1224.             }
  1225.         }
  1226.         $indexExistenceToValidate = ['lastFour''expirationDate''nameOnCard''franchise'];
  1227.         $indexInexistenceToValidate = ['name''lastname''email''birthdate''phone'];
  1228.         $isCardParams $this->paramsArrayIndexValidator($params$indexExistenceToValidate);
  1229.         $isCustomerParams $this->paramsArrayIndexValidator($params$indexInexistenceToValidatefalse);
  1230.         $newCardAsClient false;
  1231.         if ($isCardParams[0] && $isCustomerParams[0]) {
  1232.             $this->createFileJson($path'entered into ($isCardParams[0] and $isCustomerParams[0]) debug' "\r");
  1233.             
  1234.             $fullCombined $params['nameOnCard'] . '_' $params['lastFour'] . '_' $params['franchise'] . '_' $params['expirationDate'];
  1235.             $fullCombined str_replace(' ''_'strtolower(str_replace('/''-'$fullCombined)));
  1236.             $cardAsClienteRecord $em->getRepository('App\Entity\CardAsClient')->findBy(['uniqueCombined' => $fullCombined]);
  1237.             if (isset($cardAsClienteRecord[0])) {
  1238.                 $this->createFileJson($path'exist $cardAsClienteRecord[0] debug' "\r");
  1239.                 $responseArr['msg'] = 'Omt User updated successfully!';
  1240.                 $clientOmt $em->find('App\Entity\OmtClient'$cardAsClienteRecord[0]->getClient());
  1241.             
  1242.             } else {
  1243.                 $this->createFileJson($path'not exist $cardAsClienteRecord[0] debug' "\r");
  1244.                 
  1245.                 $newCardAsClient true;
  1246.                 $params['theCombined'] = $fullCombined;
  1247.                 $perhapsUniqueUserName str_replace(' ''_'strtolower(explode(' '$params['nameOnCard'])[0] . '_' $params['franchise'] . '_' $params['lastFour']));
  1248.                 $clientOmt->setName($params['nameOnCard']);
  1249.                 $clientOmt->setUsername($perhapsUniqueUserName);
  1250.                 $clientOmt->setBirthdate(\DateTime::createFromFormat('d/m/Y''01/' $params['expirationDate']));
  1251.             }
  1252.         } else {
  1253.             $this->createFileJson($path'not entered into ($isCardParams[0] and $isCustomerParams[0]) elde debug' "\r");
  1254.             
  1255.             if (isset($params['name'])) {
  1256.                 $clientOmt->setName($params['name']);
  1257.             }
  1258.             if (isset($params['lastname'])) {
  1259.                 $clientOmt->setLastname($params['lastname']);
  1260.             }
  1261.             if (isset($params['email']) && $params['email'] !== "") {
  1262.                 
  1263.                 // Se valida que el correo tenga un dominio valido y se agrega la excepción del dominio por defecto
  1264.                 if (!NewUtil::emailContainsGenericDomain($params['email'], $path) && !$this->validateFullEmail($params['email'])) {
  1265.                     return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  1266.                         ->respondWithError("The email "$params['email'] ." is not a valid"WebService::HTTP_CODE_BAD_REQUEST);
  1267.                 }
  1268.                 $clientOmt->setEmail($params['email']);
  1269.             } else {
  1270.                 $clientOmt->setEmail(null);
  1271.             }
  1272.             if (isset($params['username']) && $params['username'] != '') {
  1273.                 
  1274.                 $clientOmt->setUsername($params['username']);
  1275.             
  1276.             } else {
  1277.                 $clientOmt->setUsername(null);
  1278.             }
  1279.             if (!isset($params['birthdate'])) {
  1280.                
  1281.                 $params['birthdate'] = Util::getCurrentDate()->format('d/m/Y');
  1282.             }
  1283.             
  1284.             $clientOmt->setBirthdate(\DateTime::createFromFormat('d/m/Y'$params['birthdate']));
  1285.             
  1286.             if (isset($params['phone']) && !isset($existClientByPhone[0])) {
  1287.                 
  1288.                 $phoneClient preg_replace('/[^0-9]/'""$params['phone']);
  1289.                 $phoneClient Utilx::clearEspecialCharactersFromPhone($phoneClient);
  1290.                 $clientOmt->setPhone($phoneClient);
  1291.             }
  1292.         }
  1293.         
  1294.         
  1295.         if (isset($params['userPhoneOrder']) && $clientOmt->getUserPhoneOrder() == null) {
  1296.             $clientOmt->setUserPhoneOrder($params['userPhoneOrder']);
  1297.         }
  1298.         
  1299.         if (isset($params['langCode']) && $params['langCode'] != ''){
  1300.             $clientOmt->setLangCode($params['langCode']);
  1301.         }else{
  1302.             $clientOmt->setLangCode(null);
  1303.         }
  1304.         $clientOmt->setOmtUserId($responseCreationUserOmt['data']['id']);
  1305.         $clientOmt->setDefaultEmail(isset($params['defaultEmail']) && $params['defaultEmail'] != '' $params['defaultEmail'] : );
  1306.         $this->createFileJson($path'before of create client_omt debug' "\r");
  1307.         $em->persist($clientOmt);
  1308.         $em->flush();
  1309.         $this->createFileJson($path'after of create client_omt debug' "\r");
  1310.         if ($newCardAsClient) {
  1311.             $this->createFileJson($path'entered into $newCardAsClient debug' "\r");
  1312.             Utilx::createCardAsLoyalClientRecord($em$params$clientOmt$path);
  1313.         }
  1314.         $clientPointSearch = ['omtClient' => $clientOmt->getId()];
  1315.         $clientPointAccount $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
  1316.         if (!isset($clientPointAccount[0])) {
  1317.             $this->createFileJson($path'exist $cardAsClienteRecord[0] debug' "\r");
  1318.             $pointAccountData = new PointAcount();
  1319.             $pointAccountData->setId($clientOmt->getId());
  1320.             $baseToken = ['food' => '123'];
  1321.             while (!empty($baseToken)) {
  1322.                 $this->createFileJson($path'generating new token for PointAcount debug' "\r");
  1323.                 $token Utilx::randomPassword(32);
  1324.                 $baseToken $em->getRepository('App\Entity\PointAcount')->findBy(['basePointacount' => $token]);
  1325.             }
  1326.             $pointAccountData->setBasePointacount($token);
  1327.             $pointAccountData->setActivationDate(new \DateTime('now'));
  1328.             $clientPointAccount[0] = $pointAccountData;
  1329.         } else {
  1330.             $this->createFileJson($path'not exist $cardAsClienteRecord[0] debug' "\r");
  1331.             $pointAccountData $clientPointAccount[0];
  1332.         }
  1333.         $pointAccountData->setOmtClient($clientOmt->getId());
  1334.         $this->createFileJson($path'before of create PointAcount debug'"\r");
  1335.         $em->persist($pointAccountData);
  1336.         $em->flush();
  1337.         $this->createFileJson($path'after of create PointAcount debug'"\r");
  1338.                 
  1339.         if (isset($params['email']) && isset($params['copyAsOMTClient']) && $copyLoyaltyUserIntoOMT) {
  1340.             $this->createFileJson($path'Ready to make loyalty user cUrl request to OMT!' "\r");
  1341.             $randomOmtDashboardUserRawPass Utilx::randomPassword(7);
  1342.             $clientOmt->setTemporalOMTPass($randomOmtDashboardUserRawPass);
  1343.             $requestResult Util::copyLoyaltyUserToOMT($this->realContainer$em$clientOmt$params['countryCode'], $path);
  1344.             $this->createFileJson($path'Loyalty user to OMT request response -> ' json_encode($requestResult) . "\r");
  1345.         }
  1346.         $typePointData $em->getRepository('App\Entity\TypePoint')->findTypePointDefault();
  1347.         foreach ($typePointData AS $typePoint) {
  1348.             $tpData $em->getRepository('App\Entity\TypePoint')->find($typePoint['id']);
  1349.             if ($typePoint['type'] == TypePoint::TYPE_GLOBAL) {
  1350.                 $typePointAccountArray $em->getRepository('App\Entity\TypePointAcount')->findBy(['typePoint' => $typePoint['id'], 'pointAcount' => $pointAccountData->getId()]);
  1351.             } else {
  1352.                 $typePointAccountArray $em->getRepository('App\Entity\TypePointAcount')->findBy(['typePoint' => $typePoint['id'], 'pointAcount' => $pointAccountData->getId(), 'license' => $accountLicenseData[0]->getId()]);
  1353.             }
  1354.             if (isset($typePointAccountArray[0])) {
  1355.                 $typePointAccountData $typePointAccountArray[0];
  1356.             } else {
  1357.                 $typePointAccountData = new TypePointAcount();
  1358.                 $acountToken = ['food' => '123'];
  1359.                 while (!empty($acountToken)) {
  1360.                     $tokenAcount Encryptor::encodeInfo(Utilx::randomPassword(32), 5);
  1361.                     $acountToken $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
  1362.                 }
  1363.                 $typePointAccountData->setAmount(0);
  1364.                 $typePointAccountData->setAcountToken($tokenAcount);
  1365.                 $typePointAccountData->setStartingDate(new \DateTime('now'));
  1366.                 $typePointAccountData->setPointArmAcount('Pepito Habla Ingles!');
  1367.             }
  1368.             $typePointAccountData->setTypePoint($tpData);
  1369.             $typePointAccountData->setPointAcount($pointAccountData);
  1370.             $typePointAccountData->setCountryId($countryData);
  1371.             if ($typePoint['type'] != TypePoint::TYPE_GLOBAL) {
  1372.                 $typePointAccountData->setLicense($accountLicenseData[0]);
  1373.             }
  1374.             $this->createFileJson($path'before of create TypePointAcount debug'"\r");
  1375.             $em->persist($typePointAccountData);
  1376.             $em->flush();
  1377.             $this->createFileJson($path'after of create TypePointAcount debug'"\r");
  1378.             $log->createChannel('gift_card');
  1379.             $arrayTypePointAccountTokenToArmor PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData);
  1380.             // dump($arrayTypePointAccountTokenToArmor);
  1381.             // die;
  1382.             $encodeBase Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
  1383.             
  1384.             $request $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
  1385.             $this->createFileJson($path'Armor request send: ' $request "\r");
  1386.             $url $this->realContainer->getParameter('armor_host') . 'point/add-points';
  1387.             $this->createFileJson($path'Armor URL: ' $url "\r");
  1388.             $dataResponse $armor->armorPost($request$url$log);
  1389.             if ($dataResponse instanceof Response) {
  1390.                 $jsonResponse $dataResponse->getContent();
  1391.                 $this->createFileJson($path'Armor response instance: ' $jsonResponse "\r");
  1392.                 $decodedResponse json_decode($jsonResponsetrue);
  1393.                 if (isset($decodedResponse['data'])) {
  1394.                     $neededArmorId $decodedResponse['data']['points_id'];
  1395.                     $typePointAccountData->setArmIdentifier($neededArmorId);
  1396.                     $em->persist($typePointAccountData);
  1397.                     $em->flush();
  1398.                 }
  1399.             } else {
  1400.                 $this->createFileJson($path'Armor response: ' $dataResponse "\r");
  1401.             }
  1402.             /*
  1403.              * 
  1404.               {
  1405.               "type_point": "5555aaaa-aaaa-5555-aaaa-bdbca33ee555",
  1406.               "starting_date": "1409175049",
  1407.               "country": "US",
  1408.               "account_token": "411dfg111114444",
  1409.               "amount": "1200",
  1410.               "identifier": "b06b66b6-6ad6-6666-6af6-bdbca66ee66"
  1411.               }
  1412.              * 
  1413.              */
  1414.         }
  1415.         $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  1416.         //dump($loyaltyConfiguration[0]->getMinimumPointAmountToExchange());
  1417.         //die;
  1418.         //if ($loyaltyConfiguration[0]->getUseGlobalPoints()) {
  1419.         $pointAccountByClient $pointAccountByClientRepository->findTypePointAccountByClient(['idClient' => $clientOmt->getId(), 'restaurant' => $accountLicenseData[0]->getId()], [], true$loyaltyConfiguration->getMinimumPointAmountToExchange());
  1420.         //} else {
  1421.         //   $pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByClient(['idClient' => $clientOmt->getId(), 'restaurant' => $accountLicenseData[0]->getId()], []);
  1422.         //}
  1423.         //  if (!isset($pointAccountByClient['name'])) {
  1424.         //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1425.         //    ->respondWithError('customer not found', WebService::CODE_COULD_NOT_AUTHENTICATE);
  1426.         //  }
  1427.         // $responseAddAddressNewUser = $clientController->createAddressDummyInOmtWs($this->realContainer, $responseCreationUserOmt['data']['id'], [], $clientOmt->getId());
  1428.         // if (isset($responseAddAddressNewUser['errors'])) {
  1429.         //     return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
  1430.         //         ->respondWithError($responseAddAddressNewUser['errors']['message'], WebService::HTTP_CODE_BAD_REQUEST);
  1431.         // }
  1432.         if (isset($pointAccountByClient['accounts'][0])) {
  1433.             $responseArr['msg'] .= ', list of points by client';
  1434.             $this->createFileJson($path'list of points by client' "\r");
  1435.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1436.             $responseArr['client'] = $pointAccountByClient['accounts'][0];
  1437.             $responseArr['bigbag'] = true;
  1438.         } else {
  1439.             $responseArr['msg'] = 'No client found with the given data';
  1440.             $this->createFileJson($path'No client found with the given data' "\r");
  1441.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1442.         }
  1443.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1444.         $xxArray $theUrlTrSt->transform();
  1445.         $jsonContent json_encode($xxArray);
  1446.         $this->createFileJson($path'WS ends' "\r");
  1447.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  1448.     }
  1449.     private function updateDataOmtClient($params$path){
  1450.         $em $this->getDoctrine()->getManager();
  1451.         $omtClientRepo $em->getRepository('App\Entity\OmtClient');
  1452.         $clientToUpdateDirect null;
  1453.         if (isset($params['clientId'])) {
  1454.             $clientToUpdateDirect $omtClientRepo->find($params['clientId']);
  1455.         }
  1456.         if (is_null($clientToUpdateDirect) && isset($params['email']) && $params['email'] != '') {
  1457.             $clientToUpdateDirect $omtClientRepo->findOneBy(['email' => $params['email']]);
  1458.         }
  1459.         if (!is_null($clientToUpdateDirect)) {
  1460.             $params['userId'] = $clientToUpdateDirect->getId();
  1461.             
  1462.             $url $this->realContainer->getParameter('level_scheme') . '://' $this->realContainer->getParameter('level_host') . $this->generateUrl('data_users_loyalty_update');
  1463.             //  . '?'. http_build_query($params);
  1464.             $paramsToSend json_encode($params);
  1465.             $this->createFileJson($path'data before to send' "\r");
  1466.             $this->createFileJson($path'params => '$paramsToSend "\r");
  1467.             $this->createFileJson($path'url => '$url ."\r");
  1468.             
  1469.             $ch curl_init();
  1470.             curl_setopt($chCURLOPT_URL$url);
  1471.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1472.             curl_setopt($chCURLOPT_CUSTOMREQUESTWebService::REQUEST_METHOD_PUT);
  1473.             curl_setopt($chCURLOPT_POSTFIELDS$paramsToSend);
  1474.             $result curl_exec($ch);
  1475.             $this->createFileJson($path'result of curl the function updateDataOmtClient => '$result ."\r");
  1476.             $decodeResult json_decode($resulttrue);
  1477.             
  1478.             return $this->respondJsonAjax($decodeResult);
  1479.         }else{
  1480.             return $this->setStatusCode(WebService::CODE_ERR_CONFLICT)
  1481.                 ->respondWithError('Client not located to update'WebService::HTTP_CODE_BAD_REQUEST);
  1482.         }
  1483.     }
  1484.     /**
  1485.      * @param Request $request
  1486.      * @return type
  1487.      */
  1488.     public function chingoFuncionParaJhonier(Request $requestArmorService $armorLog $log) {
  1489.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  1490.             $path Util::getValidActiveLogByBaseName($this->realContainer'chingoFuncionParaJhonier''chingoFuncionParaJhonier0.txt');
  1491.             $this->createFileJson($path"\r" 'omtClient Ask: ' json_encode($request->query->all()) . "\r");
  1492.             $em $this->getDoctrine()->getManager();
  1493.             $indexSearch = ['nickname','phone''email'];
  1494.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  1495.             $order Paginator::filterPaginatorParameters([], $requesttrue);
  1496.             // dd($search, $order);
  1497.             $debug $request->query->get('debug');
  1498.             if ($debug) {
  1499.                 dump($search);
  1500.             }
  1501.             if (empty($search)) {
  1502.                 $this->createFileJson($path"\r" "invalid parameter name" "\r");
  1503.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1504.                                 ->respondWithError('Invalid parameter name'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1505.             }
  1506.             $data = ['alLicenseUsername' => $search['nickname']];
  1507.             $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  1508.             if (empty($accountLicenseData[0]))
  1509.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1510.                             ->respondWithError('Coulnt find any license'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1511.             $countResult count($accountLicenseData);
  1512.             $validate $this->validateLicense($countResult$path$accountLicenseData);
  1513.             if(!$validate["status"]){
  1514.                 return $this->setStatusCode($validate["status"])
  1515.                                 ->respondWithError($validate["message"], $validate["code"]);
  1516.             }
  1517.             
  1518.             // if ($countResult <= 0) {
  1519.             //     $this->createFileJson($path, "\r" . "Invalid nickname or channelname" . "\r");
  1520.             //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1521.             //                     ->respondWithError('Invalid nickname or channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
  1522.             // }
  1523.             // $this->createFileJson($path, "\r" . "license found => ". $search['nickname'] . "\r");
  1524.             // if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  1525.             //     $this->createFileJson($path, "\r" . "Account is inactive" . "\r");
  1526.             //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1527.             //                     ->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
  1528.             // }
  1529.             // if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  1530.             //     $this->createFileJson($path, "\r" . "Inactive License" . "\r");
  1531.             //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1532.             //                     ->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
  1533.             // }
  1534.             $loyaltyConfiguration $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $accountLicenseData[0]->getId()]);
  1535.             $this->createFileJson($path"\r" "searching loyalty configuration with license id => "$accountLicenseData[0]->getId() . "\r");
  1536.             // if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
  1537.             //     $this->createFileJson($path, 'Loyalty functions not configured yet o.O' . "\r");
  1538.             //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1539.             //                     ->respondWithError('Loyalty functions not configured yet', WebService::CODE_ACCOUNT_SUSPENDED);
  1540.             // } else
  1541.             if (!isset($loyaltyConfiguration[0])) {
  1542.                 $this->createFileJson($path'Loyalty functions configuration record not found o.O' "\r");
  1543.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1544.                                 ->respondWithError('Loyalty functions configuration record not found!'WebService::CODE_ACCOUNT_SUSPENDED);
  1545.             }
  1546.             $log->createChannel('local_point_automatic_creation_log');
  1547.             $search['restaurant'] = $accountLicenseData[0]->getId();
  1548.             $responseArr = [];
  1549.             if ($debug) {
  1550.                 dump($search$order$loyaltyConfiguration[0]->getMinimumPointAmountToExchange());
  1551.             }
  1552.             $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  1553.             $typePointRepository $em->getRepository('App\Entity\TypePoint');
  1554.             $pointAccountByClient $pointAccountByClientRepository->findTypePointAccountByRestaurant($request$this->realContainer$search$order$loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $accountLicenseData[0], $armor$log$pathfalse$debug);
  1555.             $this->createFileJson($path"\r" "validate and build paginator data" "\r");
  1556.             $paginatorFormatedData $this->validateAndBuildPaginatorData($order$pointAccountByClient);
  1557.             // dump($paginatorFormatedData);
  1558.             $info $typePointRepository->getRatioPoints();
  1559.             $this->createFileJson($path"\r" "pagination for data response" "\r");
  1560.             $responseArrWithPagination $this->paginationForDataResponse($paginatorFormatedData['response'], $paginatorFormatedData['paginator']);
  1561.             // dump($responseArrWithPagination);
  1562.             $responseArrWithPagination['msg'] = "List of point accounts by '$accountLicenseData[0]' restaurant";
  1563.             $responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
  1564.             $responseArrWithPagination['clients'] = $pointAccountByClient['accounts'];
  1565.             $responseArrWithPagination['info'] = $info;
  1566.             $responseArrWithPagination['bigbag'] = true;
  1567.             
  1568.             if(isset($search['restaurant']) && $search['restaurant'] != ''){
  1569.                 $loyaltyConfiguration $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->getStatusLoyaltyByRestaurand($search['restaurant']);
  1570.                 $responseArrWithPagination['loyaltyPoints'] = (boolean)$loyaltyConfiguration;
  1571.             }
  1572.             // dump(count($responseArrWithPagination['accounts']));
  1573.             // dump(count($responseArrWithPagination['clients']));
  1574.             // die;        
  1575.             if (isset($responseArrWithPagination['accounts'])) {
  1576.                 unset($responseArrWithPagination['accounts']);
  1577.             }
  1578.             if ($debug) {
  1579.                 die;
  1580.             }
  1581.             // $theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
  1582.             // $xxArray = $theUrlTrSt->transform();
  1583.             // $jsonContent = json_encode($xxArray);
  1584.             
  1585.             // 1. Crear el transformer y procesar datos base
  1586.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrWithPagination);
  1587.             $xxArray $theUrlTrSt->transform();
  1588.             // 2. Obtener tokens solo si hay clientId válido
  1589.             $baseUrl $this->realContainer->getParameter('omt_ws_url') . "common/getTokenForUser";
  1590.             $tokensData null;
  1591.             // dd($xxArray);
  1592.             if (isset($xxArray['clients'][0]['clientId']) && !empty($xxArray['clients'][0]['clientId'])) {
  1593.                 $omtClient $em->getRepository('App\Entity\OmtClient')->find($xxArray['clients'][0]['clientId']);
  1594.                 $this->createFileJson($path"\r" 'Token detectado: ' json_encode(['clientd' => $xxArray['clients'][0]['clientId']]) . "\r");
  1595.                 
  1596.                 if ($omtClient) {
  1597.                     $url $baseUrl '?loyaltyClientId=' urlencode($omtClient->getOmtUserId());
  1598.                     $this->createFileJson($path"\r" 'Token detectado: '"\r");
  1599.                     $this->createFileJson($path"\r" 'Usuario: ' json_encode(['clientd' => $xxArray['clients'][0]['clientId'], 'omt_user' => $omtClient->getOmtUserId()]) . "\r");
  1600.                     $this->createFileJson($path"\r" 'Send request to omt ' "\r");
  1601.                     $ch curl_init();
  1602.                     curl_setopt($chCURLOPT_URL$url);
  1603.                     curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  1604.                     curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  1605.                     $result curl_exec($ch);
  1606.                     $httpCode curl_getinfo($chCURLINFO_HTTP_CODE);
  1607.                     curl_close($ch);
  1608.                     if ($result !== false && $httpCode === 200) {
  1609.                         $this->createFileJson($path"\r" 'Armor response Ok: ' $result "\r");
  1610.                         $responseData json_decode($resulttrue);
  1611.                         if (isset($responseData['data'])) {
  1612.                             $tokensData $responseData['data'];
  1613.                         }
  1614.                     }
  1615.                     $this->createFileJson($path"\r" 'Armor Failed: ' $result "\r");
  1616.                 }
  1617.             } else {
  1618.                 $this->createFileJson($path"\r" 'No token detected '  "\r");
  1619.             }
  1620.             // 3. Construir respuesta final
  1621.             $finalResponse = [
  1622.                 'data' => $xxArray  // Datos base transformados
  1623.             ];
  1624.             
  1625.             // Añadir tokens solo si existen
  1626.             if ($tokensData !== null) {
  1627.                 $finalResponse['data']['clients'][0]['tokens'] = $tokensData;
  1628.             }
  1629.             // 4. Retornar respuesta
  1630.             return $this->respondWithArray($finalResponse);
  1631.         }
  1632.         if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
  1633.             $responseArrWithPagination['msg'] = "Good to go!";
  1634.             $responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
  1635.             $responseArrWithPagination['bigbag'] = false;
  1636.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrWithPagination);
  1637.             $xxArray $theUrlTrSt->transform();
  1638.             $jsonContent json_encode($xxArray);
  1639.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1640.         }
  1641.     }
  1642.     /**
  1643.      * 
  1644.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  1645.      * @return Response Json con la informacion de respuesta
  1646.      */
  1647.     public function createPointAccount(Request $request) {
  1648.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  1649.             $data json_decode($request->getContent(), true);
  1650.             if (strlen($data['omtClientId']) != 36) {
  1651.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1652.                                 ->respondWithError('Invalid omtClientId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1653.             }
  1654.             if (strlen($data['id']) != 36) {
  1655.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1656.                                 ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1657.             }
  1658.             $em $this->getDoctrine()->getManager();
  1659.             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($data['id']);
  1660.             $clientOmt $em->getRepository('App\Entity\OmtClient')->find($data['omtClientId']);
  1661.             if (!$clientOmt) {
  1662.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1663.                                 ->respondWithError('Omt client not found'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1664.             }
  1665.             $clientPointSearch = ['omtClient' => $data['omtClientId']];
  1666.             $clientPointAccount $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
  1667.             $basePointSearch = ['basePointacount' => $data['basePointacount']];
  1668.             $basePointAccount $em->getRepository('App\Entity\PointAcount')->findBy($basePointSearch);
  1669.             if ($basePointAccount && $basePointAccount[0]->getId() != $data['id']) {
  1670.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1671.                                 ->respondWithError('Invalid basePointAcount'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1672.             }
  1673.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1674.             $responseArr['msg'] = 'Point account update successfully!';
  1675.             if (!$pointAccountData) {
  1676.                 $pointAccountData = new PointAcount();
  1677.                 $pointAccountData->setId($data['id']);
  1678.                 $responseArr['msg'] = 'Point account created successfully!';
  1679.             }
  1680.             $pointAccountData->setOmtClient($clientOmt->getId());
  1681.             $pointAccountData->setBasePointacount($data['basePointacount']);
  1682.             $pointAccountData->setActivationDate(new \DateTime($data['activationDate']));
  1683.             $em->persist($pointAccountData);
  1684.             $em->flush();
  1685.             if ($clientPointAccount) {
  1686.                 $responseArr['msg'] .= ' User already has point account!';
  1687.             }
  1688.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1689.             $xxArray $theUrlTrSt->transform();
  1690.             $jsonContent json_encode($xxArray);
  1691.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1692.         }
  1693.     }
  1694.     /**
  1695.      * 
  1696.      * @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
  1697.      * @return Response Json con la informacion de respuesta
  1698.      */
  1699.     public function createTypePointAccount(Request $request) {
  1700.         if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
  1701.             $data json_decode($request->getContent(), true);
  1702.             if (strlen($data['typePoinId']) != 36) {
  1703.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1704.                                 ->respondWithError('Invalid typePoinId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1705.             }
  1706.             if (strlen($data['pointAccountId']) != 36) {
  1707.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1708.                                 ->respondWithError('Invalid pointAccountId'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1709.             }
  1710.             if (strlen($data['id']) != 36) {
  1711.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1712.                                 ->respondWithError('Invalid id'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1713.             }
  1714.             $em $this->getDoctrine()->getManager();
  1715.             $typePointAccountData $em->getRepository('App\Entity\TypePointAcount')->find($data['id']);
  1716.             $accountTokenSearch = ['acountToken' => $data['accountToken']];
  1717.             $accountTokenData $em->getRepository('App\Entity\TypePointAcount')->findBy($accountTokenSearch);
  1718.             if ($accountTokenData && $accountTokenData[0]->getId() != $data['id']) {
  1719.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1720.                                 ->respondWithError('Invalid acountToken'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1721.             }
  1722.             $typePointData $em->getRepository('App\Entity\TypePoint')->find($data['typePoinId']);
  1723.             $countrySearch = ['coVal' => $data['countryCode']];
  1724.             $countryData $em->getRepository('App\Entity\Country')->findBy($countrySearch);
  1725.             if ($countryData) {
  1726.                 $countryData $em->getRepository('App\Entity\Country')->find($countryData[0]->getCoId());
  1727.             }
  1728.             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($data['pointAccountId']);
  1729.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1730.             $responseArr['msg'] = 'Type Point account update successfully!';
  1731.             if (!$typePointAccountData) {
  1732.                 $typePointAccountData = new TypePointAcount();
  1733.                 $typePointAccountData->setId($data['id']);
  1734.                 $responseArr['msg'] = 'Type Point account created successfully!';
  1735.             }
  1736.             $typePointAccountData->setTypePoint($typePointData);
  1737.             $typePointAccountData->setPointAcount($pointAccountData);
  1738.             $typePointAccountData->setCountryId($countryData);
  1739.             $typePointAccountData->setAmount($data['ptAmount']);
  1740.             $typePointAccountData->setPointArmAcount($data['pointArmAccount']);
  1741.             $typePointAccountData->setStartingDate(new \DateTime($data['startingDate']));
  1742.             $typePointAccountData->setAcountToken($data['accountToken']);
  1743.             $em->persist($typePointAccountData);
  1744.             $em->flush();
  1745.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1746.             $xxArray $theUrlTrSt->transform();
  1747.             $jsonContent json_encode($xxArray);
  1748.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1749.         }
  1750.     }
  1751.     /**
  1752.      * @param Request $request
  1753.      * @return type
  1754.      */
  1755.     public function listOfRules(Request $request) {
  1756.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  1757.             $em $this->getDoctrine()->getManager();
  1758.             $indexSearch = ['uid''nickname'];
  1759.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  1760.             if (isset($search['uid']) && isset($search['nickname'])) {
  1761.                 $dataSearch = ['deviceUid' => $search['uid']];
  1762.                 $accountLicByUidData $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
  1763.                 if (!$accountLicByUidData) {
  1764.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1765.                                     ->respondWithError('Invalid UID'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1766.                 }
  1767.                 $dataSearch = ['alLicenseUsername' => $search['nickname']];
  1768.                 $accountLicByNicknameData $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
  1769.                 if (!$accountLicByNicknameData) {
  1770.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1771.                                     ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1772.                 }
  1773.                 if ($accountLicByNicknameData[0]->getId() != $accountLicByUidData[0]->getId()) {
  1774.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1775.                                     ->respondWithError('Invalid nickname or uid'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1776.                 }
  1777.                 if ($accountLicByUidData[0]) {
  1778.                     $search['id'] = $accountLicByUidData[0]->getId();
  1779.                 }
  1780.             }
  1781.             $listRules $em->getRepository('App\Entity\PtsAdquiRedemRules')->listRules($search);
  1782.             $responseArr['msg'] = 'List of rules';
  1783.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1784.             $responseArr['dataList'] = $listRules;
  1785.             $responseArr['bigbag'] = true;
  1786.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1787.             $xxArray $theUrlTrSt->transform();
  1788.             $jsonContent json_encode($xxArray);
  1789.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1790.         }
  1791.     }
  1792.     /**
  1793.      * WS generico para consultar el historial de transacciones punto central el cliente 
  1794.      * @author Felipe Bautista <aarango@kijho.com> 19/02/19
  1795.      * @param Request $request
  1796.      * @return type 
  1797.      */
  1798.     public function historyTransactionPoints(Request $request) {
  1799.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  1800.             $em $this->getDoctrine()->getManager();
  1801.             $indexSearch = ['nickname''accountNickname''initialDate''endDate''typePoints''typeOfPurchase''page''limit'];
  1802.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  1803.             $historyTransaction $em->getRepository('App\Entity\PointDeal')->searchHistoryTransation(null$search);
  1804.             $responseArr['msg'] = 'Transaction History';
  1805.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1806.             $responseArr['dataList'] = $historyTransaction;
  1807.             $responseArr['bigbag'] = true;
  1808.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1809.             $xxArray $theUrlTrSt->transform();
  1810.             $jsonContent json_encode($xxArray);
  1811.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1812.         }
  1813.     }
  1814.     /**
  1815.      * WS generico para consultar el historial de transacciones punto central el restaurante 
  1816.      * @author Felipe Bautista <aarango@kijho.com> 19/02/19
  1817.      * @param Request $request
  1818.      * @return type 
  1819.      */
  1820.     public function historyTransactionPointsByRestaurant(Request $request) {
  1821.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  1822.             
  1823.             $em $this->getDoctrine()->getManager();
  1824.             $indexSearch = ['nickname''accountNickname''initialDate''endDate''typePoints''typeOfPurchase''page''limit'];
  1825.             $search Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  1826.             $restaurant $em->getRepository('App\Entity\AccountLicense')->searchRestaurant($search);
  1827.             $historyTransaction $em->getRepository('App\Entity\PointDeal')->searchHistoryTransationByRestaurant($restaurant$search);
  1828.             $responseArr['msg'] = 'Transaction History By Restaurants';
  1829.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1830.             $responseArr['dataList'] = $historyTransaction;
  1831.             $responseArr['bigbag'] = true;
  1832.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1833.             $xxArray $theUrlTrSt->transform();
  1834.             $jsonContent json_encode($xxArray);
  1835.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1836.         }
  1837.     }
  1838.     /**
  1839.      * @author Felipe Bautista <aarango@kijho.com> 21/02/19
  1840.      * @param Request $request
  1841.      * @return type 
  1842.      */
  1843.     public function checkCards(Request $request) {
  1844.         if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
  1845.             $em $this->getDoctrine()->getManager();
  1846.             $indexSearch = ['uid''nickname''lastFour''expirationDate''nameOnCard''franchise''langCode''countryCode''page''limit'];
  1847.             $data Paginator::filterParameters($indexSearch$requestPaginator::REQUEST_TYPE_REQUEST);
  1848.             $cards = [];
  1849.             if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['countryCode'])) {
  1850.                 return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  1851.             }
  1852.             $nickname $em->getRepository('App\Entity\AccountLicense')->findBy(['alLicenseUsername' => $data['nickname']]);
  1853.             if (!isset($nickname) || $nickname == []) {
  1854.                 return $this->errorWrongArgs('nickname not found'WebService::CODE_WRONG_ARGUMENTS);
  1855.             }
  1856.             $uid $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
  1857.             if (!isset($uid) || $uid == []) {
  1858.                 return $this->errorWrongArgs('uid not found'WebService::CODE_WRONG_ARGUMENTS);
  1859.             }
  1860.             if ($uid[0]->getId() !== $nickname[0]->getId()) {
  1861.                 return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  1862.             }
  1863.             $fullCombined $data['nameOnCard'] . '_' $data['lastFour'] . '_' $data['franchise'] . '_' $data['expirationDate'];
  1864.             $fullCombined str_replace(' ''_'strtolower(str_replace('/''-'$fullCombined)));
  1865.             $cardClient $em->getRepository('App\Entity\CardAsClient')->findBy(['uniqueCombined' => $fullCombined]);
  1866.             if ($cardClient) {
  1867.                 $cards $em->getRepository('App\Entity\CardAsClient')->searchForCardMatches($data$fullCombined);
  1868.             }
  1869.             $responseArr['msg'] = 'Cards clients';
  1870.             $responseArr['status'] = WebService::CODE_SUCCESS;
  1871.             $responseArr['cards'] = $cards;
  1872.             $responseArr['bigbag'] = true;
  1873.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  1874.             $xxArray $theUrlTrSt->transform();
  1875.             $jsonContent json_encode($xxArray);
  1876.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  1877.         }
  1878.     }
  1879.     /**
  1880.      * @param Request $request
  1881.      * @return type
  1882.      */
  1883.     public function adjustRefundPointsOrElse(Request $requestArmorService $armorLog $log) {
  1884.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  1885.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  1886.         }
  1887.         if (!(=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
  1888.             return $this->errorWrongArgs('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  1889.         }
  1890.         $path Util::getValidActiveLogByBaseName($this->realContainer'AdjustRefundPointsOrElse''AdjustRefundPointsOrElse0.txt');
  1891.         $this->createFileJson($path"\r" 'adjustRefundPointsOrElse fever XD ' $request->getContent() . "\r");
  1892.         $data json_decode($request->getContent(), true);
  1893.         if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['transactionCodes'])) {
  1894.             return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  1895.         }
  1896.         $em $this->getDoctrine()->getManager();
  1897.         $nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
  1898.         $nicknameLicData $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
  1899.         if (empty($nicknameLicData)) {
  1900.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1901.                             ->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  1902.         }
  1903.         if ($nicknameLicData[0]->getDeviceUid() != $data['uid']) {
  1904.             $emLev Util::emLicenseConnection($this->realContainer$em$nicknameLicData[0]);
  1905.             $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
  1906.             if (empty($registeredClientsByUID)) {
  1907.                 $emLev->close();
  1908.                 $this->createFileJson($path'UID diferente! o.O' "\r");
  1909.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1910.                                 ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  1911.             } else {
  1912.                 $emLev->close();
  1913.             }
  1914.         }
  1915.         if ($nicknameLicData[0]->getAlAccountLicense()->getDeleted()) {
  1916.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1917.                             ->respondWithError('Inactive Account'WebService::CODE_ACCOUNT_SUSPENDED);
  1918.         }
  1919.         if ($nicknameLicData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  1920.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  1921.                             ->respondWithError('Inactive License'WebService::CODE_ACCOUNT_SUSPENDED);
  1922.         }
  1923.         $responseArrayAux1['msg'] = '';
  1924.         $responseArrayAux1['status'] = WebService::CODE_SUCCESS;
  1925.         $responseArrayAux1['bigbag'] = true;
  1926.         /////////
  1927.         $armorPack = [
  1928.             'request' => $request,
  1929.             'service' => $armor,
  1930.             'log' => $log
  1931.         ];
  1932.         $isCancelationOfCanceledRecords false;
  1933.         if (strpos($request->getUri(), 'cancelOfCancelationPoint')) {
  1934.             $isCancelationOfCanceledRecords true;
  1935.         }
  1936.         $data['license'] = $nicknameLicData[0];
  1937.         $data['isReopenCancelation'] = $isCancelationOfCanceledRecords;
  1938.         $armorPack['isReopenCancelation'] = $isCancelationOfCanceledRecords;
  1939.         if (isset($data['customerId'])) {
  1940.             $armorPack['customerId'] = $data['customerId'];
  1941.         }
  1942.         //        dump($request->getUri());
  1943.         //        dump($isCancelationOfCanceledRecords);
  1944.         //        die;
  1945.         $isAdjustTransaction false;
  1946.         if (isset($data['transactionCodes']) && !empty($data['transactionCodes'])) {
  1947.             $cancelationResponse PointsUtilPorcessor::proccessBasicTypeCancel($this->realContainer$em$data$armorPack$path);
  1948.         } else {
  1949.             return $this->errorWrongArgs('Error in transactions parameter'WebService::CODE_WRONG_ARGUMENTS);
  1950.         }
  1951.         //        dump($cancelationResponse);
  1952.         //        die;
  1953.         /*
  1954.           "nickname": "mauricet_311",
  1955.           "uid": "d7ee572cd137dfb7",
  1956.           "dealType": 4,
  1957.           "customerId": "bc328962-4e8a-4437-a43d-59945b82d885",
  1958.           "totalAmount": "33.90",
  1959.           "watchedTime": "2018-01-24 16:48:14"
  1960.          */
  1961.         $indexExistenceToValidate = ['transactionCodes''dealType''totalAmount''watchedTime''customerId'];
  1962.         $isCardParams $this->paramsArrayIndexValidator($data$indexExistenceToValidate);
  1963.             //        dump($isCardParams);
  1964.         if (isset($isCardParams[0]) && $isCardParams[0]) {
  1965.             $isAdjustTransaction true;
  1966.             unset($data['transactionCodes']);
  1967.             $responseArrayAux1['msg'] = 'Point transactions processed successfully!';
  1968.             $pointEvaluationResult PointsUtilPorcessor::analyzePointTransaction($this->realContainer$em$nicknameLicData[0], $data$armorPack);
  1969.             //            dump($pointEvaluationResult);
  1970.             //            die;
  1971.             $responseArrayAux2 $this->processEvaluatedTransactionResponse($pointEvaluationResult$data);
  1972.             //            dump($responseArrayAux2);
  1973.             $responseArr array_merge($responseArrayAux1$responseArrayAux2);
  1974.             //            dump($responseArr);
  1975.             //            die;
  1976.         } else {
  1977.             //            dump($cancelationResponse);
  1978.             //            die;
  1979.             if (isset($cancelationResponse[0]) && is_string($cancelationResponse[0])) {
  1980.                 $responseArr['msg'] = $cancelationResponse[0];
  1981.                 $responseArr['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
  1982.                 $responseArr['bigbag'] = true;
  1983.             } else {
  1984.                 $responseArr['msg'] = $cancelationResponse[0]['msg'];
  1985.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  1986.                 $responseArr['bigbag'] = true;
  1987.                 unset($cancelationResponse[0]['msg']);
  1988.                 $responseArr['transactionsProcessed'] = $cancelationResponse[0];
  1989.             }
  1990.             //            dump($responseArr);
  1991.         }
  1992.         //        if (isset($data['customerId'])) {
  1993.         //            $userTypePointAccount = $em->getRepository('App\Entity\PointAcount')->findBy(['omtClient' => $data['customerId']]);
  1994.         //
  1995.         //            $validationResponse = $this->vaidateIfAnotherTransactionIsInProgress($em, $userTypePointAccount, $data);
  1996.         //
  1997.         //            if (is_array($validationResponse)) {
  1998.         //                $theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $validationResponse);
  1999.         //                $jsonTransform = $theUrlTrSt->transform();
  2000.         //
  2001.         //                $jsonContent = json_encode($jsonTransform);
  2002.         //
  2003.         //                return $this->respondWithItem($jsonContent, $theUrlTrSt);
  2004.         //            } elseif (is_string($validationResponse)) {
  2005.         //                return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2006.         //                                ->respondWithError($validationResponse, WebService::CODE_ACCOUNT_SUSPENDED);
  2007.         //            }
  2008.         //        }
  2009.         //        $newIncomingPointTransaction = new PointRelatedRequest();
  2010.         //        if ($isAdjustTransaction) {
  2011.         //            $newIncomingPointTransaction->setType(PointRelatedRequest::TYPE_TRANSACTION_ADJUST);
  2012.         //        } else {
  2013.         //            $newIncomingPointTransaction->setType(PointRelatedRequest::TYPE_TRANSACTION_CANCEL);
  2014.         //        }
  2015.         //        dump($newIncomingPointTransaction);
  2016.         //        die;
  2017.         //        $pointCreatedResult = PointsUtilPorcessor::persistArrayForRequestCopy($em, $request, $nicknameLicData[0], $newIncomingPointTransaction, $data);
  2018.         //
  2019.         //        $fullCommandCallFor = $this->startAllTheCommandToRabbitTransactionProcess($pointCreatedResult, $path);
  2020.         //
  2021.         //        if (is_string($fullCommandCallFor)) {
  2022.         //            return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
  2023.         //                            ->respondWithError($fullCommandCallFor, WebService::CODE_ERR_UNPROCESSABLE);
  2024.         //        }
  2025.         //
  2026.         //        $pollingResult = $this->pollingAskingIfPointTransactionWasProcessed($em, $pointCreatedResult, $path);
  2027.         //        $this->createFileJson($path, 'The polling json result -> ' . json_encode($pollingResult) . "\r");
  2028.         //        if (isset($pollingResult['wasProcessed']) && $pollingResult['wasProcessed']) {
  2029.         //            $cancelationResponse = json_decode($pollingResult['theTransaction']->getJsonResponse(), true);
  2030.         //        } else {
  2031.         //            $cancelationResponse = [];
  2032.         //        }
  2033.         $loyaltyConfiguration $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $nicknameLicData[0]->getId()]);
  2034.         if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
  2035.             $this->createFileJson($path'Loyalty functions not configured yet o.O' "\r");
  2036.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2037.                             ->respondWithError('Loyalty functions not configured yet'WebService::CODE_ACCOUNT_SUSPENDED);
  2038.         } elseif (!isset($loyaltyConfiguration[0])) {
  2039.             $this->createFileJson($path'Loyalty functions configuration record not found o.O' "\r");
  2040.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2041.                             ->respondWithError('Loyalty functions configuration record not found!'WebService::CODE_ACCOUNT_SUSPENDED);
  2042.         }
  2043.         if (!$isAdjustTransaction && isset($cancelationResponse[1]) && $cancelationResponse[1]) {
  2044.             $this->createFileJson($path'Processgin cacelation result!' "\r");
  2045.         } elseif ($isAdjustTransaction) {
  2046.             $this->createFileJson($path'Processgin adjust result!' "\r");
  2047.             $responseArrayAux1['status'] = WebService::CODE_SUCCESS;
  2048.             $responseArrayAux1['msg'] = 'Point transactions adjust processed successfully!';
  2049.             //            $responseArrayAux2 = $this->processEvaluatedTransactionResponse($cancelationResponse, $data);
  2050.             $responseArr array_merge($responseArrayAux1$responseArrayAux2);
  2051.         }
  2052.         //        dump($responseArr);
  2053.         //        die;
  2054.         $order Paginator::filterPaginatorParameters([], $requesttrue);
  2055.         $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  2056.         $pointAccountByClient $pointAccountByClientRepository->findTypePointAccountByRestaurant(
  2057.                 $request$this->realContainer, [
  2058.             'restaurant' => $nicknameLicData[0]->getId(),
  2059.             'client' => $cancelationResponse[1]
  2060.                 ], $order$loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $nicknameLicData[0]->getId(), $armor$log$path);
  2061.         $responseArr['bigbag'] = true;
  2062.         //            $responseArr['status'] = WebService::CODE_SUCCESS;
  2063.         //            $responseArr['msg'] = $cancelationResponse[0]['msg'];
  2064.         //            unset($cancelationResponse[0]['msg']);
  2065.         //            $responseArr['transactionsProcessed'] = $cancelationResponse[0];
  2066.         $responseArr['client'] = $pointAccountByClient['accounts'][0];
  2067.         $this->createFileJson($path'The response array -> ' json_encode($responseArr) . "\r");
  2068.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  2069.         $xxArray $theUrlTrSt->transform();
  2070.         $jsonContent json_encode($xxArray);
  2071.         //        if (isset($validationResponse)) {
  2072.         //            $this->markAsNoOtherTransactionInProgress($em, $validationResponse);
  2073.         //        }
  2074.         //        $this->closePointTransactionProcessInRabbit($em, $pollingResult['theTransaction'], $path);
  2075.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  2076.     }
  2077.     /**
  2078.      * @param type $em
  2079.      * @param type $transactionRecord
  2080.      * @param type $path
  2081.      * @return boolean
  2082.      */
  2083.     public function closePointTransactionProcessInRabbit($em$transactionRecord$path) {
  2084.         try {
  2085.             $transactionRecord->setDateDelivered(Util::getCurrentDate());
  2086.             $transactionRecord->setStatus(RabbitRelatedGenericEntity::STATUS_DELIVERED);
  2087.             $em->persist($transactionRecord);
  2088.             $em->flush();
  2089.             $this->createFileJson($path'Transaction status updated!' "\r");
  2090.             return true;
  2091.         } catch (\Exception $ex) {
  2092.             Utilx::updateSyncRecordError($this->em$this->thePointTransactionRecord$ex->getMessage());
  2093.             $this->createFileJson($path'Error updating transaction record! ' $ex->getMessage() . "\r");
  2094.             return false;
  2095.         }
  2096.     }
  2097.     /**
  2098.      * @param string $pointEvaluationResult
  2099.      * @param type $params
  2100.      * @return type
  2101.      */
  2102.     public function processEvaluatedTransactionResponse($pointEvaluationResult$params) {
  2103.         if (is_array($pointEvaluationResult)) {
  2104.             if (isset($pointEvaluationResult[0]) && count($pointEvaluationResult) == && isset($pointEvaluationResult[0]['nonAplicationMsg'])) {
  2105.                 if ($pointEvaluationResult[0]['nonAplicationMsg'] == 'Little remaining amount to proccess') {
  2106.                     $responseArray['msg'] = 'No point achieved with the remaining amount.. ';
  2107.                     $responseArray['status'] = WebService::CODE_SUCCESS;
  2108.                     $responseArray['approvedPointsTransactions'] = [];
  2109.                 } elseif (strpos($pointEvaluationResult[0]['nonAplicationMsg'], 'inumum amount purchase')) {
  2110.                     $responseArray['msg'] = 'No point achieved because minimum purchase amount not reached.. ';
  2111.                     $responseArray['status'] = WebService::CODE_SUCCESS;
  2112.                     $responseArray['approvedPointsTransactions'] = [];
  2113.                 } else {
  2114.                     if (strpos($pointEvaluationResult[0]['nonAplicationMsg'], 'enough points!')) {
  2115.                         $responseArray['msg'] = $pointEvaluationResult[0]['nonAplicationMsg'];
  2116.                         $responseArray['status'] = WebService::HTTP_CODE_PAYMENT_REQUIRED;
  2117.                     } else {
  2118.                         $responseArray['msg'] = $pointEvaluationResult[0]['nonAplicationMsg'];
  2119.                         $responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
  2120.                     }
  2121.                 }
  2122.             } elseif (isset($pointEvaluationResult[0]) && count($pointEvaluationResult) == && ($params['dealType'] == TypePtsGenericDefinitionRules::TYPE_PURCHASE_WITH_LOCAL_PTS || $params['dealType'] == TypePtsGenericDefinitionRules::TYPE_PURCHASE_WITH_GLOBAL_PTS)) {
  2123.                 $responseArray['approvedPointsTransactions'] = $pointEvaluationResult[0];
  2124.             } elseif (empty($pointEvaluationResult)) {
  2125.                 $responseArray['msg'] = 'No point transactions were made.. ';
  2126.                 $responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
  2127.             } else {
  2128.                 $responseArray['approvedPointsTransactions'] = $pointEvaluationResult;
  2129.             }
  2130.         } else {
  2131.             if (strpos($pointEvaluationResult'please try again later')) {
  2132.                 $responseArray['msg'] = 'Insufficient Loyalty Cash balance to redeem the order.. ' $pointEvaluationResult;
  2133.                 $responseArray['status'] = WebService::CODE_ERR_NOT_FOUND;
  2134.             } else {
  2135.                 $responseArray['msg'] = 'Insufficient Loyalty Cash balance to redeem the order.. ' $pointEvaluationResult;
  2136.                 $responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
  2137.             }
  2138.         }
  2139.         $responseArray['bigbag'] = true;
  2140.         return $responseArray;
  2141.     }
  2142.     /**
  2143.      * @author Felipe Bautista <aarango@kijho.com> 22/02/19
  2144.      * @param Request $request
  2145.      * @return type 
  2146.      */
  2147.     public function linkingAccounts(Request $request) {
  2148.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  2149.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2150.         }
  2151.         if (!(=== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
  2152.             return $this->errorWrongArgs('Wrong Content.'WebService::CODE_WRONG_ARGUMENTS);
  2153.         }
  2154.         $em $this->getDoctrine()->getManager();
  2155.         $data json_decode($request->getContent(), true);
  2156.         if (!isset($data['nickname']) || !isset($data['uid'])) {
  2157.             return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  2158.         }
  2159.         $nickname $em->getRepository('App\Entity\AccountLicense')->findBy(['alLicenseUsername' => $data['nickname']]);
  2160.         if (!isset($nickname) || $nickname == []) {
  2161.             return $this->errorWrongArgs('nickname not found'WebService::CODE_WRONG_ARGUMENTS);
  2162.         }
  2163.         if ($nickname[0]->getDeviceUid() != $data['uid']) {
  2164.             $emLev Util::emLicenseConnection($this->realContainer$em$nickname[0]);
  2165.             $registeredClientsByUID $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
  2166.             if (empty($registeredClientsByUID)) {
  2167.                 $emLev->close();
  2168.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  2169.                                 ->respondWithError('Unknown device'WebService::CODE_UNAUTHORIZED);
  2170.             } else {
  2171.                 $emLev->close();
  2172.             }
  2173.         }
  2174.         $uid $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
  2175.         if (!isset($uid) || $uid == []) {
  2176.             return $this->errorWrongArgs('uid not found'WebService::CODE_WRONG_ARGUMENTS);
  2177.         }
  2178.         $omtClients $em->getRepository('App\Entity\OmtClient')->searchClientToLinking($data);
  2179.         if (count($omtClients) == 2) {
  2180.             $pointsByClients $em->getRepository('App\Entity\PointAcount')->searchCustomerPointsAccountsToLink($omtClients);
  2181.             $targetCustomer $pointsByClients[0];
  2182.             $originalCustomer $pointsByClients[1];
  2183.             $targetClient $em->getRepository('App\Entity\OmtClient')->find($targetCustomer['client']);
  2184.             $originalClient $em->getRepository('App\Entity\OmtClient')->find($originalCustomer['client']);
  2185.             if ($targetClient->getEmail() === null && $originalClient->getEmail() !== null) {
  2186.                 $email $originalClient->getEmail();
  2187.                 $originalClient->setEmail(null);
  2188.                 $em->persist($originalClient);
  2189.                 $em->flush();
  2190.                 $targetClient->setEmail($email);
  2191.                 $em->persist($targetClient);
  2192.                 $em->flush();
  2193.             }
  2194.             if ($targetClient->getPhone() === null && $originalClient->getPhone() !== null) {
  2195.                 $phone $originalClient->getPhone();
  2196.                 $originalClient->setPhone(null);
  2197.                 $em->persist($originalClient);
  2198.                 $em->flush();
  2199.                 $targetClient->setPhone($phone);
  2200.                 $em->persist($targetClient);
  2201.                 $em->flush();
  2202.             }
  2203.             $typePointDataOriginalCustomer $em->getRepository('App\Entity\TypePointAcount')->findPointsToTransfer($originalCustomer['id']);
  2204.             $typePointDataTargetCustomer $em->getRepository('App\Entity\TypePointAcount')->findPointsToTransfer($targetCustomer['id']);
  2205.             foreach ($typePointDataTargetCustomer AS $key1 => $pointTargetCustomer) {
  2206.                 foreach ($typePointDataOriginalCustomer AS $key2 => $pointOriginalCustomer) {
  2207.                     if ($pointOriginalCustomer['license'] == $pointTargetCustomer['license'] && $pointOriginalCustomer['typePoint'] == $pointTargetCustomer['typePoint']) {
  2208.                         $amount $pointOriginalCustomer['amount'] + $pointTargetCustomer['amount'];
  2209.                         $targetLink $em->getRepository('App\Entity\TypePointAcount')->find($pointTargetCustomer['id']);
  2210.                         $homeLink $em->getRepository('App\Entity\TypePointAcount')->find($pointOriginalCustomer['id']);
  2211.                         $targetLink->setAmount($amount);
  2212.                         $em->persist($targetLink);
  2213.                         $homeLink->setAmount(0);
  2214.                         $em->persist($homeLink);
  2215.                         $em->flush();
  2216.                         $linkingTransactionOfPoints $this->linkingOfTransactionOfPoints($em$homeLink$targetLink);
  2217.                     } else {
  2218.                         $homeLink $em->getRepository('App\Entity\TypePointAcount')->findBy(["typePoint" => $pointOriginalCustomer['typePoint'], "pointAcount" => $pointTargetCustomer['pointAcount'], "license" => $pointOriginalCustomer['license']]);
  2219.                         if (!$homeLink) {
  2220.                             $homeLink $em->getRepository('App\Entity\TypePointAcount')->find($pointOriginalCustomer['id']);
  2221.                             $homeLink->setAmount(0);
  2222.                             $em->persist($homeLink);
  2223.                             $typePointData $em->getRepository('App\Entity\TypePoint')->find($pointOriginalCustomer['typePoint']);
  2224.                             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($pointTargetCustomer['pointAcount']);
  2225.                             if (isset($pointOriginalCustomer['license'])) {
  2226.                                 $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->find($pointOriginalCustomer['license']);
  2227.                             } else {
  2228.                                 $accountLicenseData null;
  2229.                             }
  2230.                             $country $em->getRepository('App\Entity\Country')->find($pointOriginalCustomer['countryId']);
  2231.                             $acountToken = ['food' => '123'];
  2232.                             while (!empty($acountToken)) {
  2233.                                 $tokenAcount Encryptor::encodeInfo(Utilx::randomPassword(32), 5);
  2234.                                 $acountToken $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
  2235.                             }
  2236.                             $targetLink = new TypePointAcount();
  2237.                             $targetLink->setTypePoint($typePointData);
  2238.                             $targetLink->setPointAcount($pointAccountData);
  2239.                             $targetLink->setAmount($pointOriginalCustomer['amount']);
  2240.                             $targetLink->setStartingDate($pointOriginalCustomer['startingDate']);
  2241.                             $targetLink->setCountryId($country);
  2242.                             $targetLink->setPointArmAcount($pointOriginalCustomer['pointArmAcount']);
  2243.                             $targetLink->setAcountToken($tokenAcount);
  2244.                             $targetLink->setArmIdentifier($pointOriginalCustomer['armIdentifier']);
  2245.                             $targetLink->setLicense($accountLicenseData);
  2246.                             $em->persist($targetLink);
  2247.                             $em->flush();
  2248.                             $linkingTransactionOfPoints $this->linkingOfTransactionOfPoints($em$homeLink$targetLink);
  2249.                         }
  2250.                     }
  2251.                 }
  2252.             }
  2253.             $linkingCard $this->linkingOfCards($em$originalClient->getId(), $targetClient->getId());
  2254.         }
  2255.         $responseArr['msg'] = 'Successful account linking';
  2256.         $responseArr['status'] = WebService::CODE_SUCCESS;
  2257.         $responseArr['bigbag'] = true;
  2258.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  2259.         $xxArray $theUrlTrSt->transform();
  2260.         $jsonContent json_encode($xxArray);
  2261.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  2262.     }
  2263.     /**
  2264.      * Permite vincular las tarjetas de un cliente origen  a un cliente destino
  2265.      */
  2266.     public function linkingOfCards($em$idClientHome$idClientLink) {
  2267.         $cards $em->getRepository('App\Entity\CardAsClient')->findBy(['client' => $idClientHome]);
  2268.         if ($cards) {
  2269.             $clientLink $em->getRepository('App\Entity\OmtClient')->find($idClientLink);
  2270.             foreach ($cards as $key => $value) {
  2271.                 $value->setClient($clientLink->getId());
  2272.                 $value->setValidateCard(2);
  2273.                 $em->persist($value);
  2274.                 $em->flush();
  2275.             }
  2276.         }
  2277.         return true;
  2278.     }
  2279.     /**
  2280.      * Permite vincular los point deal de un point account a otro point account
  2281.      * los parametros que recibe son type point accounts
  2282.      */
  2283.     public function linkingOfTransactionOfPoints($em$typePointAccountHome$typePointAccountTarget) {
  2284.         $pointDealLinking $em->getRepository('App\Entity\PointDeal')->findBy(['pointAcount' => $typePointAccountHome->getPointAcount(), 'typePointAcount' => $typePointAccountHome->getId()]);
  2285.         if ($pointDealLinking) {
  2286.             $typePointAccountData $em->getRepository('App\Entity\TypePointAcount')->find($typePointAccountTarget->getId());
  2287.             $pointAccountData $em->getRepository('App\Entity\PointAcount')->find($typePointAccountTarget->getPointAcount());
  2288.             foreach ($pointDealLinking as $key => $value) {
  2289.                 $value->setPointAcount($pointAccountData);
  2290.                 $value->setTypePointAcount($typePointAccountData);
  2291.                 $em->persist($value);
  2292.                 $em->flush();
  2293.             }
  2294.         }
  2295.         return true;
  2296.     }
  2297.     public function updateLoyaltyConfig(Request $request$id$type$toClose null) {
  2298.         // if ($request->getMethod() !== WebService::REQUEST_METHOD_GET) {
  2299.         //     return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
  2300.         // }
  2301.         $user $this->get('security.token_storage')->getToken()->getUser();
  2302.         $em $this->getDoctrine()->getManager();
  2303.         $localRatio 0;
  2304.         $globalRatio 0;
  2305.         
  2306.         // obtenemos los parametros de la peticion
  2307.         $params $request->request->all();
  2308.         if (isset($params['points_adqui_redem_rules'])){
  2309.             $params $params['points_adqui_redem_rules'];
  2310.             // dump($params);die;
  2311.         }
  2312.         // $params = isset($params['points_adqui_redem_rules'])$params['points_adqui_redem_rules'];
  2313.         // dump($params);die;
  2314.         $path Util::getValidActiveLogByBaseName($this->realContainer'updateRestaurantLoyaltyConfig''updateRestaurantLoyaltyConfig0.txt');
  2315.         $this->createFileJson($path"\r" 'updateRestaurantLoyaltyConfig fever XD ' $request->getContent() . "\r");
  2316.         $accountLicense $em->getRepository('App\Entity\AccountLicense')->find($id);
  2317.         // consultamos si existe la configuracion para el restaurante si no creamos una nueva
  2318.         $entities $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(["license" => $id]);
  2319.         if (!isset($entities) || empty($entities)) {
  2320.             $entities = new RestaurantLoyaltyConfiguration();
  2321.             $entities->setDateCreated(new \DateTime('now'));
  2322.             $entities->setUseLocalPoints(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
  2323.             $accountLicense->setCaptivePortalStatus(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
  2324.             $entities->setUseGlobalPoints(false);
  2325.             $entities->setMinimumPointAmountToExchange(isset($params['minimumPointAmountToExchange']) && $params['minimumPointAmountToExchange'] != ""?$params['minimumPointAmountToExchange']:1);
  2326.             $entities->setLicense($accountLicense);
  2327.             $em->persist($entities);
  2328.             $em->persist($accountLicense);
  2329.             $em->flush();
  2330.             $saveLevel $this->saveSyncLoyalty($em$accountLicense,$params);
  2331.             
  2332.             if (isset($params['captivePortalStatus']) && $params['captivePortalStatus']) {
  2333.                 // Solo captive portal está siendo activado
  2334.                 Util::logAction(
  2335.                     $em'RestaurantLoyaltyConfiguration'
  2336.                     $idActionHistory::ENABLE_CAPTIVE_PORTAL$user->getUsName().' '.$user->getUsLastName(), [
  2337.                         'msg' => 'Enabled captive portal',
  2338.                         'userId' => $user->getId()
  2339.                 ]);
  2340.             } else if (isset($params['loyalty']) && $params['loyalty']) {
  2341.                 // Solo loyalty está siendo activado
  2342.                 Util::logAction(
  2343.                     $em'RestaurantLoyaltyConfiguration'
  2344.                     $idActionHistory::ENABLE_LOYALTY$user->getUsName().' '.$user->getUsLastName(), [
  2345.                         'new_status' => ActionHistory::ACTION_CREATE,
  2346.                         'userId' => $user->getId()
  2347.                 ]);
  2348.             } else if (isset($params['loyalty']) && !$params['loyalty']) {
  2349.                 // Solo loyalty está siendo desactivado
  2350.                 Util::logAction(
  2351.                     $em'RestaurantLoyaltyConfiguration'
  2352.                     $idActionHistory::DISABLE_LOYALTY$user->getUsName().' '.$user->getUsLastName(), [
  2353.                         'new_status' => ActionHistory::ACTION_DISABLED,
  2354.                         'userId' => $user->getId()
  2355.                 ]);
  2356.             }
  2357.         } else {
  2358.             $entities $entities[0];
  2359.             $oldStatus $entities->getUseLocalPoints();
  2360.             if(isset($params['minimumPointAmountToExchange'])){
  2361.                 $entities->setUseLocalPoints(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
  2362.                 $accountLicense->setCaptivePortalStatus(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
  2363.                 $entities->setMinimumPointAmountToExchange(isset($params['minimumPointAmountToExchange']) && $params['minimumPointAmountToExchange'] != ""?$params['minimumPointAmountToExchange']:1);
  2364.                 $entities->setUseLocalPoints($params['loyalty']);
  2365.                 $entities->setMinimumPointAmountToExchange($params['minimumPointAmountToExchange']);
  2366.                 $em->persist($entities);
  2367.                 $em->persist($accountLicense);
  2368.                 $em->flush();
  2369.                 // TYPE_LOYALTY_NONE
  2370.                 $saveLevel $this->saveSyncLoyalty($em$accountLicense$params);
  2371.                 
  2372.                 if (isset($params['captivePortalStatus'])) {
  2373.                     $actionType $params['captivePortalStatus'] ? ActionHistory::ENABLE_CAPTIVE_PORTAL ActionHistory::DISABLE_CAPTIVE_PORTAL;
  2374.                     Util::logAction(
  2375.                         $em'RestaurantLoyaltyConfiguration'
  2376.                         $id$actionType$user->getUsName().' '.$user->getUsLastName(), [
  2377.                             'msg' => $params['captivePortalStatus'] ? 'Enabled captive portal' 'Disabled captive portal',
  2378.                             'userId' => $user->getId()
  2379.                     ]);
  2380.                 } else if (isset($params['loyalty'])) {
  2381.                     $actionType $params['loyalty'] ? ActionHistory::ENABLE_LOYALTY ActionHistory::DISABLE_LOYALTY;
  2382.                     Util::logAction(
  2383.                         $em'RestaurantLoyaltyConfiguration'
  2384.                         $id$actionType$user->getUsName().' '.$user->getUsLastName(), [
  2385.                             'old_status' => $oldStatus
  2386.                             'new_status' => $entities->getUseLocalPoints(),
  2387.                             'userId' => $user->getId()
  2388.                     ]);
  2389.                 }
  2390.             }
  2391.         }
  2392.         if(isset($saveLevel) && !$saveLevel){
  2393.             return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
  2394.                 'entities' => $entities,
  2395.                 'toClose' => $toClose,
  2396.                 'formPtsAdquiRedemRules' => null,
  2397.                 'localPoint' => null,
  2398.                 'ratioPointLocal' => null,
  2399.                 'localRatio' => $localRatio,
  2400.                 'globalRatio' => $globalRatio,
  2401.                 'message' => "Error in save"
  2402.             ]);
  2403.         }
  2404.         
  2405.         if ($entities->getLicense()) {
  2406.             PointsUtilPorcessor::createRulesForLocalPointLoyaltyConfiguration($em$entities->getLicense(), $path);
  2407.         }
  2408.         $points $em->getRepository('App\Entity\TypePoint')->findAll();
  2409.         foreach ($points as $typePoint) {
  2410.             if ($typePoint->getType() == TypePoint::TYPE_LOCAL) {
  2411.                 $localRatio $typePoint->getCashRatio();
  2412.                 continue;
  2413.             }
  2414.             if ($typePoint->getType() == TypePoint::WORK_AS_GLOBAl) {
  2415.                 $globalRatio $typePoint->getCashRatio();
  2416.             }
  2417.         }
  2418.         $basicPurchaseRulesArray PointsUtilPorcessor::getTheBasicPurchaseRulesArray();
  2419.         // $form = $this->createForm(RestaurantLoyaltyConfig::class, $entities, [
  2420.         //     'action' => $this->generateUrl('update_loyalty_config'),
  2421.         //     'method' => 'POST'
  2422.         // ]);
  2423.         // $form = $this->createForm(PointsAdquiRedemRules::class, $entities, [
  2424.         //     'action' => $this->generateUrl('update_adqui_redem_rules'),
  2425.         //     'method' => 'POST'
  2426.         // ]);
  2427.         // if ($type == 2) {
  2428.         $entitiesadquiRedemRule $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["license" => $entities->getLicense(), "parentDefinition" => $basicPurchaseRulesArray[0]]);
  2429.         // dump($entitiesadquiRedemRule);die;
  2430.         if (!isset($entitiesadquiRedemRule[0])) {
  2431.             $entitiesadquiRedemRule $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["parentDefinition" => $basicPurchaseRulesArray[0]]);
  2432.         }
  2433.         $ptsRatePercentage 0
  2434.         $ratioPointLocal 0;
  2435.         if (isset($entitiesadquiRedemRule[0])) {
  2436.             if ($entitiesadquiRedemRule[0]->getMinimumPurchase() == null) {
  2437.                 $entitiesadquiRedemRule[0]->setMinimumPurchase(0);
  2438.             }
  2439.             $ratioPointLocal $entitiesadquiRedemRule[0]->getPtsRate() * 100;
  2440.             $entitiesadquiRedemRule[0]->setPtsRate($ratioPointLocal);
  2441.             // $formPtsAdquiRedemRules = $this->createForm(PointsAdquiRedemRules::class, $entitiesadquiRedemRule[0], [
  2442.             //     'action' => $this->generateUrl('update_adqui_redem_rules'),
  2443.             //     'method' => 'POST'
  2444.             // ]);
  2445.             
  2446.             $formPtsAdquiRedemRules $this->createForm(PointsAdquiRedemRules::class, $entitiesadquiRedemRule[0], [
  2447.                 'action' => $this->generateUrl('update_adqui_redem_rules'),
  2448.                 'minimumPointAmountToExchange' => $entities->getMinimumPointAmountToExchange(),
  2449.                 'method' => 'POST'
  2450.             ]);
  2451.             
  2452.             return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
  2453.                         'entities' => $entities,
  2454.                         'toClose' => $toClose,
  2455.                         'formPtsAdquiRedemRules' => $formPtsAdquiRedemRules->createView(),
  2456.                         'localPoint' => $entitiesadquiRedemRule[0]->getPointType()->getId(),
  2457.                         'ratioPointLocal' => $ratioPointLocal,
  2458.                         'localRatio' => $localRatio,
  2459.                         'globalRatio' => $globalRatio
  2460.             ]);
  2461.         } else {
  2462.             return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
  2463.                         'entities' => $entities,
  2464.                         'toClose' => $toClose,
  2465.                         'formPtsAdquiRedemRules' => null,
  2466.                         'localPoint' => null,
  2467.                         'ratioPointLocal' => null,
  2468.                         'localRatio' => $localRatio,
  2469.                         'globalRatio' => $globalRatio
  2470.             ]);
  2471.         }
  2472.         // } else {
  2473.         //     return $this->render('AccountLicense\restaurantLoyaltyConfig.html.twig', [
  2474.         //                 'entities' => $entities,
  2475.         //                 'form' => $form->createView(),
  2476.         //                 'localRatio' => $localRatio,
  2477.         //                 'globalRatio' => $globalRatio
  2478.         //     ]);
  2479.         // }
  2480.     }
  2481.     public function updatePointsAdquiRedemRules(Request $request) {
  2482.         $data $request->request->getIterator()->getArrayCopy();
  2483.         $em $this->getDoctrine()->getManager();
  2484.         $params $data['points_adqui_redem_rules'];
  2485.         // dd($data, $request);
  2486.         
  2487.         // En caso de no tener el tipo de puntos(Locales o globales), elegimos por defecto locales
  2488.         $params['typePoint'] = isset($params['typePoint'])? $params['typePoint']:'a00000a1-0aaa-00a0-a00a-0a0a00aaa0a0';
  2489.         // dump($params);die;  
  2490.         //  $ratioPointLocal = $params['ratioPointLocal'] * 100;
  2491.         // $ratioPointLocal = $params['ratioPointLocal'];
  2492.         $ratioPointLocal $params['ptsRate'];
  2493.         $ptsRatePercentage $ratioPointLocal 100;
  2494.         // dump($ratioPointLocal);
  2495.         // dump($ptsRatePercentage);
  2496.         // die;
  2497.         $basicPurchaseRulesArray PointsUtilPorcessor::getTheBasicPurchaseRulesArray();
  2498.         foreach ($basicPurchaseRulesArray as $basicPurchaseRule) {
  2499.             $entitiesadquiRedemRule $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["pointType" => $params['typePoint'], "license" => $params['license'], "parentDefinition" => $basicPurchaseRule]);
  2500.             foreach ($entitiesadquiRedemRule as $adquiRedemLocalRule) {
  2501.                 $adquiRedemLocalRule->setPtsRate($ptsRatePercentage);
  2502.                 $adquiRedemLocalRule->setMinimumPurchase($params['minimumPurchase']);
  2503.                 $em->persist($adquiRedemLocalRule);
  2504.                 $em->flush(); 
  2505.             }
  2506.         }
  2507.         $configLoyaltyOmt $this->createOrUpdateLoyaltyConfigurationOmt($em$params);
  2508.         return $this->updateLoyaltyConfig($request$params['license'], 2true); 
  2509.     }
  2510.     /**
  2511.      * Funcion secundaria de la configuración del delivery, para realizar determinadas acciones
  2512.      * @author Leandro Román Londoño - 03/03/2020
  2513.      */
  2514.     public function deliveryActionsConfiguration(Request $request$id){
  2515.         $params $request->request->getIterator()->getArrayCopy();
  2516.         $em $this->getDoctrine()->getManager();
  2517.         $response = new Response();
  2518.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->find($id);
  2519.         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData);
  2520.         if (isset($params['action'])) {
  2521.             /**
  2522.              * Si el params contiene un id, se refiere que va a modificar Ã³ eliminar
  2523.              */
  2524.             
  2525.             if (isset($params['id'])) {
  2526.                 $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->find($params['id']);
  2527.             }else{
  2528.                 $entity = new ConfRangedelivery();
  2529.             }
  2530.             if ($entity != '' || $entity != null) {
  2531.                 $entity $this->selectActionDelivery($entity$params$emLev);
  2532.                 $response->setStatusCode(200);
  2533.                 $responseArr['status'] = WebService::CODE_SUCCESS;
  2534.             }else{
  2535.                 $response->setStatusCode(400);
  2536.                 $responseArr['status'] = WebService::HTTP_CODE_BAD_REQUEST;
  2537.             }
  2538.             
  2539.             if ($entity != '') {
  2540.                 $emLev->persist($entity);
  2541.                 $emLev->flush();
  2542.             }
  2543.         }
  2544.         $responseArr['msg'] = 'Delivery update';
  2545.         $responseArr['bigbag'] = true;
  2546.         $responseArr['status'] = true;
  2547.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArr);
  2548.         $xxArray $theUrlTrSt->transform();
  2549.         $jsonContent json_encode($xxArray);
  2550.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  2551.     }
  2552.     /**
  2553.      * Funcion principal de la configuración del delivery, para cargar todas sus funciones
  2554.      * @author Leandro Román Londoño - 03/03/2020
  2555.      */
  2556.     public function deliveryConfiguration(Request $request$id){
  2557.         $em $this->getDoctrine()->getManager();
  2558.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->find($id);
  2559.         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData);
  2560.         $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->searchAllDates();
  2561.         $flag 0;
  2562.         $typeDelivery ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE_BY_DISTANCE;
  2563.         $statusSetting ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE;
  2564.         $typeChecked 0;
  2565.         
  2566.         /**
  2567.          * Se itera sobre el dato consultado para enviar a la vista lo que necesita
  2568.          */
  2569.         foreach ($entity as $key => $disable) {
  2570.             if ($disable['confTypeDelivery'] == ConfRangedelivery::CONF_TYPE_DELIVERY_PLAIN_RECHARGE) {
  2571.                 $disabled[] = $disable['confTypeDelivery'];
  2572.             }else if ($disable['confTypeNoRechargeDefined'] == ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE) {
  2573.                 $flag 1;
  2574.             }
  2575.             if($disable['confStatus'] == ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE){
  2576.                 $typeDelivery $disable['confTypeDelivery'];
  2577.                 $statusSetting $disable['confStatus'];
  2578.                 $typeChecked $disable['confTypeRange'];
  2579.             }
  2580.         }
  2581.         if (isset($disabled)) {
  2582.             $disabled count($disabled);
  2583.         }else{
  2584.             $disabled 0;
  2585.         }
  2586.         /**
  2587.          * Carga la vista principal de la configuración del delivery, con los parametros consultados
  2588.          */
  2589.         return $this->render('AccountLicense\deliveryConfiguration.html.twig', [
  2590.             'ide' => $id,
  2591.             'params' => $entity,
  2592.             'disabled' => $disabled,
  2593.             'noRecharge' => $flag,
  2594.             'settingActive' => [
  2595.                 'typeDelivery' => $typeDelivery,
  2596.                 'statusSetting' => $statusSetting,
  2597.                 'typeChecked' => $typeChecked
  2598.             ]
  2599.         ]);
  2600.     }
  2601.     /**
  2602.      * Funcion privada de la configuración del delivery
  2603.      * Mediante una accion, se podra editar, crear, eliminar y ademas de eso configurar el no recharge y la activacion
  2604.      * de una configuración
  2605.      * @author Leandro Román Londoño - 03/03/2020
  2606.      */
  2607.     private function selectActionDelivery($entity$params$emLev){
  2608.         switch ($params['action']) {
  2609.             
  2610.             case 'add':
  2611.                 $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2612.                 $emLev->persist($entity);
  2613.                 $emLev->flush();
  2614.                 Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$entityRegistActions::ACTION_INSERT);
  2615.                 $entity '';
  2616.                 break;
  2617.             case 'modify':
  2618.                 if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == 0) {
  2619.                     $entity->setConfRangeDelivery($params['distance']);
  2620.                     $entity->setConfDeliveryPrice($params['price']);
  2621.                 
  2622.                 }else if(isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == 1){
  2623.                     $entity->setConfFixedCostValue($params['price']);
  2624.                 }
  2625.                 
  2626.                 Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$entityRegistActions::ACTION_UPDATE);
  2627.                 break;
  2628.             case 'delete':
  2629.                 $emLev->remove($entity);
  2630.                 $emLev->flush();
  2631.                 Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$entityRegistActions::ACTION_DELETE);
  2632.                 $entity '';
  2633.                 break;
  2634.             case 'not_recharge':
  2635.                 $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
  2636.                 $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2637.                 
  2638.                 foreach ($entity as $key => $value) {
  2639.                     $emLev->persist($value);
  2640.                     $emLev->flush();
  2641.                     Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2642.                 }
  2643.                 $entity '';
  2644.                 break;
  2645.             case 'recharge':  
  2646.                 $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findBy(['confTypeNoRechargeDefined' => ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE]);
  2647.                 $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2648.                 foreach ($entity as $key => $value) {
  2649.                     $emLev->persist($value);
  2650.                     $emLev->flush();
  2651.                     Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2652.                 }
  2653.                 $entity '';
  2654.                 break;
  2655.             case 'distance_setting':
  2656.                 if (isset($params['type_recharge']) &&  $params['type_recharge'] == '0') {
  2657.                     $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
  2658.                     $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2659.                     foreach ($entity as $key => $value) {
  2660.                         $emLev->persist($value);
  2661.                         $emLev->flush();
  2662.                         Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2663.                     }
  2664.                 }
  2665.                 $entity '';
  2666.                 break;
  2667.             case 'plain_setting'
  2668.                 if (isset($params['type_recharge']) &&  $params['type_recharge'] == '1') {
  2669.                     $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
  2670.                     $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2671.                     foreach ($entity as $key => $value) {
  2672.                         $emLev->persist($value);
  2673.                         $emLev->flush();
  2674.                         Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2675.                     }
  2676.                 }
  2677.                 $entity '';
  2678.                 break;
  2679.             case 'plain_setting_exit':
  2680.             case 'distance_setting_exit':
  2681.                 if (isset($params['type_recharge']) &&  ($params['type_recharge'] == '0' || $params['type_recharge'] == '1')) {
  2682.                     $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
  2683.                     $entity $this->registerNewDeliveryRangeOrPlain($entity$params);
  2684.                     foreach ($entity as $key => $value) {
  2685.                         $emLev->persist($value);
  2686.                         $emLev->flush();
  2687.                         Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2688.                     }
  2689.                 }
  2690.                 $entity '';
  2691.                 break;  
  2692.             case 'status_type_distance':
  2693.                 $entity $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
  2694.                 
  2695.                 foreach ($entity as $key => $value) {
  2696.                     if ($value->getConfTypeRange() == (int) $params['rechargeByDistance']) {
  2697.                         $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
  2698.                     }else{
  2699.                         $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2700.                     }
  2701.                     $emLev->persist($value);
  2702.                     $emLev->flush();
  2703.                     Util::saveUpdateRecordInRegistActions($emLev'conf_rangedelivery'$valueRegistActions::ACTION_UPDATE);
  2704.                 }
  2705.                 $entity '';
  2706.                 break;
  2707.         }
  2708.         return $entity;
  2709.     }
  2710.     /**
  2711.      * Funcion privada de las acciones de la configuracion del delivery
  2712.      * Dependiendo de sus parametros, se define que va a modificar o crear
  2713.      * @author Leandro Román Londoño - 03/03/2020
  2714.      */
  2715.     private function registerNewDeliveryRangeOrPlain($entity$params){
  2716.         /**
  2717.          * Espera el parametro en "0", (string), para crear el delivery por distancia
  2718.          */
  2719.         
  2720.         if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == "0") {
  2721.             $entity->setConfTypeDelivery(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE_BY_DISTANCE);
  2722.             $entity->setConfRangemax(ConfRangedelivery::CONF_DEFAULT_RANGE_MAX);
  2723.             $entity->setConfRangecharge(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2724.             $entity->setConfTypeRange((int) $params['rechargeByDistance']);
  2725.             
  2726.             if (isset($params['categoryRechage']) && $params['categoryRechage'] != '') {
  2727.                 $entity->setConfRangeDelivery((int) $params['categoryRechage']);
  2728.             }else{
  2729.                 $entity->setConfRangeDelivery(ConfRangedelivery::CONF_TYPE_NOT_RECHARGE);
  2730.             }
  2731.             if (isset($params['valueTotal']) && $params['valueTotal'] != '') {
  2732.                 $entity->setConfDeliveryPrice((int) $params['valueTotal']);
  2733.             }else{
  2734.                 $entity->setConfDeliveryPrice(ConfRangedelivery::CONF_TYPE_NOT_RECHARGE);
  2735.             }
  2736.             
  2737.             $entity->setConfFlatFee(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2738.             $entity->setConfFixedCostValue(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2739.             $entity->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
  2740.             $entity->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2741.         }
  2742.         
  2743.         /**
  2744.          * Espera el parametro en "1", (string), para crear el delivery por plain
  2745.          */
  2746.         if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == "1") {
  2747.             $entity->setConfTypeDelivery(ConfRangedelivery::CONF_TYPE_DELIVERY_PLAIN_RECHARGE);
  2748.             $entity->setConfRangemax(ConfRangedelivery::CONF_DEFAULT_RANGE_MAX);
  2749.             $entity->setConfRangecharge(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2750.             $entity->setConfTypeRange(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2751.             $entity->setConfRangeDelivery(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2752.             $entity->setConfDeliveryPrice(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2753.             $entity->setConfFlatFee((int) $params['rechargeByPlain']);
  2754.             if(isset($params['valueTotalPlain']) && $params['valueTotalPlain'] != ''){
  2755.                 $entity->setConfFixedCostValue((int) $params['valueTotalPlain']);
  2756.             }else{
  2757.                 $entity->setConfFixedCostValue(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
  2758.             }
  2759.             $entity->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
  2760.             $entity->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2761.         }
  2762.         
  2763.         /**
  2764.          * Espera el parametro en "not_recharge", (string), para modificar y establecer que no va a cobrar por domicilios
  2765.          */
  2766.         if (isset($params['action']) && $params['action'] == 'not_recharge') {
  2767.             foreach ($entity as $key => $value) {
  2768.                 $value->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE); 
  2769.                 $entity[$key] = $value;
  2770.             }
  2771.         }
  2772.         /**
  2773.          * Espera el parametro en "recharge", (string), para modificar y establecer que va a cobrar por domicilios
  2774.          */
  2775.         
  2776.         if (isset($params['action']) && $params['action'] == 'recharge') {
  2777.             if (!empty($entity)) {
  2778.                 foreach ($entity as $key => $value) {
  2779.                     $value->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
  2780.                     $entity[$key] = $value;
  2781.                 }
  2782.             }
  2783.         }
  2784.         
  2785.         /**
  2786.          * Espera el parametro en "distance_setting", (string), para modificar y establecer que solo activa la configuración
  2787.          * domicilio por distancia
  2788.          */
  2789.         if (isset($params['action']) && $params['action'] == 'distance_setting') {
  2790.             foreach ($entity as $key => $value) {
  2791.                 $confTypeDelivery $value->getConfTypeDelivery() || 0;
  2792.                 if ((int)$confTypeDelivery == (int) $params['type_recharge'] && $value->getConfTypeRange() == (int) $params['rechargeByDistance']) {
  2793.                     $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2794.                 }else{
  2795.                     $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
  2796.                 }
  2797.                 $entity[$key] = $value;
  2798.             }
  2799.         }
  2800.         /**
  2801.          * Espera el parametro en "plain_setting", (string), para modificar y establecer que solo activa la configuración
  2802.          * domicilio por precio fijo
  2803.          */
  2804.         if (isset($params['action']) && $params['action'] == 'plain_setting') {
  2805.             foreach ($entity as $key => $value) {
  2806.                 if ($value->getConfTypeDelivery() == (int) $params['type_recharge']) {
  2807.                     $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
  2808.                 }else{
  2809.                     $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2810.                 }
  2811.                 $entity[$key] = $value;
  2812.             }
  2813.         }
  2814.         /**
  2815.          * Espera el parametro "distance_setting_exit" o "plain_setting_exit", (string) para establecer que no quiere
  2816.          * ninguna configuración
  2817.          */
  2818.         if (isset($params['action']) && ($params['action'] == 'distance_setting_exit' || $params['action'] == 'plain_setting_exit')) {
  2819.             foreach ($entity as $key => $value) {
  2820.                 $value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
  2821.                 $entity[$key] = $value;
  2822.             }
  2823.         }
  2824.         
  2825.         return $entity;
  2826.     }
  2827.     /**
  2828.      * 
  2829.      */
  2830.     public function updateRestaurantLoyaltyConfig(Request $request) {
  2831.         $data $request->request->getIterator()->getArrayCopy();
  2832.         $em $this->getDoctrine()->getManager();
  2833.         $params $data['restaurant_loyalty_config'];
  2834.         $localRatio 0;
  2835.         $globalRatio 0;
  2836.         $path Util::getValidActiveLogByBaseName($this->realContainer'updateRestaurantLoyaltyConfig''updateRestaurantLoyaltyConfig0.txt');
  2837.         $this->createFileJson($path"\r" 'updateRestaurantLoyaltyConfig fever XD ' $request->getContent() . "\r");
  2838.         $entities $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->find($params['id']);
  2839.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->find($params['license']);
  2840.         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData);
  2841.         $accountConfig $emLev->getRepository('App\Structure\Configuracion')->findAll();
  2842.         if (isset($params['typePoint']) && $params['typePoint'] == 'local') {
  2843.             $entities->setUseLocalPoints(true);
  2844.             $entities->setUseGlobalPoints(false);
  2845.             $accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_LOCAL); 
  2846.             $entities->setMinimumPointAmountToExchange($params['minimumPointAmountToExchange']);
  2847.         } elseif (isset($params['typePoint']) && $params['typePoint'] == 'global') {
  2848.             $entities->setUseLocalPoints(false);
  2849.             $entities->setUseGlobalPoints(true);
  2850.             $accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_GLOBAL);
  2851.             $entities->setMinimumPointAmountToExchange((int) $this->realContainer->getParameter('minimum_usage_of_global_points'));
  2852.         } else {
  2853.             $entities->setUseLocalPoints(false);
  2854.             $entities->setUseGlobalPoints(false);
  2855.             $accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_NONE);
  2856.         }
  2857.         if (isset($params['earnPointsInPurchaseWithPoints'])) {
  2858.             $entities->setEarnPointsInPurchaseWithPoints(true);
  2859.         } else {
  2860.             $entities->setEarnPointsInPurchaseWithPoints(false);
  2861.         }
  2862.         $em->persist($entities);
  2863.         $em->flush();
  2864.         $accountConfig[0]->setConfLoyaltyMinAmountToExchange($params['minimumPointAmountToExchange']);
  2865.         if (isset($params['earnPointsInPurchaseWithPoints'])) {
  2866.             $accountConfig[0]->setEarnPointsInPurchaseWithPoints(true);
  2867.         } else {
  2868.             $accountConfig[0]->setEarnPointsInPurchaseWithPoints(false);
  2869.         }
  2870.         $dashboardLoyaltyButton $emLev->getRepository('App\Structure\Dashboard')->find(14);
  2871.         if (!$dashboardLoyaltyButton) {
  2872.             $dashboardLoyaltyRecord = new Dashboard();
  2873.             $dashboardLoyaltyRecord->setId(14);
  2874.             $dashboardLoyaltyRecord->setDasTabToGo('openSearchLoyaltyCustomer');
  2875.             $dashboardLoyaltyRecord->setDasIcon('icon-pay-points');
  2876.             $dashboardLoyaltyRecord->setDasOrderType(14);
  2877.             $dashboardLoyaltyRecord->setDasName('GENERAL.LOYALTY');
  2878.             $dashboardLoyaltyRecord->setDasStatus(1);
  2879.             $dashboardLoyaltyRecord->setDasSorting(14);
  2880.             $emLev->persist($dashboardLoyaltyRecord);
  2881.             $emLev->flush();
  2882.             Util::saveUpdateRecordInRegistActions($emLev'dashboard'$dashboardLoyaltyRecordRegistActions::ACTION_INSERT);
  2883.         } else {
  2884.             $dashboardLoyaltyButton->setDasStatus(1);
  2885.             $emLev->persist($dashboardLoyaltyButton);
  2886.             $emLev->flush();
  2887.             Util::saveUpdateRecordInRegistActions($emLev'dashboard'$dashboardLoyaltyButtonRegistActions::ACTION_UPDATE);
  2888.         }
  2889.         $emLev->persist($accountConfig[0]);
  2890.         $emLev->flush();
  2891.         Util::saveUpdateRecordInRegistActions($emLev'configuracion'$accountConfig[0], RegistActions::ACTION_UPDATE);
  2892.         $points $em->getRepository('App\Entity\TypePoint')->findAll();
  2893.         foreach ($points as $typePoint) {
  2894.             if ($typePoint->getType() == TypePoint::TYPE_LOCAL) {
  2895.                 $localRatio $typePoint->getCashRatio();
  2896.                 continue;
  2897.             }
  2898.             if ($typePoint->getType() == TypePoint::WORK_AS_GLOBAl) {
  2899.                 $globalRatio $typePoint->getCashRatio();
  2900.             }
  2901.         }
  2902.         $form $this->createForm(RestaurantLoyaltyConfig::class, $entities, [
  2903.             'action' => $this->generateUrl('update_loyalty_config'),
  2904.             'method' => 'POST'
  2905.         ]);
  2906.         return $this->render('AccountLicense\restaurantLoyaltyConfig.html.twig', [
  2907.                     'entities' => $entities,
  2908.                     'toClose' => true,
  2909.                     'form' => $form->createView(),
  2910.                     'localRatio' => $localRatio,
  2911.                     'globalRatio' => $globalRatio
  2912.         ]);
  2913.     }
  2914.     /**
  2915.      * Función replica de updateRestaurantLoyaltyConfig pero adaptada al nuevo flujo de guardado de loyalty para sincronización en Android
  2916.      * @param EntityManager     $em
  2917.      * @param Entity            $License Entidad de AccountLicense
  2918.      * @param Array             $params Parametros de entrada['loyalty', 'minimumPointAmountToExchange']
  2919.      * @return Boolean          True o false
  2920.      */
  2921.     public function saveSyncLoyalty($em$license$params){
  2922.         try{ 
  2923.             // Se crean los logs 
  2924.             $path Util::getValidActiveLogByBaseName($this->realContainer'updateRestaurantLoyaltyConfig''updateRestaurantLoyaltyConfig0.txt');
  2925.             $this->createFileJson($path"\r" 'saveSyncLoyalty ' json_encode($params). "\r");
  2926.             
  2927.             //  Se conecta con la base de datos de level web
  2928.             $emLev Util::emLicenseConnection($this->realContainer$em$license);
  2929.             $accountConfig $emLev->getRepository('App\Structure\Configuracion')->findAll();
  2930.             
  2931.             // Util::saveUpdateRecordInRegistActions($emLev, 'licensor1', $license, RegistActions::ACTION_UPDATE);
  2932.             
  2933.             // Se valida que se active la función de loyalty, ya que para este caso solo se tiene en cuenta loyalty cash de forma local se activara esta opción.
  2934.             if (isset($params['loyalty']) && $params['loyalty'] == 1) {           
  2935.                 $accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_LOCAL); 
  2936.             
  2937.                 $this->createFileJson($path"\r" 'Set value type loyalty local '."\r" );
  2938.             } else {
  2939.                 $accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_NONE);
  2940.                 $this->createFileJson($path"\r" 'Set value type loyalty off '."\r" );
  2941.             }
  2942.             // Se ingresa el valor minimo de cash loyalty en level web
  2943.             $accountConfig[0]->setConfLoyaltyMinAmountToExchange($params['minimumPointAmountToExchange']);
  2944.             //  Se ingresan los datos de configuración en la tabla de dashboard para level web 
  2945.             $dashboardLoyaltyButton $emLev->getRepository('App\Structure\Dashboard')->find(14);
  2946.             if (!$dashboardLoyaltyButton) {
  2947.                 $this->createFileJson($path"\r" 'Save config in table Dashboard from levelweb'."\r" );
  2948.                 $dashboardLoyaltyRecord = new Dashboard();
  2949.                 $dashboardLoyaltyRecord->setId(14);
  2950.                 $dashboardLoyaltyRecord->setDasTabToGo('openSearchLoyaltyCustomer');
  2951.                 $dashboardLoyaltyRecord->setDasIcon('icon-pay-points');
  2952.                 $dashboardLoyaltyRecord->setDasOrderType(14);
  2953.                 $dashboardLoyaltyRecord->setDasName('GENERAL.LOYALTY');
  2954.                 $dashboardLoyaltyRecord->setDasStatus(1);
  2955.                 $dashboardLoyaltyRecord->setDasSorting(14);
  2956.                 $emLev->persist($dashboardLoyaltyRecord);
  2957.                 $emLev->flush();
  2958.                 // se guardan los datos en regisAction para ser sincronizados
  2959.                 Util::saveUpdateRecordInRegistActions($emLev'dashboard'$dashboardLoyaltyRecordRegistActions::ACTION_INSERT);
  2960.                 
  2961.                 $this->createFileJson($path"\r" 'regisAction Dashboard from levelweb'."\r" );
  2962.             } else {
  2963.                 $dashboardLoyaltyButton->setDasStatus(1);
  2964.                 $emLev->persist($dashboardLoyaltyButton);
  2965.                 $emLev->flush();
  2966.                 // se guardan los datos en regisAction para ser sincronizados
  2967.                 Util::saveUpdateRecordInRegistActions($emLev'dashboard'$dashboardLoyaltyButtonRegistActions::ACTION_UPDATE);
  2968.                 $this->createFileJson($path"\r" 'regisAction Dashboard from levelweb if register dasboard exist'."\r" );
  2969.             }
  2970.             $emLev->persist($accountConfig[0]);
  2971.             $emLev->flush();
  2972.             
  2973.             // se guardan los datos en regisAction para ser sincronizados
  2974.             Util::saveUpdateRecordInRegistActions($emLev'configuracion'$accountConfig[0], RegistActions::ACTION_UPDATE);
  2975.             
  2976.             $this->createFileJson($path"\r" 'regisAction configuracion from levelweb'."\r" );
  2977.             return true;
  2978.         }catch (\Throwable $th) {
  2979.             $err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
  2980.             $this->createFileJson($path"\r" 'Alert Error => 'json_encode($err) ."\r" );
  2981.             return $this->errorInternalError($err);
  2982.         }
  2983.     }
  2984.     /**
  2985.      * Web Service que recibe el nickname del restaurante, el ID del cliente, el teléfono y/o el email 
  2986.      * y responde con la cuenta de los puntos del cliente que tenga registrados en el restaurante 
  2987.      * y se le agrega el token Ãºnico de transacción para ser verificado en una compra futura.
  2988.      * @author Jhonan Vargas <jsmith@openmytab.com> 11/05/2023
  2989.      * @param Request $request
  2990.      * @return type
  2991.      */
  2992.     public function generateLoyaltyTransactionToken(Request $request){
  2993.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
  2994.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  2995.         }
  2996.         $arrayEncryptResult Util::decryptDataForAndroid($this->realContainer$request->getContent());
  2997.         $data json_decode($arrayEncryptResult['data'], true);
  2998.         $path Util::getValidActiveLogByBaseName($this->realContainer'generateLoyaltyTransactionToken''generateLoyaltyTransactionToken0.txt');
  2999.         $this->createFileJson($path"\r" 'parameters sent: ' $arrayEncryptResult['data'] . "\r");
  3000.         $existPhone = isset($data["phone"]);
  3001.         $existEmail = isset($data["email"]);
  3002.         if(!isset($data["nickname"]) || !isset($data["clientId"]) || (!$existPhone && !$existEmail)){
  3003.             $this->createFileJson($path"\r" 'Wrong Arguments!'"\r");
  3004.             return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  3005.         }
  3006.         $search = [];
  3007.         $isEmpty false;
  3008.         // se verifica que el teléfono o el email no estén vacíos
  3009.         if($existPhone){
  3010.             if($data["phone"] !== ''){
  3011.                 $search["phone"] = $data["phone"];
  3012.             }else{
  3013.                 $isEmpty true;
  3014.             }
  3015.         }
  3016.         if($existEmail){
  3017.             if($data["email"] !== ''){
  3018.                 $search["email"] = $data["email"];
  3019.             }else{
  3020.                 $isEmpty true;
  3021.             }
  3022.         }
  3023.         // se valida que los parámetros no estén vacíos
  3024.         if(empty($data["nickname"]) || empty($data["clientId"]) || $isEmpty){
  3025.             $this->createFileJson($path"\r" 'Some Fields Are Empty!'"\r");
  3026.             return $this->errorWrongArgs('Wrong Arguments!'WebService::CODE_WRONG_ARGUMENTS);
  3027.         }
  3028.         $em $this->getDoctrine()->getManager();
  3029.         
  3030.         // se valida si existe la licencia
  3031.         $nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
  3032.         $accountLicData $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
  3033.         if (empty($accountLicData)) {
  3034.             $this->createFileJson($path"\r" 'Invalid nickname!'"\r");
  3035.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3036.         }
  3037.         if(is_null($accountLicData[0]->getLoginType()) || $accountLicData[0]->getLoginType() == AccountLicense::LOGGED_OUT){
  3038.             $this->createFileJson($path"\r" 'License not logged!'"\r");
  3039.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('License not logged'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3040.         }
  3041.         // se valida que se tenga una versión de Android registrada en la licencia
  3042.         if (($accountLicData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_ANDROID || $accountLicData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID) && !is_null($accountLicData[0]->getAndroidVersionName())) {
  3043.             $this->createFileJson($path"\r" 'Android logged in license !'"\r");
  3044.             // se valida que la versión de Android de la licencia sea mayor o igual a la versión segura de Android la cual ya tiene la verificación por token para las transacciones de loyalty
  3045.             if (!NewUtil::isGreaterThanOrEqualToThisVersion($accountLicData[0]->getAndroidVersionName(), $this->realContainer->getParameter('secure_android_version'), $path)){
  3046.                 $this->createFileJson($path"\r" 'Android version is not secure!'"\r");
  3047.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Android version is not secure'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3048.             }
  3049.         } else {
  3050.             $this->createFileJson($path"\r" 'Level Lite logged in license !'"\r");
  3051.         }
  3052.         $search['restaurant'] = $accountLicData[0]->getId();
  3053.         $search["client"] = $data["clientId"];
  3054.         
  3055.         // Se busca el cliente con los parámetros de ingresados
  3056.         $client $em->getRepository('App\Entity\OmtClient')->findOmtClientByFilterSearchParameters($search);
  3057.         if(is_null($client)){
  3058.             $this->createFileJson($path"\r" 'Client does not exist!'"\r");
  3059.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Client does not exist'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3060.         }
  3061.         // se realiza la consulta de los puntos junto con el token correspondiente
  3062.         $transactionToken['tokens'] = $em->getRepository('App\Entity\TypePointAcount')->generateLoyaltyTransactionTokenByClient($search$path);
  3063.         
  3064.         $transactionToken['licenseId'] = $accountLicData[0]->getId();
  3065.         $transactionToken['msg'] = "Transaction Verification Token ";
  3066.         $transactionToken['status'] = WebService::CODE_SUCCESS;
  3067.         $transactionToken['bigbag'] = true;
  3068.         $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$transactionToken);
  3069.         $xxArray $theUrlTrSt->transform();
  3070.         $jsonContent json_encode($xxArray);
  3071.         return $this->respondWithItem($jsonContent$theUrlTrSt);
  3072.     }
  3073.     public function getLoyaltyAmount(Request $request): JsonResponse {
  3074.         $container $this->realContainer;
  3075.         $em $this->getDoctrine()->getManager();
  3076.         $search $request->query->all();
  3077.         $statusCode 200;
  3078.         $data = [
  3079.             'status' => 'success',
  3080.             'message' => 'amount by license',
  3081.         ]; 
  3082.         if (isset($search['restaurant'])) {
  3083.             $typePointAcount $em->getRepository('App\Entity\TypePointAcount');
  3084.             $amount $typePointAcount->getLoyaltyAmount($search);
  3085.     
  3086.             $data['amount'] = $amount;
  3087.         }else{
  3088.             $data['status'] = "error";
  3089.             $data['message'] = "restaurant not found";
  3090.             $data['statusCode'] = $statusCode;
  3091.             $statusCode 500;
  3092.         }
  3093.         return new JsonResponse($data$statusCode);
  3094.     }
  3095.     /**
  3096.      * Consular puntos loyalty que se encuentran en licensor
  3097.      * Se debe ingresar minimo un parametro relacionado con el cliente de los siguientes
  3098.      * @param Request $request
  3099.      * @param String $phone - numero de telefono con el que esta registrado el cliente
  3100.      * @param String $email - email con el que esta registrado el cliente
  3101.      * @param String $client - id del cliente para omt
  3102.      * @param String $restaurant - id del restaurante
  3103.      * @param String $omt - true / false dependiende desde donde se realice la patición
  3104.      * @return Json  responde con algunos datos del cliente y los puntos locales por restaurante
  3105.      */
  3106.     public function getGenericPointLoyalty(Request $request) {
  3107.         
  3108.         // Se verifica que ingrese con el mehod gett
  3109.         if ($request->getMethod() != WebService::REQUEST_METHOD_GET) {
  3110.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_GET " method");
  3111.         }
  3112.             
  3113.         // Creamos el log
  3114.         $path Util::getValidActiveLogByBaseName($this->realContainer'getGenericPointLoyalty''getGenericPointLoyalty0.txt');
  3115.         $this->createFileJson($path"\r" '**-----------------------------------------------------------------------------**' "\r");
  3116.         $this->createFileJson($path"\r" 'getGenericPointLoyalty init: ' $request->getContent() . "\r");
  3117.         $this->createFileJson($path"\r" 'query params: ' json_encode($request->query->all()) . "\r");
  3118.         $search = [];
  3119.         $indexSearch = [];
  3120.         $order = [];
  3121.         $indexOrder = ['order_by_last_visit''order_by_member_since''order_by_cash'];
  3122.         $paginator $this->get('simple_paginator');
  3123.         $pageRanges = [102550];
  3124.         $paginator->setPageRanges($pageRanges);
  3125.         (!is_null($request->query->get('itemsPerPage')) && $request->query->get('itemsPerPage') != '') ? $itemsPerPage = (int) $request->query->get('itemsPerPage') : $itemsPerPage $pageRanges[0];
  3126.         $paginator->setItemsPerPage($itemsPerPage);
  3127.         $paginator->setMaxPagerItems(10);
  3128.         
  3129.         try {
  3130.             // Se inicia el entiti manager
  3131.             $container $this->realContainer;
  3132.             $em $this->getDoctrine()->getManager();
  3133.             $search $request->query->all();
  3134.         
  3135.             if (isset( $search['phone']) &&  $search['phone'] != '' ) {
  3136.                 $search['phone'] = Utilx::clearEspecialCharactersFromPhone($search['phone']);
  3137.             }
  3138.             $debug = (isset($search['debug']) && !is_null($search['debug'])) ? (boolean) $search['debug'] : false;
  3139.             $omtRequest = (isset($search['omt']) && !is_null($search['omt'])) ? $search['omt'] : null;
  3140.             $search array_filter($search, function ($value) {
  3141.                 return !is_null($value);
  3142.             });
  3143.             
  3144.             if ($debug) {
  3145.                 dump($search);
  3146.                 $this->createFileJson($path"\r" 'Parameter debug '"\r Parametros de entrada" json_encode($search) .  "\r");
  3147.             }
  3148.             // Se validan los parmetros de llegada
  3149.             if (empty($search) ) {
  3150.                 $this->createFileJson($path"\r" 'Invalid parameters name' "\r");
  3151.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3152.                                 ->respondWithError('Invalid parameters name'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3153.             }
  3154.             if (!isset($search['restaurant'])) {
  3155.                 $client $em->getRepository('App\Entity\OmtClient')->findOmtClientByFilterSearchParametersBasicData($search$debug);
  3156.                 if ($debug) {
  3157.                     dump("respuesta cliente"$client, isset($client) && !empty($client));
  3158.                     $this->createFileJson($path"\r" 'Parameter debug '"\r Parametros de entrada" json_encode($client) .  "\r");
  3159.                 }
  3160.                 if (isset($client) && !empty($client)) {
  3161.                     
  3162.                     $this->createFileJson($path"\r" 'Client exist' .json_encode($client). "\r");
  3163.                     $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  3164.                     //  se comenta mientras tanto porque aun no se ha implementado los puntos globales
  3165.                     // // [ client, phone, email ]       
  3166.                     // $pointAccountByClientGlobal = $pointAccountByClientRepository->getPointLoyaltyClientGlobal($search,$omtRequest);
  3167.                     // if(!is_null($pointAccountByClientGlobal)){
  3168.                     //     $responseArrWithPagination['points']['global'] = $pointAccountByClientGlobal;
  3169.                     // }
  3170.                     // [ restaurant ]
  3171.                     $pointAccountByClientRestaurantResult $pointAccountByClientRepository->getPointLoyaltyClientXRestaurant($search$omtRequest);
  3172.                     $pointAccountByClientRestaurant $pointAccountByClientRestaurantResult['pointAccountByClientRestaurant'];
  3173.                     $clientsIdInArray $pointAccountByClientRestaurantResult['clientsIdInArray'];
  3174.                     if ($debug) {
  3175.                         dump("Return consulata de puntos ",$pointAccountByClientRestaurant);
  3176.                     }
  3177.                     if (!is_null($pointAccountByClientRestaurant) && !empty($pointAccountByClientRestaurant)) {
  3178.                         $responseArrWithPagination['points']['local'] = $pointAccountByClientRestaurant;
  3179.                         $this->createFileJson($path"\r" 'points local'json_encode($pointAccountByClientRestaurant) ."\r");
  3180.                         $msg "Client ok";
  3181.                     } else {
  3182.                         $this->createFileJson($path"\r" 'Not points local'."\r");
  3183.                         $msg "Client has no loyalty cash";
  3184.                     }
  3185.                     // redondeo del point2cash
  3186.                     $responseArrWithPagination['clients'] = $client;
  3187.                     $responseArrWithPagination['generalInfo'] = $em->getRepository('App\Entity\TypePoint')->getRatioPoints();
  3188.                 }
  3189.             } else if (isset($search['restaurant'])) {
  3190.                 
  3191.                 $order Paginator::filterParameters($indexOrder$requestPaginator::REQUEST_TYPE_REQUESTtrue);
  3192.                 $pointAccountByClientRepository $em->getRepository('App\Entity\TypePointAcount');
  3193.                 $search['with_portal_client'] = 1;
  3194.                 $pointAccountByClientRestaurantResult $pointAccountByClientRepository->getPointLoyaltyClientXRestaurant($search$omtRequesttrue$debug$order);
  3195.                 $pointAccountByClientRestaurant $pointAccountByClientRestaurantResult['pointAccountByClientRestaurant'];
  3196.                 $clientsIdInArray $pointAccountByClientRestaurantResult['clientsIdInArray'];
  3197.                 if (!is_null($pointAccountByClientRestaurant) && !empty($pointAccountByClientRestaurant)) {
  3198.                     $emLev WsUtilx::emLicenseIDConnection($container$em$search['restaurant']);
  3199.                     foreach ($pointAccountByClientRestaurant as $key => $value) {
  3200.                         $pointAccountByClientRestaurant[$key]['orders'] = [];
  3201.                         $pointAccountByClientRestaurant[$key]['isOmt'] = false;
  3202.                         $clientExtraInfo $emLev->getRepository('App\Structure\Cliente')->findOneBy(array(
  3203.                             "loyaltyId" => $value['typeCountId']
  3204.                         ));
  3205.                         // if (strpos($pointAccountByClientRestaurant[$key]['clientEmail'], '@test.com') !== false) {
  3206.                         //     $pointAccountByClientRestaurant[$key]['clientEmail'] = "";
  3207.                         // }
  3208.                         $clientOrders $emLev->getRepository('App\Structure\LoyaltyHistory')->findBy(array(
  3209.                             "phone" => $value['clientPhone']
  3210.                         ), ['date' => 'DESC']);
  3211.                         
  3212.                         // $dateOfLastVisit = $emLev->getRepository('App\Structure\LoyaltyHistory')->findOneBy(array(
  3213.                         //     "phone" => $value['clientPhone']
  3214.                         // ), array( 'date' => $orderLastVisit));
  3215.                         $dateOfLastVisit $emLev->getRepository('App\Structure\LoyaltyHistory')->findOneBy(["phone" => $value['clientPhone']]);
  3216.                         if ($pointAccountByClientRestaurant[$key]['clientBirthdate'] instanceof \DateTime) {
  3217.                             $pointAccountByClientRestaurant[$key]['clientBirthdate'] = $pointAccountByClientRestaurant[$key]['clientBirthdate']->format('m/d/Y');
  3218.                         }
  3219.                         if (!is_null($dateOfLastVisit)) {
  3220.                             if ($dateOfLastVisit->getDate() instanceof \DateTime
  3221.                                 $pointAccountByClientRestaurant[$key]['dateOfLastVisit'] = $dateOfLastVisit->getDate()->format('m/d/Y H:i');
  3222.                         } else if($pointAccountByClientRestaurant[$key]['createAccount'] instanceof \DateTime
  3223.                             $pointAccountByClientRestaurant[$key]['dateOfLastVisit'] = $pointAccountByClientRestaurant[$key]['createAccount']->format('m/d/Y H:i');
  3224.                         
  3225.                         if ($pointAccountByClientRestaurant[$key]['createdAt'] instanceof \DateTime) {
  3226.                             $pointAccountByClientRestaurant[$key]['createdAt'] = $pointAccountByClientRestaurant[$key]['createdAt']->format('m/d/Y');
  3227.                         }
  3228.                         if ($pointAccountByClientRestaurant[$key]['createAccount'] instanceof \DateTime) {
  3229.                             $pointAccountByClientRestaurant[$key]['createAccount'] = $pointAccountByClientRestaurant[$key]['createAccount']->format('m/d/Y');
  3230.                         }
  3231.                         if ($pointAccountByClientRestaurant[$key]['startingDate'] instanceof \DateTime) {
  3232.                             $pointAccountByClientRestaurant[$key]['startingDate'] = $pointAccountByClientRestaurant[$key]['startingDate']->format('m/d/Y');
  3233.                         }
  3234.                         if (isset($clientExtraInfo)) {
  3235.                             if ($clientExtraInfo->getCliCreacion() instanceof \DateTime) {
  3236.                                 $pointAccountByClientRestaurant[$key]['cliCreacion'] = $clientExtraInfo->getCliCreacion()->format('m/d/Y');
  3237.                             }
  3238.                             $pointAccountByClientRestaurant[$key]['cliCodigo'] = $clientExtraInfo->getId();
  3239.                         } else {
  3240.                             $pointAccountByClientRestaurant[$key]['isOmt'] = true;
  3241.                         }
  3242.                         if (isset($clientOrders)) {
  3243.                             $cashRedeemed 0;
  3244.                             $cashEarned 0;
  3245.                             foreach ($clientOrders as $key_o => $value_o) {
  3246.                                 $indiviauls number_format((float)$value_o->getPointsRedeemed() - $value_o->getPointsEarned(), 2'.'',');
  3247.                                 $getInvoice $emLev->getRepository('App\Structure\FacturaVentas')->findOneBy([ 'mpCodigo' => $value_o->getOrder() ]);
  3248.                                 $getOrder $emLev->getRepository('App\Structure\Mesapedido')->findOneBy([ 'id' => $value_o->getOrder() ]);
  3249.                                 // Obtenemos los datos de order & invoice
  3250.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderId'] = $value_o->getOrder();
  3251.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['odeTotal'] = $getOrder != null $getOrder->getMpValortotal() : null;
  3252.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['customer'] = $getOrder != null $getOrder->getMpCodcliente() : null;
  3253.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['status'] = $getOrder != null $getOrder->getMpEstado() : null;
  3254.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['invoiceId'] = $getInvoice != null $getInvoice->getId() : [];
  3255.                                 if ($value_o->getPointsRedeemed() != null) {
  3256.                                     $cashRedeemed = (float)$cashRedeemed + (float)$value_o->getPointsRedeemed(); 
  3257.                                     $pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderCashRedeemed'] = number_format((float) $value_o->getPointsRedeemed(), 2'.'',');
  3258.                                 }
  3259.                                 
  3260.                                 if ($value_o->getPointsEarned() != null) {
  3261.                                     $cashEarned = (float)$cashEarned + (float)$value_o->getPointsEarned(); 
  3262.                                     $pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderCashEarned'] = number_format((float) $value_o->getPointsEarned(), 2'.'',');
  3263.                                 }
  3264.                                 $pointAccountByClientRestaurant[$key]['orders'][$key_o]['individualOrders'] = $indiviauls;
  3265.                                 if ($value_o->getDate() instanceof \DateTime) {
  3266.                                     $pointAccountByClientRestaurant[$key]['orders'][$key_o]['cliCreacion'] = $value_o->getDate()->format('m/d/Y');
  3267.                                 }
  3268.                                 if ($value_o->getSaleAmount()) {
  3269.                                     $pointAccountByClientRestaurant[$key]['orders'][$key_o]['mpValortotal'] = number_format((float)$value_o->getSaleAmount(), 2'.'',');
  3270.                                 }
  3271.                             }
  3272.                             $pointAccountByClientRestaurant[$key]['cashEarned'] = number_format($cashEarned2'.'',');
  3273.                             $pointAccountByClientRestaurant[$key]['cashRedeemed'] = number_format(abs($cashRedeemed), 2'.'',');
  3274.                         
  3275.                         }
  3276.                     }
  3277.                     $orderLastVisit null;
  3278.                     if (isset($order['order_by_last_visit']))
  3279.                         $orderLastVisit $order['order_by_last_visit'] % "DESC" "ASC";
  3280.                     if(!is_null($orderLastVisit)){
  3281.                         usort($pointAccountByClientRestaurant, function ($a$b) use ($orderLastVisit) {
  3282.                             $dateA strtotime($a['dateOfLastVisit']);
  3283.                             $dateB strtotime($b['dateOfLastVisit']);
  3284.                             
  3285.                             if ($orderLastVisit === 'ASC'
  3286.                                 return $dateA <=> $dateB;
  3287.                             else 
  3288.                                 return $dateB <=> $dateA;
  3289.                         });
  3290.                     }
  3291.                     // usort($pointAccountByClientRestaurant, function ($a, $b) {
  3292.                     //     return strtotime($b['createAccount']) <=> strtotime($a['createAccount']);
  3293.                     // });
  3294.                     
  3295.                     $ClientPaginator $paginator->paginate($pointAccountByClientRestaurant)->getResult();
  3296.                     $params Paginator::getUrlFromParameters($indexSearch$search);
  3297.                     $orderBy Paginator::getUrlOrderFromParameters($indexOrder$order$container);
  3298.                     $responseArrWithPagination['search'] = $search;
  3299.                     $responseArrWithPagination['orderBy'] = $orderBy;
  3300.                     $responseArrWithPagination['params'] = $params;
  3301.                     $finalPaginator = [];
  3302.                     $finalPaginator['currentPage'] = $paginator->getCurrentPage();
  3303.                     $finalPaginator['itemsPerPage'] = $paginator->getItemsPerPage();
  3304.                     $finalPaginator['maxPagerItems'] = $paginator->getMaxPagerItems();
  3305.                     $finalPaginator['totalItems'] = $paginator->getTotalItems();
  3306.                     $finalPaginator['pageRanges'] = $paginator->getPageRanges();
  3307.                     $finalPaginator['previousPage'] = $paginator->getPreviousPage();
  3308.                     $finalPaginator['minPageInRange'] = $paginator->getMinPageInRange();
  3309.                     $finalPaginator['maxPageInRange'] = $paginator->getMaxPageInRange();
  3310.                     $finalPaginator['lastPage'] = $paginator->getLastPage();
  3311.                     $finalPaginator['nextPage'] = $paginator->getNextPage();
  3312.                     $finalPaginator['firstPage'] = $paginator->getFirstPage();
  3313.                     $finalPaginator['RequestStack'] = json_encode($paginator->RequestStack);
  3314.                     $responseArrWithPagination['paginator'] = $finalPaginator;
  3315.                     $responseArrWithPagination['clients'] = $ClientPaginator;
  3316.                     $this->createFileJson($path"\r" 'points local'json_encode($ClientPaginator) ."\r");
  3317.                     $msg "Restaurant ok";
  3318.                 } else {
  3319.                     $this->createFileJson($path"\r" 'Not points local'."\r");
  3320.                     $msg "Restaurant no found clients with points";
  3321.                 }
  3322.             } else {
  3323.                 $msg "Client not Found";
  3324.                 $this->createFileJson($path"\r" 'Client not found'."\r");
  3325.             } 
  3326.             if (isset($clientsIdInArray) && !empty($clientsIdInArray)) {
  3327.                 $dataToCommand = ['clientsId' => implode(' '$clientsIdInArray)];
  3328.                 ForcedAsynchronousCommandsUtil::omtClientAddressAsyncRegistOnLicensor($this->realContainer$dataToCommand);
  3329.             }
  3330.             $responseArrWithPagination['msg'] = $msg;
  3331.             $responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
  3332.             $responseArrWithPagination['bigbag'] = true;  
  3333.             
  3334.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrWithPagination);
  3335.             $xxArray $theUrlTrSt->transform();
  3336.             $jsonContent json_encode($xxArray);
  3337.             
  3338.             if ($debug) {
  3339.                 dump($responseArrWithPagination);
  3340.                 $this->createFileJson($path"\r" 'Response'."\r" $jsonContent );
  3341.                 die;
  3342.             }
  3343.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  3344.         } catch (\Throwable $th) {
  3345.             $err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
  3346.             $this->createFileJson($path"\r" 'Alert Error => 'json_encode($err) ."\r" );
  3347.             return $this->errorInternalError($err);
  3348.         }   
  3349.     }
  3350.     public function saveNewTypePointAccount($em$clientToGetPoint$data$path){
  3351.         $debug=isset($data["debug"]) ? true :false;
  3352.         if($debug){
  3353.             dump("Data de entrada ",$data);
  3354.         }
  3355.         // se verifica el restaurante
  3356.         $license=$em->getRepository('App\Entity\AccountLicense')->GetLicenseActive($data["nickname"], $debug);
  3357.         if($debug){
  3358.             dump("License ",$license);
  3359.         }
  3360.         
  3361.         if(empty($license)) {
  3362.             return false;
  3363.         } else { 
  3364.             // Se buscan todos los id de typePointAcount para luego generaruno atomaticamente
  3365.             $existingUUIDs $em->getRepository('App\Entity\TypePointAcount');
  3366.             // dump("uuid 1", $existingUUIDs);die;
  3367.             $newUUID $this->validateUUID($existingUUIDs$path);
  3368.             if (!$newUUID) {
  3369.                 $this->createFileJson($path'Limit time for valid UID search reached...' "\r");
  3370.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3371.                                 ->respondWithError('Limit time for valid UID search reached...'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3372.             }
  3373.             
  3374.             // se extraen la entidad del tipo de puntos Locales 
  3375.             $typePoint $em->getRepository('App\Entity\TypePoint')->findOneBy(["type"=>TypePoint::TYPE_LOCAL]);
  3376.             $resp $this->savePointAccount($em$clientToGetPoint$data$path);
  3377.     
  3378.             $countryData=$em->getRepository('App\Entity\City')->getLocationCountry($license[0]->getCity());
  3379.             $typePointAccountData = new TypePointAcount();
  3380.             
  3381.             $typePointAccountData->setId($newUUID);
  3382.             $typePointAccountData->setTypePoint($typePoint);
  3383.             $typePointAccountData->setLicense($license[0]);
  3384.             $typePointAccountData->setPointAcount($resp["pointAccountData"]);
  3385.             $typePointAccountData->setCountryId($countryData[0]);
  3386.             $typePointAccountData->setAmount(0);
  3387.             $typePointAccountData->setPointArmAcount('Pepito Habla Ingles!');
  3388.             $typePointAccountData->setStartingDate(new \DateTime());
  3389.             $typePointAccountData->setAcountToken($resp["tokenAcount"]);
  3390.             if (isset($data['Spots']) && !empty($data['Spots']) && $data['Spots'] != '0' && $data['Spots'] != 0) {
  3391.                 
  3392.                 if (!is_null($path)) {
  3393.                     $this->createFileJson($path'The request has spots => ' $data['Spots'] . "\r");
  3394.                 }
  3395.                 $typePointAccountData->setAmount($data['Spots']);
  3396.             }
  3397.             $em->persist($typePointAccountData);
  3398.             $em->flush();
  3399.             return $typePointAccountData;
  3400.         }  
  3401.     }
  3402.     public function validateUUID($existingUUIDs$path null){
  3403.         $validate false;
  3404.         $count 0;
  3405.         $newUUID '';
  3406.         while (!$validate && $count 50) {
  3407.             if(isset($path) && !is_null($path)){
  3408.                 $this->createFileJson($path'Generación de uuid ' $count ."\r");
  3409.             }
  3410.             $newUUID UUIDGeneratorUtil::getUUIDv4();
  3411.             $getData $existingUUIDs->getAllIv2validedateNewUuid($newUUID);
  3412.             // $validate = !in_array($newUUID, $existingUUIDs);
  3413.             $validate = !empty($getData) ? false true
  3414.             ++$count;
  3415.         }
  3416.         if(isset($path) && !is_null($path)){
  3417.                 $this->createFileJson($path'nuevo  uuid ' $newUUID ."\r");
  3418.                 $this->createFileJson($path'respuesta del validador despues del while de la muerte' $validate ."\r");
  3419.             }
  3420.         if (!$validate) {
  3421.             return false;
  3422.         }
  3423.         return $newUUID;
  3424.     }
  3425.     public function generateToken($em$path=null$base=null){
  3426.         $baseToken "";
  3427.         $tokenAcount "";
  3428.         $count=0;
  3429.         if(isset($path) && !is_null($path)){
  3430.             $this->createFileJson($path'base  ' $base ."\r");
  3431.         }
  3432.         do{
  3433.             if(isset($path) && !is_null($path)){
  3434.                 $this->createFileJson($path'Generación de token ' $count ."\r");
  3435.             }
  3436.             if($count ){
  3437.                 $baseToken Utilx::randomPassword(32);
  3438.             }
  3439.             else{
  3440.                 $baseToken is_null($base) ? Utilx::randomPassword(32):$base;
  3441.             }
  3442.             $tokenAcount Encryptor::encodeInfo($baseToken5);
  3443.             $acountToken $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
  3444.             if(isset($path) && !is_null($path)){
  3445.                 $this->createFileJson($path'base token ' $baseToken ."\r");
  3446.                 $this->createFileJson($path'token account' $tokenAcount ."\r");
  3447.                 if(isset($acountToken[0])){
  3448.                     $this->createFileJson($path'acount Token' .$acountToken[0]->getAcountToken() ."\r");
  3449.                 }
  3450.                 
  3451.             }
  3452.             ++$count;
  3453.         } while(!empty($acountToken) && $count 50);
  3454.         if (!empty($acountToken)) {
  3455.             return false;
  3456.         }
  3457.         return ["baseToken"=>$baseToken"tokenAcount" => $tokenAcount];
  3458.     }
  3459.     public function savePointAccount($em$clientToGetPoint$data$path){
  3460.         $pointAccountData $em->getRepository('App\Entity\PointAcount')->findOneBy(["omtClient" => $clientToGetPoint->getId()]);
  3461.             
  3462.         // Se valiuda si existe cuenta de puntos, sino existe se cera una 
  3463.         if (!isset($pointAccountData) && empty($pointAccountData)) {
  3464.             
  3465.             $pointAccountData = new PointAcount();
  3466.             $pointAccountData->setId($clientToGetPoint->getId());
  3467.             
  3468.             /*$existingUUIDsPA = $em->getRepository('App\Entity\PointAcount');
  3469.             
  3470.             $this->createFileJson($path, 'savePointAccount -> Se valida la existencia de la cuenta de puntos ' . "\r");
  3471.             $newUUIDPA = $this->validateUUID($existingUUIDsPA, $path);
  3472.             if (!$newUUIDPA) {
  3473.                 $this->createFileJson($path, 'savePointAccount ->Limit time for valid UID 2 search reached...' . "\r");
  3474.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3475.                                 ->respondWithError('Limit time for valid UID 2 search reached...', WebService::CODE_COULD_NOT_AUTHENTICATE);
  3476.             }
  3477.             $pointAccountData->setId($newUUIDPA);*/
  3478.             if(isset($data['basePointacount'])) {
  3479.                 $baseToken=$data['basePointacount'];
  3480.             } else {
  3481.                 $tokens=$this->generateToken($em$path);
  3482.                 if (!$tokens) {
  3483.                     $this->createFileJson($path'savePointAccount -> Limit time for valid token search reached...' "\r");
  3484.                     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3485.                                     ->respondWithError('Limit time for valid token search reached...'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3486.                 }
  3487.                 $baseToken $tokens['baseToken'];
  3488.                 $tokenAcount $tokens['tokenAcount'];
  3489.             }
  3490.             
  3491.             $pointAccountData->setOmtClient($clientToGetPoint->getId());
  3492.             $pointAccountData->setBasePointacount($baseToken);
  3493.             $date = isset($data['activationDate']) ? new \DateTime($data['activationDate']) : new \DateTime("NOW");
  3494.             $pointAccountData->setActivationDate($date);
  3495.             
  3496.             $em->persist($pointAccountData);
  3497.             $em->flush();
  3498.         } else {
  3499.             $tokens=$this->generateToken($em$path$pointAccountData->getBasePointacount());
  3500.             if (!$tokens) {
  3501.                 $this->createFileJson($path'savePointAccount -> Limit time for valid token 2 search reached...' "\r");
  3502.                 return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3503.                                 ->respondWithError('Limit time for valid token 2 search reached...'WebService::CODE_COULD_NOT_AUTHENTICATE);
  3504.             }
  3505.             $tokenAcount $tokens['tokenAcount'];
  3506.         }
  3507.         return ["tokenAcount" => $tokenAcount"pointAccountData" => $pointAccountData];
  3508.     }
  3509.     /**
  3510.      * Esta función retorna los punto a un cliente.
  3511.      * @param Uuid id de la orden
  3512.      * @param String license nickname
  3513.      * @param String clienteID from cliente
  3514.      * @param String type point local-gloval
  3515.      * @param String Uid server id
  3516.      */
  3517.     public function returnLoyaltyCash(Request $requestArmorService $armorLog $log){
  3518.          // Creamos el log
  3519.         $path Util::getValidActiveLogByBaseName($this->realContainer'returnLoyaltyCash''returnLoyaltyCash.txt');
  3520.         $this->createFileJson($path"\r" '**-----------------------------------------------------------------------------**' "\r");
  3521.         $this->createFileJson($path"\r" 'returnLoyaltyCash init: ' $request->getContent() . "\r");
  3522.         //  validamos el metodo del request
  3523.         if ($request->getMethod() !== WebService::REQUEST_METHOD_POST && $request->getMethod() !== WebService::REQUEST_METHOD_OPTIONS) {
  3524.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_POST " method");
  3525.         }
  3526.         // Validamos el metodo de la petición
  3527.         if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
  3528.             $responseArrayAux1['status'] = WebService::CODE_SUCCESS;
  3529.             $responseArrayAux1['msg'] = 'OPTIONS detected, good to go!';
  3530.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrayAux1);
  3531.             $jsonTransform $theUrlTrSt->transform();
  3532.             $jsonContent json_encode($jsonTransform);
  3533.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  3534.         }
  3535.         $params json_decode($request->getContent(), true);
  3536.         //  Validamos los parametros del de a consulta 
  3537.         if (!isset($params['nickname']) || !isset($params['orderId']) || !isset($params['clienteID'])) {
  3538.             return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  3539.         }
  3540.         // Se inicia el entiti manager
  3541.         $container $this->realContainer;
  3542.         $em $this->getDoctrine()->getManager();
  3543.         
  3544.         // se busca el restaurante en base de datos
  3545.         $data = ['alLicenseUsername' => $params['nickname']];
  3546.         $accountLicenseData $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
  3547.         //  se valida el estado del restaurante
  3548.         $validate $this->validateLicense(count($accountLicenseData), $path$accountLicenseData);
  3549.         if(!$validate["status"]){
  3550.             return $this->setStatusCode($validate["status"])
  3551.                             ->respondWithError($validate["message"], $validate["code"]);
  3552.         }
  3553.         
  3554.         // if(isset($params['uid'])){
  3555.         //     $this->createFileJson($path, "\r" . 'Request Android' . "\r");
  3556.         //     if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
  3557.         //         // $emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
  3558.         //         $registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
  3559.         //         if (empty($registeredClientsByUID)) {
  3560.         //             $emLev->close();
  3561.         //             $this->createFileJson($path, 'UID diferente! o.O' . "\r");
  3562.         //             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3563.         //                             ->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
  3564.         //         } else {
  3565.         //             $emLev->close();
  3566.         //         }
  3567.         //     }
  3568.         // }
  3569.         
  3570.         // Se crea el entity manager para level web
  3571.         $emLev Util::emLicenseConnection($this->realContainer$em$accountLicenseData[0]);
  3572.         // se crea el valor del flag (en este caso es 1) para ingresarlo en la base de datos
  3573.         $params['flagRedime'] = LoyaltyHistory::FLAG_RETURN_POINT;
  3574.         
  3575.         //  se busca y se valida la orden en mesa pedido.
  3576.         // $mesaPedido = $emLev->getRepository('App\Structure\Mesapedido')->find($params['orderId']);
  3577.         
  3578.         // if(isset($params["debug"])){
  3579.         //     dump($mesaPedido);
  3580.         // }
  3581.         
  3582.         // if(is_null($mesaPedido) || (!is_null($mesaPedido) && $mesaPedido->getMpEstado() != Mesapedido::MESAPEDIDO_STATUS_CANCELED)){
  3583.         //     $this->createFileJson($path, "\r" . 'the return of loyalty cash is inappropriate for the order' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
  3584.         //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3585.         //                 ->respondWithError("the return of loyalty cash is inappropriate for the order", WebService::CODE_ACCOUNT_SUSPENDED);
  3586.         // }
  3587.         
  3588.         // se busaca la ultima transacción hecha por loyalty
  3589.         $loyaltyHistory $emLev->getRepository('App\Structure\LoyaltyHistory')->getLastCustomerInfo($params['orderId']);
  3590.         
  3591.         //  se busca el cliente y la cuenta de loyalty
  3592.         $clientReposiroty $em->getRepository('App\Entity\OmtClient');
  3593.         $clientToGetPoint $clientReposiroty->clientWithPhone2analis($params["clienteID"]);
  3594.         if(!is_array($clientToGetPoint)){
  3595.             $this->createFileJson($path"\r" 'client not found' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  3596.             
  3597.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3598.                         ->respondWithError("client not found"WebService::CODE_ACCOUNT_SUSPENDED);
  3599.         }
  3600.         // clienteID
  3601.         $params['customerId'] = isset($clientToGetPoint["id"]) ? $clientToGetPoint["id"] : null;
  3602.         //  se obtiene la cuenta de puntos de del uysuatio en el restaurante   $seedData['customerId'], $activeRuleToAnalyze->getPointType()->getId(), $license->getId(), (isset($seedData['debug']) ? true : false)
  3603.         // $typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->findOneBy(['license' => $accountLicenseData[0]->getId(), 'pointAcount' => $clientToGetPoint["pointAcount"]]);
  3604.         $typePointAccountData $em->getRepository('App\Entity\TypePointAcount')->findUserPtAccount($params['customerId'], TypePoint::WORK_AS_LOCAL$accountLicenseData[0]->getId());
  3605.         
  3606.         if(!isset($typePointAccountData[0])){
  3607.             $this->createFileJson($path"\r" 'Account loyalty client not found' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  3608.             
  3609.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3610.             ->respondWithError("Account loyalty client not found"WebService::CODE_ACCOUNT_SUSPENDED);
  3611.         }
  3612.         
  3613.         if(isset($params["debug"])){
  3614.             dump("llegue hasta aca"$params$clientToGetPoint$typePointAccountData$loyaltyHistory);
  3615.         }
  3616.         
  3617.         if((double) $loyaltyHistory[0]["pointsRedeemed"] <= 0){
  3618.             
  3619.             // se obtiene el historial de loyalty de la orden     
  3620.             $params['totalAmount'] = $loyaltyHistory[0]["saleAmount"];
  3621.             
  3622.             
  3623.             // Datos necesarios para armor 
  3624.             $armorPack = [
  3625.                 'request' => $request,
  3626.                 'service' => $armor,
  3627.                 'log' => $log
  3628.             ];
  3629.             
  3630.             if(isset($params["debug"])){
  3631.                 dump("pre-validate armor");
  3632.                 dump($typePointAccountData[0], $armorPack);
  3633.             }
  3634.             $validateArmor PointsUtilPorcessor::validateLicensorPointsAmountWithArmor($container$em$typePointAccountData[0], $armorPack$path);
  3635.             
  3636.             if(isset($params["debug"])){
  3637.                 dump("validateArmor"$validateArmor);
  3638.             }
  3639.             $activeAplicableRule $em->getRepository("App\Entity\PtsAdquiRedemRules")->findOneBy(['license' => $accountLicenseData[0]->getId()]);
  3640.             
  3641.             if(isset($params["debug"])){
  3642.                 dump("validateArmor"$activeAplicableRule);
  3643.             }
  3644.             
  3645.             $armorPack['typePointAccount'] = $typePointAccountData[0];
  3646.             $armorPack['license'] = $accountLicenseData[0];
  3647.             $armorPack['preTransactionAmount']=$validateArmor[1];
  3648.             $totalAmount = (double) $params['totalAmount'] / (double) $activeAplicableRule->getPtsRate();
  3649.             
  3650.             $this->createFileJson($path'Pre makePtsTransactionToClientAccountInArmorServer call: $armorPack -> ' json_encode($armorPack) . ' $params -> ' json_encode($params) . "\r");
  3651.             $createArmor PointsUtilPorcessor::makePtsTransactionToClientAccountInArmorServer($container$em$params$totalAmount$activeAplicableRule$armorPack$path);
  3652.             
  3653.             if(isset($params["debug"])){
  3654.                 dump("Armor"$createArmor);
  3655.                 // die;
  3656.             }
  3657.             // se llena la base de datos de loyaltyHistory
  3658.             $params['transactionCode'] = $createArmor[1];
  3659.             $params['pointsEarned'] = (double) $createArmor[0];
  3660.             $params['actualAmount'] = (double) $createArmor[3];
  3661.             $params['totalAmount'] = $createArmor[4];
  3662.             $loyaltyRecordCreationResult PointsUtilPorcessor::createLoyaltyTransactionRecordInLicense($container$em$accountLicenseData[0], $clientToGetPoint$params$path);
  3663.             $responseArrWithPagination['msg'] = "Return of points";
  3664.             $responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
  3665.             $responseArrWithPagination['bigbag'] = true;  
  3666.             
  3667.             $theUrlTrSt = new LicensorGenericTransformer($this->realContainer$responseArrWithPagination);
  3668.             $xxArray $theUrlTrSt->transform();
  3669.             $jsonContent json_encode($xxArray);
  3670.             
  3671.             if (isset($params["debug"])) {
  3672.                 dump($responseArrWithPagination);
  3673.                 $this->createFileJson($path"\r" 'Response'."\r" $jsonContent );
  3674.                 die;
  3675.             }
  3676.             return $this->respondWithItem($jsonContent$theUrlTrSt);
  3677.             // // se suben los datos a armor 
  3678.             // $arrayTypePointAccountTokenToArmor = PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData, $typePointAccountData->getAmount(), $path);
  3679.             // $encodeBase = Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
  3680.             // $request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
  3681.         }else{
  3682.             $this->createFileJson($path"\r" 'No points found to return' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  3683.             return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3684.             ->respondWithError("No points found to return"WebService::CODE_ACCOUNT_SUSPENDED);
  3685.         }
  3686.         return true;
  3687.     }
  3688.     /**
  3689.      * Valida la licencia de que se sta consultando  
  3690.      */
  3691.     function validateLicense($countResult$path$accountLicenseData){
  3692.         if ($countResult <= 0) {
  3693.             $this->createFileJson($path"\r" 'Invalid nickname or channelname' WebService::CODE_COULD_NOT_AUTHENTICATE "\r");
  3694.             return ["status" => WebService::HTTP_CODE_UNAUTHORIZED"message" => 'Invalid nickname or channelname'"code"=>WebService::CODE_COULD_NOT_AUTHENTICATE];
  3695.             // $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3696.             //                 ->respondWithError('Invalid nickname or channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
  3697.         }
  3698.         if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
  3699.             $this->createFileJson($path"\r" 'Account is inactive' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  3700.             return ["status" => WebService::HTTP_CODE_UNAUTHORIZED"message" => 'Account is inactive'"code" => WebService::CODE_ACCOUNT_SUSPENDED];
  3701.             // return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3702.             //                 ->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
  3703.         }
  3704.         if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
  3705.             $this->createFileJson($path"\r" 'Inactive License' WebService::CODE_ACCOUNT_SUSPENDED "\r");
  3706.             return ["status" => WebService::HTTP_CODE_UNAUTHORIZED"message" => 'Inactive License'"code" => WebService::CODE_ACCOUNT_SUSPENDED];
  3707.         //     return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
  3708.         //                     ->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
  3709.         }
  3710.         return ["status" => true];
  3711.     }
  3712.     /**
  3713.      * Obtiene el balance de puntos en la targeta gift card que tenga el cliente
  3714.      * @param String id de la orden
  3715.      */
  3716.     function getGiftCardBalancePoints(Request $request) {
  3717.         // Se verifica que ingrese con el mehod get
  3718.         if ($request->getMethod() == WebService::REQUEST_METHOD_GET) {
  3719.             return $this->errorNotAllowedMethod('Method not allowed. Use ' WebService::REQUEST_METHOD_GET " method");
  3720.         }
  3721.         $params json_decode($request->getContent(), true);
  3722.         // Se inicia el entity manager
  3723.         $container $this->realContainer;
  3724.         $em $this->getDoctrine()->getManager();
  3725.         if (isset($params['orderId']) && !empty($params['orderId'])) {
  3726.             $mpCodigo $params['orderId'];
  3727.             $response = [];
  3728.             $giftCardData $em->getRepository('App\Entity\GiftCardTransaction')->getTransactionsByOrder($mpCodigo);
  3729.             $response['msg'] = "Your gift card balance";
  3730.             $response['status'] = WebService::CODE_SUCCESS;
  3731.             $response['bigbag'] = true;
  3732.             $response['data'] = $giftCardData != '' $giftCardDatanull;  
  3733.             $licensorTransformer = new LicensorGenericTransformer($this->realContainer$response);
  3734.             $transformData $licensorTransformer->transform();
  3735.             $jsonEncodedData json_encode($transformData);
  3736.             return $this->respondWithItem($jsonEncodedData$licensorTransformer);
  3737.         } else {
  3738.             return $this->errorWrongArgs('Wrong Arguments'WebService::CODE_WRONG_ARGUMENTS);
  3739.         }
  3740.     }
  3741.     /**
  3742.      * Function configuration loyalty account to restaurant in omt
  3743.      * 
  3744.      */
  3745.     public function createOrUpdateLoyaltyConfigurationOmt($em$params){
  3746.         $container $this->realContainer;
  3747.         $restaurantEntity $em->getRepository('App\Entity\AccountLicense')->find($params['license']);
  3748.         $arrayToRequest = [
  3749.             "restNickname" => $restaurantEntity->getAlLicenseUsername(),
  3750.             "minimumPointAmountToExchange" => $params['minimumPointAmountToExchange'],
  3751.             "useLocalPoints" => true,
  3752.             "useGlobalPoints" => false,
  3753.             "ptsRate" => $params['ptsRate'],
  3754.             "minimumPurchase" => $params['minimumPurchase'],
  3755.             "restaurantId" => $restaurantEntity->getAlLicenseUsername(),
  3756.         ]; 
  3757.         $url $container->getParameter('omt_scheme') . '://' $container->getParameter('omt_host') . 'common/setLoyaltyConfiguration';
  3758.         
  3759.         $ch curl_init();
  3760.         curl_setopt($chCURLOPT_URL$url);
  3761.         curl_setopt($chCURLOPT_POSTtrue);
  3762.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($arrayToRequest));
  3763.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  3764.         
  3765.         $result curl_exec($ch);
  3766.         $decodeResult json_decode($resulttrue);
  3767.         return $decodeResult;
  3768.     }
  3769. }