You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
19KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Admin;
  3. use App\Entity\MerchantConfig;
  4. use Lc\ShopBundle\Context\AddressInterface;
  5. use Lc\ShopBundle\Repository\MerchantConfigRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Doctrine\ORM\EntityRepository;
  8. use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
  9. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  10. use FOS\UserBundle\Model\UserManagerInterface;
  11. use Lc\ShopBundle\Context\MerchantConfigInterface;
  12. use Lc\ShopBundle\Context\MerchantInterface;
  13. use Lc\ShopBundle\Context\SortableInterface;
  14. use Lc\ShopBundle\Context\StatusInterface;
  15. use Lc\ShopBundle\Context\TreeInterface;
  16. use Lc\ShopBundle\Form\AbstractEditPositionType;
  17. use Lc\ShopBundle\Form\ChoiceProductCategoryType;
  18. use Lc\ShopBundle\Form\PriceType;
  19. use Lc\ShopBundle\Form\Widget\PriceWidgetType;
  20. use Lc\ShopBundle\Services\Utils;
  21. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  22. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  23. use Symfony\Component\Form\FormEvent;
  24. use Symfony\Component\Form\FormEvents;
  25. use Symfony\Component\Security\Core\Security;
  26. class AdminController extends EasyAdminController
  27. {
  28. protected $security;
  29. protected $userManager;
  30. protected $em ;
  31. protected $utils ;
  32. public function __construct(
  33. Security $security,
  34. UserManagerInterface $userManager,
  35. EntityManagerInterface $em,
  36. Utils $utils)
  37. {
  38. $this->security = $security;
  39. $this->userManager = $userManager;
  40. $this->em = $em ;
  41. $this->utils = $utils ;
  42. }
  43. public function showAction()
  44. {
  45. $id = $this->request->query->get('id');
  46. $entity = $this->request->query->get('entity');
  47. return $this->redirectToRoute('easyadmin', [
  48. 'action' => 'edit',
  49. 'entity' => $entity,
  50. 'id' => $id
  51. ]) ;
  52. }
  53. protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  54. {
  55. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  56. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  57. }
  58. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  59. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  60. else $dqlFilter .= sprintf(' entity.status > = 0');
  61. }
  62. return $dqlFilter;
  63. }
  64. protected function commonQueryFilter($entityClass, $queryBuilder)
  65. {
  66. if ($entityClass == 'App\Entity\PointSale') {
  67. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchant')
  68. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  69. }
  70. }
  71. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  72. {
  73. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter) ;
  74. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter) ;
  75. $this->commonQueryFilter($entityClass, $queryBuilder) ;
  76. return $queryBuilder ;
  77. }
  78. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  79. {
  80. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter) ;
  81. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  82. $this->commonQueryFilter($entityClass, $queryBuilder) ;
  83. return $queryBuilder ;
  84. }
  85. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  86. {
  87. $parameters = array_merge(
  88. $parameters,
  89. $this->getTwigExtraParameters()
  90. );
  91. return parent::renderTemplate($actionName, $templatePath, $parameters);
  92. }
  93. public function getTwigExtraParameters()
  94. {
  95. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  96. $merchants = $repositoryMerchant->findAll();
  97. $user = $this->security->getUser();
  98. return [
  99. 'merchants' => $merchants,
  100. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  101. ];
  102. }
  103. protected function removeEntity($entity)
  104. {
  105. if(method_exists($entity, 'setStatus')) {
  106. $entity->setStatus(-1);
  107. $this->em->persist($entity);
  108. $this->em->flush();
  109. }
  110. else {
  111. parent::removeEntity($entity);
  112. }
  113. }
  114. public function updateEntity($entity)
  115. {
  116. $this->setUpdated($entity);
  117. parent::updateEntity($entity);
  118. }
  119. public function persistEntity($entity)
  120. {
  121. if ($entity instanceof StatusInterface) {
  122. $entity->setStatus(1);
  123. }
  124. if ($entity instanceof SortableInterface) {
  125. if ($entity instanceof TreeInterface) {
  126. if ($entity->getParent()) {
  127. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => $entity->getParent()->getId()));
  128. $entity->setPosition($entity->getParent()->getId() . '_' . $total);
  129. } else {
  130. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => null));
  131. $entity->setPosition($total);
  132. }
  133. } else {
  134. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1));
  135. $entity->setPosition($total);
  136. }
  137. }
  138. if (method_exists($entity, 'setMerchant')) {
  139. $entity->setMerchant($this->security->getUser()->getMerchant());
  140. }
  141. if (method_exists($entity, 'addMerchant')) {
  142. if ($entity->getMerchant()->isEmpty()) {
  143. $entity->addMerchant($this->security->getUser()->getMerchant());
  144. }
  145. }
  146. if (method_exists($entity, 'setCreatedBy')) {
  147. $entity->setCreatedBy($this->security->getUser());
  148. }
  149. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  150. $entity->getAddress()->setCreatedBy($this->security->getUser());
  151. $entity->getAddress()->setCreatedAt(new \DateTime());
  152. }
  153. if (method_exists($entity, 'getAddresses')
  154. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  155. foreach($entity->getAddresses() as $address) {
  156. $address->setCreatedBy($this->security->getUser()) ;
  157. $address->setCreatedAt(new \DateTime()) ;
  158. }
  159. }
  160. $this->setUpdated($entity);
  161. parent::persistEntity($entity);
  162. }
  163. public function setUpdated($entity)
  164. {
  165. if (method_exists($entity, 'setUpdatedBy')) {
  166. $entity->setUpdatedBy($this->security->getUser());
  167. }
  168. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  169. $entity->getAddress()->setUpdatedBy($this->security->getUser());
  170. }
  171. if (method_exists($entity, 'getAddresses')
  172. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  173. foreach($entity->getAddresses() as $address) {
  174. $address->setUpdatedBy($this->security->getUser()) ;
  175. $address->setUpdatedAt(new \DateTime()) ;
  176. if(!$address->getCreatedBy()) {
  177. $address->setCreatedBy($this->security->getUser()) ;
  178. $address->setCreatedAt(new \DateTime()) ;
  179. }
  180. }
  181. }
  182. }
  183. public function listChildrenAction()
  184. {
  185. $this->dispatch(EasyAdminEvents::PRE_LIST);
  186. $id = $this->request->query->get('id');
  187. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  188. $easyadmin = $this->request->attributes->get('easyadmin');
  189. $entity = $easyadmin['item'];
  190. $fields = $this->entity['list']['fields'];
  191. $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']);
  192. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  193. $parameters = [
  194. 'paginator' => $paginator,
  195. 'fields' => $fields,
  196. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  197. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  198. 'entity' => $entity,
  199. ];
  200. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  201. }
  202. public function sortAction()
  203. {
  204. $this->dispatch(EasyAdminEvents::PRE_LIST);
  205. $entity = null;
  206. //Replace this with query builder function, do not use finAll of easyAdmin
  207. if ($this->request->query->get('id')) {
  208. $id = $this->request->query->get('id');
  209. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  210. $easyadmin = $this->request->attributes->get('easyadmin');
  211. $entity = $easyadmin['item'];
  212. }
  213. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  214. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  215. $fields = $this->entity['list']['fields'];
  216. $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']);
  217. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  218. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  219. ->add('entities', CollectionType::class, array(
  220. 'required' => true,
  221. 'allow_add' => true,
  222. 'entry_type' => AbstractEditPositionType::class,
  223. ))
  224. ->getForm();
  225. $positionForm->handleRequest($this->request);
  226. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  227. $class = $this->entity['class'];
  228. $repo = $this->em->getRepository($class);
  229. $latsPos = 0;
  230. foreach ($positionForm->get('entities')->getData() as $elm) {
  231. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  232. $entity = $repo->find($elm['id']);
  233. $entity->setPosition($elm['position']);
  234. $this->em->persist($entity);
  235. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  236. $latsPos = $elm['position'];
  237. }
  238. //to do récupérer les élements hors ligne et incrémenter position
  239. foreach ($repo->findAllOfflineAndDelete() as $offlineEntity) {
  240. $latsPos++;
  241. $offlineEntity->setPosition($latsPos);
  242. $this->em->persist($offlineEntity);
  243. }
  244. $this->em->flush();
  245. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  246. return $this->redirectToReferrer();
  247. }
  248. $parameters = [
  249. 'paginator' => $paginator,
  250. 'fields' => $fields,
  251. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  252. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  253. 'postion_form' => $positionForm->createView(),
  254. 'entity' => $entity,
  255. 'sortable' => true
  256. ];
  257. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  258. }
  259. public function createEntityFormBuilder($entity, $view)
  260. {
  261. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  262. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  263. if ($entity instanceof TreeInterface) {
  264. $formBuilder->add('parent', EntityType::class, array(
  265. 'class' => $this->entity['class'],
  266. 'query_builder' => function (EntityRepository $repo) use ($id) {
  267. return $repo->createQueryBuilder('e')
  268. ->where('e.parent is NULL')
  269. ->andWhere('e.status >= 0')
  270. ->orderBy('e.status', "DESC");
  271. },
  272. 'required' => false,
  273. )
  274. );
  275. }
  276. // @TODO : À passer dans le controller de App
  277. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  278. $form = $event->getForm();
  279. $allChilds = $form->all() ;
  280. foreach($allChilds as $child) {
  281. $type = $child->getConfig()->getType()->getInnerType() ;
  282. if($type instanceof EntityType) {
  283. $passedOptions = $child->getConfig()->getOptions() ;
  284. $classImplements = class_implements($passedOptions['class']) ;
  285. if(in_array('App\Context\FilterHubInterface', $classImplements) ||
  286. in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements)) {
  287. $propertyMerchant = 'merchant' ;
  288. if(in_array('App\Context\FilterHubInterface', $classImplements)) {
  289. $propertyMerchant = 'hub' ;
  290. }
  291. $form->add($child->getName(), EntityType::class, array(
  292. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  293. 'label' => $passedOptions['label'],
  294. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  295. 'placeholder' => '--',
  296. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant) {
  297. $queryBuilder = $repo->createQueryBuilder('e') ;
  298. $propertyMerchant = 'e.'.$propertyMerchant ;
  299. if($passedOptions['class'] == 'App\Entity\PointSale') {
  300. $queryBuilder->where(':currentMerchant MEMBER OF '.$propertyMerchant) ;
  301. }
  302. else {
  303. $queryBuilder->where($propertyMerchant.' = :currentMerchant') ;
  304. }
  305. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId()) ;
  306. return $queryBuilder ;
  307. },
  308. 'required' => $passedOptions['required'],
  309. )
  310. );
  311. }
  312. }
  313. }
  314. });
  315. return $formBuilder;
  316. }
  317. }