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.

368 lines
18KB

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