AdminController.php 19KB

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