選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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