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.

414 lines
18KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Admin;
  3. use App\Entity\ProductCategory;
  4. use Doctrine\DBAL\Types\TextType;
  5. use Doctrine\ORM\EntityRepository;
  6. use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  8. use FOS\UserBundle\Model\UserManagerInterface;
  9. use Lc\ShopBundle\Context\MerchantInterface;
  10. use Lc\ShopBundle\Context\ProductCategoryInterface;
  11. use Lc\ShopBundle\Context\SortableInterface;
  12. use Lc\ShopBundle\Context\StatusInterface;
  13. use Lc\ShopBundle\Context\TaxRateInterface;
  14. use Lc\ShopBundle\Context\TreeInterface;
  15. use Lc\ShopBundle\Form\AbstractEditPositionType;
  16. use Lc\ShopBundle\Form\ChoiceProductCategoryType;
  17. use Lc\ShopBundle\Form\PriceType;
  18. use Lc\ShopBundle\Form\ProductType;
  19. use Lc\ShopBundle\Form\Widget\PriceWidgetType;
  20. use Lc\ShopBundle\Repository\BaseRepository;
  21. use Lc\ShopBundle\Repository\ProductCategoryRepository;
  22. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  23. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  24. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  25. use Symfony\Component\Form\Extension\Core\Type\MoneyType;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\Security\Core\Security;
  28. class AdminController extends EasyAdminController
  29. {
  30. protected $security;
  31. protected $userManager;
  32. public function __construct(Security $security, UserManagerInterface $userManager)
  33. {
  34. $this->security = $security;
  35. $this->userManager = $userManager;
  36. }
  37. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  38. {
  39. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  40. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  41. }
  42. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  43. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  44. else $dqlFilter .= sprintf(' entity.status > = 0');
  45. }
  46. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  47. if ($entityClass == 'App\Entity\PointSale') {
  48. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchant')
  49. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  50. }
  51. return $queryBuilder;
  52. }
  53. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  54. {
  55. $parameters = array_merge(
  56. $parameters,
  57. $this->getTwigExtraParameters()
  58. );
  59. return parent::renderTemplate($actionName, $templatePath, $parameters);
  60. }
  61. public function getTwigExtraParameters()
  62. {
  63. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  64. $merchants = $repositoryMerchant->findAll();
  65. $user = $this->security->getUser();
  66. return [
  67. 'merchants' => $merchants,
  68. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  69. ];
  70. }
  71. protected function removeEntity($entity)
  72. {
  73. $entity->setStatus(-1);
  74. $this->em->persist($entity);
  75. $this->em->flush();
  76. }
  77. public function updateEntity($entity)
  78. {
  79. $this->setUpdated($entity);
  80. parent::updateEntity($entity);
  81. }
  82. public function persistEntity($entity)
  83. {
  84. if ($entity instanceof StatusInterface) {
  85. $entity->setStatus(1);
  86. }
  87. if ($entity instanceof SortableInterface) {
  88. if ($entity instanceof TreeInterface) {
  89. if ($entity->getParent()) {
  90. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => $entity->getParent()->getId()));
  91. $entity->setPosition($entity->getParent()->getId() . '_' . $total);
  92. } else {
  93. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1, 'parent' => null));
  94. $entity->setPosition($total);
  95. }
  96. } else {
  97. $total = $this->em->getRepository($this->entity['class'])->count(array('status' => 1));
  98. $entity->setPosition($total);
  99. }
  100. }
  101. if (method_exists($entity, 'setMerchant')) {
  102. $entity->setMerchant($this->security->getUser()->getMerchant());
  103. }
  104. if (method_exists($entity, 'addMerchant')) {
  105. if ($entity->getMerchant()->isEmpty()) {
  106. $entity->addMerchant($this->security->getUser()->getMerchant());
  107. }
  108. }
  109. if (method_exists($entity, 'setCreatedBy')) {
  110. $entity->setCreatedBy($this->security->getUser());
  111. }
  112. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  113. $entity->getAddress()->setCreatedBy($this->security->getUser());
  114. $entity->getAddress()->setCreatedAt(new \DateTime());
  115. }
  116. if (method_exists($entity, 'getAddresses')
  117. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  118. foreach($entity->getAddresses() as $address) {
  119. $address->setCreatedBy($this->security->getUser()) ;
  120. $address->setCreatedAt(new \DateTime()) ;
  121. }
  122. }
  123. $this->setUpdated($entity);
  124. parent::persistEntity($entity);
  125. }
  126. public function updateProductFamilyEntity($entity)
  127. {
  128. $prodductFamilyRequest = $this->request->request->get('productfamily');
  129. if ($taxRateId = intval($prodductFamilyRequest['taxRate']) > 0) {
  130. $repo = $this->em->getRepository(TaxRateInterface::class);
  131. $entity->setTaxRate($repo->find($taxRateId));
  132. }
  133. $this->setUpdated($entity);
  134. parent::updateEntity($entity);
  135. }
  136. public function setUpdated($entity)
  137. {
  138. if (method_exists($entity, 'setUpdatedBy')) {
  139. $entity->setUpdatedBy($this->security->getUser());
  140. }
  141. if (method_exists($entity, 'getAddress') && $entity->getAddress()) {
  142. $entity->getAddress()->setUpdatedBy($this->security->getUser());
  143. }
  144. if (method_exists($entity, 'getAddresses')
  145. && $entity->getAddresses() && count($entity->getAddresses()) > 0) {
  146. foreach($entity->getAddresses() as $address) {
  147. $address->setUpdatedBy($this->security->getUser()) ;
  148. $address->setUpdatedAt(new \DateTime()) ;
  149. if(!$address->getCreatedBy()) {
  150. $address->setCreatedBy($this->security->getUser()) ;
  151. $address->setCreatedAt(new \DateTime()) ;
  152. }
  153. }
  154. }
  155. }
  156. public function listChildrenAction()
  157. {
  158. $this->dispatch(EasyAdminEvents::PRE_LIST);
  159. $id = $this->request->query->get('id');
  160. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  161. $easyadmin = $this->request->attributes->get('easyadmin');
  162. $entity = $easyadmin['item'];
  163. $fields = $this->entity['list']['fields'];
  164. $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']);
  165. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  166. $parameters = [
  167. 'paginator' => $paginator,
  168. 'fields' => $fields,
  169. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  170. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  171. 'entity' => $entity,
  172. ];
  173. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  174. }
  175. public function sortAction()
  176. {
  177. $this->dispatch(EasyAdminEvents::PRE_LIST);
  178. $entity = null;
  179. //Replace this with query builder function, do not use finAll of easyAdmin
  180. if ($this->request->query->get('id')) {
  181. $id = $this->request->query->get('id');
  182. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  183. $easyadmin = $this->request->attributes->get('easyadmin');
  184. $entity = $easyadmin['item'];
  185. }
  186. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  187. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  188. $fields = $this->entity['list']['fields'];
  189. $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']);
  190. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  191. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  192. ->add('entities', CollectionType::class, array(
  193. 'required' => true,
  194. 'allow_add' => true,
  195. 'entry_type' => AbstractEditPositionType::class,
  196. ))
  197. ->getForm();
  198. $positionForm->handleRequest($this->request);
  199. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  200. $class = $this->entity['class'];
  201. $repo = $this->em->getRepository($class);
  202. $latsPos = 0;
  203. foreach ($positionForm->get('entities')->getData() as $elm) {
  204. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  205. $entity = $repo->find($elm['id']);
  206. $entity->setPosition($elm['position']);
  207. $this->em->persist($entity);
  208. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  209. $latsPos = $elm['position'];
  210. }
  211. //to do récupérer les élements hors ligne et incrémenter position
  212. foreach ($repo->findAllOfflineAndDelete() as $offlineEntity) {
  213. $latsPos++;
  214. $offlineEntity->setPosition($latsPos);
  215. $this->em->persist($offlineEntity);
  216. }
  217. $this->em->flush();
  218. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  219. return $this->redirectToReferrer();
  220. }
  221. $parameters = [
  222. 'paginator' => $paginator,
  223. 'fields' => $fields,
  224. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  225. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  226. 'postion_form' => $positionForm->createView(),
  227. 'entity' => $entity,
  228. 'sortable' => true
  229. ];
  230. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  231. }
  232. private $taxRateClass;
  233. private $choicesTaxRateParam;
  234. public function createProductFamilyEntityFormBuilder($entity, $view)
  235. {
  236. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  237. $class = $this->em->getClassMetadata(ProductCategoryInterface::class);
  238. $this->taxRateClass = $this->em->getClassMetadata(TaxRateInterface::class);
  239. //$formBuilder = $this->get('form.factory')->createBuilder(ProductType::class, $entity);*/
  240. $formBuilder->add('price', MoneyType::class, array(
  241. 'block_prefix' => 'lc_tax_price',
  242. 'attr' => array(
  243. 'class' => 'lc-price'
  244. )
  245. ));
  246. $formBuilder->add('priceWithTax', MoneyType::class, array(
  247. 'attr' => array(
  248. 'class' => 'lc-price-with-tax'
  249. ),
  250. 'required' => false,
  251. 'mapped' => false
  252. ));
  253. //CHOICE qui permet de sélectionner une taxe
  254. //ça c'est du lourd fais très attention faudra refactorer
  255. $this->getUser()->getMerchant()->getTaxRate();
  256. $choicesTaxRate['TVA valeur par défaut'] = 0;
  257. foreach ($this->em->getRepository($this->taxRateClass->name)->findAll() as $tax) {
  258. $choicesTaxRate[$tax->getTitle()] = $tax->getId();
  259. $this->choicesTaxRateParam[$tax->getId()] = $tax->getValue();
  260. }
  261. //là mon ami je kiffe symfo !!!!!
  262. $this->choicesTaxRateParam[0] = $this->getUser()->getMerchant()->getTaxRate()->getValue();
  263. $formBuilder->add('taxRate', ChoiceType::class, array(
  264. 'choices' => $choicesTaxRate,
  265. 'mapped' => false,
  266. 'choice_attr' => function ($choice, $key, $value) {
  267. return ['data-tax-rate-value' => $this->choicesTaxRateParam[$choice]];
  268. },
  269. ));
  270. $formBuilder->add('unit', ChoiceType::class, array(
  271. 'choices' => array(
  272. 'pièce' => 'piece',
  273. 'g' => 'g',
  274. 'kg' => 'kg',
  275. 'ml' => 'mL',
  276. 'l' => 'L'
  277. ),
  278. ));
  279. $formBuilder->add('behaviorCountStock', ChoiceType::class, array(
  280. 'choices' => array(
  281. 'Gèrer le stock par déclinaison' => 'by-product',
  282. 'Gèrer le stock par produit' => 'by-product-family'
  283. ),
  284. 'multiple' => false,
  285. 'expanded' => true
  286. ));
  287. $formBuilder->add('productCategories', EntityType::class, array(
  288. 'multiple' => true,
  289. 'expanded' => true,
  290. 'class' => $class->name,
  291. 'query_builder' => function (EntityRepository $repo) {
  292. return $repo->createQueryBuilder('e')
  293. ->where('e.parent is NOT NULL')
  294. ->andWhere('e.status > 0')
  295. ->orderBy('e.status', "DESC");
  296. }
  297. )
  298. );
  299. $formBuilder->add('products', CollectionType::class, array(
  300. 'entry_type'=> ProductType::class,
  301. 'allow_add'=>true,
  302. 'prototype'=> true
  303. )
  304. );
  305. return $formBuilder;
  306. }
  307. public function createEntityFormBuilder($entity, $view)
  308. {
  309. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  310. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  311. if ($entity instanceof TreeInterface) {
  312. $formBuilder->add('parent', EntityType::class, array(
  313. 'class' => $this->entity['class'],
  314. 'query_builder' => function (EntityRepository $repo) use ($id) {
  315. return $repo->createQueryBuilder('e')
  316. ->where('e.parent is NULL')
  317. ->andWhere('e.status >= 0')
  318. ->orderBy('e.status', "DESC");
  319. },
  320. 'required' => false,
  321. )
  322. );
  323. }
  324. return $formBuilder;
  325. }
  326. }