Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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