No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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