You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 line
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. dump($paginator->getCurrentPageResults());
  151. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  152. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  153. ->add('entities', CollectionType::class, array(
  154. 'required' => true,
  155. 'allow_add' => true,
  156. 'entry_type' => AbstractEditPositionType::class,
  157. ))
  158. ->getForm();
  159. $positionForm->handleRequest($this->request);
  160. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  161. $class = $this->entity['class'];
  162. $repo = $this->em->getRepository($class);
  163. $latsPos = 0;
  164. foreach ($positionForm->get('entities')->getData() as $elm) {
  165. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  166. $entity = $repo->find($elm['id']);
  167. $entity->setPosition($elm['position']);
  168. $this->em->persist($entity);
  169. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  170. $latsPos = $elm['position'];
  171. }
  172. //die();
  173. //to do récupérer les élements hors ligne et incrémenter position
  174. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  175. $latsPos++;
  176. $offlineEntity->setPosition($latsPos);
  177. $this->em->persist($offlineEntity);
  178. }*/
  179. $this->em->flush();
  180. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  181. return $this->redirectToReferrer();
  182. }
  183. $parameters = [
  184. 'paginator' => $paginator,
  185. 'fields' => $fields,
  186. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  187. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  188. 'postion_form' => $positionForm->createView(),
  189. 'entity' => $entity,
  190. 'sortable' => true
  191. ];
  192. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  193. }
  194. public function createEntityFormBuilder($entity, $view)
  195. {
  196. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  197. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  198. if ($entity instanceof StatusInterface) {
  199. $formBuilder->add('status', ChoiceType::class, array(
  200. 'choices' =>array(
  201. 'field.default.statusOptions.offline' => '0',
  202. 'field.default.statusOptions.online' => '1'
  203. ),
  204. 'expanded' => true,
  205. 'required' => true,
  206. 'translation_domain'=> 'lcshop'
  207. )
  208. );
  209. }
  210. if ($entity instanceof TreeInterface) {
  211. $formBuilder->add('parent', EntityType::class, array(
  212. 'class' => $this->entity['class'],
  213. 'query_builder' => function (EntityRepository $repo) use ($id) {
  214. return $repo->createQueryBuilder('e')
  215. ->where('e.parent is NULL')
  216. ->andWhere('e.status >= 0')
  217. ->orderBy('e.status', "DESC");
  218. },
  219. 'required' => false,
  220. )
  221. );
  222. }
  223. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  224. $form = $event->getForm();
  225. $allChilds = $form->all();
  226. foreach ($allChilds as $child) {
  227. $statusInterface = false;
  228. $treeInterface = false;
  229. $type = $child->getConfig()->getType()->getInnerType();
  230. if ($type instanceof EntityType) {
  231. $passedOptions = $child->getConfig()->getOptions();
  232. $classImplements = class_implements($passedOptions['class']);
  233. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements) ;
  234. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements) ;
  235. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  236. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  237. $statusInterface = true;
  238. }
  239. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  240. $treeInterface = true;
  241. }
  242. $propertyMerchant = 'merchant';
  243. if($isFilterMultipleMerchantsInterface) {
  244. $propertyMerchant .= 's' ;
  245. }
  246. $form->add($child->getName(), EntityType::class, array(
  247. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  248. 'label' => $passedOptions['label'],
  249. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  250. 'placeholder' => '--',
  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. }