Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

591 rinda
29KB

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