src/UI/WebBundle/Controller/User/Api/AdminUserApiController.php line 50

Open in your IDE?
  1. <?php
  2. namespace Whater\UI\WebBundle\Controller\User\Api;
  3. use FOS\RestBundle\Controller\Annotations\RequestParam;
  4. use JMS\Serializer\SerializationContext;
  5. use FOS\RestBundle\Controller\Annotations\View;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Whater\UI\WebBundle\Controller\AbstractBusController;
  9. use Hateoas\Representation\Factory\PagerfantaFactory;
  10. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  11. use Whater\Application\UseCase\User\CommandRequest\AddUserToOrganizationCommand;
  12. use Whater\Application\UseCase\User\CommandRequest\AdminAddWhaterCoinsToUserCommand;
  13. use Whater\Application\UseCase\User\CommandRequest\DeleteUserCommand;
  14. use Whater\Infrastructure\CommonBundle\Pagination\PagerTrait;
  15. use Whater\Application\UseCase\User\CommandRequest\ListUserCommand;
  16. use Whater\Application\UseCase\User\CommandRequest\RemoveUserFromOrganizationCommand;
  17. use Whater\Infrastructure\UserBundle\Form\Type\ListUserType;
  18. use Whater\Domain\User\Model\Role;
  19. use Whater\Domain\User\Model\User;
  20. use Whater\Infrastructure\UserBundle\Form\Type\AddUserToOrganizationType;
  21. use Whater\Infrastructure\UserBundle\Form\Type\AdminAddWhaterCoinsToUserType;
  22. use Whater\Infrastructure\UserBundle\Form\Type\RemoveUserFromOrganizationType;
  23. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  24. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  25. use PhpOffice\PhpSpreadsheet\Style\Color;
  26. use PhpOffice\PhpSpreadsheet\Writer as Writer;
  27. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  28. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  29. use Symfony\Component\HttpFoundation\StreamedResponse;
  30. use Whater\Application\UseCase\User\CommandRequest\ImportUsersExcelCommand;
  31. use Whater\Infrastructure\UserBundle\Form\Type\ImportUsersExcelType;
  32. /**
  33. * @Route("/web-api/admin/user")
  34. */
  35. class AdminUserApiController extends AbstractBusController
  36. {
  37. use PagerTrait;
  38. /**
  39. * @Route("/list", name="web_api_admin_users_list", defaults={"_format" = "json"})
  40. * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
  41. */
  42. public function getUsersAction(Request $request)
  43. {
  44. try {
  45. // User
  46. $user = $this->getGrantedUser();
  47. if (empty($user)) {
  48. throw new AccessDeniedHttpException();
  49. }
  50. $form = $this->getFormFactory()->create(
  51. ListUserType::class,
  52. ListUserCommand::convertToDTO(),
  53. array(
  54. 'csrf_protection' => false,
  55. )
  56. );
  57. $form->handleRequest($request);
  58. if ($form->isSubmitted() && $form->isValid()) {
  59. $command = ListUserCommand::fromDTO($form->getData(), $user);
  60. $pager = $this->handle($command);
  61. return (new PagerfantaFactory())->createRepresentation($pager, new \Hateoas\Configuration\Route('web_api_admin_users_list'));
  62. } else {
  63. return $this->sendBadRequestResponse('user.exception.invalid_query');
  64. }
  65. } catch (\Exception $e) {
  66. return $this->sendBadRequestResponse($e->getMessage());
  67. }
  68. }
  69. /**
  70. * @Route("/list_whaterpoints", name="web_api_private_get_user_whaterpoints", defaults={"_format" = "json"})
  71. * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
  72. */
  73. public function getUserWhaterpointsAction(Request $request)
  74. {
  75. try {
  76. // User
  77. $user = $this->getGrantedUser();
  78. if (empty($user)) {
  79. throw new AccessDeniedHttpException();
  80. }
  81. $form = $this->getFormFactory()->create(
  82. ListUserType::class,
  83. ListUserCommand::convertToDTO(),
  84. array(
  85. 'csrf_protection' => false,
  86. )
  87. );
  88. $form->handleRequest($request);
  89. if ($form->isSubmitted() && $form->isValid()) {
  90. $command = ListUserCommand::fromDTO($form->getData(), $user);
  91. $pager = $this->handle($command);
  92. return (new PagerfantaFactory())->createRepresentation($pager, new \Hateoas\Configuration\Route('web_api_admin_users_list'));
  93. } else {
  94. return $this->sendBadRequestResponse('user.exception.invalid_query');
  95. }
  96. } catch (\Exception $e) {
  97. return $this->sendBadRequestResponse($e->getMessage());
  98. }
  99. }
  100. /**
  101. * @Route("/add-user-to-organization", name="web_api_admin_add_user_to_organization", defaults={"_format" = "json"})
  102. * * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAddUserToOrganization"})
  103. */
  104. public function postAddUserToOrganizationAction(Request $request)
  105. {
  106. try {
  107. // User
  108. $grantUser = $this->getGrantedUser();
  109. if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
  110. return $this->sendBadRequestResponse('access_not_allowed!');
  111. }
  112. if (empty($grantUser)) {
  113. throw new AccessDeniedHttpException();
  114. }
  115. $form = $this->getFormFactory()->create(
  116. AddUserToOrganizationType::class,
  117. AddUserToOrganizationCommand::convertToDTO(),
  118. array(
  119. 'csrf_protection' => false,
  120. )
  121. );
  122. $form->handleRequest($request);
  123. if ($form->isSubmitted() && $form->isValid()) {
  124. $addUserToOrganizationCommand = AddUserToOrganizationCommand::fromDTO($form->getData(), $grantUser);
  125. $user = $this->handle($addUserToOrganizationCommand);
  126. $this->setFlash('success', 'Añadido el usuario ' . $user->email() . ' a la empresa');
  127. return $user;
  128. } else {
  129. return $this->sendBadRequestResponse('user.exception.invalid_query');
  130. }
  131. } catch (\Exception $e) {
  132. return $this->sendBadRequestResponse($e->getMessage());
  133. }
  134. }
  135. /**
  136. * @Route("/add-whatercoins-to-user", name="web_api_admin_add_whatercoins_to_user", defaults={"_format" = "json"})
  137. * * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAddWhaterCoinsToUser"})
  138. */
  139. public function postAddWhaterCoinsToUserAction(Request $request)
  140. {
  141. try {
  142. // User
  143. $grantUser = $this->getGrantedUser();
  144. if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
  145. return $this->sendBadRequestResponse('access_not_allowed!');
  146. }
  147. if (empty($grantUser)) {
  148. throw new AccessDeniedHttpException();
  149. }
  150. $form = $this->getFormFactory()->create(
  151. AdminAddWhaterCoinsToUserType::class,
  152. AdminAddWhaterCoinsToUserCommand::convertToDTO(),
  153. array(
  154. 'csrf_protection' => false,
  155. )
  156. );
  157. $form->handleRequest($request);
  158. if ($form->isSubmitted() && $form->isValid()) {
  159. $addUserToOrganizationCommand = AdminAddWhaterCoinsToUserCommand::fromDTO($form->getData(), $grantUser);
  160. $user = $this->handle($addUserToOrganizationCommand);
  161. $this->setFlash('success', 'Añadidos los whatercoins correctamente al usuario');
  162. return $user;
  163. } else {
  164. return $this->sendBadRequestResponse('user.exception.invalid_query');
  165. }
  166. } catch (\Exception $e) {
  167. return $this->sendBadRequestResponse($e->getMessage());
  168. }
  169. }
  170. /**
  171. * @Route("/remove-user-from-organization", name="web_api_admin_remove_user_from_organization", defaults={"_format" = "json"})
  172. * * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiRemoveUserFromOrganization"})
  173. */
  174. public function postAdminRemoveUserFromOrganizationAction(Request $request)
  175. {
  176. try {
  177. // User
  178. $grantUser = $this->getGrantedUser();
  179. if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
  180. return $this->sendBadRequestResponse('access_not_allowed!');
  181. }
  182. if (empty($grantUser)) {
  183. throw new AccessDeniedHttpException();
  184. }
  185. $form = $this->getFormFactory()->create(
  186. RemoveUserFromOrganizationType::class,
  187. RemoveUserFromOrganizationCommand::convertToDTO(),
  188. array(
  189. 'csrf_protection' => false,
  190. )
  191. );
  192. $form->handleRequest($request);
  193. if ($form->isSubmitted() && $form->isValid()) {
  194. $removeUserFromOrganizationCommand = RemoveUserFromOrganizationCommand::fromDTO($form->getData(), $grantUser);
  195. $user = $this->handle($removeUserFromOrganizationCommand);
  196. $this->setFlash('success', 'Eliminado el usuario ' . $user->email() . ' de la empresa');
  197. return $user;
  198. } else {
  199. return $this->sendBadRequestResponse('user.exception.invalid_query');
  200. }
  201. } catch (\Exception $e) {
  202. return $this->sendBadRequestResponse($e->getMessage());
  203. }
  204. }
  205. /**
  206. * @Route("/delete/{userId}", name="web_api_admin_remove_user", defaults={"_format" = "json"})
  207. * * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
  208. */
  209. public function postAdminRemoveUserAction(Request $request, $userId)
  210. {
  211. try {
  212. // User
  213. $grantUser = $this->getGrantedUser();
  214. if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
  215. return $this->sendBadRequestResponse('access_not_allowed!');
  216. }
  217. if (empty($grantUser)) {
  218. throw new AccessDeniedHttpException();
  219. }
  220. $deleteUserCommand = new DeleteUserCommand($userId, $grantUser);
  221. $this->handle($deleteUserCommand);
  222. $this->setFlash('success', $this->translator()->trans('admin.user.delete.success'));
  223. return true;
  224. } catch (\Exception $e) {
  225. return $this->sendBadRequestResponse($e->getMessage());
  226. }
  227. }
  228. /**
  229. * @Route("/export-xls", name="web_api_admin_users_xls", defaults={"_format" = "xls"})
  230. */
  231. public function exportUserToXlsAction(Request $request)
  232. {
  233. // User
  234. $grantUser = $this->getGrantedUser();
  235. if (!($grantUser->hasRole(Role::ROLE_ADMIN))) {
  236. return $this->sendBadRequestResponse('access_not_allowed!');
  237. }
  238. $form = $this->getFormFactory()->create(
  239. ListUserType::class,
  240. ListUserCommand::convertToDTO(),
  241. array(
  242. 'csrf_protection' => false
  243. )
  244. );
  245. $form->handleRequest($request);
  246. $result = null;
  247. if ($form->isSubmitted() && $form->isValid()) {
  248. $adminListUserCommand = ListUserCommand::fromDTO($form->getData(), $grantUser);
  249. $result = $this->handle($adminListUserCommand);
  250. }
  251. if (!is_null($result)) {
  252. // solicitamos el servicio 'phpexcel' y creamos el objeto vacio
  253. $spreadsheet = new Spreadsheet();
  254. $now = new \DateTime();
  255. $now->setTimezone(new \DateTimeZone('Europe/Madrid'));
  256. // y le asignamos una serie de propiedades
  257. $spreadsheet->getProperties()
  258. ->setCreator("whater.app")
  259. ->setLastModifiedBy("whater.app")
  260. ->setTitle("Usuarios whater.app");
  261. $spreadsheet->getActiveSheet()->setTitle('whater.app List');
  262. $spreadsheet->setActiveSheetIndex(0)->getStyle('A1:Z1')->getFont()->setBold(true);
  263. $spreadsheet->getSheet(0)->getColumnDimension('A')->setWidth(40);
  264. $spreadsheet->getSheet(0)->getColumnDimension('B')->setWidth(20);
  265. $spreadsheet->getSheet(0)->getColumnDimension('C')->setWidth(40);
  266. $spreadsheet->getSheet(0)->getColumnDimension('D')->setWidth(30);
  267. $spreadsheet->getSheet(0)->getColumnDimension('E')->setWidth(30);
  268. $spreadsheet->getSheet(0)->setCellValue([1, 1], 'Nombre');
  269. $spreadsheet->getSheet(0)->setCellValue([2, 1], 'Apellidos');
  270. $spreadsheet->getSheet(0)->setCellValue([3, 1], 'Email');
  271. $spreadsheet->getSheet(0)->setCellValue([4, 1], 'Ciudad/municipio');
  272. $spreadsheet->getSheet(0)->setCellValue([5, 1], 'Fecha de alta');
  273. $index = 0;
  274. foreach ($result as $user) {
  275. $userName = $user->firstName();
  276. $spreadsheet->getSheet(0)->setCellValue([1, $index + 2], $userName);
  277. $spreadsheet->getSheet(0)->getCell([1, $index + 2])->setDataType(DataType::TYPE_STRING2);
  278. $spreadsheet->getSheet(0)->getStyle([1, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
  279. $spreadsheet->getSheet(0)->getStyle([1, $index + 2])->getFont()->setUnderline(true);
  280. // $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
  281. // $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
  282. $userLastName = $user->lastName();
  283. $spreadsheet->getSheet(0)->setCellValue([2, $index + 2], $userLastName);
  284. $spreadsheet->getSheet(0)->getCell([2, $index + 2])->setDataType(DataType::TYPE_STRING2);
  285. $spreadsheet->getSheet(0)->getStyle([2, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
  286. $spreadsheet->getSheet(0)->getStyle([2, $index + 2])->getFont()->setUnderline(true);
  287. // $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
  288. // $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
  289. $userEmail = $user->email();
  290. $spreadsheet->getSheet(0)->setCellValue([3, $index + 2], $userEmail);
  291. $spreadsheet->getSheet(0)->getCell([3, $index + 2])->setDataType(DataType::TYPE_STRING2);
  292. $spreadsheet->getSheet(0)->getStyle([3, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
  293. $spreadsheet->getSheet(0)->getStyle([3, $index + 2])->getFont()->setUnderline(true);
  294. // $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
  295. // $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
  296. $townName = '';
  297. if($user->town()){
  298. $townName = $user->town()->name();
  299. $spreadsheet->getSheet(0)->getCell([4, $index + 2])->getHyperlink()->setUrl($this->router()->generate('web_public_town_show', array('townId' => $user->town()->id()), UrlGeneratorInterface::ABSOLUTE_URL));
  300. }
  301. $spreadsheet->getSheet(0)->setCellValue([4, $index + 2], $townName);
  302. $spreadsheet->getSheet(0)->getCell([4, $index + 2])->setDataType(DataType::TYPE_STRING2);
  303. $spreadsheet->getSheet(0)->getStyle([4, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
  304. $spreadsheet->getSheet(0)->getStyle([4, $index + 2])->getFont()->setUnderline(true);
  305. $format = 'Y-m-d';
  306. $createdAt = $user->createdAt();
  307. $createAtFormatted = null;
  308. if (!is_null($createdAt)) {
  309. $createAtFormatted = $createdAt->format($format);
  310. }
  311. $spreadsheet->getSheet(0)->setCellValue([5, $index + 2], $createAtFormatted);
  312. $index++;
  313. }
  314. // se crea el writer
  315. $writer = new Writer\Xlsx($spreadsheet);
  316. // se crea el response
  317. $response = new StreamedResponse(
  318. function () use ($writer) {
  319. $writer->save('php://output');
  320. }
  321. );
  322. // y por último se añaden las cabeceras
  323. $dispositionHeader = $response->headers->makeDisposition(
  324. ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  325. 'usuarios_' . $now->format('d-m-Y_h-m-s') . '.xls'
  326. );
  327. $response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
  328. $response->headers->set('Pragma', 'public');
  329. $response->headers->set('Cache-Control', 'maxage=1');
  330. $response->headers->set('Content-Disposition', $dispositionHeader);
  331. return $response;
  332. }
  333. }
  334. /**
  335. * @Route("/import-excel", name="web_api_admin_import_users_excel", defaults={"_format" = "xls"})
  336. */
  337. public function postImportusersExcelAction(Request $request)
  338. {
  339. // User
  340. $user = $this->getGrantedUser();
  341. if (empty($user)) {
  342. throw new AccessDeniedHttpException();
  343. }
  344. try {
  345. $form = $this->getFormFactory()->create(
  346. ImportUsersExcelType::class,
  347. ImportUsersExcelCommand::convertToDTO(),
  348. [
  349. 'csrf_protection' => false,
  350. ]
  351. );
  352. if ('POST' === $request->getMethod()) {
  353. $form->handleRequest($request);
  354. if ($form->isSubmitted() && $form->isValid()) {
  355. $command = ImportUsersExcelCommand::fromDTO($form->getData(), $user);
  356. $result = $this->handle($command);
  357. $this->setFlash('success', $this->translator()->trans('admin.user.import_excel.success'));
  358. return $result;
  359. } else {
  360. return $this->sendBadRequestResponse('user.exception.invalid_file_user_excel');
  361. }
  362. }
  363. } catch (\Exception $e) {
  364. return $this->sendBadRequestResponse($e->getMessage());
  365. }
  366. return $this->sendBadRequestResponse();
  367. }
  368. }