src/MDS/ApiBundle/Controller/ApiProposalController.php line 207

Open in your IDE?
  1. <?php
  2. namespace App\MDS\ApiBundle\Controller;
  3. use App\Entity\Card;
  4. use App\MDS\ApiBundle\Auth;
  5. use App\MDS\EventsBundle\Entity\Proposal;
  6. use App\MDS\EventsBundle\Entity\ProposalAgents;
  7. use App\MDS\EventsBundle\Entity\ProposalDocument;
  8. use App\Service\ProposalSupplierServicesService;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use FOS\RestBundle\Controller\AbstractFOSRestController;
  11. use FOS\RestBundle\Controller\Annotations as Rest;
  12. use Symfony\Component\HttpFoundation\File\UploadedFile;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. class ApiProposalController extends AbstractFOSRestController
  16. {
  17.     /**
  18.      * Devuelve una lista de todos los proposals del usuario conectado
  19.      * 
  20.      * @param Request $request (Debe recibirse el token de usuario en el header)
  21.      * 
  22.      * @Rest\Get("/api/proposal/list/user")
  23.      */
  24.     function listProposalUser(Request $request): JsonResponse
  25.     {
  26.         $token $request->headers->get('token');
  27.         try {
  28.             Auth::check($token);
  29.         } catch (\Throwable $th) {
  30.             return new JsonResponse($thJsonResponse::HTTP_BAD_REQUEST);
  31.         }
  32.         $em $this->getDoctrine()->getManager();
  33.         // $tokenData = Auth::getData($token);
  34.         //Coger los proposals del usuario
  35.         // $proposalsAgent = $em->getRepository(ProposalAgents::class)->findByAgOne($tokenData->uid);
  36.         // $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgTwo($tokenData->uid));
  37.         // $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgThree($tokenData->uid));
  38.         // $proposalsAgent = array_merge($proposalsAgent, $em->getRepository(ProposalAgents::class)->findByAgFour($tokenData->uid));
  39.         // Ordenar el array por el ID del Proposal de manera descendente
  40.         // usort($proposalsAgent, function ($a, $b) {
  41.         //     // Asumiendo que tus objetos tienen un método getId() para obtener el ID
  42.         //     return $b->getId() <=> $a->getId();
  43.         // });
  44.         $proposals = [];
  45.         // foreach ($proposalsAgent as $proposalAgent) {
  46.         //     $proposal = $em->getRepository(Proposal::class)->findOneBy(['id' => $proposalAgent->getIdProp()]);
  47.         //     //Si no hay proposals para el agente pasamos al siguiente
  48.         //     if (empty($proposal)) {
  49.         //         continue;
  50.         //     }
  51.         //     $proposals[] = [
  52.         //         'id' => $proposal->getId(),
  53.         //         'name' => $proposal->getName(),
  54.         //         'title' => $proposal->getTitle(),
  55.         //         'commission' => $proposal->getCommission(),
  56.         //         'pax' => $proposal->getPax(),
  57.         //         'bedrooms' => $proposal->getBedrooms(),
  58.         //         'briefing' => $proposal->getBriefing(),
  59.         //         'observation' => $proposal->getObservation(),
  60.         //         'category' => $proposal->getCategory(),
  61.         //         'status' => $proposal->getStatus()
  62.         //     ];
  63.         // }
  64.         $proposalsFind $em->getRepository(Proposal::class)->findAll();
  65.         foreach ($proposalsFind as $proposal) {
  66.             $proposals[] = [
  67.                 'id' => $proposal->getId(),
  68.                 'name' => $proposal->getName(),
  69.                 'title' => $proposal->getTitle(),
  70.                 'commission' => $proposal->getCommission(),
  71.                 'pax' => $proposal->getPax(),
  72.                 'bedrooms' => $proposal->getBedrooms(),
  73.                 'briefing' => $proposal->getBriefing(),
  74.                 'observation' => $proposal->getObservation(),
  75.                 'category' => $proposal->getCategory(),
  76.                 'status' => $proposal->getStatus()
  77.             ];
  78.         }
  79.         return new JsonResponse($proposalsJsonResponse::HTTP_OK);
  80.     }
  81.     /**
  82.      * Guarda el documento (imagen o PDF) relacionado al proposal indicado.
  83.      *
  84.      * @param Request $request (Recibe el token y los datos a guardar)
  85.      *
  86.      * @Rest\Post("/api/proposal/save/document/img")
  87.      */
  88.     function saveDocumentImg(Request $requestEntityManagerInterface $emProposalSupplierServicesService $proposalSupplierServicesService): JsonResponse
  89.     {
  90.         $token $request->headers->get('token');
  91.         try {
  92.             Auth::check($token);
  93.         } catch (\Throwable $th) {
  94.             return new JsonResponse(['error' => $th->getMessage()], JsonResponse::HTTP_BAD_REQUEST);
  95.         }
  96.         $tokenData Auth::getData($token);
  97.         $idProposal $request->get('idProposal');
  98.         $title $request->get('title');
  99.         $cardId $request->get('card');
  100.         $description $request->get('description');
  101.         $price $request->get('price');
  102.         $buyDate $request->get('buyDate') ? new \DateTime($request->get('buyDate')) : new \DateTime();
  103.         // Verifica si se ha proporcionado el archivo
  104.         if ($request->files->has('document')) {
  105.             /** @var UploadedFile $uploadedFile */
  106.             $uploadedFile $request->files->get('document');
  107.             // Permitimos imágenes (jpg, jpeg, png, pdf) y también pdf
  108.             $allowedExtensions = ['jpg''jpeg''png''pdf'];
  109.             $extension strtolower($uploadedFile->getClientOriginalExtension());
  110.             if ($uploadedFile instanceof UploadedFile && in_array($extension$allowedExtensions)) {
  111.                 try {
  112.                     // Generar nombre único y mover el archivo
  113.                     $fileName $idProposal '-' uniqid() . '.' $extension;
  114.                     $uploadedFile->move(
  115.                         $this->getParameter('proposal_document'), // Directorio de destino
  116.                         $fileName
  117.                     );
  118.                 } catch (\Throwable $th) {
  119.                     return new JsonResponse(['error' => 'Error al guardar el archivo.'], JsonResponse::HTTP_BAD_REQUEST);
  120.                 }
  121.                 // Buscar la tarjeta
  122.                 $card $em->getRepository(Card::class)->findOneBy(['id' => $cardId]);
  123.                 // Crear ProposalDocument
  124.                 $proposalDocument = new ProposalDocument();
  125.                 $proposalDocument->setProposalId($idProposal);
  126.                 $proposalDocument->setFile($fileName);
  127.                 $proposalDocument->setExtension($extension);
  128.                 $proposalDocument->setTitle($title);
  129.                 $proposalDocument->setCreatedId($tokenData->uid);
  130.                 $proposalDocument->setUpdatedId($tokenData->uid);
  131.                 $proposalDocument->setCategory('DOCUMENTO DE ADMINISTRACIÓN');
  132.                 $proposalDocument->setCard($card);
  133.                 $proposalDocument->setDescription($description);
  134.                 $proposalDocument->setPrice(0.0);
  135.                 $proposalDocument->setBuyDate($buyDate);
  136.                 // Comprobamos si el precio viene vacío o no
  137.                 if (!empty($price)) {
  138.                     $proposalDocument->setPrice($price);
  139.                     $data_costs = [
  140.                         'supplierId' => 0,
  141.                         'proposalId' => $idProposal,
  142.                         'name' => $title,
  143.                         'commission' => 0,
  144.                         'total' => $price,
  145.                         'opIva' => 1,
  146.                         'iva' => 0,
  147.                         'datePayment' => '',
  148.                         'waytopay' => 'VISA',
  149.                     ];
  150.                     $proposalSupplierServicesService->supplierServicesCostAdd($data_costs$tokenData->uid$em);
  151.                 }
  152.                 $em->persist($proposalDocument);
  153.                 $em->flush();
  154.                 return new JsonResponse(['msg' => 'Documento guardado correctamente.'], JsonResponse::HTTP_OK);
  155.             } else {
  156.                 return new JsonResponse(['error' => 'El archivo no es válido (solo se permiten imágenes jpg, jpeg, png y archivos PDF).'], JsonResponse::HTTP_BAD_REQUEST);
  157.             }
  158.         } else {
  159.             return new JsonResponse(['error' => 'No se ha proporcionado un archivo válido.'], JsonResponse::HTTP_BAD_REQUEST);
  160.         }
  161.     }
  162.     /**
  163.      * Devuelve los documentos asociados al proposal que recibe
  164.      * 
  165.      * @param Request $request
  166.      * 
  167.      * @Rest\Post("/api/proposal/get/documents")
  168.      */
  169.     function getProposalDocuments(Request $request): JsonResponse
  170.     {
  171.         $token $token $request->headers->get('token');
  172.         try {
  173.             Auth::check($token);
  174.         } catch (\Throwable $th) {
  175.             return new JsonResponse($thJsonResponse::HTTP_BAD_REQUEST);
  176.         }
  177.         $em $this->getDoctrine()->getManager();
  178.         $tokenData Auth::getData($token);
  179.         $documents $em->getRepository(ProposalDocument::class)->findBy(['proposalId' => $request->get('idProposal')]);
  180.         $documentsArray = [];
  181.         foreach ($documents as $document) {
  182.             $documentsArray[] = [
  183.                 'id' => $document->getId(),
  184.                 'file' => $_SERVER['HTTP_HOST'] . "/assets/document/proposals/" $document->getFile(),
  185.                 'extension' => $document->getExtension(),
  186.                 'title' => $document->getTitle(),
  187.                 'category' => $document->getCategory(),
  188.                 'disabled' => $document->getDisabled(),
  189.             ];
  190.         }
  191.         return new JsonResponse($documentsArrayJsonResponse::HTTP_OK);
  192.     }
  193. }