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.

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