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.

386 line
20KB

  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. $reductionCatalog = $editForm->get('reductionCatalog')->getData();
  159. if($reductionCatalog instanceof ReductionCatalogInterface ) {
  160. if($reductionCatalog->getValue() && $reductionCatalog->getBehaviorTaxRate() && $reductionCatalog->getUnit()){
  161. $reductionCatalog->setMerchant($entity->getMerchant());
  162. $reductionCatalog->setStatus($editForm->get('activeReductionCatalog')->getData());
  163. $reductionCatalog->setProductFamily($entity);
  164. $this->em->persist($reductionCatalog);
  165. }
  166. }
  167. }
  168. protected function processPrice($entity){
  169. if($entity->getBehaviorPrice()=='by-piece'){
  170. $entity->setPriceByRefUnit(null);
  171. $entity->setBuyingPriceByRefUnit(null);
  172. }else if($entity->getBehaviorPrice()=='by-reference-unit') {
  173. $entity->setPrice(null);
  174. $entity->setBuyingPrice(null);
  175. }
  176. }
  177. protected function processProducts($entity)
  178. {
  179. //si il existe un et un seul produit pour ce product family n'ajoute rien supprime rien
  180. if (count($entity->getProducts()) == 0) {
  181. $product = new Product();
  182. $product->setProductFamily($entity);
  183. $this->em->persist($product);
  184. $entity->addProduct($product);
  185. } else {
  186. foreach ($entity->getProducts() as $i=>$product) {
  187. $product->setProductFamily($entity);
  188. $this->em->persist($product);
  189. $entity->addProduct($product);
  190. }
  191. }
  192. }
  193. protected function processCategories(ProductFamilyInterface $entity)
  194. {
  195. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  196. $productCategories = $entity->getProductCategories();
  197. $entity->initProductCategories();
  198. foreach ($productCategories as $key => $bool) {
  199. if (is_bool($bool) && $bool) {
  200. if (strpos($key, 'category_children_') !== false) {
  201. $idCategory = (int)str_replace('category_children_', '', $key);
  202. } else {
  203. $idCategory = (int)str_replace('category_', '', $key);
  204. }
  205. $category = $productCategoryRepository->find($idCategory);
  206. $entity->addProductCategory($category);
  207. }
  208. }
  209. }
  210. protected function editAction()
  211. {
  212. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  213. $id = $this->request->query->get('id');
  214. $easyadmin = $this->request->attributes->get('easyadmin');
  215. $entity = $easyadmin['item'];
  216. $orderShopRepo = $this->em->getRepository(OrderShopInterface::class);
  217. $totalProductOrdered = array();
  218. foreach ($entity->getProducts() as $product) {
  219. $currentWeekNumber = $this->orderUtils->getWeekNumberCurrent();
  220. //Les commandes sont ouvertes ont récupèrent les commandes en cours et celle de la semaine dernière
  221. if($this->orderUtils->isOpenSale()) {
  222. $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  223. $totalProductOrdered[$product->getId()][$currentWeekNumber - 1] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber - 1, $product->getId());
  224. }else{
  225. $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  226. }
  227. }
  228. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  229. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  230. $fieldsMetadata = $this->entity['list']['fields'];
  231. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  232. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  233. }
  234. $this->updateEntityProperty($entity, $property, $newValue);
  235. // cast to integer instead of string to avoid sending empty responses for 'false'
  236. return new Response((int)$newValue);
  237. }
  238. $fields = $this->entity['edit']['fields'];
  239. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  240. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  241. $sortableProductsField = array();
  242. foreach ($editForm->get('products')->getData() as $k => $product) {
  243. $sortableProductsField[$product->getPosition()] = $k;
  244. }
  245. ksort($sortableProductsField);
  246. $editForm->handleRequest($this->request);
  247. if( $editForm->isSubmitted() && count($entity->getProductCategories()) == 0){
  248. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  249. }
  250. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories())>0) {
  251. $this->processUploadedFiles($editForm);
  252. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  253. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  254. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  255. $this->utils->addFlash('success', 'Produit sauvegardé') ;
  256. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id]) ;
  257. }
  258. $this->dispatch(EasyAdminEvents::POST_EDIT);
  259. $parameters = [
  260. 'form' => $editForm->createView(),
  261. 'entity_fields' => $fields,
  262. 'entity' => $entity,
  263. 'delete_form' => $deleteForm->createView(),
  264. 'sortableProductsField' => $sortableProductsField,
  265. 'totalProductOrdered' => $totalProductOrdered
  266. ];
  267. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  268. }
  269. protected function newAction()
  270. {
  271. $this->dispatch(EasyAdminEvents::PRE_NEW);
  272. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  273. $easyadmin = $this->request->attributes->get('easyadmin');
  274. $easyadmin['item'] = $entity;
  275. $this->request->attributes->set('easyadmin', $easyadmin);
  276. $fields = $this->entity['new']['fields'];
  277. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  278. $newForm->handleRequest($this->request);
  279. if( $newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray())===false){
  280. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  281. }
  282. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray())!==false) {
  283. $this->processUploadedFiles($newForm);
  284. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  285. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  286. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  287. return $this->redirectToReferrer();
  288. }
  289. $this->dispatch(EasyAdminEvents::POST_NEW, [
  290. 'entity_fields' => $fields,
  291. 'form' => $newForm,
  292. 'entity' => $entity
  293. ]);
  294. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  295. $categories = $productCategoryRepository->findAllParents();
  296. $parameters = [
  297. 'form' => $newForm->createView(),
  298. 'entity_fields' => $fields,
  299. 'entity' => $entity,
  300. 'categories' => $categories,
  301. 'sortableProductsField' => array(),
  302. 'totalProductOrdered' => array()
  303. ];
  304. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  305. }
  306. }