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.

ProductFamilyController.php 21KB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. namespace Lc\ShopBundle\Controller\Backend;
  3. use App\Entity\Product;
  4. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  5. use Lc\ShopBundle\Context\OrderShopInterface;
  6. use Lc\ShopBundle\Context\ProductCategoryInterface;
  7. use Lc\ShopBundle\Context\ProductFamilyInterface;
  8. use Lc\ShopBundle\Context\ReductionCatalogInterface;
  9. use Lc\ShopBundle\Context\TaxRateInterface;
  10. use Lc\ShopBundle\Form\Backend\Common\ReductionCatalogType;
  11. use Lc\ShopBundle\Form\Backend\ProductFamily\ProductType;
  12. use Lc\ShopBundle\Model\ProductFamily;
  13. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  14. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  15. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  16. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  17. use Symfony\Component\Form\FormError;
  18. use Symfony\Component\HttpFoundation\Response;
  19. class ProductFamilyController extends AdminController
  20. {
  21. private $taxRateClass;
  22. private $choicesTaxRateParam;
  23. private $choicesSupplierTaxRateParam;
  24. public function createEntityFormBuilder($entity, $view, $override = true)
  25. {
  26. $formBuilder = parent::createEntityFormBuilder($entity, $view, false);
  27. $class = $this->em->getClassMetadata(ProductCategoryInterface::class);
  28. $this->taxRateClass = $this->em->getClassMetadata(TaxRateInterface::class);
  29. //$formBuilder->add('productCategories', ProductFamilyCategoriesType::class);
  30. $reductionCatalogRepo = $this->em->getRepository(ReductionCatalogInterface::class);
  31. $reductionCatalogClass = $this->em->getClassMetadata(ReductionCatalogInterface::class);
  32. $reductionCatalog = $reductionCatalogRepo->findOneBy(array('status' => false, 'productFamily' => $entity));
  33. if ($reductionCatalog == null) $reductionCatalog = new $reductionCatalogClass->name;
  34. $formBuilder->add('reductionCatalog', ReductionCatalogType::class, array(
  35. 'mapped' => false,
  36. 'data' => $reductionCatalog
  37. ));
  38. $formBuilder->add('stayOnPage', HiddenType::class, array(
  39. 'required'=>false,
  40. 'mapped'=>false,
  41. ));
  42. $formBuilder->add('warningMessageType', ChoiceType::class, array(
  43. 'choices' => array(
  44. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS => ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS,
  45. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_ERROR => ProductFamily::WARNING_MESSAGE_TYPE_ERROR,
  46. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_WARNING => ProductFamily::WARNING_MESSAGE_TYPE_WARNING,
  47. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_INFO => ProductFamily::WARNING_MESSAGE_TYPE_INFO
  48. ),
  49. 'translation_domain' => 'lcshop',
  50. 'multiple' => false,
  51. 'expanded' => false,
  52. 'required' => false
  53. ));
  54. $formBuilder->add('behaviorCountStock', ChoiceType::class, array(
  55. 'empty_data' => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  56. 'choices' => array(
  57. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE,
  58. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  59. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT,
  60. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED => ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED
  61. ),
  62. 'translation_domain' => 'lcshop',
  63. 'multiple' => false,
  64. 'expanded' => true
  65. ));
  66. $formBuilder->add('behaviorAddToCart', ChoiceType::class, array(
  67. 'data' => $entity->getBehaviorAddToCart() ? $entity->getBehaviorAddToCart() : 'simple',
  68. 'choices' => array(
  69. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE,
  70. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE
  71. ),
  72. 'translation_domain' => 'lcshop',
  73. 'multiple' => false,
  74. 'expanded' => true
  75. ));
  76. $formBuilder->add('behaviorPrice', ChoiceType::class, array(
  77. 'empty_data' => 'by-piece',
  78. 'choices' => array(
  79. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_PIECE => ProductFamily::BEHAVIOR_PRICE_BY_PIECE,
  80. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT => ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT
  81. ),
  82. 'translation_domain' => 'lcshop',
  83. 'multiple' => false,
  84. 'expanded' => true
  85. ));
  86. $formBuilder->add('multiplyingFactor', NumberType::class, array(
  87. 'mapped' => false,
  88. 'data' => floatval($this->merchantUtils->getMerchantConfig('multiplying-factor')),
  89. ));
  90. $formBuilder->add('propertyOrganicLabel', ChoiceType::class, array(
  91. 'choices' => array(
  92. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_AB => ProductFamily::PROPERTY_ORGANIC_LABEL_AB,
  93. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_NP => ProductFamily::PROPERTY_ORGANIC_LABEL_NP,
  94. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_HVE => ProductFamily::PROPERTY_ORGANIC_LABEL_HVE
  95. ),
  96. 'translation_domain' => 'lcshop',
  97. 'multiple' => false,
  98. 'expanded' => false,
  99. 'required' => false
  100. ));
  101. $formBuilder->add('typeExpirationDate', ChoiceType::class, array(
  102. 'choices' => array(
  103. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLC => ProductFamily::TYPE_EXPIRATION_DATE_DLC,
  104. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DDM => ProductFamily::TYPE_EXPIRATION_DATE_DDM,
  105. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLUO => ProductFamily::TYPE_EXPIRATION_DATE_DLUO
  106. ),
  107. 'translation_domain' => 'lcshop',
  108. 'multiple' => false,
  109. 'expanded' => true,
  110. 'required' => false
  111. ));
  112. $formBuilder->add('behaviorStockWeek', ChoiceType::class, array(
  113. 'choices' => array(
  114. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE,
  115. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION,
  116. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE
  117. ),
  118. 'translation_domain' => 'lcshop',
  119. 'multiple' => false,
  120. 'expanded' => true,
  121. 'required' => true
  122. ));
  123. $formBuilder->add('behaviorExpirationDate', ChoiceType::class, array(
  124. 'choices' => array(
  125. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY,
  126. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT
  127. ),
  128. 'translation_domain' => 'lcshop',
  129. 'multiple' => false,
  130. 'expanded' => true,
  131. 'required' => false
  132. ));
  133. $formBuilder->add('products', CollectionType::class, array(
  134. 'label' => 'Déclinaisons',
  135. 'entry_type' => ProductType::class,
  136. 'entry_options' => ['label' => false],
  137. 'allow_add' => true,
  138. 'allow_delete' => true,
  139. 'required' => true
  140. )
  141. );
  142. $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  143. return $formBuilder;
  144. }
  145. public function updateProductFamilyEntity($entity, $editForm)
  146. {
  147. $this->processReductionCatalog($entity, $editForm);
  148. $this->processCategories($entity);
  149. $this->processProducts($entity);
  150. $this->processPrice($entity);
  151. parent::updateEntity($entity);
  152. }
  153. public function persistProductFamilyEntity($entity, $newForm)
  154. {
  155. $this->processReductionCatalog($entity, $newForm);
  156. $this->processCategories($entity);
  157. $this->processProducts($entity);
  158. $this->processPrice($entity);
  159. $this->em->persist($entity);
  160. $this->em->flush();
  161. }
  162. protected function processReductionCatalog($entity, $editForm)
  163. {
  164. $reductionCatalog = $editForm->get('reductionCatalog')->getData();
  165. if ($reductionCatalog instanceof ReductionCatalogInterface) {
  166. if ($reductionCatalog->getValue() && $reductionCatalog->getBehaviorTaxRate() && $reductionCatalog->getUnit()) {
  167. $reductionCatalog->setMerchant($entity->getMerchant());
  168. $reductionCatalog->setStatus($editForm->get('activeReductionCatalog')->getData());
  169. $reductionCatalog->setProductFamily($entity);
  170. $this->em->persist($reductionCatalog);
  171. }
  172. }
  173. }
  174. protected function processPrice($entity)
  175. {
  176. if ($entity->getBehaviorPrice() == 'by-piece') {
  177. $entity->setPriceByRefUnit(null);
  178. $entity->setBuyingPriceByRefUnit(null);
  179. } else if ($entity->getBehaviorPrice() == 'by-reference-unit') {
  180. $entity->setPrice(null);
  181. $entity->setBuyingPrice(null);
  182. }
  183. }
  184. protected function processProducts($entity)
  185. {
  186. //si il existe un et un seul produit pour ce product family n'ajoute rien supprime rien
  187. if (count($entity->getProducts()) == 0) {
  188. $product = new Product();
  189. $product->setProductFamily($entity);
  190. $this->em->persist($product);
  191. $entity->addProduct($product);
  192. } else {
  193. foreach ($entity->getProducts() as $i => $product) {
  194. $product->setProductFamily($entity);
  195. $this->em->persist($product);
  196. $entity->addProduct($product);
  197. }
  198. }
  199. }
  200. protected function processCategories(ProductFamilyInterface $entity)
  201. {
  202. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  203. $productCategories = $entity->getProductCategories();
  204. $entity->initProductCategories();
  205. foreach ($productCategories as $key => $bool) {
  206. if (is_bool($bool) && $bool) {
  207. if (strpos($key, 'category_children_') !== false) {
  208. $idCategory = (int)str_replace('category_children_', '', $key);
  209. } else {
  210. $idCategory = (int)str_replace('category_', '', $key);
  211. }
  212. $category = $productCategoryRepository->find($idCategory);
  213. $entity->addProductCategory($category);
  214. }
  215. }
  216. }
  217. protected function editAction()
  218. {
  219. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  220. $id = $this->request->query->get('id');
  221. $easyadmin = $this->request->attributes->get('easyadmin');
  222. $entity = $easyadmin['item'];
  223. $orderShopRepo = $this->em->getRepository(OrderShopInterface::class);
  224. $totalProductOrdered = array();
  225. foreach ($entity->getProducts() as $product) {
  226. $currentWeekNumber = $this->orderUtils->getWeekNumberCurrent();
  227. //Les commandes sont ouvertes ont récupèrent les commandes en cours et celle de la semaine dernière
  228. if ($this->orderUtils->isOpenSale()) {
  229. $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  230. $totalProductOrdered[$product->getId()][$currentWeekNumber - 1] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber - 1, $product->getId());
  231. } else {
  232. $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  233. }
  234. }
  235. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  236. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  237. $fieldsMetadata = $this->entity['list']['fields'];
  238. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  239. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  240. }
  241. $this->updateEntityProperty($entity, $property, $newValue);
  242. // cast to integer instead of string to avoid sending empty responses for 'false'
  243. return new Response((int)$newValue);
  244. }
  245. $fields = $this->entity['edit']['fields'];
  246. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  247. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  248. $sortableProductsField = array();
  249. foreach ($editForm->get('products')->getData() as $k => $product) {
  250. $sortableProductsField[$product->getPosition()] = $k;
  251. }
  252. ksort($sortableProductsField);
  253. $editForm->handleRequest($this->request);
  254. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  255. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  256. }
  257. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  258. $this->processUploadedFiles($editForm);
  259. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  260. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  261. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  262. $this->utils->addFlash('success', 'Produit sauvegardé');
  263. if($editForm->get('stayOnPage')->getData() || $this->request->get('submitAndStay')){
  264. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id]) ;
  265. }else {
  266. return $this->redirectToReferrer();
  267. }
  268. }
  269. $this->dispatch(EasyAdminEvents::POST_EDIT);
  270. $parameters = [
  271. 'form' => $editForm->createView(),
  272. 'entity_fields' => $fields,
  273. 'entity' => $entity,
  274. 'delete_form' => $deleteForm->createView(),
  275. 'sortableProductsField' => $sortableProductsField,
  276. 'totalProductOrdered' => $totalProductOrdered
  277. ];
  278. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  279. }
  280. protected function newAction()
  281. {
  282. $this->dispatch(EasyAdminEvents::PRE_NEW);
  283. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  284. $easyadmin = $this->request->attributes->get('easyadmin');
  285. $easyadmin['item'] = $entity;
  286. $this->request->attributes->set('easyadmin', $easyadmin);
  287. $fields = $this->entity['new']['fields'];
  288. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  289. $newForm->handleRequest($this->request);
  290. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  291. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  292. }
  293. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  294. $this->processUploadedFiles($newForm);
  295. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  296. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  297. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  298. if($newForm->get('stayOnPage')->getData() || $this->request->get('submitAndStay')){
  299. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]) ;
  300. }else {
  301. return $this->redirectToReferrer();
  302. }
  303. }
  304. $this->dispatch(EasyAdminEvents::POST_NEW, [
  305. 'entity_fields' => $fields,
  306. 'form' => $newForm,
  307. 'entity' => $entity
  308. ]);
  309. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  310. $categories = $productCategoryRepository->findAllParents();
  311. $parameters = [
  312. 'form' => $newForm->createView(),
  313. 'entity_fields' => $fields,
  314. 'entity' => $entity,
  315. 'categories' => $categories,
  316. 'sortableProductsField' => array(),
  317. 'totalProductOrdered' => array()
  318. ];
  319. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  320. }
  321. }