src/Hona/ApiBundle/Controller/InvitationController.php line 251

Open in your IDE?
  1. <?php
  2. namespace Hona\ApiBundle\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpKernel\Exception\HttpException;
  8. use Hona\ApiBundle\Exception\ErrorCodeException;
  9. use Hona\ApiBundle\Exception\MissingRequiredFieldsException;
  10. use Hona\ApiBundle\Exception\OutOfTimeWindowException;
  11. use Hona\ApiBundle\Exception\AccessHistoryNeedsToAccessException;
  12. use Hona\ApiBundle\Exception\AccessHistoryNeedsToExitException;
  13. use Hona\ApiBundle\Exception\InvitationCanceledException;
  14. use Hona\ApiBundle\Exception\InvitationRequestNotActiveException;
  15. use Hona\ApiBundle\Library\Utils;
  16. class InvitationController extends EntityController
  17. {
  18.     protected $required = array("name""type");
  19.     protected function _validateAfterGET(Request $request$entity$uuid, &$data$clean){
  20.         if($entity == "invitation"){
  21.             $this->_changeIdForEntity("event"$data$clean);
  22.             $this->_changeIdForEntity("user"$data$clean);
  23.             $this->_changeIdForEntity("address"$data$clean);
  24.             if(!empty($data["image_code_path"])){
  25.                 $data["image_code_path"] = Utils::addMediaDomainToPath($data["image_code_path"]);
  26.             }
  27.             if($data["type"] == 3){
  28.                 $this->_addListEntitiesCustomFunction("interval""InvitationId"$data["id"], $data);
  29.             }
  30.         }
  31.     }
  32.     protected function _validateAfterPUT(Request $request$entity$uuid, &$data$clean){
  33.         $this->_changeIdForEntity("event"$data$clean);
  34.         $this->_changeIdForEntity("user"$data$clean);
  35.         $this->_changeIdForEntity("address"$data$clean);
  36.         if(!empty($data["image_code_path"])){
  37.             $data["image_code_path"] = Utils::addMediaDomainToPath($data["image_code_path"]);
  38.         }
  39.         //TODO change this to a function thats support multiple updates
  40.         if($data["type"] == 3){
  41.             $dataRequest json_decode($request->getContent(), true);
  42.             if(isset($dataRequest["intervals"]) && is_array($dataRequest["intervals"])){
  43.                 if(isset($dataRequest["intervals"][0]["uuid"])){
  44.                     $response $this->forward('HonaApiBundle:Interval:intervalPUT', [
  45.                         'request' => $request,
  46.                         'uuid' => $dataRequest["intervals"][0]["uuid"],
  47.                         'data' => $dataRequest["intervals"][0]
  48.                     ]);
  49.                     $this->_addListEntitiesCustomFunction("interval""uuid"$dataRequest["intervals"][0]["uuid"], $data);
  50.                 }else{
  51.                     foreach($dataRequest["intervals"] as $interval){
  52.                         $dataInterval = array();
  53.                         $dataInterval['invitation'] = $uuid;
  54.                         $dataInterval['date_start'] = $interval["date_start"];
  55.                         $dataInterval['date_end'] = $interval["date_end"];
  56.                         $dataInterval['monday'] = $interval["monday"];
  57.                         $dataInterval['tuesday'] = $interval["tuesday"];
  58.                         $dataInterval['wednesday'] = $interval["wednesday"];
  59.                         $dataInterval['thursday'] = $interval["thursday"];
  60.                         $dataInterval['friday'] = $interval["friday"];
  61.                         $dataInterval['saturday'] = $interval["saturday"];
  62.                         $dataInterval['sunday'] = $interval["sunday"];
  63.                         $dataInterval['status'] = Utils::ACTIVE;
  64.                         
  65.                         $response $this->forward('HonaApiBundle:Interval:intervalPOST', [
  66.                             'request' => $request,
  67.                             'data' => $dataInterval
  68.                         ]);
  69.                     }
  70.         
  71.                     $this->_addListEntitiesCustomFunction("interval""InvitationId"$data["id"], $data);
  72.                 }
  73.                 
  74.             }
  75.         }
  76.     }
  77.     protected function _validateAfterPOST(Request $request$entity$uuid, &$data$clean){
  78.         $this->_changeIdForEntity("event"$data$clean);
  79.         $this->_changeIdForEntity("user"$data$clean);
  80.         $this->_changeIdForEntity("address"$data$clean);
  81.         if(!empty($data["image_code_path"])){
  82.             $data["image_code_path"] = Utils::addMediaDomainToPath($data["image_code_path"]);
  83.         }
  84.         if($data["type"] == 3){
  85.             $dataRequest json_decode($request->getContent(), true);
  86.             if(isset($dataRequest["intervals"]) && is_array($dataRequest["intervals"])){
  87.                 foreach($dataRequest["intervals"] as $interval){
  88.                     $dataInterval = array();
  89.                     $dataInterval['invitation'] = $uuid;
  90.                     $dataInterval['date_start'] = $interval["date_start"];
  91.                     $dataInterval['date_end'] = $interval["date_end"];
  92.                     $dataInterval['monday'] = $interval["monday"];
  93.                     $dataInterval['tuesday'] = $interval["tuesday"];
  94.                     $dataInterval['wednesday'] = $interval["wednesday"];
  95.                     $dataInterval['thursday'] = $interval["thursday"];
  96.                     $dataInterval['friday'] = $interval["friday"];
  97.                     $dataInterval['saturday'] = $interval["saturday"];
  98.                     $dataInterval['sunday'] = $interval["sunday"];
  99.                     $dataInterval['status'] = Utils::ACTIVE;
  100.                     
  101.                     $response $this->forward('HonaApiBundle:Interval:intervalPOST', [
  102.                         'request' => $request,
  103.                         'data' => $dataInterval
  104.                     ]);
  105.                 }
  106.     
  107.             }else{
  108.                 $startDate = new \DateTime();
  109.                 $endDate = new \DateTime();
  110.                 $dataInterval = array();
  111.                 $dataInterval['invitation'] = $uuid;
  112.                 $dataInterval['date_start'] = $startDate;
  113.                 $dataInterval['date_end'] = $endDate->add(new \DateInterval('P1Y'));
  114.                 $dataInterval['monday'] = true;
  115.                 $dataInterval['tuesday'] = true;
  116.                 $dataInterval['wednesday'] = true;
  117.                 $dataInterval['thursday'] = true;
  118.                 $dataInterval['friday'] = true;
  119.                 $dataInterval['saturday'] = true;
  120.                 $dataInterval['sunday'] = true;
  121.                 $dataInterval['status'] = Utils::ACTIVE;
  122.                 $response $this->forward('HonaApiBundle:Interval:intervalPOST', [
  123.                     'request' => $request,
  124.                     'data' => $dataInterval
  125.                 ]);
  126.             }
  127.             $this->_addListEntitiesCustomFunction("interval""InvitationId"$data["id"], $data);
  128.             
  129.         }
  130.     }
  131.     protected function _validateBeforePOST(Request $request$entity, &$data){
  132.         if(isset($data["event"])){
  133.             //This will copy user_id and address_id from event
  134.             $this->_changeUuidForId("event"$datanull, array("user""address"));
  135.         }else if(isset($data["user"]) && isset($data["address"])){
  136.             $this->_changeUuidForId("user"$data);
  137.             $this->_changeUuidForId("address"$data);
  138.             //TODO validate if relation user and address is valid probably better with permission change later
  139.             $this->_validateRelationship("address",
  140.                 array("user_id" => $data["user_id"]),
  141.                 array(
  142.                     //TODO check index table
  143.                     "id" => $data["address_id"],
  144.                     "status" => Utils::ACTIVE
  145.                 )
  146.             );
  147.         }else{
  148.             throw new MissingRequiredFieldsException(array("event or user+address"));
  149.         }
  150.         if($data["type"] != && !array_key_exists("date_invitation"$data)){
  151.             throw new MissingRequiredFieldsException(array("date_invitation"));
  152.         }
  153.         /*if($data["type"] == 3 && !array_key_exists("intervals", $data)){
  154.             throw new MissingRequiredFieldsException(array("intervals"));
  155.         }elseif($data["type"] == 3 && !is_array($data["intervals"])){
  156.             throw new MissingRequiredFieldsException(array("intervals"));
  157.         }*/
  158.         if(!isset($data["status"])){
  159.             $data["status"] = Utils::ACTIVE;
  160.         }
  161.         $data["code"] = Utils::generateAccessCode();
  162.         //TODO validate if not in the DB 
  163.         $data["image_code_path"] = Utils::generateImageForAccessCode($data["code"]);
  164.     }
  165.     protected function _validateBeforePUT(Request $request$entity$uuid, &$data){
  166.         $this->_changeUuidForId("event"$datanull, array("user""address"));
  167.         $this->_changeUuidForId("user"$data);
  168.         $this->_changeUuidForId("address"$data);
  169.     }
  170.     /**
  171.      * @Route("/invitation/from/invitation_request/{uuid}", name="invitation_from_invitation_request_uuid", methods={"GET"})
  172.      * @param $request
  173.      */
  174.     public function invitationFromInvitationRequestAction(Request $request$uuid)
  175.     {
  176.         $invitation_request $this->_entityGET($request"invitation_request"$uuidnulltruefalse'admin_object');
  177.         if(is_array($invitation_request)){
  178.             if($invitation_request["status"] == Utils::ACTIVE){
  179.                 $this->_changeIdForEntity("event"$invitation_requestfalse);
  180.                 $data = array(
  181.                     "name" => $invitation_request["name"],
  182.                     "last_name" => $invitation_request["last_name"],
  183.                     "event" => $invitation_request["event"]["uuid"],
  184.                     "date_invitation" => $invitation_request["event"]["date_event"],
  185.                     "type" => 1
  186.                 );
  187.                 $dataReturn $this->_entityPOST($request"invitation"$datatruefalse);
  188.                 
  189.                 if(is_array($dataReturn)){
  190.                     $this->_entityPUT($request"invitation_request"$uuid, array(
  191.                         "status" => Utils::ACCEPTED,
  192.                         "invitation_id" => $dataReturn["id"]
  193.                     ));
  194.                     
  195.                     Utils::sendInvitationEmail($this->get("twig"), $dataReturn$invitation_request["event"], $invitation_request);
  196.                     $this->_removeIdFields($dataReturn);
  197.                     return new JsonResponse($dataReturn);
  198.                 }else{
  199.                     return $dataReturn;
  200.                 }
  201.             }else{
  202.                 $exception = new InvitationRequestNotActiveException($uuid);
  203.                 $data = [
  204.                     'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  205.                     'code' => $exception->getErrorCode()
  206.                 ];
  207.                 return new JsonResponse($data$exception->getStatusCode());
  208.             }
  209.         }else{
  210.             return $invitation_request;
  211.         }
  212.     }
  213.     /**
  214.      * @Route("/invitation/create", name="invitation_create", methods={"POST"})
  215.      * @param $request
  216.      */
  217.     public function invitationCreateAction(Request $request)
  218.     {
  219.         $user $this->getUser();
  220.         $data json_decode($request->getContent(), true);
  221.         $data["user"] = $user->getUuid();
  222.         $userHasAddress Utils::checkUserAddressExists($this->getDoctrine()->getManager(), $data["address"], $user);
  223.         if($userHasAddress){
  224.             return $this->_entityPOST($request"invitation"$data);
  225.         }else{
  226.             $data = [
  227.                 'message' => "user with no address",
  228.                 'code' => 20
  229.             ];
  230.             
  231.             return new JsonResponse($data400);
  232.         }
  233.     }
  234.     private function _validateInvitationInterval($dataReturn){
  235.         $todayDayDate = new \DateTime();
  236.         $todayDayDate->setTimeZone(new \DateTimeZone(Utils::getParameter('default_timezone')));
  237.         $todayDay strtolower($todayDayDate->format('l'));
  238.         //TODO update this to support multiple intervals
  239.         $dayAllowed $dataReturn["intervals"][0][$todayDay];
  240.         $startDateInvitation = new \DateTime($dataReturn["intervals"][0]["date_start"]);
  241.         $endDateInvitation = new \DateTime($dataReturn["intervals"][0]["date_end"]);
  242.         $accessTolerance Utils::getParameter("access_tolerance");
  243.         $startDateInvitation->sub(date_interval_create_from_date_string($accessTolerance.' seconds'));
  244.         $endDateInvitation->add(date_interval_create_from_date_string($accessTolerance.' seconds'));
  245.         $now = new \DateTime();
  246.         if(!$dayAllowed || ($now $startDateInvitation || $now $endDateInvitation)){
  247.             return false;
  248.         }
  249.         return true;
  250.     }
  251.     private function _validationRequestCode(Request $request$data null){
  252.         try{
  253.             $user $this->getUser();
  254.             if($data == null){
  255.                 $data json_decode($request->getContent(), true);
  256.             }
  257.             
  258.             $dataReturn $this->_entityByFieldGET($request"invitation""code"$data["code"], nulltruefalse);
  259.             if(is_array($dataReturn)){
  260.                 if($dataReturn["status"] != Utils::ACTIVE && $dataReturn["status"] != Utils::HALFACTIVE){
  261.                     throw new InvitationCanceledException($data["code"]);
  262.                 }
  263.                 if(isset($dataReturn["address"]["residential_id"])){
  264.                     $this->_validateRelationship("control_gate",
  265.                         array("user_id" => $user->getId()),
  266.                         array(
  267.                             //TODO check index table
  268.                             "uuid" => $data["control_gate"],
  269.                             "residential_id" => $dataReturn["address"]["residential_id"],
  270.                             "status" => Utils::ACTIVE
  271.                         )
  272.                     );
  273.                     $accessHistory $this->_entityByFieldsGET(
  274.                         $request"access_history",
  275.                         array(
  276.                             "invitation_id" => $dataReturn["id"],
  277.                             "date_departure" => null
  278.                         ), nulltruefalse
  279.                     );
  280.                     if(is_array($accessHistory)){
  281.                         //need to exit
  282.                         $dataReturn["access_history"] = $accessHistory;
  283.                     }else{
  284.                         //Validate time window
  285.                         $startDateInvitation = new \DateTime($dataReturn["date_invitation"]);
  286.                         $endDateInvitation = new \DateTime($dataReturn["date_invitation"]);
  287.                         $accessTolerance Utils::getParameter("access_tolerance");
  288.                         $startDateInvitation->sub(date_interval_create_from_date_string($accessTolerance.' seconds'));
  289.                         $endDateInvitation->add(date_interval_create_from_date_string($accessTolerance.' seconds'));
  290.                         $now = new \DateTime();
  291.                         if($now $startDateInvitation || $now $endDateInvitation){
  292.                             throw new OutOfTimeWindowException(new \DateTime($dataReturn["date_invitation"]));
  293.                         }
  294.                     }
  295.                     
  296.                     $this->_removeIdFields($dataReturn);
  297.                     $this->_removeIdFields($dataReturn["event"]);
  298.                     $this->_removeIdFields($dataReturn["address"]);
  299.                     $this->_removeIdFields($dataReturn["user"]);
  300.                     $this->_removeIdFields($dataReturn["access_history"]);
  301.                 }
  302.             }
  303.             
  304.             return $dataReturn;
  305.         }catch(ErrorCodeException $exception){
  306.             $data = [
  307.                 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  308.                 'code' => $exception->getErrorCode()
  309.             ];
  310.             return new JsonResponse($data$exception->getStatusCode());
  311.         }catch(HttpException $exception){
  312.             $data = [
  313.                 'message' => $exception->getMessage()
  314.             ];
  315.             return new JsonResponse($data$exception->getStatusCode());
  316.         }
  317.     }
  318.     /**
  319.      * @Route("/invitation/check", name="invitation_check", methods={"POST"})
  320.      * @param $request
  321.      */
  322.     public function invitationCheckAction(Request $request)
  323.     {
  324.         $dataReturn $this->_validationRequestCode($request);
  325.         if(is_array($dataReturn)){
  326.             return new JsonResponse($dataReturn);
  327.         }
  328.         return $dataReturn;
  329.     }
  330.     /**
  331.      * @Route("/invitation/cancel", name="invitation_cancel", methods={"POST"})
  332.      * @param $request
  333.      */
  334.     public function invitationCancelAction(Request $request)
  335.     {
  336.         $user $this->getUser();
  337.         $data json_decode($request->getContent(), true);
  338.         $dataReturn $this->_validationRequestCode($request$data);
  339.         if(is_array($dataReturn)){
  340.             if(isset($dataReturn["access_history"])){
  341.                 $exception = new AccessHistoryNeedsToExitException($dataReturn["access_history"]["uuid"]);
  342.                 
  343.                 $dataReturn = [
  344.                     'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  345.                     'code' => $exception->getErrorCode()
  346.                 ];
  347.                 return new JsonResponse($dataReturn$exception->getStatusCode());
  348.             }
  349.             
  350.             //forward to create Access History
  351.             $content = array(
  352.                 "status" => Utils::CANCELED
  353.             );
  354.             $request->initialize(
  355.                 $request->query->all(),
  356.                 $request->request->all(),
  357.                 $request->attributes->all(),
  358.                 $request->cookies->all(),
  359.                 $request->files->all(),
  360.                 $request->server->all(),
  361.                 json_encode($content)
  362.             );
  363.             return $this->forward('HonaApiBundle:Invitation:invitationPUT', [
  364.                 'request' => $request,
  365.                 'uuid' => $dataReturn["uuid"]
  366.             ]);
  367.         }
  368.         return $dataReturn;
  369.     }
  370.     /**
  371.      * @Route("/invitation/registry/access", name="invitation_registry_access", methods={"POST"})
  372.      * @param $request
  373.      */
  374.     public function invitationRegistyAccessAction(Request $request)
  375.     {
  376.         $user $this->getUser();
  377.         $data json_decode($request->getContent(), true);
  378.         $dataReturn $this->_validationRequestCode($request$data);
  379.         if(is_array($dataReturn)){
  380.             if(isset($dataReturn["access_history"])){
  381.                 $exception = new AccessHistoryNeedsToExitException($dataReturn["access_history"]["uuid"]);
  382.                 
  383.                 $dataReturn = [
  384.                     'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  385.                     'code' => $exception->getErrorCode()
  386.                 ];
  387.                 return new JsonResponse($dataReturn$exception->getStatusCode());
  388.             }
  389.             if($dataReturn["type"] == && isset($dataReturn["intervals"]) && is_array($dataReturn["intervals"])){
  390.             
  391.                 if(!$this->_validateInvitationInterval($dataReturn)){
  392.                     $exception = new OutOfTimeWindowException(new \DateTime());
  393.                     $dataReturn = [
  394.                         'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  395.                         'code' => $exception->getErrorCode()
  396.                     ];
  397.                     return new JsonResponse($dataReturn$exception->getStatusCode());
  398.                 }
  399.             }
  400.             if($dataReturn["type"] != 3){
  401.                 $dataTemp = array(
  402.                     "status" => Utils::HALFACTIVE
  403.                 );
  404.                 $this->_entityPUT($request"invitation"$dataReturn["uuid"], $dataTemp);
  405.             }
  406.             
  407.             //forward to create Access History
  408.             $content = array(
  409.                 "control_gate_entry" => $data["control_gate"],
  410.                 "user_allow_entry" => $user->getUuid(),
  411.                 "date_entry" => date("Y-m-d H:i:s"),
  412.                 "invitation" => $dataReturn["uuid"]
  413.             );
  414.             $request->initialize(
  415.                 $request->query->all(),
  416.                 $request->request->all(),
  417.                 $request->attributes->all(),
  418.                 $request->cookies->all(),
  419.                 $request->files->all(),
  420.                 $request->server->all(),
  421.                 json_encode($content)
  422.             );
  423.             return $this->forward('HonaApiBundle:AccessHistory:accessHistoryPOST', [
  424.                 'request' => $request
  425.             ]);
  426.         }
  427.         return $dataReturn;
  428.     }
  429.     /**
  430.      * @Route("/invitation/registry/exit", name="invitation_registry_exit", methods={"POST"})
  431.      * @param $request
  432.      */
  433.     public function invitationRegistyExitAction(Request $request)
  434.     {
  435.         $user $this->getUser();
  436.         $data json_decode($request->getContent(), true);
  437.         $dataReturn $this->_validationRequestCode($request$data);
  438.         $exception null;
  439.         if(is_array($dataReturn)){
  440.             if(isset($dataReturn["access_history"])){
  441.                 if($dataReturn["access_history"]["uuid"] == $data["access_history"]){
  442.                     $content = array(
  443.                         "control_gate_departure" => $data["control_gate"],
  444.                         "user_allow_departure" => $user->getUuid(),
  445.                         "date_departure" => date("Y-m-d H:i:s")
  446.                     );
  447.                     if($dataReturn["type"] != 3){
  448.                         $dataTemp = array(
  449.                             "status" => Utils::USED
  450.                         );
  451.                         $this->_entityPUT($request"invitation"$dataReturn["uuid"], $dataTemp);
  452.                     }
  453.                     $request->initialize(
  454.                         $request->query->all(),
  455.                         $request->request->all(),
  456.                         $request->attributes->all(),
  457.                         $request->cookies->all(),
  458.                         $request->files->all(),
  459.                         $request->server->all(),
  460.                         json_encode($content)
  461.                     );
  462.                     return $this->forward('HonaApiBundle:AccessHistory:accessHistoryPUT', [
  463.                         'request' => $request,
  464.                         'uuid' => $dataReturn["access_history"]["uuid"]
  465.                     ]);
  466.                 }else{
  467.                     $exception = new AccessHistoryNeedsToExitException($dataReturn["access_history"]["uuid"]);
  468.                 }
  469.             }else{
  470.                 $exception = new AccessHistoryNeedsToAccessException();
  471.             }
  472.         }
  473.         if($exception != null){
  474.             $dataReturn = [
  475.                 'message' => strtr($exception->getMessageKey(), $exception->getMessageData()),
  476.                 'code' => $exception->getErrorCode()
  477.             ];
  478.             return new JsonResponse($dataReturn$exception->getStatusCode());
  479.         }
  480.         return $dataReturn;
  481.     }
  482.     /**
  483.      * @Route("/invitation/{uuid}", name="invitation_get_uuid", methods={"GET"})
  484.      * @param $request
  485.      */
  486.     public function invitationGETAction(Request $request$uuid)
  487.     {
  488.         return $this->_entityGET($request"invitation"$uuid);
  489.     }
  490.     /**
  491.      * @Route("/invitation", name="invitation_post_uuid", methods={"POST"})
  492.      * @param $request
  493.      */
  494.     public function invitationPOSTAction(Request $request)
  495.     {
  496.         return $this->_entityPOST($request"invitation");
  497.     }
  498.     /**
  499.      * @Route("/invitation/{uuid}", name="invitation_put_uuid", methods={"PUT"})
  500.      * @param $request
  501.      */
  502.     public function invitationPUTAction(Request $request$uuid)
  503.     {
  504.         return $this->_entityPUT($request"invitation"$uuid);
  505.     }
  506.     /**
  507.      * @Route("/invitation/{uuid}", name="invitation_delete_uuid", methods={"DELETE"})
  508.      * @param $request
  509.      */
  510.     public function invitationDELETEAction(Request $request$uuid)
  511.     {
  512.         return $this->_entityDELETE($request"invitation"$uuid);
  513.     }
  514. }