352 líneas
18KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Admin;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\EntityRepository;
  5. use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  7. use FOS\UserBundle\Model\UserManagerInterface;
  8. use Lc\ShopBundle\Context\FilterMultipleMerchantsInterface;
  9. use Lc\ShopBundle\Context\MerchantInterface;
  10. use Lc\ShopBundle\Context\MerchantUtilsInterface;
  11. use Lc\ShopBundle\Context\StatusInterface;
  12. use Lc\ShopBundle\Context\TreeInterface;
  13. use Lc\ShopBundle\Form\AbstractEditPositionType;
  14. use Lc\ShopBundle\Services\Utils;
  15. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  16. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  17. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  18. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  19. use Symfony\Component\Form\FormEvent;
  20. use Symfony\Component\Form\FormEvents;
  21. use Symfony\Component\Security\Core\Security;
  22. class AdminController extends EasyAdminController
  23. {
  24. protected $security;
  25. protected $userManager;
  26. protected $em;
  27. protected $utils;
  28. protected $merchantUtils ;
  29. protected $mailjetTransport ;
  30. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em, Utils $utils,
  31. MerchantUtilsInterface $merchantUtils, MailjetTransport $mailjetTransport)
  32. {
  33. $this->security = $security;
  34. $this->userManager = $userManager;
  35. $this->em = $em;
  36. $this->utils = $utils;
  37. $this->merchantUtils = $merchantUtils ;
  38. $this->mailjetTransport = $mailjetTransport ;
  39. }
  40. /**
  41. * Réécriture de show action pr rediriger vers l'édition
  42. */
  43. public function showAction()
  44. {
  45. $id = $this->request->query->get('id');
  46. $entity = $this->request->query->get('entity');
  47. return $this->redirectToRoute('easyadmin', [
  48. 'action' => 'edit',
  49. 'entity' => $entity,
  50. 'id' => $id
  51. ]);
  52. }
  53. /**
  54. * Réécriture de removeEntity pour passer les status à -1
  55. */
  56. protected function removeEntity($entity)
  57. {
  58. if ($entity instanceof StatusInterface) {
  59. $entity->setStatus(-1);
  60. $this->em->persist($entity);
  61. $this->em->flush();
  62. } else {
  63. parent::removeEntity($entity);
  64. }
  65. }
  66. protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  67. {
  68. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  69. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  70. }
  71. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  72. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  73. else $dqlFilter .= sprintf(' entity.status > = 0');
  74. }
  75. return $dqlFilter;
  76. }
  77. protected function commonQueryFilter($entityClass, $queryBuilder)
  78. {
  79. if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
  80. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
  81. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  82. }
  83. }
  84. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  85. {
  86. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  87. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
  88. $this->commonQueryFilter($entityClass, $queryBuilder);
  89. return $queryBuilder;
  90. }
  91. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  92. {
  93. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  94. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  95. $this->commonQueryFilter($entityClass, $queryBuilder);
  96. return $queryBuilder;
  97. }
  98. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  99. {
  100. $parameters = array_merge(
  101. $parameters,
  102. $this->getTwigExtraParameters()
  103. );
  104. return parent::renderTemplate($actionName, $templatePath, $parameters);
  105. }
  106. public function getTwigExtraParameters()
  107. {
  108. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  109. $merchants = $repositoryMerchant->findAll();
  110. $user = $this->security->getUser();
  111. return [
  112. 'merchants' => $merchants,
  113. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  114. ];
  115. }
  116. public function listChildrenAction()
  117. {
  118. $this->dispatch(EasyAdminEvents::PRE_LIST);
  119. $id = $this->request->query->get('id');
  120. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  121. $easyadmin = $this->request->attributes->get('easyadmin');
  122. $entity = $easyadmin['item'];
  123. $fields = $this->entity['list']['fields'];
  124. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  125. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  126. $parameters = [
  127. 'paginator' => $paginator,
  128. 'fields' => $fields,
  129. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  130. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  131. 'entity' => $entity,
  132. ];
  133. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  134. }
  135. public function sortAction()
  136. {
  137. $this->dispatch(EasyAdminEvents::PRE_LIST);
  138. $entity = null;
  139. //Replace this with query builder function, do not use finAll of easyAdmin
  140. if ($this->request->query->get('id')) {
  141. $id = $this->request->query->get('id');
  142. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  143. $easyadmin = $this->request->attributes->get('easyadmin');
  144. $entity = $easyadmin['item'];
  145. }
  146. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  147. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  148. $fields = $this->entity['list']['fields'];
  149. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  150. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  151. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  152. ->add('entities', CollectionType::class, array(
  153. 'required' => true,
  154. 'allow_add' => true,
  155. 'entry_type' => AbstractEditPositionType::class,
  156. ))
  157. ->getForm();
  158. $positionForm->handleRequest($this->request);
  159. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  160. $class = $this->entity['class'];
  161. $repo = $this->em->getRepository($class);
  162. $latsPos = 0;
  163. foreach ($positionForm->get('entities')->getData() as $elm) {
  164. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  165. $entity = $repo->find($elm['id']);
  166. $entity->setPosition($elm['position']);
  167. $this->em->persist($entity);
  168. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  169. $latsPos = $elm['position'];
  170. }
  171. //die();
  172. //to do récupérer les élements hors ligne et incrémenter position
  173. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  174. $latsPos++;
  175. $offlineEntity->setPosition($latsPos);
  176. $this->em->persist($offlineEntity);
  177. }*/
  178. $this->em->flush();
  179. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  180. return $this->redirectToReferrer();
  181. }
  182. $parameters = [
  183. 'paginator' => $paginator,
  184. 'fields' => $fields,
  185. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  186. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  187. 'postion_form' => $positionForm->createView(),
  188. 'entity' => $entity,
  189. 'sortable' => true
  190. ];
  191. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  192. }
  193. public function createEntityFormBuilder($entity, $view)
  194. {
  195. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  196. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  197. if ($entity instanceof StatusInterface) {
  198. $formBuilder->add('status', ChoiceType::class, array(
  199. 'choices' =>array(
  200. 'field.default.statusOptions.offline' => '0',
  201. 'field.default.statusOptions.online' => '1'
  202. ),
  203. 'expanded' => true,
  204. 'required' => true,
  205. 'translation_domain'=> 'lcshop'
  206. )
  207. );
  208. }
  209. if ($entity instanceof TreeInterface) {
  210. $formBuilder->add('parent', EntityType::class, array(
  211. 'class' => $this->entity['class'],
  212. 'query_builder' => function (EntityRepository $repo) use ($id) {
  213. return $repo->createQueryBuilder('e')
  214. ->where('e.parent is NULL')
  215. ->andWhere('e.status >= 0')
  216. ->orderBy('e.status', "DESC");
  217. },
  218. 'required' => false,
  219. )
  220. );
  221. }
  222. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  223. $form = $event->getForm();
  224. $allChilds = $form->all();
  225. foreach ($allChilds as $child) {
  226. $statusInterface = false;
  227. $treeInterface = false;
  228. $type = $child->getConfig()->getType()->getInnerType();
  229. if ($type instanceof EntityType) {
  230. $passedOptions = $child->getConfig()->getOptions();
  231. $classImplements = class_implements($passedOptions['class']);
  232. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements) ;
  233. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements) ;
  234. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  235. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  236. $statusInterface = true;
  237. }
  238. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  239. $treeInterface = true;
  240. }
  241. $propertyMerchant = 'merchant';
  242. if($isFilterMultipleMerchantsInterface) {
  243. $propertyMerchant .= 's' ;
  244. }
  245. $form->add($child->getName(), EntityType::class, array(
  246. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  247. 'label' => $passedOptions['label'],
  248. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  249. 'placeholder' => '--',
  250. 'translation_domain'=> 'lcshop',
  251. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  252. $queryBuilder = $repo->createQueryBuilder('e');
  253. $propertyMerchant = 'e.' . $propertyMerchant;
  254. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  255. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  256. } else {
  257. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  258. }
  259. if($statusInterface){
  260. $queryBuilder->andWhere('e.status >= 0');
  261. }
  262. if($treeInterface && $child->getName() =='parent'){
  263. $queryBuilder->andWhere('e.parent is null');
  264. }
  265. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  266. return $queryBuilder;
  267. },
  268. 'choice_label' => function($choice) {
  269. if($choice instanceof StatusInterface && $choice->getStatus() == 0){
  270. return $choice.' [hors ligne]';
  271. }
  272. return $choice;
  273. },
  274. 'required' => $passedOptions['required'],
  275. )
  276. );
  277. }
  278. }
  279. }
  280. });
  281. return $formBuilder;
  282. }
  283. }