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.

AdminController.php 27KB

4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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\HttpFoundation\Response;
  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. protected $filtersForm = null;
  39. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
  40. MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator)
  41. {
  42. $this->security = $security;
  43. $this->userManager = $userManager;
  44. $this->em = $em;
  45. $this->mailjetTransport = $mailjetTransport;
  46. $this->utils = $utilsManager->getUtils();
  47. $this->merchantUtils = $utilsManager->getMerchantUtils();
  48. $this->orderUtils = $utilsManager->getOrderUtils();;
  49. $this->translator = $translator;
  50. }
  51. public function createCustomForm($class, $action, $parameters, $data = true)
  52. {
  53. $options = array();
  54. if ($data) $options['data'] = $parameters['entity'];
  55. $options['action'] = $this->generateUrl('easyadmin', array(
  56. 'action' => $action,
  57. 'entity' => $this->entity['name'],
  58. 'id' => $parameters['entity']->getId()
  59. ));
  60. return $this->createForm($class, null, $options);
  61. }
  62. /**
  63. * Réécriture de show action pr rediriger vers l'édition
  64. */
  65. /* public function showAction()
  66. {
  67. $id = $this->request->query->get('id');
  68. $entity = $this->request->query->get('entity');
  69. return $this->redirectToRoute('easyadmin', [
  70. 'action' => 'edit',
  71. 'entity' => $entity,
  72. 'id' => $id
  73. ]);
  74. }*/
  75. /**
  76. * Réécriture de removeEntity pour passer les status à -1
  77. */
  78. protected function removeEntity($entity)
  79. {
  80. if ($entity instanceof StatusInterface) {
  81. $entity->setStatus(-1);
  82. $this->em->persist($entity);
  83. $this->em->flush();
  84. } else {
  85. parent::removeEntity($entity);
  86. }
  87. }
  88. protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  89. {
  90. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  91. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  92. }
  93. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  94. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  95. else $dqlFilter .= sprintf(' entity.status > = 0');
  96. }
  97. return $dqlFilter;
  98. }
  99. protected function commonQueryFilter($entityClass, $queryBuilder)
  100. {
  101. if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
  102. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
  103. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  104. }
  105. }
  106. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  107. {
  108. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  109. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
  110. $this->commonQueryFilter($entityClass, $queryBuilder);
  111. return $queryBuilder;
  112. }
  113. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  114. {
  115. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  116. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  117. $this->commonQueryFilter($entityClass, $queryBuilder);
  118. $listFields = $this->entity['list']['fields'];
  119. $this->filtersForm = $this->createForm(ListFilterType::class, null, array(
  120. 'fields' => $listFields,
  121. 'method' => 'get'
  122. ));
  123. $this->filtersForm->handleRequest($this->request);
  124. if ($this->filtersForm->isSubmitted() && $this->filtersForm->isValid()) {
  125. foreach ($listFields as $field) {
  126. if ($this->filtersForm->has($field['property'])) {
  127. switch ($field['dataType']) {
  128. case 'integer':
  129. case 'text':
  130. case 'string':
  131. case 'toggle':
  132. $filter = $this->filtersForm->get($field['property'])->getData();
  133. if ($filter !== null) {
  134. $queryBuilder->andWhere('entity.' . $field['property'] . ' LIKE :' . $field['property'] . '');
  135. $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
  136. }
  137. break;
  138. case 'association' :
  139. $filter = $this->filtersForm->get($field['property'])->getData();
  140. if ($filter !== null) {
  141. if ($field['type_options']['multiple']) {
  142. $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
  143. } else {
  144. $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
  145. }
  146. $queryBuilder->setParameter($field['property'], $filter);
  147. }
  148. break;
  149. case 'datetime':
  150. case 'date':
  151. $dateStart = $this->filtersForm->get($field['property'])->get('dateStart')->getData();
  152. $dateEnd = $this->filtersForm->get($field['property'])->get('dateEnd')->getData();
  153. if ($dateStart) $queryBuilder->andWhere('entity.' . $field['property'] . ' >= :dateStart')->setParameter('dateStart', $dateStart);
  154. if ($dateEnd) $queryBuilder->andWhere('entity.' . $field['property'] . ' <= :dateEnd')->setParameter('dateEnd', $dateEnd);
  155. }
  156. }
  157. }
  158. }
  159. return $queryBuilder;
  160. }
  161. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  162. {
  163. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  164. $easyadmin = $this->request->attributes->get('easyadmin');
  165. $entityName = $easyadmin['entity']['name'];
  166. $id = null;
  167. if ($easyadmin['item']) $id = $easyadmin['item']->getId();
  168. $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfig($actionName, $entityName, $id));
  169. if ($actionName == 'list') {
  170. if ($this->filtersForm === null) {
  171. $options['fields'] = $parameters['fields'];
  172. $options['method'] = 'get';
  173. $this->filtersForm = $this->createForm(ListFilterType::class, null, $options);
  174. }
  175. $parameters = array_merge(
  176. $parameters,
  177. array(
  178. 'filters_form' => $this->filtersForm->createView()
  179. )
  180. );
  181. }
  182. $parameters = array_merge(
  183. $parameters,
  184. $this->getTwigExtraParameters(),
  185. $reminders
  186. );
  187. return parent::renderTemplate($actionName, $templatePath, $parameters);
  188. }
  189. public function getTwigExtraParameters()
  190. {
  191. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  192. $merchants = $repositoryMerchant->findAll();
  193. $user = $this->security->getUser();
  194. return [
  195. 'merchants' => $merchants,
  196. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  197. ];
  198. }
  199. public function listChildrenAction()
  200. {
  201. $this->dispatch(EasyAdminEvents::PRE_LIST);
  202. $id = $this->request->query->get('id');
  203. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  204. $easyadmin = $this->request->attributes->get('easyadmin');
  205. $entity = $easyadmin['item'];
  206. $fields = $this->entity['list']['fields'];
  207. $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']);
  208. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  209. $parameters = [
  210. 'paginator' => $paginator,
  211. 'fields' => $fields,
  212. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  213. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  214. 'entity' => $entity,
  215. ];
  216. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  217. }
  218. public function sortAction()
  219. {
  220. $this->dispatch(EasyAdminEvents::PRE_LIST);
  221. $entity = null;
  222. //Replace this with query builder function, do not use finAll of easyAdmin
  223. if ($this->request->query->get('id')) {
  224. $id = $this->request->query->get('id');
  225. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  226. $easyadmin = $this->request->attributes->get('easyadmin');
  227. $entity = $easyadmin['item'];
  228. }
  229. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  230. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  231. $fields = $this->entity['list']['fields'];
  232. $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']);
  233. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  234. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  235. ->add('entities', CollectionType::class, array(
  236. 'required' => true,
  237. 'allow_add' => true,
  238. 'entry_type' => AbstractEditPositionType::class,
  239. ))
  240. ->getForm();
  241. $positionForm->handleRequest($this->request);
  242. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  243. $class = $this->entity['class'];
  244. $repo = $this->em->getRepository($class);
  245. $latsPos = 0;
  246. foreach ($positionForm->get('entities')->getData() as $elm) {
  247. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  248. $entity = $repo->find($elm['id']);
  249. $entity->setPosition($elm['position']);
  250. $this->em->persist($entity);
  251. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  252. $latsPos = $elm['position'];
  253. }
  254. //die();
  255. //to do récupérer les élements hors ligne et incrémenter position
  256. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  257. $latsPos++;
  258. $offlineEntity->setPosition($latsPos);
  259. $this->em->persist($offlineEntity);
  260. }*/
  261. $this->em->flush();
  262. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  263. return $this->redirectToReferrer();
  264. }
  265. $parameters = [
  266. 'paginator' => $paginator,
  267. 'fields' => $fields,
  268. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  269. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  270. 'postion_form' => $positionForm->createView(),
  271. 'entity' => $entity,
  272. 'sortable' => true
  273. ];
  274. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  275. }
  276. public function createEntityFormBuilder($entity, $view, $override = true)
  277. {
  278. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  279. if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  280. return $formBuilder;
  281. }
  282. public function overrideFormBuilder($formBuilder, $entity, $view)
  283. {
  284. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  285. if ($entity instanceof SeoInterface) {
  286. $formBuilder->add('metaTitle', TextType::class, array(
  287. 'required' => false,
  288. 'translation_domain' => 'lcshop'
  289. )
  290. );
  291. $formBuilder->add('metaDescription', TextareaType::class, array(
  292. 'required' => false,
  293. 'translation_domain' => 'lcshop'
  294. )
  295. );
  296. /*$formBuilder->add('oldUrls', TextareaType::class, array(
  297. 'required' => false,
  298. 'translation_domain' => 'lcshop'
  299. )
  300. );*/
  301. }
  302. if ($entity instanceof StatusInterface) {
  303. $formBuilder->add('status', ChoiceType::class, array(
  304. 'choices' => array(
  305. 'field.default.statusOptions.offline' => '0',
  306. 'field.default.statusOptions.online' => '1'
  307. ),
  308. 'expanded' => true,
  309. 'required' => true,
  310. 'translation_domain' => 'lcshop'
  311. )
  312. );
  313. }
  314. if ($entity instanceof TreeInterface) {
  315. $formBuilder->add('parent', EntityType::class, array(
  316. 'class' => $this->entity['class'],
  317. 'query_builder' => function (EntityRepository $repo) use ($id) {
  318. return $repo->createQueryBuilder('e')
  319. ->where('e.parent is NULL')
  320. ->andWhere('e.status >= 0')
  321. ->orderBy('e.status', "DESC");
  322. },
  323. 'required' => false,
  324. )
  325. );
  326. }
  327. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  328. $form = $event->getForm();
  329. $childrens = $form->all();
  330. $this->loopFormField($form, $childrens);
  331. });
  332. return $formBuilder;
  333. }
  334. private function loopFormField($form, $childrens)
  335. {
  336. foreach ($childrens as $child) {
  337. $statusInterface = false;
  338. $treeInterface = false;
  339. $type = $child->getConfig()->getType()->getInnerType();;
  340. if ($type instanceof EntityType) {
  341. $passedOptions = $child->getConfig()->getOptions();
  342. $classImplements = class_implements($passedOptions['class']);
  343. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
  344. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
  345. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  346. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  347. $statusInterface = true;
  348. }
  349. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  350. $treeInterface = true;
  351. }
  352. $propertyMerchant = 'merchant';
  353. if ($isFilterMultipleMerchantsInterface) {
  354. $propertyMerchant .= 's';
  355. }
  356. $form->add($child->getName(), EntityType::class, array(
  357. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  358. 'label' => $passedOptions['label'],
  359. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  360. 'placeholder' => '--',
  361. 'translation_domain' => 'lcshop',
  362. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  363. $queryBuilder = $repo->createQueryBuilder('e');
  364. $propertyMerchant = 'e.' . $propertyMerchant;
  365. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  366. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  367. } else {
  368. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  369. }
  370. if ($statusInterface) {
  371. $queryBuilder->andWhere('e.status >= 0');
  372. }
  373. if ($treeInterface && $child->getName() == 'parent') {
  374. $queryBuilder->andWhere('e.parent is null');
  375. }
  376. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  377. return $queryBuilder;
  378. },
  379. 'choice_label' => function ($choice) {
  380. if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
  381. return $choice . ' [hors ligne]';
  382. }
  383. return $choice;
  384. },
  385. 'required' => $passedOptions['required'],
  386. 'choice_attr' => $passedOptions['choice_attr'],
  387. )
  388. );
  389. }
  390. } else {
  391. $subChildrens = $child->all();
  392. if (count($subChildrens)) {
  393. $this->loopFormField($child, $subChildrens);
  394. }
  395. }
  396. }
  397. }
  398. protected function editAction()
  399. {
  400. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  401. $id = $this->request->query->get('id');
  402. $easyadmin = $this->request->attributes->get('easyadmin');
  403. $entity = $easyadmin['item'];
  404. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  405. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  406. $fieldsMetadata = $this->entity['list']['fields'];
  407. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  408. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  409. }
  410. $this->updateEntityProperty($entity, $property, $newValue);
  411. $this->utils->addFlash('success', 'success.common.fieldChange');
  412. $response['flashMessages'] = $this->utils->getFlashMessages();
  413. return new Response(json_encode($response));
  414. }
  415. $fields = $this->entity['edit']['fields'];
  416. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  417. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  418. $editForm->handleRequest($this->request);
  419. if ($editForm->isSubmitted() && $editForm->isValid()) {
  420. $this->processUploadedFiles($editForm);
  421. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  422. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  423. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  424. return $this->redirectToReferrer();
  425. }
  426. $this->dispatch(EasyAdminEvents::POST_EDIT);
  427. $parameters = [
  428. 'form' => $editForm->createView(),
  429. 'entity_fields' => $fields,
  430. 'entity' => $entity,
  431. 'delete_form' => $deleteForm->createView(),
  432. ];
  433. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  434. }
  435. }