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.

463 line
24KB

  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\ReductionCatalogInterface;
  12. use Lc\ShopBundle\Context\TaxRateInterface;
  13. use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
  14. use Lc\ShopBundle\Form\Backend\Common\ReductionCatalogType;
  15. use Lc\ShopBundle\Form\Backend\ProductFamily\ProductType;
  16. use Lc\ShopBundle\Model\ProductFamily;
  17. use Lc\ShopBundle\Services\UtilsManager;
  18. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  19. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  20. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  21. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  22. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  23. use Symfony\Component\Form\FormError;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Security\Core\Security;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  28. class ProductFamilyController extends AdminController
  29. {
  30. private $taxRateClass;
  31. private $choicesTaxRateParam;
  32. private $choicesSupplierTaxRateParam;
  33. private $parameterBag ;
  34. private $productFamilyUtils ;
  35. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
  36. MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator,
  37. ParameterBagInterface $parameterBag)
  38. {
  39. parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator);
  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. $sortableProductsField[$product->getPosition()] = $k;
  201. }
  202. ksort($sortableProductsField);
  203. $editForm->handleRequest($this->request);
  204. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  205. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  206. }
  207. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  208. $this->processUploadedFiles($editForm);
  209. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  210. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  211. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  212. $this->utils->addFlash('success', 'Produit sauvegardé');
  213. if ($editForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  214. $refererUrl = $this->request->query->get('referer', '');
  215. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id, 'referer' => $refererUrl]);
  216. } else {
  217. return $this->redirectToReferrer();
  218. }
  219. }
  220. $this->dispatch(EasyAdminEvents::POST_EDIT);
  221. $parameters = [
  222. 'form' => $editForm->createView(),
  223. 'entity_fields' => $fields,
  224. 'entity' => $entity,
  225. 'delete_form' => $deleteForm->createView(),
  226. 'sortableProductsField' => $sortableProductsField,
  227. 'totalProductOrdered' => $this->orderUtils->getTotalProductOrderedLastWeeks($entity)
  228. ];
  229. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  230. }
  231. protected function newAction()
  232. {
  233. $this->dispatch(EasyAdminEvents::PRE_NEW);
  234. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  235. $easyadmin = $this->request->attributes->get('easyadmin');
  236. $easyadmin['item'] = $entity;
  237. $this->request->attributes->set('easyadmin', $easyadmin);
  238. $fields = $this->entity['new']['fields'];
  239. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  240. $newForm->handleRequest($this->request);
  241. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  242. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  243. }
  244. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  245. $this->processUploadedFiles($newForm);
  246. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  247. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  248. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  249. if ($newForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  250. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]);
  251. } else {
  252. return $this->redirectToReferrer();
  253. }
  254. }
  255. $this->dispatch(EasyAdminEvents::POST_NEW, [
  256. 'entity_fields' => $fields,
  257. 'form' => $newForm,
  258. 'entity' => $entity
  259. ]);
  260. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  261. $categories = $productCategoryRepository->findAllParents();
  262. $parameters = [
  263. 'form' => $newForm->createView(),
  264. 'entity_fields' => $fields,
  265. 'entity' => $entity,
  266. 'categories' => $categories,
  267. 'sortableProductsField' => array(),
  268. 'totalProductOrdered' => array()
  269. ];
  270. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  271. }
  272. /*public function duplicateAction()
  273. {
  274. $id = $this->request->query->get('id');
  275. $refererUrl = $this->request->query->get('referer', '');
  276. $easyadmin = $this->request->attributes->get('easyadmin');
  277. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  278. $newProductFamily = clone $entity;
  279. if ($easyadmin['entity']['name'] == "ProductFamily") {
  280. }
  281. $this->em->persist($newProductFamily);
  282. $this->em->flush();
  283. return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newProductFamily->getId(), 'referer' => $refererUrl]);
  284. }*/
  285. //hack utilisé pour filter sur les catégories lors du tri des produits par sous cat
  286. //A améliorer à l'occas
  287. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  288. {
  289. $productCategoryId = false;
  290. if (isset($dqlFilter['productCategoryId'])) $productCategoryId = $dqlFilter['productCategoryId'];
  291. if(isset($dqlFilter['filter']))$dqlFilter = $dqlFilter['filter'];
  292. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  293. $queryBuilder->leftJoin('entity.productCategories', 'product_categories');
  294. if ($productCategoryId) {
  295. $queryBuilder->andWhere('product_categories.id = :cat');
  296. $queryBuilder->setParameter('cat', $productCategoryId);
  297. }
  298. return $queryBuilder;
  299. }
  300. public function sortByProductCategoryAction(){
  301. $this->dispatch(EasyAdminEvents::PRE_LIST);
  302. $entity = null;
  303. //Replace this with query builder function, do not use finAll of easyAdmin
  304. if ($this->request->query->get('productCategoryId')) {
  305. if(!is_array($this->entity['list']['dql_filter'])) {
  306. $this->entity['list']['dql_filter'] = array('filter' => $this->entity['list']['dql_filter']);
  307. }
  308. $this->entity['list']['dql_filter']['productCategoryId'] = $this->request->query->get('productCategoryId');
  309. $easyadmin = $this->request->attributes->get('easyadmin');
  310. $entity = $easyadmin['item'];
  311. }else{
  312. throw new \ErrorException('Action impossible') ;
  313. }
  314. if ($this->entity['list']['dql_filter']['filter']) $this->entity['list']['dql_filter']['filter'] .= sprintf(' AND entity.status = 1');
  315. else $this->entity['list']['dql_filter']['filter'] .= sprintf(' entity.status = 1');
  316. $fields = $this->entity['list']['fields'];
  317. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, 'position', 'asc', $this->entity['list']['dql_filter']);
  318. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  319. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  320. ->add('entities', CollectionType::class, array(
  321. 'required' => true,
  322. 'allow_add' => true,
  323. 'entry_type' => AbstractEditPositionType::class,
  324. ))
  325. ->getForm();
  326. $positionForm->handleRequest($this->request);
  327. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  328. $class = $this->entity['class'];
  329. $repo = $this->em->getRepository($class);
  330. $latsPos = 0;
  331. foreach ($positionForm->get('entities')->getData() as $elm) {
  332. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  333. $entity = $repo->find($elm['id']);
  334. $entity->setPosition($elm['position']);
  335. $this->em->persist($entity);
  336. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  337. $latsPos = $elm['position'];
  338. }
  339. //die();
  340. //to do récupérer les élements hors ligne et incrémenter position
  341. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  342. $latsPos++;
  343. $offlineEntity->setPosition($latsPos);
  344. $this->em->persist($offlineEntity);
  345. }*/
  346. $this->em->flush();
  347. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  348. return $this->redirectToReferrer();
  349. }
  350. $parameters = [
  351. 'paginator' => $paginator,
  352. 'fields' => $fields,
  353. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  354. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  355. 'postion_form' => $positionForm->createView(),
  356. 'entity' => $entity,
  357. 'sortable' => true
  358. ];
  359. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  360. }
  361. }