Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

444 lines
23KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Backend;
  3. use App\Entity\Product;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  6. use FOS\UserBundle\Model\UserManagerInterface;
  7. use Lc\ShopBundle\Context\ImageInterface;
  8. use Lc\ShopBundle\Context\OrderShopInterface;
  9. use Lc\ShopBundle\Context\ProductCategoryInterface;
  10. use Lc\ShopBundle\Context\ProductFamilyInterface;
  11. use Lc\ShopBundle\Context\ProductInterface;
  12. use Lc\ShopBundle\Context\ReductionCatalogInterface;
  13. use Lc\ShopBundle\Context\TaxRateInterface;
  14. use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
  15. use Lc\ShopBundle\Form\Backend\Common\ReductionCatalogType;
  16. use Lc\ShopBundle\Form\Backend\ProductFamily\ProductType;
  17. use Lc\ShopBundle\Model\ProductFamily;
  18. use Lc\ShopBundle\Services\UtilsManager;
  19. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  20. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  21. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  22. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  23. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  24. use Symfony\Component\Form\FormError;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  27. use Symfony\Component\Security\Core\Security;
  28. use Symfony\Contracts\Translation\TranslatorInterface;
  29. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  30. class ProductFamilyController extends AdminController
  31. {
  32. private $taxRateClass;
  33. private $choicesTaxRateParam;
  34. private $choicesSupplierTaxRateParam;
  35. private $parameterBag ;
  36. private $productFamilyUtils ;
  37. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em, MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator, SessionInterface $session, ParameterBagInterface $parameterBag)
  38. {
  39. parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator, $session);
  40. $this->parameterBag = $parameterBag ;
  41. $this->productFamilyUtils = $utilsManager->getProductFamilyUtils() ;
  42. }
  43. public function createEntityFormBuilder($entity, $view, $override = true)
  44. {
  45. $formBuilder = parent::createEntityFormBuilder($entity, $view, false);
  46. $class = $this->em->getClassMetadata(ProductCategoryInterface::class);
  47. $this->taxRateClass = $this->em->getClassMetadata(TaxRateInterface::class);
  48. //$formBuilder->add('productCategories', ProductFamilyCategoriesType::class);
  49. $reductionCatalogRepo = $this->em->getRepository(ReductionCatalogInterface::class);
  50. $reductionCatalogClass = $this->em->getClassMetadata(ReductionCatalogInterface::class);
  51. $reductionCatalog = $reductionCatalogRepo->findOneBy(array('status' => false, 'productFamily' => $entity));
  52. if ($reductionCatalog == null) $reductionCatalog = new $reductionCatalogClass->name;
  53. $formBuilder->add('reductionCatalog', ReductionCatalogType::class, array(
  54. 'mapped' => false,
  55. 'data' => $reductionCatalog
  56. ));
  57. $formBuilder->add('stayOnPage', HiddenType::class, array(
  58. 'required' => false,
  59. 'mapped' => false,
  60. ));
  61. $formBuilder->add('warningMessageType', ChoiceType::class, array(
  62. 'choices' => array(
  63. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS => ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS,
  64. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_ERROR => ProductFamily::WARNING_MESSAGE_TYPE_ERROR,
  65. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_WARNING => ProductFamily::WARNING_MESSAGE_TYPE_WARNING,
  66. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_INFO => ProductFamily::WARNING_MESSAGE_TYPE_INFO
  67. ),
  68. 'translation_domain' => 'lcshop',
  69. 'multiple' => false,
  70. 'expanded' => false,
  71. 'required' => false
  72. ));
  73. $formBuilder->add('behaviorCountStock', ChoiceType::class, array(
  74. 'empty_data' => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  75. 'choices' => array(
  76. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE,
  77. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  78. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT,
  79. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED => ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED
  80. ),
  81. 'translation_domain' => 'lcshop',
  82. 'multiple' => false,
  83. 'expanded' => true
  84. ));
  85. $formBuilder->add('behaviorAddToCart', ChoiceType::class, array(
  86. 'data' => $entity->getBehaviorAddToCart() ? $entity->getBehaviorAddToCart() : 'simple',
  87. 'choices' => array(
  88. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE,
  89. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE
  90. ),
  91. 'translation_domain' => 'lcshop',
  92. 'multiple' => false,
  93. 'expanded' => true
  94. ));
  95. $formBuilder->add('behaviorPrice', ChoiceType::class, array(
  96. 'empty_data' => 'by-piece',
  97. 'choices' => array(
  98. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_PIECE => ProductFamily::BEHAVIOR_PRICE_BY_PIECE,
  99. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT => ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT
  100. ),
  101. 'translation_domain' => 'lcshop',
  102. 'multiple' => false,
  103. 'expanded' => true
  104. ));
  105. $formBuilder->add('multiplyingFactor', NumberType::class, array(
  106. 'mapped' => false,
  107. 'data' => floatval($this->merchantUtils->getMerchantConfig('multiplying-factor')),
  108. ));
  109. $formBuilder->add('propertyOrganicLabel', ChoiceType::class, array(
  110. 'choices' => array(
  111. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_AB => ProductFamily::PROPERTY_ORGANIC_LABEL_AB,
  112. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_NP => ProductFamily::PROPERTY_ORGANIC_LABEL_NP,
  113. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_HVE => ProductFamily::PROPERTY_ORGANIC_LABEL_HVE
  114. ),
  115. 'translation_domain' => 'lcshop',
  116. 'multiple' => false,
  117. 'expanded' => false,
  118. 'required' => false
  119. ));
  120. $formBuilder->add('typeExpirationDate', ChoiceType::class, array(
  121. 'choices' => array(
  122. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLC => ProductFamily::TYPE_EXPIRATION_DATE_DLC,
  123. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DDM => ProductFamily::TYPE_EXPIRATION_DATE_DDM,
  124. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLUO => ProductFamily::TYPE_EXPIRATION_DATE_DLUO
  125. ),
  126. 'translation_domain' => 'lcshop',
  127. 'multiple' => false,
  128. 'expanded' => true,
  129. 'required' => false
  130. ));
  131. $formBuilder->add('behaviorStockWeek', ChoiceType::class, array(
  132. 'choices' => array(
  133. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE,
  134. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION,
  135. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE
  136. ),
  137. 'translation_domain' => 'lcshop',
  138. 'multiple' => false,
  139. 'expanded' => true,
  140. 'required' => true
  141. ));
  142. $formBuilder->add('behaviorExpirationDate', ChoiceType::class, array(
  143. 'choices' => array(
  144. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY,
  145. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT
  146. ),
  147. 'translation_domain' => 'lcshop',
  148. 'multiple' => false,
  149. 'expanded' => true,
  150. 'required' => false
  151. ));
  152. $formBuilder->add('products', CollectionType::class, array(
  153. 'label' => 'Déclinaisons',
  154. 'entry_type' => ProductType::class,
  155. 'entry_options' => ['label' => false],
  156. 'allow_add' => true,
  157. 'allow_delete' => true,
  158. 'required' => true
  159. )
  160. );
  161. $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  162. return $formBuilder;
  163. }
  164. public function updateProductFamilyEntity($entity, $editForm = false)
  165. {
  166. if ($editForm) {
  167. $entity = $this->productFamilyUtils->processBeforePersistProductFamily($entity, $editForm);
  168. }
  169. parent::updateEntity($entity);
  170. $this->orderUtils->updatePriceByProductFamily($entity);
  171. }
  172. public function persistProductFamilyEntity($entity, $newForm)
  173. {
  174. $entity = $this->productFamilyUtils->processBeforePersistProductFamily($entity, $newForm);
  175. $this->em->persist($entity);
  176. $this->em->flush();
  177. }
  178. protected function editAction()
  179. {
  180. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  181. $id = $this->request->query->get('id');
  182. $easyadmin = $this->request->attributes->get('easyadmin');
  183. $entity = $easyadmin['item'];
  184. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  185. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  186. $fieldsMetadata = $this->entity['list']['fields'];
  187. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  188. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  189. }
  190. $this->updateEntityProperty($entity, $property, $newValue);
  191. $this->utils->addFlash('success', 'success.common.fieldChange');
  192. $response['flashMessages'] = $this->utils->getFlashMessages();
  193. return new Response(json_encode($response));
  194. }
  195. $fields = $this->entity['edit']['fields'];
  196. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  197. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  198. $sortableProductsField = array();
  199. foreach ($editForm->get('products')->getData() as $k => $product) {
  200. if($product->getOriginProduct() == false) {
  201. $sortableProductsField[$product->getPosition()] = $k;
  202. }else{
  203. $sortableProductsField[-1] = $k;
  204. }
  205. }
  206. ksort($sortableProductsField);
  207. $editForm->handleRequest($this->request);
  208. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  209. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  210. }
  211. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  212. $this->processUploadedFiles($editForm);
  213. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  214. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  215. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  216. $this->utils->addFlash('success', 'Produit sauvegardé');
  217. if ($editForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  218. $refererUrl = $this->request->query->get('referer', '');
  219. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id, 'referer' => $refererUrl, 'ajax' => $this->request->query->get('ajax')]);
  220. } else {
  221. return $this->redirectToReferrer();
  222. }
  223. }
  224. $this->dispatch(EasyAdminEvents::POST_EDIT);
  225. $parameters = [
  226. 'form' => $editForm->createView(),
  227. 'entity_fields' => $fields,
  228. 'entity' => $entity,
  229. 'delete_form' => $deleteForm->createView(),
  230. 'sortableProductsField' => $sortableProductsField,
  231. 'totalProductOrdered' => $this->orderUtils->getTotalProductOrderedLastWeeks($entity)
  232. ];
  233. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  234. }
  235. protected function newAction()
  236. {
  237. $this->dispatch(EasyAdminEvents::PRE_NEW);
  238. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  239. $easyadmin = $this->request->attributes->get('easyadmin');
  240. $easyadmin['item'] = $entity;
  241. $this->request->attributes->set('easyadmin', $easyadmin);
  242. $fields = $this->entity['new']['fields'];
  243. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  244. $newForm->handleRequest($this->request);
  245. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  246. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  247. }
  248. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  249. $this->processUploadedFiles($newForm);
  250. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  251. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  252. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  253. if ($newForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  254. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]);
  255. } else {
  256. return $this->redirectToReferrer();
  257. }
  258. }
  259. $this->dispatch(EasyAdminEvents::POST_NEW, [
  260. 'entity_fields' => $fields,
  261. 'form' => $newForm,
  262. 'entity' => $entity
  263. ]);
  264. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  265. $categories = $productCategoryRepository->findAllParents();
  266. $parameters = [
  267. 'form' => $newForm->createView(),
  268. 'entity_fields' => $fields,
  269. 'entity' => $entity,
  270. 'categories' => $categories,
  271. 'sortableProductsField' => array(),
  272. 'totalProductOrdered' => array('total'=>0)
  273. ];
  274. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  275. }
  276. //hack utilisé pour filter sur les catégories lors du tri des produits par sous cat
  277. //A améliorer à l'occas
  278. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  279. {
  280. $productCategoryId = false;
  281. if (isset($dqlFilter['productCategoryId'])) $productCategoryId = $dqlFilter['productCategoryId'];
  282. if(isset($dqlFilter['filter']))$dqlFilter = $dqlFilter['filter'];
  283. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  284. $queryBuilder->leftJoin('entity.productCategories', 'product_categories');
  285. if ($productCategoryId) {
  286. $queryBuilder->andWhere('product_categories.id = :cat');
  287. $queryBuilder->setParameter('cat', $productCategoryId);
  288. }
  289. return $queryBuilder;
  290. }
  291. public function sortByProductCategoryAction(){
  292. $this->dispatch(EasyAdminEvents::PRE_LIST);
  293. $entity = null;
  294. //Replace this with query builder function, do not use finAll of easyAdmin
  295. if ($this->request->query->get('productCategoryId')) {
  296. if(!is_array($this->entity['list']['dql_filter'])) {
  297. $this->entity['list']['dql_filter'] = array('filter' => $this->entity['list']['dql_filter']);
  298. }
  299. $this->entity['list']['dql_filter']['productCategoryId'] = $this->request->query->get('productCategoryId');
  300. $easyadmin = $this->request->attributes->get('easyadmin');
  301. $entity = $easyadmin['item'];
  302. }else{
  303. throw new \ErrorException('Action impossible') ;
  304. }
  305. if ($this->entity['list']['dql_filter']['filter']) $this->entity['list']['dql_filter']['filter'] .= sprintf(' AND entity.status = 1');
  306. else $this->entity['list']['dql_filter']['filter'] .= sprintf(' entity.status = 1');
  307. $fields = $this->entity['list']['fields'];
  308. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, 'position', 'asc', $this->entity['list']['dql_filter']);
  309. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  310. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  311. ->add('entities', CollectionType::class, array(
  312. 'required' => true,
  313. 'allow_add' => true,
  314. 'entry_type' => AbstractEditPositionType::class,
  315. ))
  316. ->getForm();
  317. $positionForm->handleRequest($this->request);
  318. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  319. $class = $this->entity['class'];
  320. $repo = $this->em->getRepository($class);
  321. $latsPos = 0;
  322. foreach ($positionForm->get('entities')->getData() as $elm) {
  323. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  324. $entity = $repo->find($elm['id']);
  325. $entity->setPosition($elm['position']);
  326. $this->em->persist($entity);
  327. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  328. $latsPos = $elm['position'];
  329. }
  330. //die();
  331. //to do récupérer les élements hors ligne et incrémenter position
  332. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  333. $latsPos++;
  334. $offlineEntity->setPosition($latsPos);
  335. $this->em->persist($offlineEntity);
  336. }*/
  337. $this->em->flush();
  338. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  339. return $this->redirectToReferrer();
  340. }
  341. $parameters = [
  342. 'paginator' => $paginator,
  343. 'fields' => $fields,
  344. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  345. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  346. 'postion_form' => $positionForm->createView(),
  347. 'entity' => $entity,
  348. 'sortable' => true
  349. ];
  350. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  351. }
  352. }