Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

373 lines
17KB

  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 commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  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. return $dqlFilter;
  66. }
  67. protected function commonQueryFilter($entityClass, $queryBuilder)
  68. {
  69. if ($entityClass == 'App\Entity\PointSale') {
  70. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchant')
  71. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  72. }
  73. }
  74. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  75. {
  76. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter) ;
  77. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter) ;
  78. $this->commonQueryFilter($entityClass, $queryBuilder) ;
  79. return $queryBuilder ;
  80. }
  81. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  82. {
  83. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter) ;
  84. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  85. $this->commonQueryFilter($entityClass, $queryBuilder) ;
  86. return $queryBuilder ;
  87. }
  88. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  89. {
  90. $parameters = array_merge(
  91. $parameters,
  92. $this->getTwigExtraParameters()
  93. );
  94. return parent::renderTemplate($actionName, $templatePath, $parameters);
  95. }
  96. public function getTwigExtraParameters()
  97. {
  98. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  99. $merchants = $repositoryMerchant->findAll();
  100. $user = $this->security->getUser();
  101. return [
  102. 'merchants' => $merchants,
  103. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  104. ];
  105. }
  106. protected function removeEntity($entity)
  107. {
  108. $entity->setStatus(-1);
  109. $this->em->persist($entity);
  110. $this->em->flush();
  111. }
  112. public function updateEntity($entity)
  113. {
  114. $this->setUpdated($entity);
  115. parent::updateEntity($entity);
  116. }
  117. public function persistEntity($entity)
  118. {
  119. if ($entity instanceof StatusInterface) {
  120. $entity->setStatus(1);
  121. }
  122. if ($entity instanceof SortableInterface) {
  123. if ($entity instanceof TreeInterface) {
  124. if ($entity->getParent()) {
  125. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => $entity->getParent()->getId()));
  126. $entity->setPosition($entity->getParent()->getId() . '_' . $total);
  127. } else {
  128. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => null));
  129. $entity->setPosition($total);
  130. }
  131. } else {
  132. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1));
  133. $entity->setPosition($total);
  134. }
  135. }
  136. if (method_exists($entity, 'setMerchant')) {
  137. $entity->setMerchant($this->security->getUser()->getMerchant());
  138. }
  139. if (method_exists($entity, 'addMerchant')) {
  140. if ($entity->getMerchant()->isEmpty()) {
  141. $entity->addMerchant($this->security->getUser()->getMerchant());
  142. }
  143. }
  144. if (method_exists($entity, 'setCreatedBy')) {
  145. $entity->setCreatedBy($this->security->getUser());
  146. }
  147. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  148. $entity->getAddress()->setCreatedBy($this->security->getUser());
  149. $entity->getAddress()->setCreatedAt(new \DateTime());
  150. }
  151. if (method_exists($entity, 'getAddresses')
  152. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  153. foreach($entity->getAddresses() as $address) {
  154. $address->setCreatedBy($this->security->getUser()) ;
  155. $address->setCreatedAt(new \DateTime()) ;
  156. }
  157. }
  158. $this->setUpdated($entity);
  159. parent::persistEntity($entity);
  160. }
  161. public function setUpdated($entity)
  162. {
  163. if (method_exists($entity, 'setUpdatedBy')) {
  164. $entity->setUpdatedBy($this->security->getUser());
  165. }
  166. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  167. $entity->getAddress()->setUpdatedBy($this->security->getUser());
  168. }
  169. if (method_exists($entity, 'getAddresses')
  170. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  171. foreach($entity->getAddresses() as $address) {
  172. $address->setUpdatedBy($this->security->getUser()) ;
  173. $address->setUpdatedAt(new \DateTime()) ;
  174. if(!$address->getCreatedBy()) {
  175. $address->setCreatedBy($this->security->getUser()) ;
  176. $address->setCreatedAt(new \DateTime()) ;
  177. }
  178. }
  179. }
  180. }
  181. public function listChildrenAction()
  182. {
  183. $this->dispatch(EasyAdminEvents::PRE_LIST);
  184. $id = $this->request->query->get('id');
  185. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  186. $easyadmin = $this->request->attributes->get('easyadmin');
  187. $entity = $easyadmin['item'];
  188. $fields = $this->entity['list']['fields'];
  189. $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']);
  190. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  191. $parameters = [
  192. 'paginator' => $paginator,
  193. 'fields' => $fields,
  194. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  195. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  196. 'entity' => $entity,
  197. ];
  198. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  199. }
  200. public function sortAction()
  201. {
  202. $this->dispatch(EasyAdminEvents::PRE_LIST);
  203. $entity = null;
  204. //Replace this with query builder function, do not use finAll of easyAdmin
  205. if ($this->request->query->get('id')) {
  206. $id = $this->request->query->get('id');
  207. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  208. $easyadmin = $this->request->attributes->get('easyadmin');
  209. $entity = $easyadmin['item'];
  210. }
  211. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  212. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  213. $fields = $this->entity['list']['fields'];
  214. $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']);
  215. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  216. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  217. ->add('entities', CollectionType::class, array(
  218. 'required' => true,
  219. 'allow_add' => true,
  220. 'entry_type' => AbstractEditPositionType::class,
  221. ))
  222. ->getForm();
  223. $positionForm->handleRequest($this->request);
  224. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  225. $class = $this->entity['class'];
  226. $repo = $this->em->getRepository($class);
  227. $latsPos = 0;
  228. foreach ($positionForm->get('entities')->getData() as $elm) {
  229. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  230. $entity = $repo->find($elm['id']);
  231. $entity->setPosition($elm['position']);
  232. $this->em->persist($entity);
  233. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  234. $latsPos = $elm['position'];
  235. }
  236. //to do récupérer les élements hors ligne et incrémenter position
  237. foreach ($repo->findAllOfflineAndDelete() as $offlineEntity) {
  238. $latsPos++;
  239. $offlineEntity->setPosition($latsPos);
  240. $this->em->persist($offlineEntity);
  241. }
  242. $this->em->flush();
  243. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  244. return $this->redirectToReferrer();
  245. }
  246. $parameters = [
  247. 'paginator' => $paginator,
  248. 'fields' => $fields,
  249. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  250. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  251. 'postion_form' => $positionForm->createView(),
  252. 'entity' => $entity,
  253. 'sortable' => true
  254. ];
  255. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  256. }
  257. public function createEntityFormBuilder($entity, $view)
  258. {
  259. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  260. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  261. if ($entity instanceof TreeInterface) {
  262. $formBuilder->add('parent', EntityType::class, array(
  263. 'class' => $this->entity['class'],
  264. 'query_builder' => function (EntityRepository $repo) use ($id) {
  265. return $repo->createQueryBuilder('e')
  266. ->where('e.parent is NULL')
  267. ->andWhere('e.status >= 0')
  268. ->orderBy('e.status', "DESC");
  269. },
  270. 'required' => false,
  271. )
  272. );
  273. }
  274. // @TODO : À passer dans le controller de App
  275. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  276. $form = $event->getForm();
  277. $allChilds = $form->all() ;
  278. foreach($allChilds as $child) {
  279. $type = $child->getConfig()->getType()->getInnerType() ;
  280. if($type instanceof EntityType) {
  281. $attributes = $child->getConfig()->getAttributes() ;
  282. $passedOptions = $attributes['data_collector/passed_options'] ;
  283. $classImplements = class_implements($passedOptions['class']) ;
  284. if(in_array('App\Context\FilterHubInterface', $classImplements)) {
  285. $form->add($child->getName(), EntityType::class, array(
  286. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  287. 'label' => $passedOptions['label'],
  288. 'query_builder' => function (EntityRepository $repo) {
  289. return $repo->createQueryBuilder('e')
  290. ->where('e.hub = :currentMerchant')
  291. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  292. },
  293. 'required' => $passedOptions['required'],
  294. )
  295. );
  296. }
  297. }
  298. }
  299. });
  300. return $formBuilder;
  301. }
  302. }