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.

402 lines
19KB

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