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.

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