409 lines
20KB

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