Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

371 lines
18KB

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