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 20KB

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