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.

458 lines
24KB

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