420 linhas
21KB

  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 Lc\ShopBundle\Services\UtilsManager;
  19. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  20. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  21. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  22. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  23. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  24. use Symfony\Component\Form\Extension\Core\Type\TextType;
  25. use Symfony\Component\Form\FormEvent;
  26. use Symfony\Component\Form\FormEvents;
  27. use Symfony\Component\Security\Core\Security;
  28. use Symfony\Contracts\Translation\TranslatorInterface;
  29. class AdminController extends EasyAdminController
  30. {
  31. protected $security;
  32. protected $userManager;
  33. protected $em;
  34. protected $utils;
  35. protected $merchantUtils;
  36. protected $mailjetTransport;
  37. protected $orderUtils;
  38. protected $translator;
  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. return $queryBuilder;
  119. }
  120. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  121. {
  122. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  123. $easyadmin = $this->request->attributes->get('easyadmin');
  124. $entityName = $easyadmin['entity']['name'];
  125. $id=null;
  126. if($easyadmin['item'])$id = $easyadmin['item']->getId();
  127. $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfig($actionName, $entityName, $id ));
  128. $parameters = array_merge(
  129. $parameters,
  130. $this->getTwigExtraParameters(),
  131. $reminders
  132. );
  133. return parent::renderTemplate($actionName, $templatePath, $parameters);
  134. }
  135. public function getTwigExtraParameters()
  136. {
  137. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  138. $merchants = $repositoryMerchant->findAll();
  139. $user = $this->security->getUser();
  140. return [
  141. 'merchants' => $merchants,
  142. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  143. ];
  144. }
  145. public function listChildrenAction()
  146. {
  147. $this->dispatch(EasyAdminEvents::PRE_LIST);
  148. $id = $this->request->query->get('id');
  149. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  150. $easyadmin = $this->request->attributes->get('easyadmin');
  151. $entity = $easyadmin['item'];
  152. $fields = $this->entity['list']['fields'];
  153. $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']);
  154. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  155. $parameters = [
  156. 'paginator' => $paginator,
  157. 'fields' => $fields,
  158. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  159. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  160. 'entity' => $entity,
  161. ];
  162. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  163. }
  164. public function sortAction()
  165. {
  166. $this->dispatch(EasyAdminEvents::PRE_LIST);
  167. $entity = null;
  168. //Replace this with query builder function, do not use finAll of easyAdmin
  169. if ($this->request->query->get('id')) {
  170. $id = $this->request->query->get('id');
  171. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  172. $easyadmin = $this->request->attributes->get('easyadmin');
  173. $entity = $easyadmin['item'];
  174. }
  175. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  176. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  177. $fields = $this->entity['list']['fields'];
  178. $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']);
  179. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  180. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  181. ->add('entities', CollectionType::class, array(
  182. 'required' => true,
  183. 'allow_add' => true,
  184. 'entry_type' => AbstractEditPositionType::class,
  185. ))
  186. ->getForm();
  187. $positionForm->handleRequest($this->request);
  188. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  189. $class = $this->entity['class'];
  190. $repo = $this->em->getRepository($class);
  191. $latsPos = 0;
  192. foreach ($positionForm->get('entities')->getData() as $elm) {
  193. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  194. $entity = $repo->find($elm['id']);
  195. $entity->setPosition($elm['position']);
  196. $this->em->persist($entity);
  197. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  198. $latsPos = $elm['position'];
  199. }
  200. //die();
  201. //to do récupérer les élements hors ligne et incrémenter position
  202. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  203. $latsPos++;
  204. $offlineEntity->setPosition($latsPos);
  205. $this->em->persist($offlineEntity);
  206. }*/
  207. $this->em->flush();
  208. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  209. return $this->redirectToReferrer();
  210. }
  211. $parameters = [
  212. 'paginator' => $paginator,
  213. 'fields' => $fields,
  214. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  215. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  216. 'postion_form' => $positionForm->createView(),
  217. 'entity' => $entity,
  218. 'sortable' => true
  219. ];
  220. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  221. }
  222. public function createEntityFormBuilder($entity, $view, $override = true)
  223. {
  224. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  225. if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  226. return $formBuilder;
  227. }
  228. public function overrideFormBuilder($formBuilder, $entity, $view)
  229. {
  230. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  231. if ($entity instanceof SeoInterface) {
  232. $formBuilder->add('metaTitle', TextType::class, array(
  233. 'required' => false,
  234. 'translation_domain' => 'lcshop'
  235. )
  236. );
  237. $formBuilder->add('metaDescription', TextareaType::class, array(
  238. 'required' => false,
  239. 'translation_domain' => 'lcshop'
  240. )
  241. );
  242. /*$formBuilder->add('oldUrls', TextareaType::class, array(
  243. 'required' => false,
  244. 'translation_domain' => 'lcshop'
  245. )
  246. );*/
  247. }
  248. if ($entity instanceof StatusInterface) {
  249. $formBuilder->add('status', ChoiceType::class, array(
  250. 'choices' => array(
  251. 'field.default.statusOptions.offline' => '0',
  252. 'field.default.statusOptions.online' => '1'
  253. ),
  254. 'expanded' => true,
  255. 'required' => true,
  256. 'translation_domain' => 'lcshop'
  257. )
  258. );
  259. }
  260. if ($entity instanceof TreeInterface) {
  261. $formBuilder->add('parent', EntityType::class, array(
  262. 'class' => $this->entity['class'],
  263. 'query_builder' => function (EntityRepository $repo) use ($id) {
  264. return $repo->createQueryBuilder('e')
  265. ->where('e.parent is NULL')
  266. ->andWhere('e.status >= 0')
  267. ->orderBy('e.status', "DESC");
  268. },
  269. 'required' => false,
  270. )
  271. );
  272. }
  273. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  274. $form = $event->getForm();
  275. $childrens = $form->all();
  276. $this->loopFormField($form, $childrens);
  277. });
  278. return $formBuilder;
  279. }
  280. private function loopFormField($form, $childrens)
  281. {
  282. foreach ($childrens as $child) {
  283. $statusInterface = false;
  284. $treeInterface = false;
  285. $type = $child->getConfig()->getType()->getInnerType();;
  286. if ($type instanceof EntityType) {
  287. $passedOptions = $child->getConfig()->getOptions();
  288. $classImplements = class_implements($passedOptions['class']);
  289. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
  290. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
  291. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  292. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  293. $statusInterface = true;
  294. }
  295. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  296. $treeInterface = true;
  297. }
  298. $propertyMerchant = 'merchant';
  299. if ($isFilterMultipleMerchantsInterface) {
  300. $propertyMerchant .= 's';
  301. }
  302. $form->add($child->getName(), EntityType::class, array(
  303. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  304. 'label' => $passedOptions['label'],
  305. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  306. 'placeholder' => '--',
  307. 'translation_domain' => 'lcshop',
  308. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  309. $queryBuilder = $repo->createQueryBuilder('e');
  310. $propertyMerchant = 'e.' . $propertyMerchant;
  311. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  312. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  313. } else {
  314. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  315. }
  316. if ($statusInterface) {
  317. $queryBuilder->andWhere('e.status >= 0');
  318. }
  319. if ($treeInterface && $child->getName() == 'parent') {
  320. $queryBuilder->andWhere('e.parent is null');
  321. }
  322. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  323. return $queryBuilder;
  324. },
  325. 'choice_label' => function ($choice) {
  326. if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
  327. return $choice . ' [hors ligne]';
  328. }
  329. return $choice;
  330. },
  331. 'required' => $passedOptions['required'],
  332. 'choice_attr' => $passedOptions['choice_attr'],
  333. )
  334. );
  335. }
  336. } else {
  337. $subChildrens = $child->all();
  338. if (count($subChildrens)) {
  339. $this->loopFormField($child, $subChildrens);
  340. }
  341. }
  342. }
  343. }
  344. }