AdminController.php 20KB

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