Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

AdminController.php 25KB

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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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\ReminderInterface;
  11. use Lc\ShopBundle\Context\SeoInterface;
  12. use Lc\ShopBundle\Context\StatusInterface;
  13. use Lc\ShopBundle\Context\TreeInterface;
  14. use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
  15. use Lc\ShopBundle\Form\Backend\Filters\ListFilterType;
  16. use Lc\ShopBundle\Services\UtilsManager;
  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. protected $filtersForm = null;
  38. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
  39. MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator)
  40. {
  41. $this->security = $security;
  42. $this->userManager = $userManager;
  43. $this->em = $em;
  44. $this->mailjetTransport = $mailjetTransport;
  45. $this->utils = $utilsManager->getUtils();
  46. $this->merchantUtils = $utilsManager->getMerchantUtils();
  47. $this->orderUtils = $utilsManager->getOrderUtils();;
  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. $listFields = $this->entity['list']['fields'];
  118. $this->filtersForm = $this->createForm(ListFilterType::class, null, array(
  119. 'fields' => $listFields,
  120. 'method' => 'get'
  121. ));
  122. $this->filtersForm->handleRequest($this->request);
  123. if ($this->filtersForm->isSubmitted() && $this->filtersForm->isValid()) {
  124. foreach ($listFields as $field) {
  125. if ($this->filtersForm->has($field['property'])) {
  126. switch ($field['dataType']) {
  127. case 'integer':
  128. case 'text':
  129. case 'string':
  130. case 'toggle':
  131. $filter = $this->filtersForm->get($field['property'])->getData();
  132. if ($filter !== null) {
  133. $queryBuilder->andWhere('entity.' . $field['property'] . ' LIKE :' . $field['property'] . '');
  134. $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
  135. }
  136. break;
  137. case 'association' :
  138. $filter = $this->filtersForm->get($field['property'])->getData();
  139. if ($filter !== null) {
  140. if ($field['type_options']['multiple']) {
  141. $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
  142. } else {
  143. $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
  144. }
  145. $queryBuilder->setParameter($field['property'], $filter);
  146. }
  147. break;
  148. case 'datetime':
  149. case 'date':
  150. $dateStart = $this->filtersForm->get($field['property'])->get('dateStart')->getData();
  151. $dateEnd = $this->filtersForm->get($field['property'])->get('dateEnd')->getData();
  152. if ($dateStart) $queryBuilder->andWhere('entity.' . $field['property'] . ' >= :dateStart')->setParameter('dateStart', $dateStart);
  153. if ($dateEnd) $queryBuilder->andWhere('entity.' . $field['property'] . ' <= :dateEnd')->setParameter('dateEnd', $dateEnd);
  154. }
  155. }
  156. }
  157. }
  158. return $queryBuilder;
  159. }
  160. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  161. {
  162. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  163. $easyadmin = $this->request->attributes->get('easyadmin');
  164. $entityName = $easyadmin['entity']['name'];
  165. $id = null;
  166. if ($easyadmin['item']) $id = $easyadmin['item']->getId();
  167. $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfig($actionName, $entityName, $id));
  168. if ($actionName == 'list') {
  169. if ($this->filtersForm === null) {
  170. $options['fields'] = $parameters['fields'];
  171. $options['method'] = 'get';
  172. $this->filtersForm = $this->createForm(ListFilterType::class, null, $options);
  173. }
  174. $parameters = array_merge(
  175. $parameters,
  176. array(
  177. 'filters_form' => $this->filtersForm->createView()
  178. )
  179. );
  180. }
  181. $parameters = array_merge(
  182. $parameters,
  183. $this->getTwigExtraParameters(),
  184. $reminders
  185. );
  186. return parent::renderTemplate($actionName, $templatePath, $parameters);
  187. }
  188. public function getTwigExtraParameters()
  189. {
  190. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  191. $merchants = $repositoryMerchant->findAll();
  192. $user = $this->security->getUser();
  193. return [
  194. 'merchants' => $merchants,
  195. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  196. ];
  197. }
  198. public function listChildrenAction()
  199. {
  200. $this->dispatch(EasyAdminEvents::PRE_LIST);
  201. $id = $this->request->query->get('id');
  202. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  203. $easyadmin = $this->request->attributes->get('easyadmin');
  204. $entity = $easyadmin['item'];
  205. $fields = $this->entity['list']['fields'];
  206. $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']);
  207. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  208. $parameters = [
  209. 'paginator' => $paginator,
  210. 'fields' => $fields,
  211. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  212. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  213. 'entity' => $entity,
  214. ];
  215. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  216. }
  217. public function sortAction()
  218. {
  219. $this->dispatch(EasyAdminEvents::PRE_LIST);
  220. $entity = null;
  221. //Replace this with query builder function, do not use finAll of easyAdmin
  222. if ($this->request->query->get('id')) {
  223. $id = $this->request->query->get('id');
  224. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  225. $easyadmin = $this->request->attributes->get('easyadmin');
  226. $entity = $easyadmin['item'];
  227. }
  228. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  229. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  230. $fields = $this->entity['list']['fields'];
  231. $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']);
  232. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  233. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  234. ->add('entities', CollectionType::class, array(
  235. 'required' => true,
  236. 'allow_add' => true,
  237. 'entry_type' => AbstractEditPositionType::class,
  238. ))
  239. ->getForm();
  240. $positionForm->handleRequest($this->request);
  241. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  242. $class = $this->entity['class'];
  243. $repo = $this->em->getRepository($class);
  244. $latsPos = 0;
  245. foreach ($positionForm->get('entities')->getData() as $elm) {
  246. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  247. $entity = $repo->find($elm['id']);
  248. $entity->setPosition($elm['position']);
  249. $this->em->persist($entity);
  250. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  251. $latsPos = $elm['position'];
  252. }
  253. //die();
  254. //to do récupérer les élements hors ligne et incrémenter position
  255. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  256. $latsPos++;
  257. $offlineEntity->setPosition($latsPos);
  258. $this->em->persist($offlineEntity);
  259. }*/
  260. $this->em->flush();
  261. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  262. return $this->redirectToReferrer();
  263. }
  264. $parameters = [
  265. 'paginator' => $paginator,
  266. 'fields' => $fields,
  267. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  268. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  269. 'postion_form' => $positionForm->createView(),
  270. 'entity' => $entity,
  271. 'sortable' => true
  272. ];
  273. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  274. }
  275. public function createEntityFormBuilder($entity, $view, $override = true)
  276. {
  277. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  278. if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  279. return $formBuilder;
  280. }
  281. public function overrideFormBuilder($formBuilder, $entity, $view)
  282. {
  283. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  284. if ($entity instanceof SeoInterface) {
  285. $formBuilder->add('metaTitle', TextType::class, array(
  286. 'required' => false,
  287. 'translation_domain' => 'lcshop'
  288. )
  289. );
  290. $formBuilder->add('metaDescription', TextareaType::class, array(
  291. 'required' => false,
  292. 'translation_domain' => 'lcshop'
  293. )
  294. );
  295. /*$formBuilder->add('oldUrls', TextareaType::class, array(
  296. 'required' => false,
  297. 'translation_domain' => 'lcshop'
  298. )
  299. );*/
  300. }
  301. if ($entity instanceof StatusInterface) {
  302. $formBuilder->add('status', ChoiceType::class, array(
  303. 'choices' => array(
  304. 'field.default.statusOptions.offline' => '0',
  305. 'field.default.statusOptions.online' => '1'
  306. ),
  307. 'expanded' => true,
  308. 'required' => true,
  309. 'translation_domain' => 'lcshop'
  310. )
  311. );
  312. }
  313. if ($entity instanceof TreeInterface) {
  314. $formBuilder->add('parent', EntityType::class, array(
  315. 'class' => $this->entity['class'],
  316. 'query_builder' => function (EntityRepository $repo) use ($id) {
  317. return $repo->createQueryBuilder('e')
  318. ->where('e.parent is NULL')
  319. ->andWhere('e.status >= 0')
  320. ->orderBy('e.status', "DESC");
  321. },
  322. 'required' => false,
  323. )
  324. );
  325. }
  326. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  327. $form = $event->getForm();
  328. $childrens = $form->all();
  329. $this->loopFormField($form, $childrens);
  330. });
  331. return $formBuilder;
  332. }
  333. private function loopFormField($form, $childrens)
  334. {
  335. foreach ($childrens as $child) {
  336. $statusInterface = false;
  337. $treeInterface = false;
  338. $type = $child->getConfig()->getType()->getInnerType();;
  339. if ($type instanceof EntityType) {
  340. $passedOptions = $child->getConfig()->getOptions();
  341. $classImplements = class_implements($passedOptions['class']);
  342. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
  343. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
  344. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  345. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  346. $statusInterface = true;
  347. }
  348. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  349. $treeInterface = true;
  350. }
  351. $propertyMerchant = 'merchant';
  352. if ($isFilterMultipleMerchantsInterface) {
  353. $propertyMerchant .= 's';
  354. }
  355. $form->add($child->getName(), EntityType::class, array(
  356. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  357. 'label' => $passedOptions['label'],
  358. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  359. 'placeholder' => '--',
  360. 'translation_domain' => 'lcshop',
  361. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  362. $queryBuilder = $repo->createQueryBuilder('e');
  363. $propertyMerchant = 'e.' . $propertyMerchant;
  364. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  365. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  366. } else {
  367. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  368. }
  369. if ($statusInterface) {
  370. $queryBuilder->andWhere('e.status >= 0');
  371. }
  372. if ($treeInterface && $child->getName() == 'parent') {
  373. $queryBuilder->andWhere('e.parent is null');
  374. }
  375. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  376. return $queryBuilder;
  377. },
  378. 'choice_label' => function ($choice) {
  379. if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
  380. return $choice . ' [hors ligne]';
  381. }
  382. return $choice;
  383. },
  384. 'required' => $passedOptions['required'],
  385. 'choice_attr' => $passedOptions['choice_attr'],
  386. )
  387. );
  388. }
  389. } else {
  390. $subChildrens = $child->all();
  391. if (count($subChildrens)) {
  392. $this->loopFormField($child, $subChildrens);
  393. }
  394. }
  395. }
  396. }
  397. }