No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

450 líneas
25KB

  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 = false)
  146. {
  147. if ($editForm) {
  148. $this->processReductionCatalog($entity, $editForm);
  149. $this->processCategories($entity);
  150. $this->processProducts($entity);
  151. $this->processPrice($entity);
  152. }
  153. parent::updateEntity($entity);
  154. }
  155. public function persistProductFamilyEntity($entity, $newForm)
  156. {
  157. $this->processReductionCatalog($entity, $newForm);
  158. $this->processCategories($entity);
  159. $this->processProducts($entity);
  160. $this->processPrice($entity);
  161. $this->em->persist($entity);
  162. $this->em->flush();
  163. }
  164. protected function processReductionCatalog($entity, $editForm)
  165. {
  166. $reductionCatalog = $editForm->get('reductionCatalog')->getData();
  167. if ($reductionCatalog instanceof ReductionCatalogInterface) {
  168. if ($reductionCatalog->getValue() && $reductionCatalog->getBehaviorTaxRate() && $reductionCatalog->getUnit()) {
  169. $reductionCatalog->setMerchant($entity->getMerchant());
  170. $reductionCatalog->setStatus($editForm->get('activeReductionCatalog')->getData());
  171. $reductionCatalog->setProductFamily($entity);
  172. $this->em->persist($reductionCatalog);
  173. }
  174. }
  175. }
  176. protected function processPrice($entity)
  177. {
  178. if ($entity->getBehaviorPrice() == 'by-piece') {
  179. $entity->setPriceByRefUnit(null);
  180. $entity->setBuyingPriceByRefUnit(null);
  181. } else if ($entity->getBehaviorPrice() == 'by-reference-unit') {
  182. $entity->setPrice(null);
  183. $entity->setBuyingPrice(null);
  184. }
  185. }
  186. protected function processProducts($entity, $clone = false)
  187. {
  188. //si il existe un et un seul produit pour ce product family n'ajoute rien supprime rien
  189. if (count($entity->getProducts()) == 0) {
  190. $product = new Product();
  191. $product->setProductFamily($entity);
  192. $this->em->persist($product);
  193. $entity->addProduct($product);
  194. } else {
  195. foreach ($entity->getProducts() as $i => $product) {
  196. if ($clone) {
  197. $newProduct = clone $product;
  198. $newProduct->setProductFamily($entity);
  199. $this->em->persist($newProduct);
  200. $entity->addProduct($newProduct);
  201. } else {
  202. $product->setProductFamily($entity);
  203. $this->em->persist($product);
  204. $entity->addProduct($product);
  205. }
  206. }
  207. }
  208. }
  209. protected function processCategories(ProductFamilyInterface $entity)
  210. {
  211. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  212. $productCategories = $entity->getProductCategories();
  213. $entity->initProductCategories();
  214. foreach ($productCategories as $key => $bool) {
  215. if (is_bool($bool) && $bool) {
  216. if (strpos($key, 'category_children_') !== false) {
  217. $idCategory = (int)str_replace('category_children_', '', $key);
  218. } else {
  219. $idCategory = (int)str_replace('category_', '', $key);
  220. }
  221. $category = $productCategoryRepository->find($idCategory);
  222. $entity->addProductCategory($category);
  223. }
  224. }
  225. }
  226. protected function editAction()
  227. {
  228. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  229. $id = $this->request->query->get('id');
  230. $easyadmin = $this->request->attributes->get('easyadmin');
  231. $entity = $easyadmin['item'];
  232. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  233. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  234. $fieldsMetadata = $this->entity['list']['fields'];
  235. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  236. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  237. }
  238. $this->updateEntityProperty($entity, $property, $newValue);
  239. $this->utils->addFlash('success', 'success.common.fieldChange');
  240. $response['flashMessages'] = $this->utils->getFlashMessages();
  241. return new Response(json_encode($response));
  242. }
  243. $fields = $this->entity['edit']['fields'];
  244. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  245. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  246. $sortableProductsField = array();
  247. foreach ($editForm->get('products')->getData() as $k => $product) {
  248. $sortableProductsField[$product->getPosition()] = $k;
  249. }
  250. ksort($sortableProductsField);
  251. $editForm->handleRequest($this->request);
  252. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  253. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  254. }
  255. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  256. $this->processUploadedFiles($editForm);
  257. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  258. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  259. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  260. $this->utils->addFlash('success', 'Produit sauvegardé');
  261. if ($editForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  262. $refererUrl = $this->request->query->get('referer', '');
  263. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id, 'referer' => $refererUrl]);
  264. } else {
  265. return $this->redirectToReferrer();
  266. }
  267. }
  268. $this->dispatch(EasyAdminEvents::POST_EDIT);
  269. $parameters = [
  270. 'form' => $editForm->createView(),
  271. 'entity_fields' => $fields,
  272. 'entity' => $entity,
  273. 'delete_form' => $deleteForm->createView(),
  274. 'sortableProductsField' => $sortableProductsField,
  275. 'totalProductOrdered' => $this->getTotalProductOrdered($entity)
  276. ];
  277. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  278. }
  279. protected function newAction()
  280. {
  281. $this->dispatch(EasyAdminEvents::PRE_NEW);
  282. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  283. $easyadmin = $this->request->attributes->get('easyadmin');
  284. $easyadmin['item'] = $entity;
  285. $this->request->attributes->set('easyadmin', $easyadmin);
  286. $fields = $this->entity['new']['fields'];
  287. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  288. $newForm->handleRequest($this->request);
  289. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  290. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  291. }
  292. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  293. $this->processUploadedFiles($newForm);
  294. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  295. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  296. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  297. if ($newForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  298. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]);
  299. } else {
  300. return $this->redirectToReferrer();
  301. }
  302. }
  303. $this->dispatch(EasyAdminEvents::POST_NEW, [
  304. 'entity_fields' => $fields,
  305. 'form' => $newForm,
  306. 'entity' => $entity
  307. ]);
  308. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  309. $categories = $productCategoryRepository->findAllParents();
  310. $parameters = [
  311. 'form' => $newForm->createView(),
  312. 'entity_fields' => $fields,
  313. 'entity' => $entity,
  314. 'categories' => $categories,
  315. 'sortableProductsField' => array(),
  316. 'totalProductOrdered' => array()
  317. ];
  318. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  319. }
  320. public function duplicateAction()
  321. {
  322. $id = $this->request->query->get('id');
  323. $refererUrl = $this->request->query->get('referer', '');
  324. $easyadmin = $this->request->attributes->get('easyadmin');
  325. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  326. $newProductFamily = clone $entity;
  327. if ($easyadmin['entity']['name'] == "ProductFamily") {
  328. $this->processProducts($newProductFamily, true);
  329. }
  330. $this->em->persist($newProductFamily);
  331. $this->em->flush();
  332. return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newProductFamily->getId(), 'referer' => $refererUrl]);
  333. }
  334. public function getTotalProductOrdered($entity)
  335. {
  336. $orderShopRepo = $this->em->getRepository(OrderShopInterface::class);
  337. $totalProductOrdered = array();
  338. $currentWeekNumber = $this->orderUtils->getWeekNumberCurrent();
  339. $totalProductOrdered['total'][$currentWeekNumber +1] = 0;
  340. $totalProductOrdered['total'][$currentWeekNumber ] = 0;
  341. foreach ($entity->getProducts() as $product) {
  342. //Les commandes sont ouvertes ont récupèrent les commandes en cours et celle de la semaine dernière
  343. if ($this->orderUtils->isOpenSale()) {
  344. $totalProductOrdered[$product->getId()][$currentWeekNumber +1] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber +1, $product->getId());
  345. $totalProductOrdered[$product->getId()][$currentWeekNumber] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  346. if ($entity->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE) {
  347. $ratioByMeasure = $product->getQuantity() / $product->getUnitInherited()->getCoefficient();
  348. $totalProductOrdered['total'][$currentWeekNumber +1] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber +1, $product->getId()) * $ratioByMeasure;
  349. $totalProductOrdered['total'][$currentWeekNumber] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId()) * $ratioByMeasure;
  350. } else {
  351. $totalProductOrdered['total'][$currentWeekNumber +1] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber+1, $product->getId());
  352. $totalProductOrdered['total'][$currentWeekNumber] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber, $product->getId());
  353. }
  354. } else {
  355. $totalProductOrdered[$product->getId()][$currentWeekNumber +1] = $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber+1, $product->getId());
  356. if ($entity->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE) {
  357. $ratioByMeasure = $product->getQuantity() / $product->getUnitInherited()->getCoefficient();
  358. $totalProductOrdered['total'][$currentWeekNumber+1] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber+1, $product->getId()) * $ratioByMeasure;
  359. }else{
  360. $totalProductOrdered['total'][$currentWeekNumber+1] += $orderShopRepo->countValidOrderProductsOfWeekByProduct($currentWeekNumber+1, $product->getId());
  361. }
  362. }
  363. }
  364. return $totalProductOrdered;
  365. }
  366. }