Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

398 lines
19KB

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