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.

355 lines
16KB

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