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.

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