<?php
namespace Whater\UI\WebBundle\Controller\User\Api;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use JMS\Serializer\SerializationContext;
use FOS\RestBundle\Controller\Annotations\View;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Whater\UI\WebBundle\Controller\AbstractBusController;
use Hateoas\Representation\Factory\PagerfantaFactory;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Whater\Application\UseCase\User\CommandRequest\AddUserToOrganizationCommand;
use Whater\Application\UseCase\User\CommandRequest\AdminAddWhaterCoinsToUserCommand;
use Whater\Application\UseCase\User\CommandRequest\DeleteUserCommand;
use Whater\Infrastructure\CommonBundle\Pagination\PagerTrait;
use Whater\Application\UseCase\User\CommandRequest\ListUserCommand;
use Whater\Application\UseCase\User\CommandRequest\RemoveUserFromOrganizationCommand;
use Whater\Infrastructure\UserBundle\Form\Type\ListUserType;
use Whater\Domain\User\Model\Role;
use Whater\Domain\User\Model\User;
use Whater\Infrastructure\UserBundle\Form\Type\AddUserToOrganizationType;
use Whater\Infrastructure\UserBundle\Form\Type\AdminAddWhaterCoinsToUserType;
use Whater\Infrastructure\UserBundle\Form\Type\RemoveUserFromOrganizationType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Writer as Writer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Whater\Application\UseCase\User\CommandRequest\ImportUsersExcelCommand;
use Whater\Infrastructure\UserBundle\Form\Type\ImportUsersExcelType;
/**
* @Route("/web-api/admin/user")
*/
class AdminUserApiController extends AbstractBusController
{
use PagerTrait;
/**
* @Route("/list", name="web_api_admin_users_list", defaults={"_format" = "json"})
* @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
*/
public function getUsersAction(Request $request)
{
try {
// User
$user = $this->getGrantedUser();
if (empty($user)) {
throw new AccessDeniedHttpException();
}
$form = $this->getFormFactory()->create(
ListUserType::class,
ListUserCommand::convertToDTO(),
array(
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$command = ListUserCommand::fromDTO($form->getData(), $user);
$pager = $this->handle($command);
return (new PagerfantaFactory())->createRepresentation($pager, new \Hateoas\Configuration\Route('web_api_admin_users_list'));
} else {
return $this->sendBadRequestResponse('user.exception.invalid_query');
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/list_whaterpoints", name="web_api_private_get_user_whaterpoints", defaults={"_format" = "json"})
* @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
*/
public function getUserWhaterpointsAction(Request $request)
{
try {
// User
$user = $this->getGrantedUser();
if (empty($user)) {
throw new AccessDeniedHttpException();
}
$form = $this->getFormFactory()->create(
ListUserType::class,
ListUserCommand::convertToDTO(),
array(
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$command = ListUserCommand::fromDTO($form->getData(), $user);
$pager = $this->handle($command);
return (new PagerfantaFactory())->createRepresentation($pager, new \Hateoas\Configuration\Route('web_api_admin_users_list'));
} else {
return $this->sendBadRequestResponse('user.exception.invalid_query');
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/add-user-to-organization", name="web_api_admin_add_user_to_organization", defaults={"_format" = "json"})
* * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAddUserToOrganization"})
*/
public function postAddUserToOrganizationAction(Request $request)
{
try {
// User
$grantUser = $this->getGrantedUser();
if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
return $this->sendBadRequestResponse('access_not_allowed!');
}
if (empty($grantUser)) {
throw new AccessDeniedHttpException();
}
$form = $this->getFormFactory()->create(
AddUserToOrganizationType::class,
AddUserToOrganizationCommand::convertToDTO(),
array(
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$addUserToOrganizationCommand = AddUserToOrganizationCommand::fromDTO($form->getData(), $grantUser);
$user = $this->handle($addUserToOrganizationCommand);
$this->setFlash('success', 'Añadido el usuario ' . $user->email() . ' a la empresa');
return $user;
} else {
return $this->sendBadRequestResponse('user.exception.invalid_query');
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/add-whatercoins-to-user", name="web_api_admin_add_whatercoins_to_user", defaults={"_format" = "json"})
* * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAddWhaterCoinsToUser"})
*/
public function postAddWhaterCoinsToUserAction(Request $request)
{
try {
// User
$grantUser = $this->getGrantedUser();
if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
return $this->sendBadRequestResponse('access_not_allowed!');
}
if (empty($grantUser)) {
throw new AccessDeniedHttpException();
}
$form = $this->getFormFactory()->create(
AdminAddWhaterCoinsToUserType::class,
AdminAddWhaterCoinsToUserCommand::convertToDTO(),
array(
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$addUserToOrganizationCommand = AdminAddWhaterCoinsToUserCommand::fromDTO($form->getData(), $grantUser);
$user = $this->handle($addUserToOrganizationCommand);
$this->setFlash('success', 'Añadidos los whatercoins correctamente al usuario');
return $user;
} else {
return $this->sendBadRequestResponse('user.exception.invalid_query');
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/remove-user-from-organization", name="web_api_admin_remove_user_from_organization", defaults={"_format" = "json"})
* * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiRemoveUserFromOrganization"})
*/
public function postAdminRemoveUserFromOrganizationAction(Request $request)
{
try {
// User
$grantUser = $this->getGrantedUser();
if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
return $this->sendBadRequestResponse('access_not_allowed!');
}
if (empty($grantUser)) {
throw new AccessDeniedHttpException();
}
$form = $this->getFormFactory()->create(
RemoveUserFromOrganizationType::class,
RemoveUserFromOrganizationCommand::convertToDTO(),
array(
'csrf_protection' => false,
)
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$removeUserFromOrganizationCommand = RemoveUserFromOrganizationCommand::fromDTO($form->getData(), $grantUser);
$user = $this->handle($removeUserFromOrganizationCommand);
$this->setFlash('success', 'Eliminado el usuario ' . $user->email() . ' de la empresa');
return $user;
} else {
return $this->sendBadRequestResponse('user.exception.invalid_query');
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/delete/{userId}", name="web_api_admin_remove_user", defaults={"_format" = "json"})
* * @View(serializerEnableMaxDepthChecks=true, serializerGroups={"Default", "ApiAdminUserList"})
*/
public function postAdminRemoveUserAction(Request $request, $userId)
{
try {
// User
$grantUser = $this->getGrantedUser();
if (!$grantUser->hasRole(Role::ROLE_ADMIN)) {
return $this->sendBadRequestResponse('access_not_allowed!');
}
if (empty($grantUser)) {
throw new AccessDeniedHttpException();
}
$deleteUserCommand = new DeleteUserCommand($userId, $grantUser);
$this->handle($deleteUserCommand);
$this->setFlash('success', $this->translator()->trans('admin.user.delete.success'));
return true;
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
}
/**
* @Route("/export-xls", name="web_api_admin_users_xls", defaults={"_format" = "xls"})
*/
public function exportUserToXlsAction(Request $request)
{
// User
$grantUser = $this->getGrantedUser();
if (!($grantUser->hasRole(Role::ROLE_ADMIN))) {
return $this->sendBadRequestResponse('access_not_allowed!');
}
$form = $this->getFormFactory()->create(
ListUserType::class,
ListUserCommand::convertToDTO(),
array(
'csrf_protection' => false
)
);
$form->handleRequest($request);
$result = null;
if ($form->isSubmitted() && $form->isValid()) {
$adminListUserCommand = ListUserCommand::fromDTO($form->getData(), $grantUser);
$result = $this->handle($adminListUserCommand);
}
if (!is_null($result)) {
// solicitamos el servicio 'phpexcel' y creamos el objeto vacio
$spreadsheet = new Spreadsheet();
$now = new \DateTime();
$now->setTimezone(new \DateTimeZone('Europe/Madrid'));
// y le asignamos una serie de propiedades
$spreadsheet->getProperties()
->setCreator("whater.app")
->setLastModifiedBy("whater.app")
->setTitle("Usuarios whater.app");
$spreadsheet->getActiveSheet()->setTitle('whater.app List');
$spreadsheet->setActiveSheetIndex(0)->getStyle('A1:Z1')->getFont()->setBold(true);
$spreadsheet->getSheet(0)->getColumnDimension('A')->setWidth(40);
$spreadsheet->getSheet(0)->getColumnDimension('B')->setWidth(20);
$spreadsheet->getSheet(0)->getColumnDimension('C')->setWidth(40);
$spreadsheet->getSheet(0)->getColumnDimension('D')->setWidth(30);
$spreadsheet->getSheet(0)->getColumnDimension('E')->setWidth(30);
$spreadsheet->getSheet(0)->setCellValue([1, 1], 'Nombre');
$spreadsheet->getSheet(0)->setCellValue([2, 1], 'Apellidos');
$spreadsheet->getSheet(0)->setCellValue([3, 1], 'Email');
$spreadsheet->getSheet(0)->setCellValue([4, 1], 'Ciudad/municipio');
$spreadsheet->getSheet(0)->setCellValue([5, 1], 'Fecha de alta');
$index = 0;
foreach ($result as $user) {
$userName = $user->firstName();
$spreadsheet->getSheet(0)->setCellValue([1, $index + 2], $userName);
$spreadsheet->getSheet(0)->getCell([1, $index + 2])->setDataType(DataType::TYPE_STRING2);
$spreadsheet->getSheet(0)->getStyle([1, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
$spreadsheet->getSheet(0)->getStyle([1, $index + 2])->getFont()->setUnderline(true);
// $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
// $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
$userLastName = $user->lastName();
$spreadsheet->getSheet(0)->setCellValue([2, $index + 2], $userLastName);
$spreadsheet->getSheet(0)->getCell([2, $index + 2])->setDataType(DataType::TYPE_STRING2);
$spreadsheet->getSheet(0)->getStyle([2, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
$spreadsheet->getSheet(0)->getStyle([2, $index + 2])->getFont()->setUnderline(true);
// $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
// $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
$userEmail = $user->email();
$spreadsheet->getSheet(0)->setCellValue([3, $index + 2], $userEmail);
$spreadsheet->getSheet(0)->getCell([3, $index + 2])->setDataType(DataType::TYPE_STRING2);
$spreadsheet->getSheet(0)->getStyle([3, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
$spreadsheet->getSheet(0)->getStyle([3, $index + 2])->getFont()->setUnderline(true);
// $spreadsheet->getSheet(0)->getCellByColumnAndRow(1, $index + 2)->getHyperlink()->setUrl($this->router()->generate('web_public_user_show', array('userId' => $user->id()), UrlGeneratorInterface::ABSOLUTE_URL));
// $spreadsheet->getSheet(0)->getRowDimension($index + 2)->setRowHeight(60);
$townName = '';
if($user->town()){
$townName = $user->town()->name();
$spreadsheet->getSheet(0)->getCell([4, $index + 2])->getHyperlink()->setUrl($this->router()->generate('web_public_town_show', array('townId' => $user->town()->id()), UrlGeneratorInterface::ABSOLUTE_URL));
}
$spreadsheet->getSheet(0)->setCellValue([4, $index + 2], $townName);
$spreadsheet->getSheet(0)->getCell([4, $index + 2])->setDataType(DataType::TYPE_STRING2);
$spreadsheet->getSheet(0)->getStyle([4, $index + 2])->getFont()->setColor(new Color(Color::COLOR_BLUE));
$spreadsheet->getSheet(0)->getStyle([4, $index + 2])->getFont()->setUnderline(true);
$format = 'Y-m-d';
$createdAt = $user->createdAt();
$createAtFormatted = null;
if (!is_null($createdAt)) {
$createAtFormatted = $createdAt->format($format);
}
$spreadsheet->getSheet(0)->setCellValue([5, $index + 2], $createAtFormatted);
$index++;
}
// se crea el writer
$writer = new Writer\Xlsx($spreadsheet);
// se crea el response
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
// y por último se añaden las cabeceras
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'usuarios_' . $now->format('d-m-Y_h-m-s') . '.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
}
}
/**
* @Route("/import-excel", name="web_api_admin_import_users_excel", defaults={"_format" = "xls"})
*/
public function postImportusersExcelAction(Request $request)
{
// User
$user = $this->getGrantedUser();
if (empty($user)) {
throw new AccessDeniedHttpException();
}
try {
$form = $this->getFormFactory()->create(
ImportUsersExcelType::class,
ImportUsersExcelCommand::convertToDTO(),
[
'csrf_protection' => false,
]
);
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$command = ImportUsersExcelCommand::fromDTO($form->getData(), $user);
$result = $this->handle($command);
$this->setFlash('success', $this->translator()->trans('admin.user.import_excel.success'));
return $result;
} else {
return $this->sendBadRequestResponse('user.exception.invalid_file_user_excel');
}
}
} catch (\Exception $e) {
return $this->sendBadRequestResponse($e->getMessage());
}
return $this->sendBadRequestResponse();
}
}