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ů.

456 lines
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\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('behaviorDisplaySale', ChoiceType::class, array(
  86. 'empty_data' => ProductFamily::BEHAVIOR_DISPLAY_SALE_BY_QUANTITY,
  87. 'choices' => array(
  88. 'field.ProductFamily.behaviorDisplaySaleOptions.' . ProductFamily::BEHAVIOR_DISPLAY_SALE_BY_MEASURE => ProductFamily::BEHAVIOR_DISPLAY_SALE_BY_MEASURE,
  89. 'field.ProductFamily.behaviorDisplaySaleOptions.' . ProductFamily::BEHAVIOR_DISPLAY_SALE_BY_QUANTITY => ProductFamily::BEHAVIOR_DISPLAY_SALE_BY_QUANTITY,
  90. ),
  91. 'translation_domain' => 'lcshop',
  92. 'multiple' => false,
  93. 'expanded' => true
  94. ));
  95. $formBuilder->add('behaviorAddToCart', ChoiceType::class, array(
  96. 'data' => $entity->getBehaviorAddToCart() ? $entity->getBehaviorAddToCart() : 'simple',
  97. 'choices' => array(
  98. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE,
  99. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE
  100. ),
  101. 'translation_domain' => 'lcshop',
  102. 'multiple' => false,
  103. 'expanded' => true
  104. ));
  105. $formBuilder->add('behaviorPrice', ChoiceType::class, array(
  106. 'empty_data' => 'by-piece',
  107. 'choices' => array(
  108. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_PIECE => ProductFamily::BEHAVIOR_PRICE_BY_PIECE,
  109. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT => ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT
  110. ),
  111. 'translation_domain' => 'lcshop',
  112. 'multiple' => false,
  113. 'expanded' => true
  114. ));
  115. $formBuilder->add('multiplyingFactor', NumberType::class, array(
  116. 'mapped' => false,
  117. 'data' => floatval($this->merchantUtils->getMerchantConfig('multiplying-factor')),
  118. ));
  119. $formBuilder->add('propertyOrganicLabel', ChoiceType::class, array(
  120. 'choices' => array(
  121. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_AB => ProductFamily::PROPERTY_ORGANIC_LABEL_AB,
  122. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_NP => ProductFamily::PROPERTY_ORGANIC_LABEL_NP,
  123. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_HVE => ProductFamily::PROPERTY_ORGANIC_LABEL_HVE,
  124. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_TVVR => ProductFamily::PROPERTY_ORGANIC_LABEL_TVVR
  125. ),
  126. 'translation_domain' => 'lcshop',
  127. 'multiple' => false,
  128. 'expanded' => false,
  129. 'required' => false
  130. ));
  131. $formBuilder->add('typeExpirationDate', ChoiceType::class, array(
  132. 'choices' => array(
  133. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLC => ProductFamily::TYPE_EXPIRATION_DATE_DLC,
  134. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DDM => ProductFamily::TYPE_EXPIRATION_DATE_DDM,
  135. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLUO => ProductFamily::TYPE_EXPIRATION_DATE_DLUO
  136. ),
  137. 'translation_domain' => 'lcshop',
  138. 'multiple' => false,
  139. 'expanded' => true,
  140. 'required' => false
  141. ));
  142. $formBuilder->add('behaviorStockWeek', ChoiceType::class, array(
  143. 'choices' => array(
  144. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE,
  145. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION,
  146. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE
  147. ),
  148. 'translation_domain' => 'lcshop',
  149. 'multiple' => false,
  150. 'expanded' => true,
  151. 'required' => true
  152. ));
  153. $formBuilder->add('behaviorExpirationDate', ChoiceType::class, array(
  154. 'choices' => array(
  155. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY,
  156. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT
  157. ),
  158. 'translation_domain' => 'lcshop',
  159. 'multiple' => false,
  160. 'expanded' => true,
  161. 'required' => false
  162. ));
  163. $formBuilder->add('products', CollectionType::class, array(
  164. 'label' => 'Déclinaisons',
  165. 'entry_type' => ProductType::class,
  166. 'entry_options' => ['label' => false],
  167. 'allow_add' => true,
  168. 'allow_delete' => true,
  169. 'required' => true
  170. )
  171. );
  172. $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  173. return $formBuilder;
  174. }
  175. public function updateProductFamilyEntity($entity, $editForm = false)
  176. {
  177. if ($editForm) {
  178. $entity = $this->productFamilyUtils->processBeforePersistProductFamily($entity, $editForm);
  179. }
  180. parent::updateEntity($entity);
  181. $this->orderUtils->updatePriceByProductFamily($entity);
  182. }
  183. public function persistProductFamilyEntity($entity, $newForm)
  184. {
  185. $entity = $this->productFamilyUtils->processBeforePersistProductFamily($entity, $newForm);
  186. $this->em->persist($entity);
  187. $this->em->flush();
  188. }
  189. protected function editAction()
  190. {
  191. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  192. $id = $this->request->query->get('id');
  193. $easyadmin = $this->request->attributes->get('easyadmin');
  194. $entity = $easyadmin['item'];
  195. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  196. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  197. $fieldsMetadata = $this->entity['list']['fields'];
  198. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  199. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  200. }
  201. $this->updateEntityProperty($entity, $property, $newValue);
  202. $this->utils->addFlash('success', 'success.common.fieldChange');
  203. $response['flashMessages'] = $this->utils->getFlashMessages();
  204. return new Response(json_encode($response));
  205. }
  206. $fields = $this->entity['edit']['fields'];
  207. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  208. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  209. $sortableProductsField = array();
  210. foreach ($editForm->get('products')->getData() as $k => $product) {
  211. if($product->getOriginProduct() == false) {
  212. $sortableProductsField[$product->getPosition()] = $k;
  213. }else{
  214. $sortableProductsField[-1] = $k;
  215. }
  216. }
  217. ksort($sortableProductsField);
  218. $editForm->handleRequest($this->request);
  219. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  220. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  221. }
  222. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  223. $this->processUploadedFiles($editForm);
  224. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  225. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  226. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  227. $this->utils->addFlash('success', 'Produit sauvegardé');
  228. if ($editForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  229. $refererUrl = $this->request->query->get('referer', '');
  230. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id, 'referer' => $refererUrl, 'ajax' => $this->request->query->get('ajax')]);
  231. } else {
  232. return $this->redirectToReferrer();
  233. }
  234. }
  235. $this->dispatch(EasyAdminEvents::POST_EDIT);
  236. $parameters = [
  237. 'form' => $editForm->createView(),
  238. 'entity_fields' => $fields,
  239. 'entity' => $entity,
  240. 'delete_form' => $deleteForm->createView(),
  241. 'sortableProductsField' => $sortableProductsField,
  242. 'productsSalesStatistic' => $this->orderUtils->getProductsSalesStatistic($entity)
  243. ];
  244. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  245. }
  246. protected function newAction()
  247. {
  248. $this->dispatch(EasyAdminEvents::PRE_NEW);
  249. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  250. $easyadmin = $this->request->attributes->get('easyadmin');
  251. $easyadmin['item'] = $entity;
  252. $this->request->attributes->set('easyadmin', $easyadmin);
  253. $fields = $this->entity['new']['fields'];
  254. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  255. $newForm->handleRequest($this->request);
  256. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  257. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  258. }
  259. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  260. $this->processUploadedFiles($newForm);
  261. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  262. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  263. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  264. if ($newForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  265. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]);
  266. } else {
  267. return $this->redirectToReferrer();
  268. }
  269. }
  270. $this->dispatch(EasyAdminEvents::POST_NEW, [
  271. 'entity_fields' => $fields,
  272. 'form' => $newForm,
  273. 'entity' => $entity
  274. ]);
  275. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  276. $categories = $productCategoryRepository->findAllParents();
  277. $parameters = [
  278. 'form' => $newForm->createView(),
  279. 'entity_fields' => $fields,
  280. 'entity' => $entity,
  281. 'categories' => $categories,
  282. 'sortableProductsField' => array(),
  283. 'productsSalesStatistic' => null
  284. ];
  285. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  286. }
  287. //hack utilisé pour filter sur les catégories lors du tri des produits par sous cat
  288. //A améliorer à l'occas
  289. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  290. {
  291. $productCategoryId = false;
  292. if (isset($dqlFilter['productCategoryId'])) $productCategoryId = $dqlFilter['productCategoryId'];
  293. if(isset($dqlFilter['filter']))$dqlFilter = $dqlFilter['filter'];
  294. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  295. $queryBuilder->leftJoin('entity.productCategories', 'product_categories');
  296. if ($productCategoryId) {
  297. $queryBuilder->andWhere('product_categories.id = :cat');
  298. $queryBuilder->setParameter('cat', $productCategoryId);
  299. }
  300. return $queryBuilder;
  301. }
  302. public function sortByProductCategoryAction(){
  303. $this->dispatch(EasyAdminEvents::PRE_LIST);
  304. $entity = null;
  305. //Replace this with query builder function, do not use finAll of easyAdmin
  306. if ($this->request->query->get('productCategoryId')) {
  307. if(!is_array($this->entity['list']['dql_filter'])) {
  308. $this->entity['list']['dql_filter'] = array('filter' => $this->entity['list']['dql_filter']);
  309. }
  310. $this->entity['list']['dql_filter']['productCategoryId'] = $this->request->query->get('productCategoryId');
  311. $easyadmin = $this->request->attributes->get('easyadmin');
  312. $entity = $easyadmin['item'];
  313. }else{
  314. throw new \ErrorException('Action impossible') ;
  315. }
  316. if ($this->entity['list']['dql_filter']['filter']) $this->entity['list']['dql_filter']['filter'] .= sprintf(' AND entity.status = 1');
  317. else $this->entity['list']['dql_filter']['filter'] .= sprintf(' entity.status = 1');
  318. $fields = $this->entity['list']['fields'];
  319. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, 'position', 'asc', $this->entity['list']['dql_filter']);
  320. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  321. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  322. ->add('entities', CollectionType::class, array(
  323. 'required' => true,
  324. 'allow_add' => true,
  325. 'entry_type' => AbstractEditPositionType::class,
  326. ))
  327. ->getForm();
  328. $positionForm->handleRequest($this->request);
  329. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  330. $class = $this->entity['class'];
  331. $repo = $this->em->getRepository($class);
  332. $latsPos = 0;
  333. foreach ($positionForm->get('entities')->getData() as $elm) {
  334. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  335. $entity = $repo->find($elm['id']);
  336. $entity->setPosition($elm['position']);
  337. $this->em->persist($entity);
  338. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  339. $latsPos = $elm['position'];
  340. }
  341. //die();
  342. //to do récupérer les élements hors ligne et incrémenter position
  343. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  344. $latsPos++;
  345. $offlineEntity->setPosition($latsPos);
  346. $this->em->persist($offlineEntity);
  347. }*/
  348. $this->em->flush();
  349. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  350. return $this->redirectToReferrer();
  351. }
  352. $parameters = [
  353. 'paginator' => $paginator,
  354. 'fields' => $fields,
  355. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  356. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  357. 'postion_form' => $positionForm->createView(),
  358. 'entity' => $entity,
  359. 'sortable' => true
  360. ];
  361. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  362. }
  363. }