Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

613 lines
30KB

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