<?php
namespace App\Controller\WS;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Util\Util as Utilx;
use App\Util\WS\Util;
use App\Util\NewUtil;
use App\Util\WS\PointsUtilPorcessor;
use App\Entity\AccountLicense;
use App\Entity\PointAcount;
use App\Entity\PtsAdquiRedemRules;
use App\Entity\TypePoint;
use App\Entity\TypePointAcount;
use App\Entity\OmtClient;
use App\Entity\WebService;
use App\Entity\PointRelatedRequest;
use App\Entity\RabbitRelatedGenericEntity;
use App\Entity\TypePtsGenericDefinitionRules;
use App\Entity\RestaurantLoyaltyConfiguration;
use App\Entity\ActionHistory;
use App\Util\Paginator;
use App\Util\UUIDGeneratorUtil;
use App\Transformer\LicensorGenericTransformer;
use App\Controller\Application\Service\ArmorService;
use App\Controller\Application\Service\Log\Log;
use App\Controller\Application\Service\Util\Encryptor;
use App\Controller\WS\ClientController;
use App\Form\RestaurantLoyaltyConfig;
use App\Form\PointsAdquiRedemRules;
use App\Structure\Dashboard;
use App\Structure\Configuracion;
use App\Structure\RegistActions;
use App\Structure\ConfRangedelivery;
use App\Structure\ValorEpiMerchant;
use App\Form\MerchantAccountType;
use App\Structure\ConfGeneralDelivery;
use App\Structure\ConfMerchantAccount;
use App\Util\WS\ForcedAsynchronousCommandsUtil;
use App\Util\WS\Util as WsUtilx;
use App\Structure\LoyaltyHistory;
use App\Structure\MesaPedido;
use DateTime;
class GiftCardPointController extends ApiController {
/**
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createOmtClientRecord(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (!isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
$accountLicData = $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
if (empty($accountLicData)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicData[0]->getDeviceUid() != $data['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid Id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
$clientOmt = $em->getRepository('App\Entity\OmtClient')->find($data['id']);
$nicknameClientSearch = ['username' => $data['username']];
$nicknameCliData = $em->getRepository('App\Entity\OmtClient')->findBy($nicknameClientSearch);
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Omt User update successfully!';
$responseArr['url'] = '';
if (!$clientOmt) {
if ($nicknameCliData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Username invalid', WebService::CODE_ACCOUNT_SUSPENDED);
}
$clientOmt = new OmtClient();
$clientOmt->setId($data['id']);
$responseArr['msg'] = 'Omt User created successfully!';
}
if ($nicknameCliData && $clientOmt->getId() != $nicknameCliData[0]->getId()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Username invalid', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (!checkdnsrr($data['email'], "MX")) {
return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
->respondWithError("The email ". $data['email'] ." is not a valid", WebService::HTTP_CODE_BAD_REQUEST);
}
$clientOmt->setName($data['name']);
$clientOmt->setLastname($data['lastname']);
$clientOmt->setEmail($data['email']);
$clientOmt->setUsername($data['username']);
$clientOmt->setBirthdate(new \DateTime($data['birthdate']));
$clientOmt->setPhone(Utilx::clearEspecialCharactersFromPhone($data['phone']));
$clientOmt->setLangCode($data['langCode']);
$em->persist($clientOmt);
$em->flush();
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createPointAccountRecord(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (strlen($data['omtClientId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid omtClientId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$em = $this->getDoctrine()->getManager();
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($data['id']);
$clientOmt = $em->getRepository('App\Entity\OmtClient')->find($data['omtClientId']);
if (!$clientOmt) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Omt client not found', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$clientPointSearch = ['omtClient' => $data['omtClientId']];
$clientPointAccount = $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
$basePointSearch = ['basePointacount' => $data['basePointacount']];
$basePointAccount = $em->getRepository('App\Entity\PointAcount')->findBy($basePointSearch);
if ($basePointAccount && $basePointAccount[0]->getId() != $data['id']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid account token', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Point account update successfully!';
if (!$pointAccountData) {
$pointAccountData = new PointAcount();
$pointAccountData->setId($data['id']);
$responseArr['msg'] = 'Point account created successfully!';
}
$pointAccountData->setOmtClient($clientOmt->getId());
$pointAccountData->setBasePointacount($data['basePointacount']);
$pointAccountData->setActivationDate(new \DateTime($data['activationDate']));
$em->persist($pointAccountData);
$em->flush();
if ($clientPointAccount) {
$responseArr['msg'] .= ' User already has point account!';
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createTypePointAccountRecord(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (strlen($data['typePoinId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid typePoinId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['pointAccountId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid pointAccountId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$em = $this->getDoctrine()->getManager();
$typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->find($data['id']);
$accountTokenSearch = ['acountToken' => $data['accountToken']];
$accountTokenData = $em->getRepository('App\Entity\TypePointAcount')->findBy($accountTokenSearch);
if ($accountTokenData && $accountTokenData[0]->getId() != $data['id']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid acountToken', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$typePointData = $em->getRepository('App\Entity\TypePoint')->find($data['typePoinId']);
$countrySearch = ['coVal' => $data['countryCode']];
$countryData = $em->getRepository('App\Entity\Country')->findBy($countrySearch);
if ($countryData) {
$countryData = $em->getRepository('App\Entity\Country')->find($countryData[0]->getCoId());
}
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($data['pointAccountId']);
if (isset($pointAccountData) && $pointAccountData == []) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('pointAccountId not found', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Type Point account update successfully!';
if (!$typePointAccountData) {
$typePointAccountData = new TypePointAcount();
$typePointAccountData->setId($data['id']);
$responseArr['msg'] = 'Type Point account created successfully!';
}
$typePointAccountData->setTypePoint($typePointData);
$typePointAccountData->setPointAcount($pointAccountData);
$typePointAccountData->setCountryId($countryData);
$typePointAccountData->setAmount($data['ptAmount']);
$typePointAccountData->setPointArmAcount($data['pointArmAccount']);
$typePointAccountData->setStartingDate(new \DateTime($data['startingDate']));
$typePointAccountData->setAcountToken($data['accountToken']);
$em->persist($typePointAccountData);
$em->flush();
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* Obtener los puntos acumulados por clientes
* @param Request $request
* @return type
*/
public function getPointAccountByClient(Request $request, ArmorService $armor, Log $log) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'getPointAccountByClient', 'getPointAccountByClient0.txt');
$this->createFileJson($path, "\r" . 'Hello Points: ' . $request->getContent() . "\r");
$indexSearch = ['idClient', 'nickname'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
$order = Paginator::filterPaginatorParameters([], $request, true);
$log->createChannel('getPointAccountByClient');
if (!isset($search['nickname'])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (!isset($search['idClient'])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid idClient', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($search['idClient']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid idClient', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$search['client'] = $search['idClient'];
if (isset($search['nickname'])) {
$dataNicknameSearch = ['alLicenseUsername' => $search['nickname']];
$accountLicByNicknameData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataNicknameSearch);
if (!isset($accountLicByNicknameData[0])) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname 2', WebService::CODE_COULD_NOT_AUTHENTICATE);
} else {
$search['restaurant'] = $accountLicByNicknameData[0];
}
}
$loyaltyConfiguration = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $accountLicByNicknameData[0]->getId()]);
if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
$this->createFileJson($path, 'Loyalty functions not configured yet o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Loyalty functions not configured yet', WebService::CODE_ACCOUNT_SUSPENDED);
} elseif (!isset($loyaltyConfiguration[0])) {
$this->createFileJson($path, 'Loyalty functions configuration record not found o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Loyalty functions configuration record not found!', WebService::CODE_ACCOUNT_SUSPENDED);
}
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
$pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByRestaurant($request, $this->realContainer, $search, $order, $loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $accountLicByNicknameData[0], $armor, $log, $path);
if (isset($pointAccountByClient['accounts'][0])) {
$responseArr['msg'] = 'List of points by client';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['client'] = $pointAccountByClient['accounts'][0];
$responseArr['bigbag'] = true;
} else {
$responseArr['msg'] = 'No client found with the given data';
$responseArr['status'] = WebService::CODE_SUCCESS;
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* funcion encargada de obtener los puntos de una orden en OMT
* @param Request $request
* @return array - se retorna arreglo con los puntos obtenidos
**/
public function getPointsByOrder(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$em = $this->getDoctrine()->getManager();
$params = json_decode($request->getContent(), true);
$response_array = $data_response = [];
if (isset($params['order_id']) && $params['order_id']) {
// Se obtienen los datos mediante el order_id
$points_data = $em->getRepository('App\Entity\PointDeal')->findOneBy([ 'order' => $params['order_id'] ]);
if ($points_data) {
$data_response = [
"earned" => $points_data->getDealPtsAmount()
];
}
// Respuesta
$response_array['msg'] = 'List of points by order';
$response_array['status'] = WebService::CODE_SUCCESS;
$response_array['data'] = $data_response;
$response_array['bigbag'] = true;
} else {
$response_array['msg'] = 'Invalid Params';
$response_array['status'] = WebService::CODE_WRONG_ARGUMENTS;
$response_array['data'] = false;
$response_array['bigbag'] = false;
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $response_array);
$transform_fnc = $theUrlTrSt->transform();
$json_content_data = json_encode($transform_fnc);
return $this->respondWithItem($json_content_data, $theUrlTrSt);
} else {
$response_array['msg'] = 'METHOD '. $request->getMethod() .' NOT ALLOWED';
$response_array['status'] = WebService::CODE_NOT_ALLOWED_METHOD;
$response_array['data'] = null;
$response_array['false'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $response_array);
$transform_fnc = $theUrlTrSt->transform();
$json_content_data = json_encode($transform_fnc);
return $this->respondWithItem($json_content_data, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function createPtsAdquiRedemRules(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$em = $this->getDoctrine()->getManager();
$nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
$accountLicData = $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
if (empty($accountLicData)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicData[0]->getDeviceUid() != $data['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
$typePointData = $em->getRepository('App\Entity\TypePoint')->find($data['PointType']);
if (!$typePointData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid PointType', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$basicDefinitionData = $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->find($data['BasicDefinition']);
if (!$basicDefinitionData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid BasicDefinition', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$ptsAdquiRedemRulesData = $em->getRepository('App\Entity\PtsAdquiRedemRules')->find($data['id']);
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Pts Adqui Redem Rules update successfully!';
if (!$ptsAdquiRedemRulesData) {
$ptsAdquiRedemRulesData = new PtsAdquiRedemRules;
$ptsAdquiRedemRulesData->setId($data['id']);
$responseArr['msg'] = 'Pts Adqui Redem Rules created successfully!';
}
if ($data['minimumPurchase'] == "") {
$data['minimumPurchase'] = null;
}
if ($data['QuantityPurchase'] == "") {
$data['QuantityPurchase'] = null;
}
$ptsAdquiRedemRulesData->setName($data['Name']);
$ptsAdquiRedemRulesData->setPtsRate($data['PtsRate']);
$ptsAdquiRedemRulesData->setBasicDefinition($basicDefinitionData);
$ptsAdquiRedemRulesData->setPointType($typePointData);
$ptsAdquiRedemRulesData->setCreationDate(new \DateTime($data['CreationDate']));
$ptsAdquiRedemRulesData->setInitialActivationDate(new \DateTime($data['InitialActivationDate']));
$ptsAdquiRedemRulesData->setJustClaimOnce($data['JustClaimOnce']);
$ptsAdquiRedemRulesData->setApplyToSpecificRecord($data['ApplyToSpecificRecord']);
$ptsAdquiRedemRulesData->setWatchableObject($data['WatchableObject']);
$ptsAdquiRedemRulesData->setLicense($data['License']);
$ptsAdquiRedemRulesData->setMinimumPurchase($data['minimumPurchase']);
$ptsAdquiRedemRulesData->setMinimumQuantityPurchase($data['QuantityPurchase']);
$em->persist($ptsAdquiRedemRulesData);
$em->flush();
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function listTypePoint(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['typePoint'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
if ($search) {
$dataSearch = ['type' => $search['typePoint']];
$typePointData = $em->getRepository('App\Entity\TypePoint')->findBy($dataSearch);
} else {
$typePointData = $em->getRepository('App\Entity\TypePoint')->findAll();
}
$arrayTypePoint = [];
foreach ($typePointData as $datos) {
$tpData = $datos->showEverything();
array_push($arrayTypePoint, $tpData);
}
$responseArr['msg'] = 'List of points types';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['listTypePoint'] = $arrayTypePoint;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function listTypePtsGenericRules(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['BasicType', 'Type'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
if (isset($search['BasicType']) && !isset($search['Type'])) {
$dataSearch = ['basicType' => $search['BasicType']];
$ptsGenericRule = $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->findBy($dataSearch);
}
if (isset($search['Type']) && !isset($search['BasicType'])) {
$dataSearch = ['type' => $search['Type']];
$ptsGenericRule = $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->findBy($dataSearch);
}
if (isset($search['Type']) && isset($search['BasicType'])) {
$ptsGenericRule = $em->getRepository('App\Entity\TypePtsGenericDefinitionRules')->listPtsgenericDefinitionRules($search);
}
$arrayPtsGenericRule = [];
if (isset($ptsGenericRule)) {
foreach ($ptsGenericRule as $datos) {
if (is_object($datos)) {
$pgrData = $datos->showEverything();
array_push($arrayPtsGenericRule, $pgrData);
} else {
array_push($arrayPtsGenericRule, $datos);
}
}
}
$responseArr['msg'] = 'List of point types with generic rules';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['listTypePoint'] = $arrayPtsGenericRule;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function listProductRestaurant(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['uid', 'nickname', 'type'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
if (!isset($search['uid'])) {
return $this->errorWrongArgs('Uid undefined!', WebService::CODE_WRONG_ARGUMENTS);
}
if (!isset($search['nickname'])) {
return $this->errorWrongArgs('Nickname undefined!', WebService::CODE_WRONG_ARGUMENTS);
}
if (!isset($search['type'])) {
return $this->errorWrongArgs('type undefined!', WebService::CODE_WRONG_ARGUMENTS);
}
$dataSearch = ['alLicenseUsername' => $search['nickname']];
$accountLicByUidData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
if (!$accountLicByUidData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid Nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicByUidData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicByUidData[0]->getAlLicenseStatus() != AccountLicense::LICENSE_STATUS_ACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('License is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicByUidData[0]->getDeviceUid() != $search['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicByUidData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $search['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
if ($search['type'] == "category" || $search['type'] == "product" || $search['type'] == "product_modifier_map") {
$repository = Util::getStructureEntityDir($search['type']);
} else {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid type', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$arrayListCategory = [];
if (isset($repository)) {
$auxLevEm = Util::emLicenseConnection($this->realContainer, $em, $accountLicByUidData[0]);
$configuracionForAll = $auxLevEm->getRepository($repository)->findAll();
foreach ($configuracionForAll as $datos) {
if (is_object($datos)) {
$pgrData = $datos->showEverything();
array_push($arrayListCategory, $pgrData);
} else {
array_push($arrayListCategory, $datos);
}
}
}
if ($search['type'] == 'product_modifier_map') {
$search['type'] = "'product modifier'";
} else if ($search['type'] == 'product') {
$search['type'] = "'product'";
} else if ($search['type'] == 'category') {
$search['type'] = "'category'";
}
$responseArr['msg'] = 'List of ' . $search['type'] . ' of the restaurant: ' . $accountLicByUidData[0]->getAlRestaurantName();
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['dataList'] = $arrayListCategory;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function pointDealTransition(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['idClient'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
if (isset($search['idClient'])) {
$client = $em->getRepository('App\Entity\OmtClient')->find($search['idClient']);
if (!$client) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$responseArr['dataList']['id'] = $client->getId();
$responseArr['dataList']['name'] = $client->getName();
$responseArr['dataList']['lastname'] = $client->getLastname();
$responseArr['dataList']['phone'] = $client->getPhone();
}
$listRules = $em->getRepository('App\Entity\PointDeal')->listOfPointDeal($search);
$responseArr['msg'] = 'List of rules';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['dataList']['pointDeal'] = $listRules;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* WS generico para que el servidor andorid responda una pregunta realizada en un push
* @author Aealan Z <lrobledo@kijho.com> 15/06/16
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function evaluateCustomerPurchaseForPointsOrElse(Request $request, ArmorService $armor, Log $log) {
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST && $request->getMethod() !== WebService::REQUEST_METHOD_OPTIONS) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
$responseArrayAux1['status'] = WebService::CODE_SUCCESS;
$responseArrayAux1['msg'] = 'OPTIONS detected, good to go!';
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrayAux1);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
if (0 == !strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT) && 0 == !strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
return $this->errorWrongArgs('Wrong content', WebService::CODE_WRONG_ARGUMENTS);
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'evaluateCustomerPurchaseForPointsOrElse', 'evaluateCustomerPurchaseForPointsOrElse0.txt');
$this->createFileJson($path, "\r" . 'Hello Points: ' . $request->getContent() . "\r");
// try {
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'Decode params: ' . $arrayEncryptResult['data'] . "\r");
$customerId="";
$flagAndroid = false;
if(isset($params['requestFrom'])){
if (!isset($params['nickname']) || !isset($params['dealType']) || !isset($params['omtCustomerId']) || !isset($params['totalAmount'])) {
$this->createFileJson($path, "\r" . 'Wrong arguments!' . WebService::CODE_WRONG_ARGUMENTS . "\r");
return $this->errorWrongArgs('Wrong arguments!', WebService::CODE_WRONG_ARGUMENTS);
} else {
$customerId = $params['omtCustomerId'];
}
} elseif (!isset($params['nickname']) || !isset($params['uid']) || !isset($params['dealType']) || !isset($params['customerId']) || !isset($params['totalAmount'])) {
$this->createFileJson($path, "\r" . 'Wrong arguments!' . WebService::CODE_WRONG_ARGUMENTS . "\r");
return $this->errorWrongArgs('Wrong arguments!', WebService::CODE_WRONG_ARGUMENTS);
} else {
$customerId = $params['customerId'];
$flagAndroid = true;
}
$em = $this->getDoctrine()->getManager();
$data = ['alLicenseUsername' => $params['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
$countResult = count($accountLicenseData);
$validate = $this->validateLicense($countResult, $path, $accountLicenseData);
if (!$validate["status"]) {
$this->createFileJson($path, 'licencia no eliminada logicamente' . "\r");
return $this->setStatusCode($validate["status"])->respondWithError($validate["message"], $validate["code"]);
}
$clientReposiroty = $em->getRepository('App\Entity\OmtClient');
if($flagAndroid){
$this->createFileJson($path, "\r" . 'Request Android' . "\r");
if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
$this->createFileJson($path, 'UID diferente! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
$clientToGetPoint = $clientReposiroty->find($customerId);
}else{
$clientToGetPoint = $clientReposiroty->findOneBy(["omtUserId"=>$customerId]);
$params['customerId'] = !is_null($clientToGetPoint) && is_object($clientToGetPoint) ? $clientToGetPoint->getId() : null;
}
if (!$clientToGetPoint) {
$this->createFileJson($path, 'Unknown customer' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown customer', WebService::CODE_ACCOUNT_SUSPENDED);
}
$log->createChannel('gift_card');
$armorPack = [
'request' => $request,
'service' => $armor,
'log' => $log
];
if (isset($params['debug']) && $params['debug']) {
dump("Parametros de entrada",$params);
}
if ($params['totalAmount'] > 0) {
if (isset($params['debug']) && $params['debug']) {
dump('Total amount', $params['totalAmount']);
}
$this->createFileJson($path, 'Points evaluation' . "\r");
$pointEvaluationResult = PointsUtilPorcessor::analyzePointTransaction($this->realContainer, $em, $accountLicenseData[0], $params, $armorPack);
if (isset($params['debug']) && $params['debug']) {
dump("Point evaluation result", $pointEvaluationResult);
}
if (empty($pointEvaluationResult) && isset($params['omtCustomerId'])) {
$this->createFileJson($path, 'create automatic' . "\r");
$typePointAccountData = $this->saveNewTypePointAccount($em, $clientToGetPoint,$params, $path);
$aux = ($typePointAccountData instanceof TypePointAcount) ? 'YES' : 'NO';
$this->createFileJson($path, '$typePointAccountData is TypePointAcount ' .$aux. "\r");
$aux = gettype($typePointAccountData);
$this->createFileJson($path, '$typePointAccountData is ' .$aux. "\r");
// save on armor
if (isset($params['debug']) && $params['debug']) {
dump("Create typePointAccount", $typePointAccountData);die;
}
if ($typePointAccountData instanceof TypePointAcount){
$arrayTypePointAccountTokenToArmor = PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData, $typePointAccountData->getAmount(), $path);
$encodeBase = Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
$request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
$pointEvaluationResult = PointsUtilPorcessor::analyzePointTransaction($this->realContainer, $em, $accountLicenseData[0], $params, $armorPack);
}
}
} else {
if (isset($params['debug']) && $params['debug']) {
dump('No es mayor que 0? o.O!');
dump($params['totalAmount'] > 0);
}
$pointEvaluationResult = [];
}
$responseArrayAux1['status'] = WebService::CODE_SUCCESS;
$responseArrayAux1['msg'] = 'Point transactions processed successfully!';
$responseArrayAux1['bigbag'] = true;
$responseArrayAux2 = $this->processEvaluatedTransactionResponse($pointEvaluationResult, $params);
$responseArray = array_merge($responseArrayAux1, $responseArrayAux2);
if (isset($params['debug']) && $params['debug']) {
dump("Response",$responseArray);die;
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArray);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
$this->createFileJson($path, 'Response' .$jsonContent. "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
// } catch (\Throwable $th) {
// $err = json_encode(['Error Message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trace' => $th->getTrace()]);
// $this->createFileJson($path, "\r Alert Error => $err \r");
// return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)->respondWithError($err, WebService::HTTP_CODE_INTERNAL_ERROR);
// }
}
/**
* @param type $em
* @param type $userTypePointAccount
*/
public function markAsNoOtherTransactionInProgress($em, $userTypePointAccount) {
$userTypePointAccount = $em->getRepository('App\Entity\PointAcount')->find($userTypePointAccount->getId());
$userTypePointAccount->setIsBlockedByOtherTransaction(false);
$em->persist($userTypePointAccount);
$em->flush();
}
/**
* @param type $em
* @param type $userTypePointAccount
* @return type
*/
public function vaidateIfAnotherTransactionIsInProgress($em, $userTypePointAccount, $params) {
if (!isset($userTypePointAccount[0])) {
return 'No point account found for customer!';
} else {
$userTypePointAccount = $userTypePointAccount[0];
}
if ($userTypePointAccount->getIsBlockedByOtherTransaction()) {
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['msg'] = '';
$processedArrayResponse = $this->processEvaluatedTransactionResponse('other point transaction is being processed for this account, please wait a few minutes..', $params);
$responseArray = array_merge($responseArray, $processedArrayResponse);
return $responseArray;
} else {
$userTypePointAccount->setIsBlockedByOtherTransaction(true);
$em->persist($userTypePointAccount);
$em->flush();
}
return $userTypePointAccount;
}
/**
* @param PointRelatedRequest $pointCreatedResult
* @return type
*/
public function startAllTheCommandToRabbitTransactionProcess($pointCreatedResult, $path) {
if ($pointCreatedResult instanceof PointRelatedRequest) {
$kernel = $this->get('real_kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'level:duce:point_transaction',
'pointRequestId' => $pointCreatedResult->getId()
]);
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
$this->createFileJson($path, 'Producer command response: ' . $content . "\r");
sleep(1);
$input2 = new ArrayInput([
'command' => 'level:nsume:point_transaction',
'pointRequestId' => $pointCreatedResult->getId()
]);
// You can use NullOutput() if you don't need the output
$output2 = new BufferedOutput();
$application->run($input2, $output2);
// return the output, don't use if you used NullOutput()
$content2 = $output->fetch();
$this->createFileJson($path, 'Consumer command response: ' . $content2 . "\r");
} else {
return $pointCreatedResult;
}
return true;
}
/**
* @param type $em
* @param type $theTransactionToCheck
* @param type $path
* @return boolean
*/
public function pollingAskingIfPointTransactionWasProcessed($em, $theTransactionToCheck, $path) {
$responseToPolling = [];
$auxCounter = 0;
$keepInWhile = true;
$this->createFileJson($path, 'Checking if point transaction was concluded....' . "\r");
$this->createFileJson($path, 'Checking -> ' . $theTransactionToCheck->getId() . "\r");
do {
sleep(4);
++$auxCounter;
$theTransactionToCheck = $em->getRepository('App\Entity\PointRelatedRequest')->find($theTransactionToCheck->getId());
$responseToPolling['theTransaction'] = $theTransactionToCheck;
if ($theTransactionToCheck->getStatus() == RabbitRelatedGenericEntity::STATUS_PROCCESSED) {
$keepInWhile = false;
$responseToPolling['msg'] = 'Transaction processed.. going forward whith the delivery!';
$this->createFileJson($path, 'Transaction processed.. going forward whith the delivery!' . "\r");
$responseToPolling['wasProcessed'] = true;
} elseif ($auxCounter > 7) {
$keepInWhile = false;
if ($theTransactionToCheck->getStatus() < RabbitRelatedGenericEntity::STATUS_PROCCESSED) {
$responseToPolling['msg'] = 'Maximum waiting reached for a processed point transaction, aborting!';
$this->createFileJson($path, 'Maximum waiting reached for a processed point transaction, aborting!' . "\r");
$responseToPolling['wasProcessed'] = false;
}
} else {
$responseToPolling['msg'] = 'Waiting for transaction to be processed..';
$responseToPolling['wasProcessed'] = false;
$this->createFileJson($path, "$auxCounter try, asking again..." . "\r");
}
} while ($keepInWhile);
return $responseToPolling;
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createOmtClientAndPointsAccountsRecord(Request $request, ArmorService $armor, Log $log) {
if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT)) {
if (0 !== strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE)) {
return $this->errorWrongArgs('Wrong content');
}
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'omtClientAndPointsAccountsRecord', 'omtClientAndPointsAccountsRecord0.txt');
$this->createFileJson($path, "\r" . 'omtClient Ask: ' . $request->getContent() . "\r");
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$params = json_decode($arrayEncryptResult['data'], true);
$this->createFileJson($path, 'Push Responded decode params: ' . $arrayEncryptResult['data'] . "\r");
if (!isset($params['nickname']) || !isset($params['uid']) || !isset($params['countryCode'])) {
$this->createFileJson($path, 'posiblement falte parametro nickname, uid o countryCode' . "\r");
return $this->errorWrongArgs('Wrong Arguments');
}
$em = $this->getDoctrine()->getManager();
$countryData = $em->getRepository('App\Entity\Country')->findBy(['coVal' => $params['countryCode']]);
if (!isset($countryData[0])) {
$this->createFileJson($path, 'Contry code not found!' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Contry code not found!', WebService::CODE_ACCOUNT_SUSPENDED);
} else {
$this->createFileJson($path, 'Contry code exist!' . "\r");
$countryData = $countryData[0];
}
$data = ['alLicenseUsername' => $params['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
$countResult = count($accountLicenseData);
$this->createFileJson($path, 'busqueda del restaurante por nickname' . "\r");
$validate = $this->validateLicense($countResult, $path, $accountLicenseData);
if(!$validate["status"]) {
$this->createFileJson($path, 'licencia no eliminada logicamente' . "\r");
return $this->setStatusCode($validate["status"])
->respondWithError($validate["message"], $validate["code"]);
}
$this->createFileJson($path, 'licencia activa' . "\r");
if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
$this->createFileJson($path, 'UID diferente! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
if(isset($params['phone'])){
$this->createFileJson($path, 'special characters removed in phone' . "\r");
$tmpPhoneClient = preg_replace('/[^0-9]/', "", $params['phone']);
$tmpPhoneClient = Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
$this->createFileJson($path, 'before ' .$params['phone']. ' ,after '.$tmpPhoneClient. "\r");
$params['phone'] = $tmpPhoneClient;
}
$this->createFileJson($path, 'validacion metodo put' . "\r");
if ($request->getMethod() === WebService::REQUEST_METHOD_PUT) {
$params['alLicenseUsername'] = $params['nickname'];
return $this->updateDataOmtClient($params, $path);
}
$this->createFileJson($path, 'ya termino... sigue ..' . "\r");
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
$uniqueValidationArray = [];
$this->createFileJson($path, 'consulta en RestaurantLoyaltyConfiguration' . "\r");
$loyaltyConfiguration = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findOneBy(['license' => $accountLicenseData[0]->getId()]);
if (is_null($loyaltyConfiguration)) {
$loyaltyConfiguration = new RestaurantLoyaltyConfiguration();
$loyaltyConfiguration->setDateCreated(new \DateTime('now'));
$loyaltyConfiguration->setUseLocalPoints(false);
$loyaltyConfiguration->setUseGlobalPoints(false);
$loyaltyConfiguration->setMinimumPointAmountToExchange(1);
$loyaltyConfiguration->setLicense($accountLicenseData[0]);
$em->persist($loyaltyConfiguration);
$em->flush();
}
$this->createFileJson($path, 'Entering into the pit...1 o.O!' . "\r");
if (isset($params['lastFour'])) {
$requiredFields = [
"nameOnCard",
"franchise",
"lastFour"
];
$fieldValidations = $this->validateParams($request, $requiredFields);
$params = $this->getContentInRequest($request);
if(isset($params['phone'])){
$this->createFileJson($path, 'special characters removed ' . "\r");
$tmpPhoneClient = preg_replace('/[^0-9]/', "", $params['phone']);
$tmpPhoneClient = Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
$this->createFileJson($path, 'before ' .$params['phone']. ' ,after '.$tmpPhoneClient. "\r");
$params['phone'] = $tmpPhoneClient;
}
// Validamos que se envien lios campos requeridos
if ($fieldValidations !== true) {
return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
->respondWithError($fieldValidations, WebService::CODE_WRONG_ARGUMENTS);
}
$perhapsUniqueUserName = str_replace(' ', '_', strtolower(explode(' ', $params['nameOnCard'])[0] . '_' . $params['franchise'] . '_' . $params['lastFour']));
$uniqueValidationArray = ['username'];
$params['username'] = $perhapsUniqueUserName;
} else {
$requiredFields = [
"phone"
];
$fieldValidations = $this->validateParams($request, $requiredFields);
$params = $this->getContentInRequest($request);
if(isset($params['phone'])){
$this->createFileJson($path, 'special characters removed ' . "\r");
$tmpPhoneClient = preg_replace('/[^0-9]/', "", $params['phone']);
$tmpPhoneClient = Utilx::clearEspecialCharactersFromPhone($tmpPhoneClient);
$this->createFileJson($path, 'before ' .$params['phone']. ' ,after '.$tmpPhoneClient. "\r");
$params['phone'] = $tmpPhoneClient;
}
/**
* Validamos que se envien lios campos requeridos
*/
if ($fieldValidations !== true) {
return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
->respondWithError($fieldValidations
, WebService::CODE_WRONG_ARGUMENTS);
}
$uniqueValidationArray = ['username', 'email', 'phone'];
if (!isset($params['username'])) {
if (isset($params['name'])) {
// se reemplaza los espacios en blanco del nombre por guion bajo
$usernamesufix = str_replace(' ', '_', $params['name']) . '_' . Utilx::randomPassword(3);
} else {
$usernamesufix = 'NoName_' . Utilx::randomPassword(5);
}
$params['username'] = $usernamesufix;
}
}
$this->createFileJson($path, 'Entering into the pit...2 o.O!' . "\r");
$clientController = new ClientController($this->realContainer);
$nickUsername = Utilx::replaceCharactersEspecials($params['name']);
$nickUsername = strtolower(substr($nickUsername, 0, 8) . '_');
$repositoryClients = $em->getRepository('App\Entity\OmtClient');
$countClients = $repositoryClients->counting();
$this->createFileJson($path, 'number of OMTClient records ' .$countClients. "\r");
$nickUsername .= uniqid() ."_". $countClients;
$lastParamsNotSend = $params;
if (!isset($params['lastname']) || $params['lastname'] == '') {
$params['lastname'] = "(temporal lastname)";
}
if (!isset($params['username']) || $params['username'] == '') {
$params['username'] = $nickUsername;
}
if (!isset($params['email']) || $params['email'] == '') {
$email = NewUtil::generateEmailGeneric($params['name'], $repositoryClients, $path);
// $nickUsername . "@gmail.com";
$params['email'] = $email;
$lastParamsNotSend['email'] = $email;
}
unset($params['uid'], $params['countryCode']);
if (isset($params['clientId'])) {
$auxOmtClient = $em->getRepository('App\Entity\OmtClient')->find($params['clientId']);
if($auxOmtClient && $auxOmtClient->getOmtUserId()){
$params['omtClientId'] = $auxOmtClient->getOmtUserId();
}
}
// debido a que dos funciones que crean usuario loyalty se agregan parametros para que haya igualdad en el body de ambos webservices
$params['alLicenseUsername'] = $params['nickname'];
$params['companyName'] = 'omt';
$params['phone_2'] = '';
$params['fromLicensor'] = true;
unset($params['clientId']);
unset($params['nickname']);
unset($params['langCode']);
// se valida que el teléfono y el email no este utilizados por un cliente en OMTWS
$this->createFileJson($path, "\r" . 'parameters to send to isPhoneAndEmailUsingAtOMT => ' . json_encode(['phone' => $params['phone'], 'email' => $params['email']]) . "\r");
$tmpValidOMT = $clientController->isPhoneAndEmailUsingAtOMT($this->realContainer, $params['phone'], $params['email']);
$this->createFileJson($path, "\r" . 'isPhoneAndEmailUsingAtOMT => ' . json_encode($tmpValidOMT) . "\r");
if (isset($tmpValidOMT['data']['message'])){
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError($tmpValidOMT['data']['message'], WebService::CODE_COULD_NOT_AUTHENTICATE);
}
// se envia la peticion para crear el usuario a OMTWS
$responseCreationUserOmt = $clientController->createNewUserLoyaltyInOmtWsFromAndroid($this->realContainer, $params);
$this->createFileJson($path, 'Creation from omtws, response => '. json_encode($responseCreationUserOmt) . "\r");
$existErrorCreationUserOmt = $clientController->existErrorsWhenCreateUserLoyaltyInOmtWs($responseCreationUserOmt);
if (isset($existErrorCreationUserOmt['error']) && $existErrorCreationUserOmt['error']){
return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
->respondWithError($existErrorCreationUserOmt['message'], WebService::HTTP_CODE_BAD_REQUEST);
}
$params = $lastParamsNotSend;
$clientOmt = null;
$omtClientRepo = $em->getRepository('App\Entity\OmtClient');
$clientToUpdateDirect = null;
if (isset($params['clientId'])) {
$clientToUpdateDirect = $omtClientRepo->find($params['clientId']);
}
if (is_null($clientToUpdateDirect) && isset($params['email']) && $params['email'] != '') {
$clientToUpdateDirect = $omtClientRepo->findOneBy(['email' => $params['email']]);
}
$this->createFileJson($path, 'Entering into the pit...3 o.O!' . "\r");
$nicknameCliData = null;
foreach ($uniqueValidationArray as $uniqueFieldToValidate) {
if (isset($params[$uniqueFieldToValidate])) {
$nicknameClientSearch = [$uniqueFieldToValidate => $params[$uniqueFieldToValidate]];
$nicknameCliData = $omtClientRepo->findBy($nicknameClientSearch);
$this->createFileJson($path, 'checking if user exists ' .json_encode($nicknameClientSearch). "\r");
if (isset($nicknameCliData[0])) {
$clientOmt = $nicknameCliData[0];
$this->createFileJson($path, 'yes, the customer exists with the ID '. $clientOmt->getId().' ' .$clientOmt. "\r");
break;
}
}
}
$unexpectedEditFlag = false;
/**
* Esta condicion permite validar si el cliente que va a ser creado
* tiene el email y el telefono valido lo deja crear de lo contrario
* le retorna un mensaje con su respectivo error
*/
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'] !== ""))) {
if (isset($params['email'])) {
$existClientByEmail = $omtClientRepo->findBy(['email' => $params['email']]);
}
if (isset($params['phone'])) {
$existClientByPhone = $omtClientRepo->findBy(['phone' => $params['phone']]);
}
if (isset($existClientByEmail[0]) && $existClientByEmail[0]->getLastname() == 'Default GiftCard Customer') {
$this->createFileJson($path, 'Invalid email' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid email', WebService::CODE_ERR_CONFLICT);
}
if (isset($existClientByPhone[0]) && $existClientByPhone[0]->getLastname() == 'Default GiftCard Customer') {
$this->createFileJson($path, 'Invalid phone number' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid phone number', WebService::CODE_ERR_CONFLICT);
}
if (isset($existClientByEmail[0]) && isset($existClientByPhone[0]) && $existClientByPhone[0]->getId() != $existClientByEmail[0]->getId()) {
unset($params['email']);
}
if (isset($existClientByPhone[0])) {
$typePointAccountByClient = $em->getRepository('App\Entity\TypePointAcount')->findUserPtAccount($existClientByPhone[0]->getId(), TypePoint::WORK_AS_LOCAL, $accountLicenseData[0]->getId());
if (!$clientOmt) {
$clientOmt = $existClientByPhone[0];
}
if (!isset($typePointAccountByClient[0])) {
$unexpectedEditFlag = true;
} else {
if (isset($existClientByEmail[0])) {
$responseArr['status'] = WebService::CODE_WRONG_ARGUMENTS;
if (isset($existClientByEmail[0]) && isset($params['omtUserId']) && $existClientByEmail[0]->getOmtUserId() == $params['omtUserId'] && isset($params['omtUserUsername']) && $existClientByEmail[0]->getOmtUserUsername() == null) {
$existClientByEmail[0]->setOmtUserUsername($params['omtUserUsername']);
$em->persist($existClientByEmail[0]);
$em->flush();
}
$responseArr['msg'] = 'Email is already in use!';
$this->createFileJson($path, 'Email is already in use!' . "\r");
$responseArr['idClient'] = $existClientByEmail[0]->getId();
} elseif (isset($existClientByPhone[0])) {
if (isset($existClientByPhone[0]) && isset($params['omtUserId']) && $existClientByPhone[0]->getOmtUserId() == $params['omtUserId'] && isset($params['omtUserUsername']) && $existClientByPhone[0]->getOmtUserUsername() == null) {
$existClientByPhone[0]->setOmtUserUsername($params['omtUserUsername']);
$em->persist($existClientByPhone[0]);
$em->flush();
}
$responseArr['status'] = WebService::CODE_ERR_CONFLICT;
$responseArr['msg'] = 'The user could not be created!';
$this->createFileJson($path, 'The user could not be created!' . "\r");
return $this->setStatusCode($responseArr['status'])
->respondWithError($responseArr['msg'], WebService::CODE_ERR_CONFLICT);
}
if (isset($existClientByEmail) && $existClientByEmail !== []) {
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
} else {
if (isset($existClientByEmail[0])) {
$responseArr['status'] = WebService::CODE_WRONG_ARGUMENTS;
$responseArr['msg'] = 'Email is already in use!';
$this->createFileJson($path, 'Email is already in use!' . "\r");
$responseArr['idClient'] = $existClientByEmail[0]->getId();
}
if (isset($existClientByEmail) && $existClientByEmail !== []) {
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
}
$copyLoyaltyUserIntoOMT = false;
$this->createFileJson($path, '!$clientOmt'. !$clientOmt . "\r");
if (!$clientOmt) {
if ($nicknameCliData) {
$this->createFileJson($path, 'Username invalid' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Username invalid', WebService::CODE_ACCOUNT_SUSPENDED);
}
$copyLoyaltyUserIntoOMT = true;
$clientOmt = new OmtClient();
//$params['id'] = UUIDGeneratorUtil::getUUIDv4();
// se le asigna la llave primaria del usuario de omtws
$params['id'] = $responseCreationUserOmt['data']['id'];
$this->createFileJson($path, 'UUID generated!: ' .$params['id']. "\r");
$clientOmt->setId($params['id']);
if (isset($params['omtUserId'])) {
$clientOmt->setOmtUserId($params['omtUserId']);
}
if (isset($params['omtUserUsername'])) {
$clientOmt->setOmtUserUsername($params['omtUserUsername']);
}
$responseArr['msg'] = 'Omt User created successfully!';
$this->createFileJson($path, 'Omt User created successfully!' . "\r");
} else {
$this->createFileJson($path, 'the customer already exists debuger'. "\r");
if ($unexpectedEditFlag) {
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Omt client created for restaurant successfully!';
$this->createFileJson($path, 'Omt client created for restaurant successfully!' . "\r");
} else {
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Omt client update successfully!';
$this->createFileJson($path, 'Omt client update successfully!' . "\r");
}
}
$indexExistenceToValidate = ['lastFour', 'expirationDate', 'nameOnCard', 'franchise'];
$indexInexistenceToValidate = ['name', 'lastname', 'email', 'birthdate', 'phone'];
$isCardParams = $this->paramsArrayIndexValidator($params, $indexExistenceToValidate);
$isCustomerParams = $this->paramsArrayIndexValidator($params, $indexInexistenceToValidate, false);
$newCardAsClient = false;
if ($isCardParams[0] && $isCustomerParams[0]) {
$this->createFileJson($path, 'entered into ($isCardParams[0] and $isCustomerParams[0]) debug' . "\r");
$fullCombined = $params['nameOnCard'] . '_' . $params['lastFour'] . '_' . $params['franchise'] . '_' . $params['expirationDate'];
$fullCombined = str_replace(' ', '_', strtolower(str_replace('/', '-', $fullCombined)));
$cardAsClienteRecord = $em->getRepository('App\Entity\CardAsClient')->findBy(['uniqueCombined' => $fullCombined]);
if (isset($cardAsClienteRecord[0])) {
$this->createFileJson($path, 'exist $cardAsClienteRecord[0] debug' . "\r");
$responseArr['msg'] = 'Omt User updated successfully!';
$clientOmt = $em->find('App\Entity\OmtClient', $cardAsClienteRecord[0]->getClient());
} else {
$this->createFileJson($path, 'not exist $cardAsClienteRecord[0] debug' . "\r");
$newCardAsClient = true;
$params['theCombined'] = $fullCombined;
$perhapsUniqueUserName = str_replace(' ', '_', strtolower(explode(' ', $params['nameOnCard'])[0] . '_' . $params['franchise'] . '_' . $params['lastFour']));
$clientOmt->setName($params['nameOnCard']);
$clientOmt->setUsername($perhapsUniqueUserName);
$clientOmt->setBirthdate(\DateTime::createFromFormat('d/m/Y', '01/' . $params['expirationDate']));
}
} else {
$this->createFileJson($path, 'not entered into ($isCardParams[0] and $isCustomerParams[0]) elde debug' . "\r");
if (isset($params['name'])) {
$clientOmt->setName($params['name']);
}
if (isset($params['lastname'])) {
$clientOmt->setLastname($params['lastname']);
}
if (isset($params['email']) && $params['email'] !== "") {
// Se valida que el correo tenga un dominio valido y se agrega la excepción del dominio por defecto
if (!NewUtil::emailContainsGenericDomain($params['email'], $path) && !$this->validateFullEmail($params['email'])) {
return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
->respondWithError("The email ". $params['email'] ." is not a valid", WebService::HTTP_CODE_BAD_REQUEST);
}
$clientOmt->setEmail($params['email']);
} else {
$clientOmt->setEmail(null);
}
if (isset($params['username']) && $params['username'] != '') {
$clientOmt->setUsername($params['username']);
} else {
$clientOmt->setUsername(null);
}
if (!isset($params['birthdate'])) {
$params['birthdate'] = Util::getCurrentDate()->format('d/m/Y');
}
$clientOmt->setBirthdate(\DateTime::createFromFormat('d/m/Y', $params['birthdate']));
if (isset($params['phone']) && !isset($existClientByPhone[0])) {
$phoneClient = preg_replace('/[^0-9]/', "", $params['phone']);
$phoneClient = Utilx::clearEspecialCharactersFromPhone($phoneClient);
$clientOmt->setPhone($phoneClient);
}
}
if (isset($params['userPhoneOrder']) && $clientOmt->getUserPhoneOrder() == null) {
$clientOmt->setUserPhoneOrder($params['userPhoneOrder']);
}
if (isset($params['langCode']) && $params['langCode'] != ''){
$clientOmt->setLangCode($params['langCode']);
}else{
$clientOmt->setLangCode(null);
}
$clientOmt->setOmtUserId($responseCreationUserOmt['data']['id']);
$clientOmt->setDefaultEmail(isset($params['defaultEmail']) && $params['defaultEmail'] != '' ? $params['defaultEmail'] : 0 );
$this->createFileJson($path, 'before of create client_omt debug' . "\r");
$em->persist($clientOmt);
$em->flush();
$this->createFileJson($path, 'after of create client_omt debug' . "\r");
if ($newCardAsClient) {
$this->createFileJson($path, 'entered into $newCardAsClient debug' . "\r");
Utilx::createCardAsLoyalClientRecord($em, $params, $clientOmt, $path);
}
$clientPointSearch = ['omtClient' => $clientOmt->getId()];
$clientPointAccount = $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
if (!isset($clientPointAccount[0])) {
$this->createFileJson($path, 'exist $cardAsClienteRecord[0] debug' . "\r");
$pointAccountData = new PointAcount();
$pointAccountData->setId($clientOmt->getId());
$baseToken = ['food' => '123'];
while (!empty($baseToken)) {
$this->createFileJson($path, 'generating new token for PointAcount debug' . "\r");
$token = Utilx::randomPassword(32);
$baseToken = $em->getRepository('App\Entity\PointAcount')->findBy(['basePointacount' => $token]);
}
$pointAccountData->setBasePointacount($token);
$pointAccountData->setActivationDate(new \DateTime('now'));
$clientPointAccount[0] = $pointAccountData;
} else {
$this->createFileJson($path, 'not exist $cardAsClienteRecord[0] debug' . "\r");
$pointAccountData = $clientPointAccount[0];
}
$pointAccountData->setOmtClient($clientOmt->getId());
$this->createFileJson($path, 'before of create PointAcount debug'. "\r");
$em->persist($pointAccountData);
$em->flush();
$this->createFileJson($path, 'after of create PointAcount debug'. "\r");
if (isset($params['email']) && isset($params['copyAsOMTClient']) && $copyLoyaltyUserIntoOMT) {
$this->createFileJson($path, 'Ready to make loyalty user cUrl request to OMT!' . "\r");
$randomOmtDashboardUserRawPass = Utilx::randomPassword(7);
$clientOmt->setTemporalOMTPass($randomOmtDashboardUserRawPass);
$requestResult = Util::copyLoyaltyUserToOMT($this->realContainer, $em, $clientOmt, $params['countryCode'], $path);
$this->createFileJson($path, 'Loyalty user to OMT request response -> ' . json_encode($requestResult) . "\r");
}
$typePointData = $em->getRepository('App\Entity\TypePoint')->findTypePointDefault();
foreach ($typePointData AS $typePoint) {
$tpData = $em->getRepository('App\Entity\TypePoint')->find($typePoint['id']);
if ($typePoint['type'] == TypePoint::TYPE_GLOBAL) {
$typePointAccountArray = $em->getRepository('App\Entity\TypePointAcount')->findBy(['typePoint' => $typePoint['id'], 'pointAcount' => $pointAccountData->getId()]);
} else {
$typePointAccountArray = $em->getRepository('App\Entity\TypePointAcount')->findBy(['typePoint' => $typePoint['id'], 'pointAcount' => $pointAccountData->getId(), 'license' => $accountLicenseData[0]->getId()]);
}
if (isset($typePointAccountArray[0])) {
$typePointAccountData = $typePointAccountArray[0];
} else {
$typePointAccountData = new TypePointAcount();
$acountToken = ['food' => '123'];
while (!empty($acountToken)) {
$tokenAcount = Encryptor::encodeInfo(Utilx::randomPassword(32), 5);
$acountToken = $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
}
$typePointAccountData->setAmount(0);
$typePointAccountData->setAcountToken($tokenAcount);
$typePointAccountData->setStartingDate(new \DateTime('now'));
$typePointAccountData->setPointArmAcount('Pepito Habla Ingles!');
}
$typePointAccountData->setTypePoint($tpData);
$typePointAccountData->setPointAcount($pointAccountData);
$typePointAccountData->setCountryId($countryData);
if ($typePoint['type'] != TypePoint::TYPE_GLOBAL) {
$typePointAccountData->setLicense($accountLicenseData[0]);
}
$this->createFileJson($path, 'before of create TypePointAcount debug'. "\r");
$em->persist($typePointAccountData);
$em->flush();
$this->createFileJson($path, 'after of create TypePointAcount debug'. "\r");
$log->createChannel('gift_card');
$arrayTypePointAccountTokenToArmor = PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData);
// dump($arrayTypePointAccountTokenToArmor);
// die;
$encodeBase = Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
$request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
$this->createFileJson($path, 'Armor request send: ' . $request . "\r");
$url = $this->realContainer->getParameter('armor_host') . 'point/add-points';
$this->createFileJson($path, 'Armor URL: ' . $url . "\r");
$dataResponse = $armor->armorPost($request, $url, $log);
if ($dataResponse instanceof Response) {
$jsonResponse = $dataResponse->getContent();
$this->createFileJson($path, 'Armor response instance: ' . $jsonResponse . "\r");
$decodedResponse = json_decode($jsonResponse, true);
if (isset($decodedResponse['data'])) {
$neededArmorId = $decodedResponse['data']['points_id'];
$typePointAccountData->setArmIdentifier($neededArmorId);
$em->persist($typePointAccountData);
$em->flush();
}
} else {
$this->createFileJson($path, 'Armor response: ' . $dataResponse . "\r");
}
/*
*
{
"type_point": "5555aaaa-aaaa-5555-aaaa-bdbca33ee555",
"starting_date": "1409175049",
"country": "US",
"account_token": "411dfg111114444",
"amount": "1200",
"identifier": "b06b66b6-6ad6-6666-6af6-bdbca66ee66"
}
*
*/
}
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
//dump($loyaltyConfiguration[0]->getMinimumPointAmountToExchange());
//die;
//if ($loyaltyConfiguration[0]->getUseGlobalPoints()) {
$pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByClient(['idClient' => $clientOmt->getId(), 'restaurant' => $accountLicenseData[0]->getId()], [], true, $loyaltyConfiguration->getMinimumPointAmountToExchange());
//} else {
// $pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByClient(['idClient' => $clientOmt->getId(), 'restaurant' => $accountLicenseData[0]->getId()], []);
//}
// if (!isset($pointAccountByClient['name'])) {
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('customer not found', WebService::CODE_COULD_NOT_AUTHENTICATE);
// }
// $responseAddAddressNewUser = $clientController->createAddressDummyInOmtWs($this->realContainer, $responseCreationUserOmt['data']['id'], [], $clientOmt->getId());
// if (isset($responseAddAddressNewUser['errors'])) {
// return $this->setStatusCode(WebService::HTTP_CODE_BAD_REQUEST)
// ->respondWithError($responseAddAddressNewUser['errors']['message'], WebService::HTTP_CODE_BAD_REQUEST);
// }
if (isset($pointAccountByClient['accounts'][0])) {
$responseArr['msg'] .= ', list of points by client';
$this->createFileJson($path, 'list of points by client' . "\r");
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['client'] = $pointAccountByClient['accounts'][0];
$responseArr['bigbag'] = true;
} else {
$responseArr['msg'] = 'No client found with the given data';
$this->createFileJson($path, 'No client found with the given data' . "\r");
$responseArr['status'] = WebService::CODE_SUCCESS;
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
$this->createFileJson($path, 'WS ends' . "\r");
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
private function updateDataOmtClient($params, $path){
$em = $this->getDoctrine()->getManager();
$omtClientRepo = $em->getRepository('App\Entity\OmtClient');
$clientToUpdateDirect = null;
if (isset($params['clientId'])) {
$clientToUpdateDirect = $omtClientRepo->find($params['clientId']);
}
if (is_null($clientToUpdateDirect) && isset($params['email']) && $params['email'] != '') {
$clientToUpdateDirect = $omtClientRepo->findOneBy(['email' => $params['email']]);
}
if (!is_null($clientToUpdateDirect)) {
$params['userId'] = $clientToUpdateDirect->getId();
$url = $this->realContainer->getParameter('level_scheme') . '://' . $this->realContainer->getParameter('level_host') . $this->generateUrl('data_users_loyalty_update');
// . '?'. http_build_query($params);
$paramsToSend = json_encode($params);
$this->createFileJson($path, 'data before to send' . "\r");
$this->createFileJson($path, 'params => '. $paramsToSend . "\r");
$this->createFileJson($path, 'url => '. $url ."\r");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, WebService::REQUEST_METHOD_PUT);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsToSend);
$result = curl_exec($ch);
$this->createFileJson($path, 'result of curl the function updateDataOmtClient => '. $result ."\r");
$decodeResult = json_decode($result, true);
return $this->respondJsonAjax($decodeResult);
}else{
return $this->setStatusCode(WebService::CODE_ERR_CONFLICT)
->respondWithError('Client not located to update', WebService::HTTP_CODE_BAD_REQUEST);
}
}
/**
* @param Request $request
* @return type
*/
public function chingoFuncionParaJhonier(Request $request, ArmorService $armor, Log $log) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'chingoFuncionParaJhonier', 'chingoFuncionParaJhonier0.txt');
$this->createFileJson($path, "\r" . 'omtClient Ask: ' . json_encode($request->query->all()) . "\r");
$em = $this->getDoctrine()->getManager();
$indexSearch = ['nickname','phone', 'email'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
$order = Paginator::filterPaginatorParameters([], $request, true);
// dd($search, $order);
$debug = $request->query->get('debug');
if ($debug) {
dump($search);
}
if (empty($search)) {
$this->createFileJson($path, "\r" . "invalid parameter name" . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid parameter name', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$data = ['alLicenseUsername' => $search['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
if (empty($accountLicenseData[0]))
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Coulnt find any license', WebService::CODE_COULD_NOT_AUTHENTICATE);
$countResult = count($accountLicenseData);
$validate = $this->validateLicense($countResult, $path, $accountLicenseData);
if(!$validate["status"]){
return $this->setStatusCode($validate["status"])
->respondWithError($validate["message"], $validate["code"]);
}
// if ($countResult <= 0) {
// $this->createFileJson($path, "\r" . "Invalid nickname or channelname" . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Invalid nickname or channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
// }
// $this->createFileJson($path, "\r" . "license found => ". $search['nickname'] . "\r");
// if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
// $this->createFileJson($path, "\r" . "Account is inactive" . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
// }
// if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
// $this->createFileJson($path, "\r" . "Inactive License" . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
// }
$loyaltyConfiguration = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $accountLicenseData[0]->getId()]);
$this->createFileJson($path, "\r" . "searching loyalty configuration with license id => ". $accountLicenseData[0]->getId() . "\r");
// if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
// $this->createFileJson($path, 'Loyalty functions not configured yet o.O' . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Loyalty functions not configured yet', WebService::CODE_ACCOUNT_SUSPENDED);
// } else
if (!isset($loyaltyConfiguration[0])) {
$this->createFileJson($path, 'Loyalty functions configuration record not found o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Loyalty functions configuration record not found!', WebService::CODE_ACCOUNT_SUSPENDED);
}
$log->createChannel('local_point_automatic_creation_log');
$search['restaurant'] = $accountLicenseData[0]->getId();
$responseArr = [];
if ($debug) {
dump($search, $order, $loyaltyConfiguration[0]->getMinimumPointAmountToExchange());
}
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
$typePointRepository = $em->getRepository('App\Entity\TypePoint');
$pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByRestaurant($request, $this->realContainer, $search, $order, $loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $accountLicenseData[0], $armor, $log, $path, false, $debug);
$this->createFileJson($path, "\r" . "validate and build paginator data" . "\r");
$paginatorFormatedData = $this->validateAndBuildPaginatorData($order, $pointAccountByClient);
// dump($paginatorFormatedData);
$info = $typePointRepository->getRatioPoints();
$this->createFileJson($path, "\r" . "pagination for data response" . "\r");
$responseArrWithPagination = $this->paginationForDataResponse($paginatorFormatedData['response'], $paginatorFormatedData['paginator']);
// dump($responseArrWithPagination);
$responseArrWithPagination['msg'] = "List of point accounts by '$accountLicenseData[0]' restaurant";
$responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
$responseArrWithPagination['clients'] = $pointAccountByClient['accounts'];
$responseArrWithPagination['info'] = $info;
$responseArrWithPagination['bigbag'] = true;
if(isset($search['restaurant']) && $search['restaurant'] != ''){
$loyaltyConfiguration = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->getStatusLoyaltyByRestaurand($search['restaurant']);
$responseArrWithPagination['loyaltyPoints'] = (boolean)$loyaltyConfiguration;
}
// dump(count($responseArrWithPagination['accounts']));
// dump(count($responseArrWithPagination['clients']));
// die;
if (isset($responseArrWithPagination['accounts'])) {
unset($responseArrWithPagination['accounts']);
}
if ($debug) {
die;
}
// $theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
// $xxArray = $theUrlTrSt->transform();
// $jsonContent = json_encode($xxArray);
// 1. Crear el transformer y procesar datos base
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
$xxArray = $theUrlTrSt->transform();
// 2. Obtener tokens solo si hay clientId válido
$baseUrl = $this->realContainer->getParameter('omt_ws_url') . "common/getTokenForUser";
$tokensData = null;
// dd($xxArray);
if (isset($xxArray['clients'][0]['clientId']) && !empty($xxArray['clients'][0]['clientId'])) {
$omtClient = $em->getRepository('App\Entity\OmtClient')->find($xxArray['clients'][0]['clientId']);
$this->createFileJson($path, "\r" . 'Token detectado: ' . json_encode(['clientd' => $xxArray['clients'][0]['clientId']]) . "\r");
if ($omtClient) {
$url = $baseUrl . '?loyaltyClientId=' . urlencode($omtClient->getOmtUserId());
$this->createFileJson($path, "\r" . 'Token detectado: '. "\r");
$this->createFileJson($path, "\r" . 'Usuario: ' . json_encode(['clientd' => $xxArray['clients'][0]['clientId'], 'omt_user' => $omtClient->getOmtUserId()]) . "\r");
$this->createFileJson($path, "\r" . 'Send request to omt ' . "\r");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($result !== false && $httpCode === 200) {
$this->createFileJson($path, "\r" . 'Armor response Ok: ' . $result . "\r");
$responseData = json_decode($result, true);
if (isset($responseData['data'])) {
$tokensData = $responseData['data'];
}
}
$this->createFileJson($path, "\r" . 'Armor Failed: ' . $result . "\r");
}
} else {
$this->createFileJson($path, "\r" . 'No token detected ' . "\r");
}
// 3. Construir respuesta final
$finalResponse = [
'data' => $xxArray // Datos base transformados
];
// Añadir tokens solo si existen
if ($tokensData !== null) {
$finalResponse['data']['clients'][0]['tokens'] = $tokensData;
}
// 4. Retornar respuesta
return $this->respondWithArray($finalResponse);
}
if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
$responseArrWithPagination['msg'] = "Good to go!";
$responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
$responseArrWithPagination['bigbag'] = false;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
*
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createPointAccount(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (strlen($data['omtClientId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid omtClientId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$em = $this->getDoctrine()->getManager();
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($data['id']);
$clientOmt = $em->getRepository('App\Entity\OmtClient')->find($data['omtClientId']);
if (!$clientOmt) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Omt client not found', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$clientPointSearch = ['omtClient' => $data['omtClientId']];
$clientPointAccount = $em->getRepository('App\Entity\PointAcount')->findBy($clientPointSearch);
$basePointSearch = ['basePointacount' => $data['basePointacount']];
$basePointAccount = $em->getRepository('App\Entity\PointAcount')->findBy($basePointSearch);
if ($basePointAccount && $basePointAccount[0]->getId() != $data['id']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid basePointAcount', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Point account update successfully!';
if (!$pointAccountData) {
$pointAccountData = new PointAcount();
$pointAccountData->setId($data['id']);
$responseArr['msg'] = 'Point account created successfully!';
}
$pointAccountData->setOmtClient($clientOmt->getId());
$pointAccountData->setBasePointacount($data['basePointacount']);
$pointAccountData->setActivationDate(new \DateTime($data['activationDate']));
$em->persist($pointAccountData);
$em->flush();
if ($clientPointAccount) {
$responseArr['msg'] .= ' User already has point account!';
}
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
*
* @param \Symfony\Component\HttpFoundation\Request $request datos de la solicitud
* @return Response Json con la informacion de respuesta
*/
public function createTypePointAccount(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_POST) {
$data = json_decode($request->getContent(), true);
if (strlen($data['typePoinId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid typePoinId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['pointAccountId']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid pointAccountId', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (strlen($data['id']) != 36) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid id', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$em = $this->getDoctrine()->getManager();
$typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->find($data['id']);
$accountTokenSearch = ['acountToken' => $data['accountToken']];
$accountTokenData = $em->getRepository('App\Entity\TypePointAcount')->findBy($accountTokenSearch);
if ($accountTokenData && $accountTokenData[0]->getId() != $data['id']) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid acountToken', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$typePointData = $em->getRepository('App\Entity\TypePoint')->find($data['typePoinId']);
$countrySearch = ['coVal' => $data['countryCode']];
$countryData = $em->getRepository('App\Entity\Country')->findBy($countrySearch);
if ($countryData) {
$countryData = $em->getRepository('App\Entity\Country')->find($countryData[0]->getCoId());
}
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($data['pointAccountId']);
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['msg'] = 'Type Point account update successfully!';
if (!$typePointAccountData) {
$typePointAccountData = new TypePointAcount();
$typePointAccountData->setId($data['id']);
$responseArr['msg'] = 'Type Point account created successfully!';
}
$typePointAccountData->setTypePoint($typePointData);
$typePointAccountData->setPointAcount($pointAccountData);
$typePointAccountData->setCountryId($countryData);
$typePointAccountData->setAmount($data['ptAmount']);
$typePointAccountData->setPointArmAcount($data['pointArmAccount']);
$typePointAccountData->setStartingDate(new \DateTime($data['startingDate']));
$typePointAccountData->setAcountToken($data['accountToken']);
$em->persist($typePointAccountData);
$em->flush();
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function listOfRules(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['uid', 'nickname'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
if (isset($search['uid']) && isset($search['nickname'])) {
$dataSearch = ['deviceUid' => $search['uid']];
$accountLicByUidData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
if (!$accountLicByUidData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid UID', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$dataSearch = ['alLicenseUsername' => $search['nickname']];
$accountLicByNicknameData = $em->getRepository('App\Entity\AccountLicense')->findBy($dataSearch);
if (!$accountLicByNicknameData) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicByNicknameData[0]->getId() != $accountLicByUidData[0]->getId()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname or uid', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicByUidData[0]) {
$search['id'] = $accountLicByUidData[0]->getId();
}
}
$listRules = $em->getRepository('App\Entity\PtsAdquiRedemRules')->listRules($search);
$responseArr['msg'] = 'List of rules';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['dataList'] = $listRules;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* WS generico para consultar el historial de transacciones punto central el cliente
* @author Felipe Bautista <aarango@kijho.com> 19/02/19
* @param Request $request
* @return type
*/
public function historyTransactionPoints(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['nickname', 'accountNickname', 'initialDate', 'endDate', 'typePoints', 'typeOfPurchase', 'page', 'limit'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
$historyTransaction = $em->getRepository('App\Entity\PointDeal')->searchHistoryTransation(null, $search);
$responseArr['msg'] = 'Transaction History';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['dataList'] = $historyTransaction;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* WS generico para consultar el historial de transacciones punto central el restaurante
* @author Felipe Bautista <aarango@kijho.com> 19/02/19
* @param Request $request
* @return type
*/
public function historyTransactionPointsByRestaurant(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['nickname', 'accountNickname', 'initialDate', 'endDate', 'typePoints', 'typeOfPurchase', 'page', 'limit'];
$search = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
$restaurant = $em->getRepository('App\Entity\AccountLicense')->searchRestaurant($search);
$historyTransaction = $em->getRepository('App\Entity\PointDeal')->searchHistoryTransationByRestaurant($restaurant, $search);
$responseArr['msg'] = 'Transaction History By Restaurants';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['dataList'] = $historyTransaction;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @author Felipe Bautista <aarango@kijho.com> 21/02/19
* @param Request $request
* @return type
*/
public function checkCards(Request $request) {
if ($request->getMethod() === WebService::REQUEST_METHOD_GET) {
$em = $this->getDoctrine()->getManager();
$indexSearch = ['uid', 'nickname', 'lastFour', 'expirationDate', 'nameOnCard', 'franchise', 'langCode', 'countryCode', 'page', 'limit'];
$data = Paginator::filterParameters($indexSearch, $request, Paginator::REQUEST_TYPE_REQUEST);
$cards = [];
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['countryCode'])) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
$nickname = $em->getRepository('App\Entity\AccountLicense')->findBy(['alLicenseUsername' => $data['nickname']]);
if (!isset($nickname) || $nickname == []) {
return $this->errorWrongArgs('nickname not found', WebService::CODE_WRONG_ARGUMENTS);
}
$uid = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
if (!isset($uid) || $uid == []) {
return $this->errorWrongArgs('uid not found', WebService::CODE_WRONG_ARGUMENTS);
}
if ($uid[0]->getId() !== $nickname[0]->getId()) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
$fullCombined = $data['nameOnCard'] . '_' . $data['lastFour'] . '_' . $data['franchise'] . '_' . $data['expirationDate'];
$fullCombined = str_replace(' ', '_', strtolower(str_replace('/', '-', $fullCombined)));
$cardClient = $em->getRepository('App\Entity\CardAsClient')->findBy(['uniqueCombined' => $fullCombined]);
if ($cardClient) {
$cards = $em->getRepository('App\Entity\CardAsClient')->searchForCardMatches($data, $fullCombined);
}
$responseArr['msg'] = 'Cards clients';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['cards'] = $cards;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
}
/**
* @param Request $request
* @return type
*/
public function adjustRefundPointsOrElse(Request $request, ArmorService $armor, Log $log) {
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if (!(0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
return $this->errorWrongArgs('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'AdjustRefundPointsOrElse', 'AdjustRefundPointsOrElse0.txt');
$this->createFileJson($path, "\r" . 'adjustRefundPointsOrElse fever XD ' . $request->getContent() . "\r");
$data = json_decode($request->getContent(), true);
if (!isset($data['nickname']) || !isset($data['uid']) || !isset($data['transactionCodes'])) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
$nicknameLicData = $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
if (empty($nicknameLicData)) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($nicknameLicData[0]->getDeviceUid() != $data['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $nicknameLicData[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
$this->createFileJson($path, 'UID diferente! o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
if ($nicknameLicData[0]->getAlAccountLicense()->getDeleted()) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive Account', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($nicknameLicData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
$responseArrayAux1['msg'] = '';
$responseArrayAux1['status'] = WebService::CODE_SUCCESS;
$responseArrayAux1['bigbag'] = true;
/////////
$armorPack = [
'request' => $request,
'service' => $armor,
'log' => $log
];
$isCancelationOfCanceledRecords = false;
if (strpos($request->getUri(), 'cancelOfCancelationPoint')) {
$isCancelationOfCanceledRecords = true;
}
$data['license'] = $nicknameLicData[0];
$data['isReopenCancelation'] = $isCancelationOfCanceledRecords;
$armorPack['isReopenCancelation'] = $isCancelationOfCanceledRecords;
if (isset($data['customerId'])) {
$armorPack['customerId'] = $data['customerId'];
}
// dump($request->getUri());
// dump($isCancelationOfCanceledRecords);
// die;
$isAdjustTransaction = false;
if (isset($data['transactionCodes']) && !empty($data['transactionCodes'])) {
$cancelationResponse = PointsUtilPorcessor::proccessBasicTypeCancel($this->realContainer, $em, $data, $armorPack, $path);
} else {
return $this->errorWrongArgs('Error in transactions parameter', WebService::CODE_WRONG_ARGUMENTS);
}
// dump($cancelationResponse);
// die;
/*
"nickname": "mauricet_311",
"uid": "d7ee572cd137dfb7",
"dealType": 4,
"customerId": "bc328962-4e8a-4437-a43d-59945b82d885",
"totalAmount": "33.90",
"watchedTime": "2018-01-24 16:48:14"
*/
$indexExistenceToValidate = ['transactionCodes', 'dealType', 'totalAmount', 'watchedTime', 'customerId'];
$isCardParams = $this->paramsArrayIndexValidator($data, $indexExistenceToValidate);
// dump($isCardParams);
if (isset($isCardParams[0]) && $isCardParams[0]) {
$isAdjustTransaction = true;
unset($data['transactionCodes']);
$responseArrayAux1['msg'] = 'Point transactions processed successfully!';
$pointEvaluationResult = PointsUtilPorcessor::analyzePointTransaction($this->realContainer, $em, $nicknameLicData[0], $data, $armorPack);
// dump($pointEvaluationResult);
// die;
$responseArrayAux2 = $this->processEvaluatedTransactionResponse($pointEvaluationResult, $data);
// dump($responseArrayAux2);
$responseArr = array_merge($responseArrayAux1, $responseArrayAux2);
// dump($responseArr);
// die;
} else {
// dump($cancelationResponse);
// die;
if (isset($cancelationResponse[0]) && is_string($cancelationResponse[0])) {
$responseArr['msg'] = $cancelationResponse[0];
$responseArr['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
$responseArr['bigbag'] = true;
} else {
$responseArr['msg'] = $cancelationResponse[0]['msg'];
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['bigbag'] = true;
unset($cancelationResponse[0]['msg']);
$responseArr['transactionsProcessed'] = $cancelationResponse[0];
}
// dump($responseArr);
}
// if (isset($data['customerId'])) {
// $userTypePointAccount = $em->getRepository('App\Entity\PointAcount')->findBy(['omtClient' => $data['customerId']]);
//
// $validationResponse = $this->vaidateIfAnotherTransactionIsInProgress($em, $userTypePointAccount, $data);
//
// if (is_array($validationResponse)) {
// $theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $validationResponse);
// $jsonTransform = $theUrlTrSt->transform();
//
// $jsonContent = json_encode($jsonTransform);
//
// return $this->respondWithItem($jsonContent, $theUrlTrSt);
// } elseif (is_string($validationResponse)) {
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError($validationResponse, WebService::CODE_ACCOUNT_SUSPENDED);
// }
// }
// $newIncomingPointTransaction = new PointRelatedRequest();
// if ($isAdjustTransaction) {
// $newIncomingPointTransaction->setType(PointRelatedRequest::TYPE_TRANSACTION_ADJUST);
// } else {
// $newIncomingPointTransaction->setType(PointRelatedRequest::TYPE_TRANSACTION_CANCEL);
// }
// dump($newIncomingPointTransaction);
// die;
// $pointCreatedResult = PointsUtilPorcessor::persistArrayForRequestCopy($em, $request, $nicknameLicData[0], $newIncomingPointTransaction, $data);
//
// $fullCommandCallFor = $this->startAllTheCommandToRabbitTransactionProcess($pointCreatedResult, $path);
//
// if (is_string($fullCommandCallFor)) {
// return $this->setStatusCode(WebService::HTTP_CODE_INTERNAL_ERROR)
// ->respondWithError($fullCommandCallFor, WebService::CODE_ERR_UNPROCESSABLE);
// }
//
// $pollingResult = $this->pollingAskingIfPointTransactionWasProcessed($em, $pointCreatedResult, $path);
// $this->createFileJson($path, 'The polling json result -> ' . json_encode($pollingResult) . "\r");
// if (isset($pollingResult['wasProcessed']) && $pollingResult['wasProcessed']) {
// $cancelationResponse = json_decode($pollingResult['theTransaction']->getJsonResponse(), true);
// } else {
// $cancelationResponse = [];
// }
$loyaltyConfiguration = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(['license' => $nicknameLicData[0]->getId()]);
if (isset($loyaltyConfiguration[0]) && (!$loyaltyConfiguration[0]->getUseLocalPoints() && !$loyaltyConfiguration[0]->getUseGlobalPoints())) {
$this->createFileJson($path, 'Loyalty functions not configured yet o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Loyalty functions not configured yet', WebService::CODE_ACCOUNT_SUSPENDED);
} elseif (!isset($loyaltyConfiguration[0])) {
$this->createFileJson($path, 'Loyalty functions configuration record not found o.O' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Loyalty functions configuration record not found!', WebService::CODE_ACCOUNT_SUSPENDED);
}
if (!$isAdjustTransaction && isset($cancelationResponse[1]) && $cancelationResponse[1]) {
$this->createFileJson($path, 'Processgin cacelation result!' . "\r");
} elseif ($isAdjustTransaction) {
$this->createFileJson($path, 'Processgin adjust result!' . "\r");
$responseArrayAux1['status'] = WebService::CODE_SUCCESS;
$responseArrayAux1['msg'] = 'Point transactions adjust processed successfully!';
// $responseArrayAux2 = $this->processEvaluatedTransactionResponse($cancelationResponse, $data);
$responseArr = array_merge($responseArrayAux1, $responseArrayAux2);
}
// dump($responseArr);
// die;
$order = Paginator::filterPaginatorParameters([], $request, true);
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
$pointAccountByClient = $pointAccountByClientRepository->findTypePointAccountByRestaurant(
$request, $this->realContainer, [
'restaurant' => $nicknameLicData[0]->getId(),
'client' => $cancelationResponse[1]
], $order, $loyaltyConfiguration[0]->getMinimumPointAmountToExchange(), $nicknameLicData[0]->getId(), $armor, $log, $path);
$responseArr['bigbag'] = true;
// $responseArr['status'] = WebService::CODE_SUCCESS;
// $responseArr['msg'] = $cancelationResponse[0]['msg'];
// unset($cancelationResponse[0]['msg']);
// $responseArr['transactionsProcessed'] = $cancelationResponse[0];
$responseArr['client'] = $pointAccountByClient['accounts'][0];
$this->createFileJson($path, 'The response array -> ' . json_encode($responseArr) . "\r");
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
// if (isset($validationResponse)) {
// $this->markAsNoOtherTransactionInProgress($em, $validationResponse);
// }
// $this->closePointTransactionProcessInRabbit($em, $pollingResult['theTransaction'], $path);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* @param type $em
* @param type $transactionRecord
* @param type $path
* @return boolean
*/
public function closePointTransactionProcessInRabbit($em, $transactionRecord, $path) {
try {
$transactionRecord->setDateDelivered(Util::getCurrentDate());
$transactionRecord->setStatus(RabbitRelatedGenericEntity::STATUS_DELIVERED);
$em->persist($transactionRecord);
$em->flush();
$this->createFileJson($path, 'Transaction status updated!' . "\r");
return true;
} catch (\Exception $ex) {
Utilx::updateSyncRecordError($this->em, $this->thePointTransactionRecord, $ex->getMessage());
$this->createFileJson($path, 'Error updating transaction record! ' . $ex->getMessage() . "\r");
return false;
}
}
/**
* @param string $pointEvaluationResult
* @param type $params
* @return type
*/
public function processEvaluatedTransactionResponse($pointEvaluationResult, $params) {
if (is_array($pointEvaluationResult)) {
if (isset($pointEvaluationResult[0]) && count($pointEvaluationResult) == 1 && isset($pointEvaluationResult[0]['nonAplicationMsg'])) {
if ($pointEvaluationResult[0]['nonAplicationMsg'] == 'Little remaining amount to proccess') {
$responseArray['msg'] = 'No point achieved with the remaining amount.. ';
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['approvedPointsTransactions'] = [];
} elseif (strpos($pointEvaluationResult[0]['nonAplicationMsg'], 'inumum amount purchase')) {
$responseArray['msg'] = 'No point achieved because minimum purchase amount not reached.. ';
$responseArray['status'] = WebService::CODE_SUCCESS;
$responseArray['approvedPointsTransactions'] = [];
} else {
if (strpos($pointEvaluationResult[0]['nonAplicationMsg'], 'enough points!')) {
$responseArray['msg'] = $pointEvaluationResult[0]['nonAplicationMsg'];
$responseArray['status'] = WebService::HTTP_CODE_PAYMENT_REQUIRED;
} else {
$responseArray['msg'] = $pointEvaluationResult[0]['nonAplicationMsg'];
$responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
}
}
} elseif (isset($pointEvaluationResult[0]) && count($pointEvaluationResult) == 1 && ($params['dealType'] == TypePtsGenericDefinitionRules::TYPE_PURCHASE_WITH_LOCAL_PTS || $params['dealType'] == TypePtsGenericDefinitionRules::TYPE_PURCHASE_WITH_GLOBAL_PTS)) {
$responseArray['approvedPointsTransactions'] = $pointEvaluationResult[0];
} elseif (empty($pointEvaluationResult)) {
$responseArray['msg'] = 'No point transactions were made.. ';
$responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
} else {
$responseArray['approvedPointsTransactions'] = $pointEvaluationResult;
}
} else {
if (strpos($pointEvaluationResult, 'please try again later')) {
$responseArray['msg'] = 'Insufficient Loyalty Cash balance to redeem the order.. ' . $pointEvaluationResult;
$responseArray['status'] = WebService::CODE_ERR_NOT_FOUND;
} else {
$responseArray['msg'] = 'Insufficient Loyalty Cash balance to redeem the order.. ' . $pointEvaluationResult;
$responseArray['status'] = WebService::CODE_SUCCESS_NOT_MODIFIED;
}
}
$responseArray['bigbag'] = true;
return $responseArray;
}
/**
* @author Felipe Bautista <aarango@kijho.com> 22/02/19
* @param Request $request
* @return type
*/
public function linkingAccounts(Request $request) {
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
if (!(0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_STRUCTURE) || 0 === strpos($request->headers->get('Content-Type'), WebService::CONTENT_TYPE_TEXT))) {
return $this->errorWrongArgs('Wrong Content.', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), true);
if (!isset($data['nickname']) || !isset($data['uid'])) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
$nickname = $em->getRepository('App\Entity\AccountLicense')->findBy(['alLicenseUsername' => $data['nickname']]);
if (!isset($nickname) || $nickname == []) {
return $this->errorWrongArgs('nickname not found', WebService::CODE_WRONG_ARGUMENTS);
}
if ($nickname[0]->getDeviceUid() != $data['uid']) {
$emLev = Util::emLicenseConnection($this->realContainer, $em, $nickname[0]);
$registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $data['uid']]);
if (empty($registeredClientsByUID)) {
$emLev->close();
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
} else {
$emLev->close();
}
}
$uid = $em->getRepository('App\Entity\AccountLicense')->findBy(['deviceUid' => $data['uid']]);
if (!isset($uid) || $uid == []) {
return $this->errorWrongArgs('uid not found', WebService::CODE_WRONG_ARGUMENTS);
}
$omtClients = $em->getRepository('App\Entity\OmtClient')->searchClientToLinking($data);
if (count($omtClients) == 2) {
$pointsByClients = $em->getRepository('App\Entity\PointAcount')->searchCustomerPointsAccountsToLink($omtClients);
$targetCustomer = $pointsByClients[0];
$originalCustomer = $pointsByClients[1];
$targetClient = $em->getRepository('App\Entity\OmtClient')->find($targetCustomer['client']);
$originalClient = $em->getRepository('App\Entity\OmtClient')->find($originalCustomer['client']);
if ($targetClient->getEmail() === null && $originalClient->getEmail() !== null) {
$email = $originalClient->getEmail();
$originalClient->setEmail(null);
$em->persist($originalClient);
$em->flush();
$targetClient->setEmail($email);
$em->persist($targetClient);
$em->flush();
}
if ($targetClient->getPhone() === null && $originalClient->getPhone() !== null) {
$phone = $originalClient->getPhone();
$originalClient->setPhone(null);
$em->persist($originalClient);
$em->flush();
$targetClient->setPhone($phone);
$em->persist($targetClient);
$em->flush();
}
$typePointDataOriginalCustomer = $em->getRepository('App\Entity\TypePointAcount')->findPointsToTransfer($originalCustomer['id']);
$typePointDataTargetCustomer = $em->getRepository('App\Entity\TypePointAcount')->findPointsToTransfer($targetCustomer['id']);
foreach ($typePointDataTargetCustomer AS $key1 => $pointTargetCustomer) {
foreach ($typePointDataOriginalCustomer AS $key2 => $pointOriginalCustomer) {
if ($pointOriginalCustomer['license'] == $pointTargetCustomer['license'] && $pointOriginalCustomer['typePoint'] == $pointTargetCustomer['typePoint']) {
$amount = $pointOriginalCustomer['amount'] + $pointTargetCustomer['amount'];
$targetLink = $em->getRepository('App\Entity\TypePointAcount')->find($pointTargetCustomer['id']);
$homeLink = $em->getRepository('App\Entity\TypePointAcount')->find($pointOriginalCustomer['id']);
$targetLink->setAmount($amount);
$em->persist($targetLink);
$homeLink->setAmount(0);
$em->persist($homeLink);
$em->flush();
$linkingTransactionOfPoints = $this->linkingOfTransactionOfPoints($em, $homeLink, $targetLink);
} else {
$homeLink = $em->getRepository('App\Entity\TypePointAcount')->findBy(["typePoint" => $pointOriginalCustomer['typePoint'], "pointAcount" => $pointTargetCustomer['pointAcount'], "license" => $pointOriginalCustomer['license']]);
if (!$homeLink) {
$homeLink = $em->getRepository('App\Entity\TypePointAcount')->find($pointOriginalCustomer['id']);
$homeLink->setAmount(0);
$em->persist($homeLink);
$typePointData = $em->getRepository('App\Entity\TypePoint')->find($pointOriginalCustomer['typePoint']);
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($pointTargetCustomer['pointAcount']);
if (isset($pointOriginalCustomer['license'])) {
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->find($pointOriginalCustomer['license']);
} else {
$accountLicenseData = null;
}
$country = $em->getRepository('App\Entity\Country')->find($pointOriginalCustomer['countryId']);
$acountToken = ['food' => '123'];
while (!empty($acountToken)) {
$tokenAcount = Encryptor::encodeInfo(Utilx::randomPassword(32), 5);
$acountToken = $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
}
$targetLink = new TypePointAcount();
$targetLink->setTypePoint($typePointData);
$targetLink->setPointAcount($pointAccountData);
$targetLink->setAmount($pointOriginalCustomer['amount']);
$targetLink->setStartingDate($pointOriginalCustomer['startingDate']);
$targetLink->setCountryId($country);
$targetLink->setPointArmAcount($pointOriginalCustomer['pointArmAcount']);
$targetLink->setAcountToken($tokenAcount);
$targetLink->setArmIdentifier($pointOriginalCustomer['armIdentifier']);
$targetLink->setLicense($accountLicenseData);
$em->persist($targetLink);
$em->flush();
$linkingTransactionOfPoints = $this->linkingOfTransactionOfPoints($em, $homeLink, $targetLink);
}
}
}
}
$linkingCard = $this->linkingOfCards($em, $originalClient->getId(), $targetClient->getId());
}
$responseArr['msg'] = 'Successful account linking';
$responseArr['status'] = WebService::CODE_SUCCESS;
$responseArr['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* Permite vincular las tarjetas de un cliente origen a un cliente destino
*/
public function linkingOfCards($em, $idClientHome, $idClientLink) {
$cards = $em->getRepository('App\Entity\CardAsClient')->findBy(['client' => $idClientHome]);
if ($cards) {
$clientLink = $em->getRepository('App\Entity\OmtClient')->find($idClientLink);
foreach ($cards as $key => $value) {
$value->setClient($clientLink->getId());
$value->setValidateCard(2);
$em->persist($value);
$em->flush();
}
}
return true;
}
/**
* Permite vincular los point deal de un point account a otro point account
* los parametros que recibe son type point accounts
*/
public function linkingOfTransactionOfPoints($em, $typePointAccountHome, $typePointAccountTarget) {
$pointDealLinking = $em->getRepository('App\Entity\PointDeal')->findBy(['pointAcount' => $typePointAccountHome->getPointAcount(), 'typePointAcount' => $typePointAccountHome->getId()]);
if ($pointDealLinking) {
$typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->find($typePointAccountTarget->getId());
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->find($typePointAccountTarget->getPointAcount());
foreach ($pointDealLinking as $key => $value) {
$value->setPointAcount($pointAccountData);
$value->setTypePointAcount($typePointAccountData);
$em->persist($value);
$em->flush();
}
}
return true;
}
public function updateLoyaltyConfig(Request $request, $id, $type, $toClose = null) {
// if ($request->getMethod() !== WebService::REQUEST_METHOD_GET) {
// return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
// }
$user = $this->get('security.token_storage')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
$localRatio = 0;
$globalRatio = 0;
// obtenemos los parametros de la peticion
$params = $request->request->all();
if (isset($params['points_adqui_redem_rules'])){
$params = $params['points_adqui_redem_rules'];
// dump($params);die;
}
// $params = isset($params['points_adqui_redem_rules'])$params['points_adqui_redem_rules'];
// dump($params);die;
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'updateRestaurantLoyaltyConfig', 'updateRestaurantLoyaltyConfig0.txt');
$this->createFileJson($path, "\r" . 'updateRestaurantLoyaltyConfig fever XD ' . $request->getContent() . "\r");
$accountLicense = $em->getRepository('App\Entity\AccountLicense')->find($id);
// consultamos si existe la configuracion para el restaurante si no creamos una nueva
$entities = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->findBy(["license" => $id]);
if (!isset($entities) || empty($entities)) {
$entities = new RestaurantLoyaltyConfiguration();
$entities->setDateCreated(new \DateTime('now'));
$entities->setUseLocalPoints(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
$accountLicense->setCaptivePortalStatus(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
$entities->setUseGlobalPoints(false);
$entities->setMinimumPointAmountToExchange(isset($params['minimumPointAmountToExchange']) && $params['minimumPointAmountToExchange'] != ""?$params['minimumPointAmountToExchange']:1);
$entities->setLicense($accountLicense);
$em->persist($entities);
$em->persist($accountLicense);
$em->flush();
$saveLevel = $this->saveSyncLoyalty($em, $accountLicense,$params);
if (isset($params['captivePortalStatus']) && $params['captivePortalStatus']) {
// Solo captive portal está siendo activado
Util::logAction(
$em, 'RestaurantLoyaltyConfiguration',
$id, ActionHistory::ENABLE_CAPTIVE_PORTAL, $user->getUsName().' '.$user->getUsLastName(), [
'msg' => 'Enabled captive portal',
'userId' => $user->getId()
]);
} else if (isset($params['loyalty']) && $params['loyalty']) {
// Solo loyalty está siendo activado
Util::logAction(
$em, 'RestaurantLoyaltyConfiguration',
$id, ActionHistory::ENABLE_LOYALTY, $user->getUsName().' '.$user->getUsLastName(), [
'new_status' => ActionHistory::ACTION_CREATE,
'userId' => $user->getId()
]);
} else if (isset($params['loyalty']) && !$params['loyalty']) {
// Solo loyalty está siendo desactivado
Util::logAction(
$em, 'RestaurantLoyaltyConfiguration',
$id, ActionHistory::DISABLE_LOYALTY, $user->getUsName().' '.$user->getUsLastName(), [
'new_status' => ActionHistory::ACTION_DISABLED,
'userId' => $user->getId()
]);
}
} else {
$entities = $entities[0];
$oldStatus = $entities->getUseLocalPoints();
if(isset($params['minimumPointAmountToExchange'])){
$entities->setUseLocalPoints(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
$accountLicense->setCaptivePortalStatus(isset($params['minimumPointAmountToExchange']) && $params['loyalty'] != ""?(boolean)$params['loyalty']:false);
$entities->setMinimumPointAmountToExchange(isset($params['minimumPointAmountToExchange']) && $params['minimumPointAmountToExchange'] != ""?$params['minimumPointAmountToExchange']:1);
$entities->setUseLocalPoints($params['loyalty']);
$entities->setMinimumPointAmountToExchange($params['minimumPointAmountToExchange']);
$em->persist($entities);
$em->persist($accountLicense);
$em->flush();
// TYPE_LOYALTY_NONE
$saveLevel = $this->saveSyncLoyalty($em, $accountLicense, $params);
if (isset($params['captivePortalStatus'])) {
$actionType = $params['captivePortalStatus'] ? ActionHistory::ENABLE_CAPTIVE_PORTAL : ActionHistory::DISABLE_CAPTIVE_PORTAL;
Util::logAction(
$em, 'RestaurantLoyaltyConfiguration',
$id, $actionType, $user->getUsName().' '.$user->getUsLastName(), [
'msg' => $params['captivePortalStatus'] ? 'Enabled captive portal' : 'Disabled captive portal',
'userId' => $user->getId()
]);
} else if (isset($params['loyalty'])) {
$actionType = $params['loyalty'] ? ActionHistory::ENABLE_LOYALTY : ActionHistory::DISABLE_LOYALTY;
Util::logAction(
$em, 'RestaurantLoyaltyConfiguration',
$id, $actionType, $user->getUsName().' '.$user->getUsLastName(), [
'old_status' => $oldStatus,
'new_status' => $entities->getUseLocalPoints(),
'userId' => $user->getId()
]);
}
}
}
if(isset($saveLevel) && !$saveLevel){
return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
'entities' => $entities,
'toClose' => $toClose,
'formPtsAdquiRedemRules' => null,
'localPoint' => null,
'ratioPointLocal' => null,
'localRatio' => $localRatio,
'globalRatio' => $globalRatio,
'message' => "Error in save"
]);
}
if ($entities->getLicense()) {
PointsUtilPorcessor::createRulesForLocalPointLoyaltyConfiguration($em, $entities->getLicense(), $path);
}
$points = $em->getRepository('App\Entity\TypePoint')->findAll();
foreach ($points as $typePoint) {
if ($typePoint->getType() == TypePoint::TYPE_LOCAL) {
$localRatio = $typePoint->getCashRatio();
continue;
}
if ($typePoint->getType() == TypePoint::WORK_AS_GLOBAl) {
$globalRatio = $typePoint->getCashRatio();
}
}
$basicPurchaseRulesArray = PointsUtilPorcessor::getTheBasicPurchaseRulesArray();
// $form = $this->createForm(RestaurantLoyaltyConfig::class, $entities, [
// 'action' => $this->generateUrl('update_loyalty_config'),
// 'method' => 'POST'
// ]);
// $form = $this->createForm(PointsAdquiRedemRules::class, $entities, [
// 'action' => $this->generateUrl('update_adqui_redem_rules'),
// 'method' => 'POST'
// ]);
// if ($type == 2) {
$entitiesadquiRedemRule = $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["license" => $entities->getLicense(), "parentDefinition" => $basicPurchaseRulesArray[0]]);
// dump($entitiesadquiRedemRule);die;
if (!isset($entitiesadquiRedemRule[0])) {
$entitiesadquiRedemRule = $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["parentDefinition" => $basicPurchaseRulesArray[0]]);
}
$ptsRatePercentage = 0;
$ratioPointLocal = 0;
if (isset($entitiesadquiRedemRule[0])) {
if ($entitiesadquiRedemRule[0]->getMinimumPurchase() == null) {
$entitiesadquiRedemRule[0]->setMinimumPurchase(0);
}
$ratioPointLocal = $entitiesadquiRedemRule[0]->getPtsRate() * 100;
$entitiesadquiRedemRule[0]->setPtsRate($ratioPointLocal);
// $formPtsAdquiRedemRules = $this->createForm(PointsAdquiRedemRules::class, $entitiesadquiRedemRule[0], [
// 'action' => $this->generateUrl('update_adqui_redem_rules'),
// 'method' => 'POST'
// ]);
$formPtsAdquiRedemRules = $this->createForm(PointsAdquiRedemRules::class, $entitiesadquiRedemRule[0], [
'action' => $this->generateUrl('update_adqui_redem_rules'),
'minimumPointAmountToExchange' => $entities->getMinimumPointAmountToExchange(),
'method' => 'POST'
]);
return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
'entities' => $entities,
'toClose' => $toClose,
'formPtsAdquiRedemRules' => $formPtsAdquiRedemRules->createView(),
'localPoint' => $entitiesadquiRedemRule[0]->getPointType()->getId(),
'ratioPointLocal' => $ratioPointLocal,
'localRatio' => $localRatio,
'globalRatio' => $globalRatio
]);
} else {
return $this->render('AccountLicense\formPointsAdquiRedemRule.html.twig', [
'entities' => $entities,
'toClose' => $toClose,
'formPtsAdquiRedemRules' => null,
'localPoint' => null,
'ratioPointLocal' => null,
'localRatio' => $localRatio,
'globalRatio' => $globalRatio
]);
}
// } else {
// return $this->render('AccountLicense\restaurantLoyaltyConfig.html.twig', [
// 'entities' => $entities,
// 'form' => $form->createView(),
// 'localRatio' => $localRatio,
// 'globalRatio' => $globalRatio
// ]);
// }
}
public function updatePointsAdquiRedemRules(Request $request) {
$data = $request->request->getIterator()->getArrayCopy();
$em = $this->getDoctrine()->getManager();
$params = $data['points_adqui_redem_rules'];
// dd($data, $request);
// En caso de no tener el tipo de puntos(Locales o globales), elegimos por defecto locales
$params['typePoint'] = isset($params['typePoint'])? $params['typePoint']:'a00000a1-0aaa-00a0-a00a-0a0a00aaa0a0';
// dump($params);die;
// $ratioPointLocal = $params['ratioPointLocal'] * 100;
// $ratioPointLocal = $params['ratioPointLocal'];
$ratioPointLocal = $params['ptsRate'];
$ptsRatePercentage = $ratioPointLocal / 100;
// dump($ratioPointLocal);
// dump($ptsRatePercentage);
// die;
$basicPurchaseRulesArray = PointsUtilPorcessor::getTheBasicPurchaseRulesArray();
foreach ($basicPurchaseRulesArray as $basicPurchaseRule) {
$entitiesadquiRedemRule = $em->getRepository('App\Entity\PtsAdquiRedemRules')->findBy(["pointType" => $params['typePoint'], "license" => $params['license'], "parentDefinition" => $basicPurchaseRule]);
foreach ($entitiesadquiRedemRule as $adquiRedemLocalRule) {
$adquiRedemLocalRule->setPtsRate($ptsRatePercentage);
$adquiRedemLocalRule->setMinimumPurchase($params['minimumPurchase']);
$em->persist($adquiRedemLocalRule);
$em->flush();
}
}
$configLoyaltyOmt = $this->createOrUpdateLoyaltyConfigurationOmt($em, $params);
return $this->updateLoyaltyConfig($request, $params['license'], 2, true);
}
/**
* Funcion secundaria de la configuración del delivery, para realizar determinadas acciones
* @author Leandro Román Londoño - 03/03/2020
*/
public function deliveryActionsConfiguration(Request $request, $id){
$params = $request->request->getIterator()->getArrayCopy();
$em = $this->getDoctrine()->getManager();
$response = new Response();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->find($id);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData);
if (isset($params['action'])) {
/**
* Si el params contiene un id, se refiere que va a modificar ó eliminar
*/
if (isset($params['id'])) {
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->find($params['id']);
}else{
$entity = new ConfRangedelivery();
}
if ($entity != '' || $entity != null) {
$entity = $this->selectActionDelivery($entity, $params, $emLev);
$response->setStatusCode(200);
$responseArr['status'] = WebService::CODE_SUCCESS;
}else{
$response->setStatusCode(400);
$responseArr['status'] = WebService::HTTP_CODE_BAD_REQUEST;
}
if ($entity != '') {
$emLev->persist($entity);
$emLev->flush();
}
}
$responseArr['msg'] = 'Delivery update';
$responseArr['bigbag'] = true;
$responseArr['status'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArr);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
/**
* Funcion principal de la configuración del delivery, para cargar todas sus funciones
* @author Leandro Román Londoño - 03/03/2020
*/
public function deliveryConfiguration(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->find($id);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData);
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->searchAllDates();
$flag = 0;
$typeDelivery = ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE_BY_DISTANCE;
$statusSetting = ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE;
$typeChecked = 0;
/**
* Se itera sobre el dato consultado para enviar a la vista lo que necesita
*/
foreach ($entity as $key => $disable) {
if ($disable['confTypeDelivery'] == ConfRangedelivery::CONF_TYPE_DELIVERY_PLAIN_RECHARGE) {
$disabled[] = $disable['confTypeDelivery'];
}else if ($disable['confTypeNoRechargeDefined'] == ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE) {
$flag = 1;
}
if($disable['confStatus'] == ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE){
$typeDelivery = $disable['confTypeDelivery'];
$statusSetting = $disable['confStatus'];
$typeChecked = $disable['confTypeRange'];
}
}
if (isset($disabled)) {
$disabled = count($disabled);
}else{
$disabled = 0;
}
/**
* Carga la vista principal de la configuración del delivery, con los parametros consultados
*/
return $this->render('AccountLicense\deliveryConfiguration.html.twig', [
'ide' => $id,
'params' => $entity,
'disabled' => $disabled,
'noRecharge' => $flag,
'settingActive' => [
'typeDelivery' => $typeDelivery,
'statusSetting' => $statusSetting,
'typeChecked' => $typeChecked
]
]);
}
/**
* Funcion privada de la configuración del delivery
* Mediante una accion, se podra editar, crear, eliminar y ademas de eso configurar el no recharge y la activacion
* de una configuración
* @author Leandro Román Londoño - 03/03/2020
*/
private function selectActionDelivery($entity, $params, $emLev){
switch ($params['action']) {
case 'add':
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
$emLev->persist($entity);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $entity, RegistActions::ACTION_INSERT);
$entity = '';
break;
case 'modify':
if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == 0) {
$entity->setConfRangeDelivery($params['distance']);
$entity->setConfDeliveryPrice($params['price']);
}else if(isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == 1){
$entity->setConfFixedCostValue($params['price']);
}
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $entity, RegistActions::ACTION_UPDATE);
break;
case 'delete':
$emLev->remove($entity);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $entity, RegistActions::ACTION_DELETE);
$entity = '';
break;
case 'not_recharge':
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
foreach ($entity as $key => $value) {
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
$entity = '';
break;
case 'recharge':
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findBy(['confTypeNoRechargeDefined' => ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE]);
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
foreach ($entity as $key => $value) {
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
$entity = '';
break;
case 'distance_setting':
if (isset($params['type_recharge']) && $params['type_recharge'] == '0') {
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
foreach ($entity as $key => $value) {
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
}
$entity = '';
break;
case 'plain_setting':
if (isset($params['type_recharge']) && $params['type_recharge'] == '1') {
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
foreach ($entity as $key => $value) {
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
}
$entity = '';
break;
case 'plain_setting_exit':
case 'distance_setting_exit':
if (isset($params['type_recharge']) && ($params['type_recharge'] == '0' || $params['type_recharge'] == '1')) {
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
$entity = $this->registerNewDeliveryRangeOrPlain($entity, $params);
foreach ($entity as $key => $value) {
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
}
$entity = '';
break;
case 'status_type_distance':
$entity = $emLev->getRepository('App\Structure\ConfRangedelivery')->findAll();
foreach ($entity as $key => $value) {
if ($value->getConfTypeRange() == (int) $params['rechargeByDistance']) {
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
}else{
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
}
$emLev->persist($value);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'conf_rangedelivery', $value, RegistActions::ACTION_UPDATE);
}
$entity = '';
break;
}
return $entity;
}
/**
* Funcion privada de las acciones de la configuracion del delivery
* Dependiendo de sus parametros, se define que va a modificar o crear
* @author Leandro Román Londoño - 03/03/2020
*/
private function registerNewDeliveryRangeOrPlain($entity, $params){
/**
* Espera el parametro en "0", (string), para crear el delivery por distancia
*/
if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == "0") {
$entity->setConfTypeDelivery(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE_BY_DISTANCE);
$entity->setConfRangemax(ConfRangedelivery::CONF_DEFAULT_RANGE_MAX);
$entity->setConfRangecharge(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfTypeRange((int) $params['rechargeByDistance']);
if (isset($params['categoryRechage']) && $params['categoryRechage'] != '') {
$entity->setConfRangeDelivery((int) $params['categoryRechage']);
}else{
$entity->setConfRangeDelivery(ConfRangedelivery::CONF_TYPE_NOT_RECHARGE);
}
if (isset($params['valueTotal']) && $params['valueTotal'] != '') {
$entity->setConfDeliveryPrice((int) $params['valueTotal']);
}else{
$entity->setConfDeliveryPrice(ConfRangedelivery::CONF_TYPE_NOT_RECHARGE);
}
$entity->setConfFlatFee(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfFixedCostValue(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
$entity->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
}
/**
* Espera el parametro en "1", (string), para crear el delivery por plain
*/
if (isset($params['changeTypeRecharge']) && $params['changeTypeRecharge'] == "1") {
$entity->setConfTypeDelivery(ConfRangedelivery::CONF_TYPE_DELIVERY_PLAIN_RECHARGE);
$entity->setConfRangemax(ConfRangedelivery::CONF_DEFAULT_RANGE_MAX);
$entity->setConfRangecharge(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfTypeRange(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfRangeDelivery(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfDeliveryPrice(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
$entity->setConfFlatFee((int) $params['rechargeByPlain']);
if(isset($params['valueTotalPlain']) && $params['valueTotalPlain'] != ''){
$entity->setConfFixedCostValue((int) $params['valueTotalPlain']);
}else{
$entity->setConfFixedCostValue(ConfRangedelivery::CONF_FLAT_FEE_INACTIVE);
}
$entity->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
$entity->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
}
/**
* Espera el parametro en "not_recharge", (string), para modificar y establecer que no va a cobrar por domicilios
*/
if (isset($params['action']) && $params['action'] == 'not_recharge') {
foreach ($entity as $key => $value) {
$value->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_NOT_RECHARGE);
$entity[$key] = $value;
}
}
/**
* Espera el parametro en "recharge", (string), para modificar y establecer que va a cobrar por domicilios
*/
if (isset($params['action']) && $params['action'] == 'recharge') {
if (!empty($entity)) {
foreach ($entity as $key => $value) {
$value->setConfTypeNoRechargeDefined(ConfRangedelivery::CONF_TYPE_DELIVERY_RECHARGE);
$entity[$key] = $value;
}
}
}
/**
* Espera el parametro en "distance_setting", (string), para modificar y establecer que solo activa la configuración
* domicilio por distancia
*/
if (isset($params['action']) && $params['action'] == 'distance_setting') {
foreach ($entity as $key => $value) {
$confTypeDelivery = $value->getConfTypeDelivery() || 0;
if ((int)$confTypeDelivery == (int) $params['type_recharge'] && $value->getConfTypeRange() == (int) $params['rechargeByDistance']) {
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
}else{
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
}
$entity[$key] = $value;
}
}
/**
* Espera el parametro en "plain_setting", (string), para modificar y establecer que solo activa la configuración
* domicilio por precio fijo
*/
if (isset($params['action']) && $params['action'] == 'plain_setting') {
foreach ($entity as $key => $value) {
if ($value->getConfTypeDelivery() == (int) $params['type_recharge']) {
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_ACTIVE);
}else{
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
}
$entity[$key] = $value;
}
}
/**
* Espera el parametro "distance_setting_exit" o "plain_setting_exit", (string) para establecer que no quiere
* ninguna configuración
*/
if (isset($params['action']) && ($params['action'] == 'distance_setting_exit' || $params['action'] == 'plain_setting_exit')) {
foreach ($entity as $key => $value) {
$value->setConfStatus(ConfRangedelivery::CONF_TYPE_STATUS_INACTIVE);
$entity[$key] = $value;
}
}
return $entity;
}
/**
*
*/
public function updateRestaurantLoyaltyConfig(Request $request) {
$data = $request->request->getIterator()->getArrayCopy();
$em = $this->getDoctrine()->getManager();
$params = $data['restaurant_loyalty_config'];
$localRatio = 0;
$globalRatio = 0;
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'updateRestaurantLoyaltyConfig', 'updateRestaurantLoyaltyConfig0.txt');
$this->createFileJson($path, "\r" . 'updateRestaurantLoyaltyConfig fever XD ' . $request->getContent() . "\r");
$entities = $em->getRepository('App\Entity\RestaurantLoyaltyConfiguration')->find($params['id']);
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->find($params['license']);
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData);
$accountConfig = $emLev->getRepository('App\Structure\Configuracion')->findAll();
if (isset($params['typePoint']) && $params['typePoint'] == 'local') {
$entities->setUseLocalPoints(true);
$entities->setUseGlobalPoints(false);
$accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_LOCAL);
$entities->setMinimumPointAmountToExchange($params['minimumPointAmountToExchange']);
} elseif (isset($params['typePoint']) && $params['typePoint'] == 'global') {
$entities->setUseLocalPoints(false);
$entities->setUseGlobalPoints(true);
$accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_GLOBAL);
$entities->setMinimumPointAmountToExchange((int) $this->realContainer->getParameter('minimum_usage_of_global_points'));
} else {
$entities->setUseLocalPoints(false);
$entities->setUseGlobalPoints(false);
$accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_NONE);
}
if (isset($params['earnPointsInPurchaseWithPoints'])) {
$entities->setEarnPointsInPurchaseWithPoints(true);
} else {
$entities->setEarnPointsInPurchaseWithPoints(false);
}
$em->persist($entities);
$em->flush();
$accountConfig[0]->setConfLoyaltyMinAmountToExchange($params['minimumPointAmountToExchange']);
if (isset($params['earnPointsInPurchaseWithPoints'])) {
$accountConfig[0]->setEarnPointsInPurchaseWithPoints(true);
} else {
$accountConfig[0]->setEarnPointsInPurchaseWithPoints(false);
}
$dashboardLoyaltyButton = $emLev->getRepository('App\Structure\Dashboard')->find(14);
if (!$dashboardLoyaltyButton) {
$dashboardLoyaltyRecord = new Dashboard();
$dashboardLoyaltyRecord->setId(14);
$dashboardLoyaltyRecord->setDasTabToGo('openSearchLoyaltyCustomer');
$dashboardLoyaltyRecord->setDasIcon('icon-pay-points');
$dashboardLoyaltyRecord->setDasOrderType(14);
$dashboardLoyaltyRecord->setDasName('GENERAL.LOYALTY');
$dashboardLoyaltyRecord->setDasStatus(1);
$dashboardLoyaltyRecord->setDasSorting(14);
$emLev->persist($dashboardLoyaltyRecord);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'dashboard', $dashboardLoyaltyRecord, RegistActions::ACTION_INSERT);
} else {
$dashboardLoyaltyButton->setDasStatus(1);
$emLev->persist($dashboardLoyaltyButton);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'dashboard', $dashboardLoyaltyButton, RegistActions::ACTION_UPDATE);
}
$emLev->persist($accountConfig[0]);
$emLev->flush();
Util::saveUpdateRecordInRegistActions($emLev, 'configuracion', $accountConfig[0], RegistActions::ACTION_UPDATE);
$points = $em->getRepository('App\Entity\TypePoint')->findAll();
foreach ($points as $typePoint) {
if ($typePoint->getType() == TypePoint::TYPE_LOCAL) {
$localRatio = $typePoint->getCashRatio();
continue;
}
if ($typePoint->getType() == TypePoint::WORK_AS_GLOBAl) {
$globalRatio = $typePoint->getCashRatio();
}
}
$form = $this->createForm(RestaurantLoyaltyConfig::class, $entities, [
'action' => $this->generateUrl('update_loyalty_config'),
'method' => 'POST'
]);
return $this->render('AccountLicense\restaurantLoyaltyConfig.html.twig', [
'entities' => $entities,
'toClose' => true,
'form' => $form->createView(),
'localRatio' => $localRatio,
'globalRatio' => $globalRatio
]);
}
/**
* Función replica de updateRestaurantLoyaltyConfig pero adaptada al nuevo flujo de guardado de loyalty para sincronización en Android
* @param EntityManager $em
* @param Entity $License Entidad de AccountLicense
* @param Array $params Parametros de entrada['loyalty', 'minimumPointAmountToExchange']
* @return Boolean True o false
*/
public function saveSyncLoyalty($em, $license, $params){
try{
// Se crean los logs
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'updateRestaurantLoyaltyConfig', 'updateRestaurantLoyaltyConfig0.txt');
$this->createFileJson($path, "\r" . 'saveSyncLoyalty ' . json_encode($params). "\r");
// Se conecta con la base de datos de level web
$emLev = Util::emLicenseConnection($this->realContainer, $em, $license);
$accountConfig = $emLev->getRepository('App\Structure\Configuracion')->findAll();
// Util::saveUpdateRecordInRegistActions($emLev, 'licensor1', $license, RegistActions::ACTION_UPDATE);
// 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.
if (isset($params['loyalty']) && $params['loyalty'] == 1) {
$accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_LOCAL);
$this->createFileJson($path, "\r" . 'Set value type loyalty local '."\r" );
} else {
$accountConfig[0]->setConfLoyaltyTypePoints(Configuracion::TYPE_LOYALTY_NONE);
$this->createFileJson($path, "\r" . 'Set value type loyalty off '."\r" );
}
// Se ingresa el valor minimo de cash loyalty en level web
$accountConfig[0]->setConfLoyaltyMinAmountToExchange($params['minimumPointAmountToExchange']);
// Se ingresan los datos de configuración en la tabla de dashboard para level web
$dashboardLoyaltyButton = $emLev->getRepository('App\Structure\Dashboard')->find(14);
if (!$dashboardLoyaltyButton) {
$this->createFileJson($path, "\r" . 'Save config in table Dashboard from levelweb'."\r" );
$dashboardLoyaltyRecord = new Dashboard();
$dashboardLoyaltyRecord->setId(14);
$dashboardLoyaltyRecord->setDasTabToGo('openSearchLoyaltyCustomer');
$dashboardLoyaltyRecord->setDasIcon('icon-pay-points');
$dashboardLoyaltyRecord->setDasOrderType(14);
$dashboardLoyaltyRecord->setDasName('GENERAL.LOYALTY');
$dashboardLoyaltyRecord->setDasStatus(1);
$dashboardLoyaltyRecord->setDasSorting(14);
$emLev->persist($dashboardLoyaltyRecord);
$emLev->flush();
// se guardan los datos en regisAction para ser sincronizados
Util::saveUpdateRecordInRegistActions($emLev, 'dashboard', $dashboardLoyaltyRecord, RegistActions::ACTION_INSERT);
$this->createFileJson($path, "\r" . 'regisAction Dashboard from levelweb'."\r" );
} else {
$dashboardLoyaltyButton->setDasStatus(1);
$emLev->persist($dashboardLoyaltyButton);
$emLev->flush();
// se guardan los datos en regisAction para ser sincronizados
Util::saveUpdateRecordInRegistActions($emLev, 'dashboard', $dashboardLoyaltyButton, RegistActions::ACTION_UPDATE);
$this->createFileJson($path, "\r" . 'regisAction Dashboard from levelweb if register dasboard exist'."\r" );
}
$emLev->persist($accountConfig[0]);
$emLev->flush();
// se guardan los datos en regisAction para ser sincronizados
Util::saveUpdateRecordInRegistActions($emLev, 'configuracion', $accountConfig[0], RegistActions::ACTION_UPDATE);
$this->createFileJson($path, "\r" . 'regisAction configuracion from levelweb'."\r" );
return true;
}catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
$this->createFileJson($path, "\r" . 'Alert Error => '. json_encode($err) ."\r" );
return $this->errorInternalError($err);
}
}
/**
* Web Service que recibe el nickname del restaurante, el ID del cliente, el teléfono y/o el email
* y responde con la cuenta de los puntos del cliente que tenga registrados en el restaurante
* y se le agrega el token único de transacción para ser verificado en una compra futura.
* @author Jhonan Vargas <jsmith@openmytab.com> 11/05/2023
* @param Request $request
* @return type
*/
public function generateLoyaltyTransactionToken(Request $request){
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
$arrayEncryptResult = Util::decryptDataForAndroid($this->realContainer, $request->getContent());
$data = json_decode($arrayEncryptResult['data'], true);
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'generateLoyaltyTransactionToken', 'generateLoyaltyTransactionToken0.txt');
$this->createFileJson($path, "\r" . 'parameters sent: ' . $arrayEncryptResult['data'] . "\r");
$existPhone = isset($data["phone"]);
$existEmail = isset($data["email"]);
if(!isset($data["nickname"]) || !isset($data["clientId"]) || (!$existPhone && !$existEmail)){
$this->createFileJson($path, "\r" . 'Wrong Arguments!'. "\r");
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$search = [];
$isEmpty = false;
// se verifica que el teléfono o el email no estén vacÃos
if($existPhone){
if($data["phone"] !== ''){
$search["phone"] = $data["phone"];
}else{
$isEmpty = true;
}
}
if($existEmail){
if($data["email"] !== ''){
$search["email"] = $data["email"];
}else{
$isEmpty = true;
}
}
// se valida que los parámetros no estén vacÃos
if(empty($data["nickname"]) || empty($data["clientId"]) || $isEmpty){
$this->createFileJson($path, "\r" . 'Some Fields Are Empty!'. "\r");
return $this->errorWrongArgs('Wrong Arguments!', WebService::CODE_WRONG_ARGUMENTS);
}
$em = $this->getDoctrine()->getManager();
// se valida si existe la licencia
$nicknameDataSearch = ['alLicenseUsername' => $data['nickname']];
$accountLicData = $em->getRepository('App\Entity\AccountLicense')->findBy($nicknameDataSearch);
if (empty($accountLicData)) {
$this->createFileJson($path, "\r" . 'Invalid nickname!'. "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Invalid nickname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if(is_null($accountLicData[0]->getLoginType()) || $accountLicData[0]->getLoginType() == AccountLicense::LOGGED_OUT){
$this->createFileJson($path, "\r" . 'License not logged!'. "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('License not logged', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
// se valida que se tenga una versión de Android registrada en la licencia
if (($accountLicData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_ANDROID || $accountLicData[0]->getLoginType() == AccountLicense::LOGGED_BY_LEVEL_LITE_AND_ANDROID) && !is_null($accountLicData[0]->getAndroidVersionName())) {
$this->createFileJson($path, "\r" . 'Android logged in license !'. "\r");
// 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
if (!NewUtil::isGreaterThanOrEqualToThisVersion($accountLicData[0]->getAndroidVersionName(), $this->realContainer->getParameter('secure_android_version'), $path)){
$this->createFileJson($path, "\r" . 'Android version is not secure!'. "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Android version is not secure', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
} else {
$this->createFileJson($path, "\r" . 'Level Lite logged in license !'. "\r");
}
$search['restaurant'] = $accountLicData[0]->getId();
$search["client"] = $data["clientId"];
// Se busca el cliente con los parámetros de ingresados
$client = $em->getRepository('App\Entity\OmtClient')->findOmtClientByFilterSearchParameters($search);
if(is_null($client)){
$this->createFileJson($path, "\r" . 'Client does not exist!'. "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)->respondWithError('Client does not exist', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
// se realiza la consulta de los puntos junto con el token correspondiente
$transactionToken['tokens'] = $em->getRepository('App\Entity\TypePointAcount')->generateLoyaltyTransactionTokenByClient($search, $path);
$transactionToken['licenseId'] = $accountLicData[0]->getId();
$transactionToken['msg'] = "Transaction Verification Token ";
$transactionToken['status'] = WebService::CODE_SUCCESS;
$transactionToken['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $transactionToken);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
public function getLoyaltyAmount(Request $request): JsonResponse {
$container = $this->realContainer;
$em = $this->getDoctrine()->getManager();
$search = $request->query->all();
$statusCode = 200;
$data = [
'status' => 'success',
'message' => 'amount by license',
];
if (isset($search['restaurant'])) {
$typePointAcount = $em->getRepository('App\Entity\TypePointAcount');
$amount = $typePointAcount->getLoyaltyAmount($search);
$data['amount'] = $amount;
}else{
$data['status'] = "error";
$data['message'] = "restaurant not found";
$data['statusCode'] = $statusCode;
$statusCode = 500;
}
return new JsonResponse($data, $statusCode);
}
/**
* Consular puntos loyalty que se encuentran en licensor
* Se debe ingresar minimo un parametro relacionado con el cliente de los siguientes
* @param Request $request
* @param String $phone - numero de telefono con el que esta registrado el cliente
* @param String $email - email con el que esta registrado el cliente
* @param String $client - id del cliente para omt
* @param String $restaurant - id del restaurante
* @param String $omt - true / false dependiende desde donde se realice la patición
* @return Json responde con algunos datos del cliente y los puntos locales por restaurante
*/
public function getGenericPointLoyalty(Request $request) {
// Se verifica que ingrese con el mehod gett
if ($request->getMethod() != WebService::REQUEST_METHOD_GET) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_GET . " method");
}
// Creamos el log
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'getGenericPointLoyalty', 'getGenericPointLoyalty0.txt');
$this->createFileJson($path, "\r" . '**-----------------------------------------------------------------------------**' . "\r");
$this->createFileJson($path, "\r" . 'getGenericPointLoyalty init: ' . $request->getContent() . "\r");
$this->createFileJson($path, "\r" . 'query params: ' . json_encode($request->query->all()) . "\r");
$search = [];
$indexSearch = [];
$order = [];
$indexOrder = ['order_by_last_visit', 'order_by_member_since', 'order_by_cash'];
$paginator = $this->get('simple_paginator');
$pageRanges = [10, 25, 50];
$paginator->setPageRanges($pageRanges);
(!is_null($request->query->get('itemsPerPage')) && $request->query->get('itemsPerPage') != '') ? $itemsPerPage = (int) $request->query->get('itemsPerPage') : $itemsPerPage = $pageRanges[0];
$paginator->setItemsPerPage($itemsPerPage);
$paginator->setMaxPagerItems(10);
try {
// Se inicia el entiti manager
$container = $this->realContainer;
$em = $this->getDoctrine()->getManager();
$search = $request->query->all();
if (isset( $search['phone']) && $search['phone'] != '' ) {
$search['phone'] = Utilx::clearEspecialCharactersFromPhone($search['phone']);
}
$debug = (isset($search['debug']) && !is_null($search['debug'])) ? (boolean) $search['debug'] : false;
$omtRequest = (isset($search['omt']) && !is_null($search['omt'])) ? $search['omt'] : null;
$search = array_filter($search, function ($value) {
return !is_null($value);
});
if ($debug) {
dump($search);
$this->createFileJson($path, "\r" . 'Parameter debug '. "\r Parametros de entrada" . json_encode($search) . "\r");
}
// Se validan los parmetros de llegada
if (empty($search) ) {
$this->createFileJson($path, "\r" . 'Invalid parameters name' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Invalid parameters name', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if (!isset($search['restaurant'])) {
$client = $em->getRepository('App\Entity\OmtClient')->findOmtClientByFilterSearchParametersBasicData($search, $debug);
if ($debug) {
dump("respuesta cliente", $client, isset($client) && !empty($client));
$this->createFileJson($path, "\r" . 'Parameter debug '. "\r Parametros de entrada" . json_encode($client) . "\r");
}
if (isset($client) && !empty($client)) {
$this->createFileJson($path, "\r" . 'Client exist' .json_encode($client). "\r");
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
// se comenta mientras tanto porque aun no se ha implementado los puntos globales
// // [ client, phone, email ]
// $pointAccountByClientGlobal = $pointAccountByClientRepository->getPointLoyaltyClientGlobal($search,$omtRequest);
// if(!is_null($pointAccountByClientGlobal)){
// $responseArrWithPagination['points']['global'] = $pointAccountByClientGlobal;
// }
// [ restaurant ]
$pointAccountByClientRestaurantResult = $pointAccountByClientRepository->getPointLoyaltyClientXRestaurant($search, $omtRequest);
$pointAccountByClientRestaurant = $pointAccountByClientRestaurantResult['pointAccountByClientRestaurant'];
$clientsIdInArray = $pointAccountByClientRestaurantResult['clientsIdInArray'];
if ($debug) {
dump("Return consulata de puntos ",$pointAccountByClientRestaurant);
}
if (!is_null($pointAccountByClientRestaurant) && !empty($pointAccountByClientRestaurant)) {
$responseArrWithPagination['points']['local'] = $pointAccountByClientRestaurant;
$this->createFileJson($path, "\r" . 'points local'. json_encode($pointAccountByClientRestaurant) ."\r");
$msg = "Client ok";
} else {
$this->createFileJson($path, "\r" . 'Not points local'."\r");
$msg = "Client has no loyalty cash";
}
// redondeo del point2cash
$responseArrWithPagination['clients'] = $client;
$responseArrWithPagination['generalInfo'] = $em->getRepository('App\Entity\TypePoint')->getRatioPoints();
}
} else if (isset($search['restaurant'])) {
$order = Paginator::filterParameters($indexOrder, $request, Paginator::REQUEST_TYPE_REQUEST, true);
$pointAccountByClientRepository = $em->getRepository('App\Entity\TypePointAcount');
$search['with_portal_client'] = 1;
$pointAccountByClientRestaurantResult = $pointAccountByClientRepository->getPointLoyaltyClientXRestaurant($search, $omtRequest, true, $debug, $order);
$pointAccountByClientRestaurant = $pointAccountByClientRestaurantResult['pointAccountByClientRestaurant'];
$clientsIdInArray = $pointAccountByClientRestaurantResult['clientsIdInArray'];
if (!is_null($pointAccountByClientRestaurant) && !empty($pointAccountByClientRestaurant)) {
$emLev = WsUtilx::emLicenseIDConnection($container, $em, $search['restaurant']);
foreach ($pointAccountByClientRestaurant as $key => $value) {
$pointAccountByClientRestaurant[$key]['orders'] = [];
$pointAccountByClientRestaurant[$key]['isOmt'] = false;
$clientExtraInfo = $emLev->getRepository('App\Structure\Cliente')->findOneBy(array(
"loyaltyId" => $value['typeCountId']
));
// if (strpos($pointAccountByClientRestaurant[$key]['clientEmail'], '@test.com') !== false) {
// $pointAccountByClientRestaurant[$key]['clientEmail'] = "";
// }
$clientOrders = $emLev->getRepository('App\Structure\LoyaltyHistory')->findBy(array(
"phone" => $value['clientPhone']
), ['date' => 'DESC']);
// $dateOfLastVisit = $emLev->getRepository('App\Structure\LoyaltyHistory')->findOneBy(array(
// "phone" => $value['clientPhone']
// ), array( 'date' => $orderLastVisit));
$dateOfLastVisit = $emLev->getRepository('App\Structure\LoyaltyHistory')->findOneBy(["phone" => $value['clientPhone']]);
if ($pointAccountByClientRestaurant[$key]['clientBirthdate'] instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['clientBirthdate'] = $pointAccountByClientRestaurant[$key]['clientBirthdate']->format('m/d/Y');
}
if (!is_null($dateOfLastVisit)) {
if ($dateOfLastVisit->getDate() instanceof \DateTime)
$pointAccountByClientRestaurant[$key]['dateOfLastVisit'] = $dateOfLastVisit->getDate()->format('m/d/Y H:i');
} else if($pointAccountByClientRestaurant[$key]['createAccount'] instanceof \DateTime)
$pointAccountByClientRestaurant[$key]['dateOfLastVisit'] = $pointAccountByClientRestaurant[$key]['createAccount']->format('m/d/Y H:i');
if ($pointAccountByClientRestaurant[$key]['createdAt'] instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['createdAt'] = $pointAccountByClientRestaurant[$key]['createdAt']->format('m/d/Y');
}
if ($pointAccountByClientRestaurant[$key]['createAccount'] instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['createAccount'] = $pointAccountByClientRestaurant[$key]['createAccount']->format('m/d/Y');
}
if ($pointAccountByClientRestaurant[$key]['startingDate'] instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['startingDate'] = $pointAccountByClientRestaurant[$key]['startingDate']->format('m/d/Y');
}
if (isset($clientExtraInfo)) {
if ($clientExtraInfo->getCliCreacion() instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['cliCreacion'] = $clientExtraInfo->getCliCreacion()->format('m/d/Y');
}
$pointAccountByClientRestaurant[$key]['cliCodigo'] = $clientExtraInfo->getId();
} else {
$pointAccountByClientRestaurant[$key]['isOmt'] = true;
}
if (isset($clientOrders)) {
$cashRedeemed = 0;
$cashEarned = 0;
foreach ($clientOrders as $key_o => $value_o) {
$indiviauls = number_format((float)$value_o->getPointsRedeemed() - $value_o->getPointsEarned(), 2, '.', ',');
$getInvoice = $emLev->getRepository('App\Structure\FacturaVentas')->findOneBy([ 'mpCodigo' => $value_o->getOrder() ]);
$getOrder = $emLev->getRepository('App\Structure\Mesapedido')->findOneBy([ 'id' => $value_o->getOrder() ]);
// Obtenemos los datos de order & invoice
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderId'] = $value_o->getOrder();
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['odeTotal'] = $getOrder != null ? $getOrder->getMpValortotal() : null;
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['customer'] = $getOrder != null ? $getOrder->getMpCodcliente() : null;
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['status'] = $getOrder != null ? $getOrder->getMpEstado() : null;
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['invoiceId'] = $getInvoice != null ? $getInvoice->getId() : [];
if ($value_o->getPointsRedeemed() != null) {
$cashRedeemed = (float)$cashRedeemed + (float)$value_o->getPointsRedeemed();
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderCashRedeemed'] = number_format((float) $value_o->getPointsRedeemed(), 2, '.', ',');
}
if ($value_o->getPointsEarned() != null) {
$cashEarned = (float)$cashEarned + (float)$value_o->getPointsEarned();
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['orderCashEarned'] = number_format((float) $value_o->getPointsEarned(), 2, '.', ',');
}
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['individualOrders'] = $indiviauls;
if ($value_o->getDate() instanceof \DateTime) {
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['cliCreacion'] = $value_o->getDate()->format('m/d/Y');
}
if ($value_o->getSaleAmount()) {
$pointAccountByClientRestaurant[$key]['orders'][$key_o]['mpValortotal'] = number_format((float)$value_o->getSaleAmount(), 2, '.', ',');
}
}
$pointAccountByClientRestaurant[$key]['cashEarned'] = number_format($cashEarned, 2, '.', ',');
$pointAccountByClientRestaurant[$key]['cashRedeemed'] = number_format(abs($cashRedeemed), 2, '.', ',');
}
}
$orderLastVisit = null;
if (isset($order['order_by_last_visit']))
$orderLastVisit = $order['order_by_last_visit'] % 2 ? "DESC" : "ASC";
if(!is_null($orderLastVisit)){
usort($pointAccountByClientRestaurant, function ($a, $b) use ($orderLastVisit) {
$dateA = strtotime($a['dateOfLastVisit']);
$dateB = strtotime($b['dateOfLastVisit']);
if ($orderLastVisit === 'ASC')
return $dateA <=> $dateB;
else
return $dateB <=> $dateA;
});
}
// usort($pointAccountByClientRestaurant, function ($a, $b) {
// return strtotime($b['createAccount']) <=> strtotime($a['createAccount']);
// });
$ClientPaginator = $paginator->paginate($pointAccountByClientRestaurant)->getResult();
$params = Paginator::getUrlFromParameters($indexSearch, $search);
$orderBy = Paginator::getUrlOrderFromParameters($indexOrder, $order, $container);
$responseArrWithPagination['search'] = $search;
$responseArrWithPagination['orderBy'] = $orderBy;
$responseArrWithPagination['params'] = $params;
$finalPaginator = [];
$finalPaginator['currentPage'] = $paginator->getCurrentPage();
$finalPaginator['itemsPerPage'] = $paginator->getItemsPerPage();
$finalPaginator['maxPagerItems'] = $paginator->getMaxPagerItems();
$finalPaginator['totalItems'] = $paginator->getTotalItems();
$finalPaginator['pageRanges'] = $paginator->getPageRanges();
$finalPaginator['previousPage'] = $paginator->getPreviousPage();
$finalPaginator['minPageInRange'] = $paginator->getMinPageInRange();
$finalPaginator['maxPageInRange'] = $paginator->getMaxPageInRange();
$finalPaginator['lastPage'] = $paginator->getLastPage();
$finalPaginator['nextPage'] = $paginator->getNextPage();
$finalPaginator['firstPage'] = $paginator->getFirstPage();
$finalPaginator['RequestStack'] = json_encode($paginator->RequestStack);
$responseArrWithPagination['paginator'] = $finalPaginator;
$responseArrWithPagination['clients'] = $ClientPaginator;
$this->createFileJson($path, "\r" . 'points local'. json_encode($ClientPaginator) ."\r");
$msg = "Restaurant ok";
} else {
$this->createFileJson($path, "\r" . 'Not points local'."\r");
$msg = "Restaurant no found clients with points";
}
} else {
$msg = "Client not Found";
$this->createFileJson($path, "\r" . 'Client not found'."\r");
}
if (isset($clientsIdInArray) && !empty($clientsIdInArray)) {
$dataToCommand = ['clientsId' => implode(' ', $clientsIdInArray)];
ForcedAsynchronousCommandsUtil::omtClientAddressAsyncRegistOnLicensor($this->realContainer, $dataToCommand);
}
$responseArrWithPagination['msg'] = $msg;
$responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
$responseArrWithPagination['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
if ($debug) {
dump($responseArrWithPagination);
$this->createFileJson($path, "\r" . 'Response'."\r" . $jsonContent );
die;
}
return $this->respondWithItem($jsonContent, $theUrlTrSt);
} catch (\Throwable $th) {
$err = ['Error message' => $th->getMessage(), 'Error Line' => $th->getLine(), 'Error File' => $th->getFile(), 'Error Trance' => $th->getTrace()];
$this->createFileJson($path, "\r" . 'Alert Error => '. json_encode($err) ."\r" );
return $this->errorInternalError($err);
}
}
public function saveNewTypePointAccount($em, $clientToGetPoint, $data, $path){
$debug=isset($data["debug"]) ? true :false;
if($debug){
dump("Data de entrada ",$data);
}
// se verifica el restaurante
$license=$em->getRepository('App\Entity\AccountLicense')->GetLicenseActive($data["nickname"], $debug);
if($debug){
dump("License ",$license);
}
if(empty($license)) {
return false;
} else {
// Se buscan todos los id de typePointAcount para luego generaruno atomaticamente
$existingUUIDs = $em->getRepository('App\Entity\TypePointAcount');
// dump("uuid 1", $existingUUIDs);die;
$newUUID = $this->validateUUID($existingUUIDs, $path);
if (!$newUUID) {
$this->createFileJson($path, 'Limit time for valid UID search reached...' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Limit time for valid UID search reached...', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
// se extraen la entidad del tipo de puntos Locales
$typePoint = $em->getRepository('App\Entity\TypePoint')->findOneBy(["type"=>TypePoint::TYPE_LOCAL]);
$resp = $this->savePointAccount($em, $clientToGetPoint, $data, $path);
$countryData=$em->getRepository('App\Entity\City')->getLocationCountry($license[0]->getCity());
$typePointAccountData = new TypePointAcount();
$typePointAccountData->setId($newUUID);
$typePointAccountData->setTypePoint($typePoint);
$typePointAccountData->setLicense($license[0]);
$typePointAccountData->setPointAcount($resp["pointAccountData"]);
$typePointAccountData->setCountryId($countryData[0]);
$typePointAccountData->setAmount(0);
$typePointAccountData->setPointArmAcount('Pepito Habla Ingles!');
$typePointAccountData->setStartingDate(new \DateTime());
$typePointAccountData->setAcountToken($resp["tokenAcount"]);
if (isset($data['Spots']) && !empty($data['Spots']) && $data['Spots'] != '0' && $data['Spots'] != 0) {
if (!is_null($path)) {
$this->createFileJson($path, 'The request has spots => ' . $data['Spots'] . "\r");
}
$typePointAccountData->setAmount($data['Spots']);
}
$em->persist($typePointAccountData);
$em->flush();
return $typePointAccountData;
}
}
public function validateUUID($existingUUIDs, $path = null){
$validate = false;
$count = 0;
$newUUID = '';
while (!$validate && $count < 50) {
if(isset($path) && !is_null($path)){
$this->createFileJson($path, 'Generación de uuid ' . $count ."\r");
}
$newUUID = UUIDGeneratorUtil::getUUIDv4();
$getData = $existingUUIDs->getAllIv2validedateNewUuid($newUUID);
// $validate = !in_array($newUUID, $existingUUIDs);
$validate = !empty($getData) ? false : true;
++$count;
}
if(isset($path) && !is_null($path)){
$this->createFileJson($path, 'nuevo uuid ' . $newUUID ."\r");
$this->createFileJson($path, 'respuesta del validador despues del while de la muerte' . $validate ."\r");
}
if (!$validate) {
return false;
}
return $newUUID;
}
public function generateToken($em, $path=null, $base=null){
$baseToken = "";
$tokenAcount = "";
$count=0;
if(isset($path) && !is_null($path)){
$this->createFileJson($path, 'base ' . $base ."\r");
}
do{
if(isset($path) && !is_null($path)){
$this->createFileJson($path, 'Generación de token ' . $count ."\r");
}
if($count > 0 ){
$baseToken = Utilx::randomPassword(32);
}
else{
$baseToken = is_null($base) ? Utilx::randomPassword(32):$base;
}
$tokenAcount = Encryptor::encodeInfo($baseToken, 5);
$acountToken = $em->getRepository('App\Entity\TypePointAcount')->findBy(['acountToken' => $tokenAcount]);
if(isset($path) && !is_null($path)){
$this->createFileJson($path, 'base token ' . $baseToken ."\r");
$this->createFileJson($path, 'token account' . $tokenAcount ."\r");
if(isset($acountToken[0])){
$this->createFileJson($path, 'acount Token' .$acountToken[0]->getAcountToken() ."\r");
}
}
++$count;
} while(!empty($acountToken) && $count < 50);
if (!empty($acountToken)) {
return false;
}
return ["baseToken"=>$baseToken, "tokenAcount" => $tokenAcount];
}
public function savePointAccount($em, $clientToGetPoint, $data, $path){
$pointAccountData = $em->getRepository('App\Entity\PointAcount')->findOneBy(["omtClient" => $clientToGetPoint->getId()]);
// Se valiuda si existe cuenta de puntos, sino existe se cera una
if (!isset($pointAccountData) && empty($pointAccountData)) {
$pointAccountData = new PointAcount();
$pointAccountData->setId($clientToGetPoint->getId());
/*$existingUUIDsPA = $em->getRepository('App\Entity\PointAcount');
$this->createFileJson($path, 'savePointAccount -> Se valida la existencia de la cuenta de puntos ' . "\r");
$newUUIDPA = $this->validateUUID($existingUUIDsPA, $path);
if (!$newUUIDPA) {
$this->createFileJson($path, 'savePointAccount ->Limit time for valid UID 2 search reached...' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Limit time for valid UID 2 search reached...', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$pointAccountData->setId($newUUIDPA);*/
if(isset($data['basePointacount'])) {
$baseToken=$data['basePointacount'];
} else {
$tokens=$this->generateToken($em, $path);
if (!$tokens) {
$this->createFileJson($path, 'savePointAccount -> Limit time for valid token search reached...' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Limit time for valid token search reached...', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$baseToken = $tokens['baseToken'];
$tokenAcount = $tokens['tokenAcount'];
}
$pointAccountData->setOmtClient($clientToGetPoint->getId());
$pointAccountData->setBasePointacount($baseToken);
$date = isset($data['activationDate']) ? new \DateTime($data['activationDate']) : new \DateTime("NOW");
$pointAccountData->setActivationDate($date);
$em->persist($pointAccountData);
$em->flush();
} else {
$tokens=$this->generateToken($em, $path, $pointAccountData->getBasePointacount());
if (!$tokens) {
$this->createFileJson($path, 'savePointAccount -> Limit time for valid token 2 search reached...' . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError('Limit time for valid token 2 search reached...', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
$tokenAcount = $tokens['tokenAcount'];
}
return ["tokenAcount" => $tokenAcount, "pointAccountData" => $pointAccountData];
}
/**
* Esta función retorna los punto a un cliente.
* @param Uuid id de la orden
* @param String license nickname
* @param String clienteID from cliente
* @param String type point local-gloval
* @param String Uid server id
*/
public function returnLoyaltyCash(Request $request, ArmorService $armor, Log $log){
// Creamos el log
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'returnLoyaltyCash', 'returnLoyaltyCash.txt');
$this->createFileJson($path, "\r" . '**-----------------------------------------------------------------------------**' . "\r");
$this->createFileJson($path, "\r" . 'returnLoyaltyCash init: ' . $request->getContent() . "\r");
// validamos el metodo del request
if ($request->getMethod() !== WebService::REQUEST_METHOD_POST && $request->getMethod() !== WebService::REQUEST_METHOD_OPTIONS) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_POST . " method");
}
// Validamos el metodo de la petición
if ($request->getMethod() === WebService::REQUEST_METHOD_OPTIONS) {
$responseArrayAux1['status'] = WebService::CODE_SUCCESS;
$responseArrayAux1['msg'] = 'OPTIONS detected, good to go!';
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrayAux1);
$jsonTransform = $theUrlTrSt->transform();
$jsonContent = json_encode($jsonTransform);
return $this->respondWithItem($jsonContent, $theUrlTrSt);
}
$params = json_decode($request->getContent(), true);
// Validamos los parametros del de a consulta
if (!isset($params['nickname']) || !isset($params['orderId']) || !isset($params['clienteID'])) {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
// Se inicia el entiti manager
$container = $this->realContainer;
$em = $this->getDoctrine()->getManager();
// se busca el restaurante en base de datos
$data = ['alLicenseUsername' => $params['nickname']];
$accountLicenseData = $em->getRepository('App\Entity\AccountLicense')->findByAlLicenseUsername($data);
// se valida el estado del restaurante
$validate = $this->validateLicense(count($accountLicenseData), $path, $accountLicenseData);
if(!$validate["status"]){
return $this->setStatusCode($validate["status"])
->respondWithError($validate["message"], $validate["code"]);
}
// if(isset($params['uid'])){
// $this->createFileJson($path, "\r" . 'Request Android' . "\r");
// if ($accountLicenseData[0]->getDeviceUid() != $params['uid']) {
// // $emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
// $registeredClientsByUID = $emLev->getRepository('App\Structure\Stations')->findBy(['staDeviceCode' => $params['uid']]);
// if (empty($registeredClientsByUID)) {
// $emLev->close();
// $this->createFileJson($path, 'UID diferente! o.O' . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Unknown device', WebService::CODE_UNAUTHORIZED);
// } else {
// $emLev->close();
// }
// }
// }
// Se crea el entity manager para level web
$emLev = Util::emLicenseConnection($this->realContainer, $em, $accountLicenseData[0]);
// se crea el valor del flag (en este caso es 1) para ingresarlo en la base de datos
$params['flagRedime'] = LoyaltyHistory::FLAG_RETURN_POINT;
// se busca y se valida la orden en mesa pedido.
// $mesaPedido = $emLev->getRepository('App\Structure\Mesapedido')->find($params['orderId']);
// if(isset($params["debug"])){
// dump($mesaPedido);
// }
// if(is_null($mesaPedido) || (!is_null($mesaPedido) && $mesaPedido->getMpEstado() != Mesapedido::MESAPEDIDO_STATUS_CANCELED)){
// $this->createFileJson($path, "\r" . 'the return of loyalty cash is inappropriate for the order' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError("the return of loyalty cash is inappropriate for the order", WebService::CODE_ACCOUNT_SUSPENDED);
// }
// se busaca la ultima transacción hecha por loyalty
$loyaltyHistory = $emLev->getRepository('App\Structure\LoyaltyHistory')->getLastCustomerInfo($params['orderId']);
// se busca el cliente y la cuenta de loyalty
$clientReposiroty = $em->getRepository('App\Entity\OmtClient');
$clientToGetPoint = $clientReposiroty->clientWithPhone2analis($params["clienteID"]);
if(!is_array($clientToGetPoint)){
$this->createFileJson($path, "\r" . 'client not found' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("client not found", WebService::CODE_ACCOUNT_SUSPENDED);
}
// clienteID
$params['customerId'] = isset($clientToGetPoint["id"]) ? $clientToGetPoint["id"] : null;
// se obtiene la cuenta de puntos de del uysuatio en el restaurante $seedData['customerId'], $activeRuleToAnalyze->getPointType()->getId(), $license->getId(), (isset($seedData['debug']) ? true : false)
// $typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->findOneBy(['license' => $accountLicenseData[0]->getId(), 'pointAcount' => $clientToGetPoint["pointAcount"]]);
$typePointAccountData = $em->getRepository('App\Entity\TypePointAcount')->findUserPtAccount($params['customerId'], TypePoint::WORK_AS_LOCAL, $accountLicenseData[0]->getId());
if(!isset($typePointAccountData[0])){
$this->createFileJson($path, "\r" . 'Account loyalty client not found' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("Account loyalty client not found", WebService::CODE_ACCOUNT_SUSPENDED);
}
if(isset($params["debug"])){
dump("llegue hasta aca", $params, $clientToGetPoint, $typePointAccountData, $loyaltyHistory);
}
if((double) $loyaltyHistory[0]["pointsRedeemed"] <= 0){
// se obtiene el historial de loyalty de la orden
$params['totalAmount'] = $loyaltyHistory[0]["saleAmount"];
// Datos necesarios para armor
$armorPack = [
'request' => $request,
'service' => $armor,
'log' => $log
];
if(isset($params["debug"])){
dump("pre-validate armor");
dump($typePointAccountData[0], $armorPack);
}
$validateArmor = PointsUtilPorcessor::validateLicensorPointsAmountWithArmor($container, $em, $typePointAccountData[0], $armorPack, $path);
if(isset($params["debug"])){
dump("validateArmor", $validateArmor);
}
$activeAplicableRule = $em->getRepository("App\Entity\PtsAdquiRedemRules")->findOneBy(['license' => $accountLicenseData[0]->getId()]);
if(isset($params["debug"])){
dump("validateArmor", $activeAplicableRule);
}
$armorPack['typePointAccount'] = $typePointAccountData[0];
$armorPack['license'] = $accountLicenseData[0];
$armorPack['preTransactionAmount']=$validateArmor[1];
$totalAmount = (double) $params['totalAmount'] / (double) $activeAplicableRule->getPtsRate();
$this->createFileJson($path, 'Pre makePtsTransactionToClientAccountInArmorServer call: $armorPack -> ' . json_encode($armorPack) . ' $params -> ' . json_encode($params) . "\r");
$createArmor = PointsUtilPorcessor::makePtsTransactionToClientAccountInArmorServer($container, $em, $params, $totalAmount, $activeAplicableRule, $armorPack, $path);
if(isset($params["debug"])){
dump("Armor", $createArmor);
// die;
}
// se llena la base de datos de loyaltyHistory
$params['transactionCode'] = $createArmor[1];
$params['pointsEarned'] = (double) $createArmor[0];
$params['actualAmount'] = (double) $createArmor[3];
$params['totalAmount'] = $createArmor[4];
$loyaltyRecordCreationResult = PointsUtilPorcessor::createLoyaltyTransactionRecordInLicense($container, $em, $accountLicenseData[0], $clientToGetPoint, $params, $path);
$responseArrWithPagination['msg'] = "Return of points";
$responseArrWithPagination['status'] = WebService::CODE_SUCCESS;
$responseArrWithPagination['bigbag'] = true;
$theUrlTrSt = new LicensorGenericTransformer($this->realContainer, $responseArrWithPagination);
$xxArray = $theUrlTrSt->transform();
$jsonContent = json_encode($xxArray);
if (isset($params["debug"])) {
dump($responseArrWithPagination);
$this->createFileJson($path, "\r" . 'Response'."\r" . $jsonContent );
die;
}
return $this->respondWithItem($jsonContent, $theUrlTrSt);
// // se suben los datos a armor
// $arrayTypePointAccountTokenToArmor = PointsUtilPorcessor::createArrayForPostPutArmorPointRequest($typePointAccountData, $typePointAccountData->getAmount(), $path);
// $encodeBase = Encryptor::encodeInfo(json_encode($arrayTypePointAccountTokenToArmor));
// $request = $armor->duplicateRequestWithOverwritedContentForArmorServer($request, ['token' => $encodeBase]);
}else{
$this->createFileJson($path, "\r" . 'No points found to return' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
->respondWithError("No points found to return", WebService::CODE_ACCOUNT_SUSPENDED);
}
return true;
}
/**
* Valida la licencia de que se sta consultando
*/
function validateLicense($countResult, $path, $accountLicenseData){
if ($countResult <= 0) {
$this->createFileJson($path, "\r" . 'Invalid nickname or channelname' . WebService::CODE_COULD_NOT_AUTHENTICATE . "\r");
return ["status" => WebService::HTTP_CODE_UNAUTHORIZED, "message" => 'Invalid nickname or channelname', "code"=>WebService::CODE_COULD_NOT_AUTHENTICATE];
// $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Invalid nickname or channelname', WebService::CODE_COULD_NOT_AUTHENTICATE);
}
if ($accountLicenseData[0]->getAlAccountLicense()->getDeleted()) {
$this->createFileJson($path, "\r" . 'Account is inactive' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return ["status" => WebService::HTTP_CODE_UNAUTHORIZED, "message" => 'Account is inactive', "code" => WebService::CODE_ACCOUNT_SUSPENDED];
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Account is inactive', WebService::CODE_ACCOUNT_SUSPENDED);
}
if ($accountLicenseData[0]->getAlLicenseStatus() == AccountLicense::LICENSE_STATUS_INACTIVE) {
$this->createFileJson($path, "\r" . 'Inactive License' . WebService::CODE_ACCOUNT_SUSPENDED . "\r");
return ["status" => WebService::HTTP_CODE_UNAUTHORIZED, "message" => 'Inactive License', "code" => WebService::CODE_ACCOUNT_SUSPENDED];
// return $this->setStatusCode(WebService::HTTP_CODE_UNAUTHORIZED)
// ->respondWithError('Inactive License', WebService::CODE_ACCOUNT_SUSPENDED);
}
return ["status" => true];
}
/**
* Obtiene el balance de puntos en la targeta gift card que tenga el cliente
* @param String id de la orden
*/
function getGiftCardBalancePoints(Request $request) {
// Se verifica que ingrese con el mehod get
if ($request->getMethod() == WebService::REQUEST_METHOD_GET) {
return $this->errorNotAllowedMethod('Method not allowed. Use ' . WebService::REQUEST_METHOD_GET . " method");
}
$params = json_decode($request->getContent(), true);
// Se inicia el entity manager
$container = $this->realContainer;
$em = $this->getDoctrine()->getManager();
if (isset($params['orderId']) && !empty($params['orderId'])) {
$mpCodigo = $params['orderId'];
$response = [];
$giftCardData = $em->getRepository('App\Entity\GiftCardTransaction')->getTransactionsByOrder($mpCodigo);
$response['msg'] = "Your gift card balance";
$response['status'] = WebService::CODE_SUCCESS;
$response['bigbag'] = true;
$response['data'] = $giftCardData != '' ? $giftCardData: null;
$licensorTransformer = new LicensorGenericTransformer($this->realContainer, $response);
$transformData = $licensorTransformer->transform();
$jsonEncodedData = json_encode($transformData);
return $this->respondWithItem($jsonEncodedData, $licensorTransformer);
} else {
return $this->errorWrongArgs('Wrong Arguments', WebService::CODE_WRONG_ARGUMENTS);
}
}
/**
* Function configuration loyalty account to restaurant in omt
*
*/
public function createOrUpdateLoyaltyConfigurationOmt($em, $params){
$container = $this->realContainer;
$restaurantEntity = $em->getRepository('App\Entity\AccountLicense')->find($params['license']);
$arrayToRequest = [
"restNickname" => $restaurantEntity->getAlLicenseUsername(),
"minimumPointAmountToExchange" => $params['minimumPointAmountToExchange'],
"useLocalPoints" => true,
"useGlobalPoints" => false,
"ptsRate" => $params['ptsRate'],
"minimumPurchase" => $params['minimumPurchase'],
"restaurantId" => $restaurantEntity->getAlLicenseUsername(),
];
$url = $container->getParameter('omt_scheme') . '://' . $container->getParameter('omt_host') . 'common/setLoyaltyConfiguration';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arrayToRequest));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$decodeResult = json_decode($result, true);
return $decodeResult;
}
}