|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599 |
- <?php
-
- namespace Lc\ShopBundle\Controller\Backend;
-
- use Doctrine\ORM\EntityManagerInterface;
- use Doctrine\ORM\EntityRepository;
- use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
- use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
- use FOS\UserBundle\Model\UserManagerInterface;
- use Lc\ShopBundle\Context\FilterMultipleMerchantsInterface;
- use Lc\ShopBundle\Context\MerchantInterface;
- use Lc\ShopBundle\Context\ReminderInterface;
- use Lc\ShopBundle\Context\SeoInterface;
- use Lc\ShopBundle\Context\StatusInterface;
- use Lc\ShopBundle\Context\TreeInterface;
- use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
- use Lc\ShopBundle\Form\Backend\Filters\ListFilterType;
- use Lc\ShopBundle\Model\User;
- use Lc\ShopBundle\Services\UtilsManager;
- use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
- use Symfony\Bridge\Doctrine\Form\Type\EntityType;
- use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
- use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
- use Symfony\Component\Form\Extension\Core\Type\CollectionType;
- use Symfony\Component\Form\Extension\Core\Type\TextareaType;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\FormEvent;
- use Symfony\Component\Form\FormEvents;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\Security\Core\Security;
- use Symfony\Contracts\Translation\TranslatorInterface;
-
- class AdminController extends EasyAdminController
- {
- protected $security;
- protected $userManager;
- protected $em;
- protected $utils;
- protected $merchantUtils;
- protected $mailjetTransport;
- protected $orderUtils;
- protected $mailUtils ;
- protected $translator;
- protected $filtersForm = null;
-
- public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
- MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator)
- {
- $this->security = $security;
- $this->userManager = $userManager;
- $this->em = $em;
- $this->mailjetTransport = $mailjetTransport;
- $this->utils = $utilsManager->getUtils();
- $this->merchantUtils = $utilsManager->getMerchantUtils();
- $this->orderUtils = $utilsManager->getOrderUtils();;
- $this->mailUtils = $utilsManager->getMailUtils() ;
- $this->translator = $translator;
- }
-
- public function createCustomForm($class, $action, $parameters, $data = true)
- {
-
- $options = array();
- if ($data) $options['data'] = $parameters['entity'];
- $options['action'] = $this->generateUrl('easyadmin', array(
- 'action' => $action,
- 'entity' => $this->entity['name'],
- 'id' => $parameters['entity']->getId()
- ));
-
- return $this->createForm($class, null, $options);
- }
-
-
- public function autocompleteAction()
- {
-
- $entityName = $this->request->query->get('entity');
- $valueSearched = $this->request->query->get('q');
- $field = $this->request->query->get('field');
-
- $class = $this->entity['class'];
- $repo = $this->em->getRepository($class);
-
- $values = $repo->findByTerm($field, $valueSearched);
-
- $response = array();
- foreach ($values as $value) {
- $response[] = $value[$field];
- }
- return new JsonResponse($response);
-
- }
-
- /**
- * Réécriture de show action pr rediriger vers l'édition
- */
- public function showAction()
- {
- $id = $this->request->query->get('id');
- $entity = $this->request->query->get('entity');
-
- return $this->redirectToRoute('easyadmin', [
- 'action' => 'edit',
- 'entity' => $entity,
- 'id' => $id
- ]);
- }
-
-
- /**
- * Réécriture de removeEntity pour passer les status à -1
- */
- protected function removeEntity($entity)
- {
- if ($entity instanceof StatusInterface) {
- $entity->setStatus(-1);
- $this->em->persist($entity);
- $this->em->flush();
-
- } else {
- parent::removeEntity($entity);
- }
- }
-
- protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
- {
- if ($pos = strpos($dqlFilter, 'currentMerchant')) {
- $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
- }
-
- if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
- if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
- else $dqlFilter .= sprintf(' entity.status > = 0');
- }
-
- return $dqlFilter;
- }
-
- protected function commonQueryFilter($entityClass, $queryBuilder)
- {
- if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
- $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
- ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
- }
-
- }
-
- protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
- {
- $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
- $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
- $this->commonQueryFilter($entityClass, $queryBuilder);
-
- return $queryBuilder;
- }
-
- protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
- {
- $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
- $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
- $this->commonQueryFilter($entityClass, $queryBuilder);
-
- $listFields = $this->entity['list']['fields'];
-
- $this->filtersForm = $this->createForm(ListFilterType::class, null, array(
- 'fields' => $listFields,
- 'method' => 'get',
- 'entity_name' => $this->entity['name'],
- //'entityClass' => $this->entity['class'],
- 'entity_class' => $this->entity['class']
- ));
- $this->filtersForm->handleRequest($this->request);
-
- if ($this->filtersForm->isSubmitted() && $this->filtersForm->isValid()) {
- foreach ($listFields as $field) {
- if ($this->filtersForm->has($field['property'])) {
- switch ($field['dataType']) {
- case 'option':
- case 'integer':
- case 'text':
- case 'string':
- case 'toggle':
- $filter = $this->filtersForm->get($field['property'])->getData();
- if ($filter !== null) {
-
- $queryBuilder->andWhere('entity.' . $field['property'] . ' LIKE :' . $field['property'] . '');
- $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
- }
- break;
- case 'association' :
- $filter = $this->filtersForm->get($field['property'])->getData();
- if ($filter !== null) {
- if ($field['type_options']['multiple']) {
- $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
- } else {
- $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
- }
- $queryBuilder->setParameter($field['property'], $filter);
- }
- break;
- case 'datetime':
- case 'date':
- $dateStart = $this->filtersForm->get($field['property'])->get('dateStart')->getData();
- $dateEnd = $this->filtersForm->get($field['property'])->get('dateEnd')->getData();
-
-
- if ($dateStart) $queryBuilder->andWhere('entity.' . $field['property'] . ' >= :dateStart')->setParameter('dateStart', $dateStart);
- if ($dateEnd) $queryBuilder->andWhere('entity.' . $field['property'] . ' <= :dateEnd')->setParameter('dateEnd', $dateEnd);
-
- }
-
-
- }
- }
- }
-
- return $queryBuilder;
- }
-
-
- public function renderTemplate($actionName, $templatePath, array $parameters = [])
- {
-
- $reminderRepo = $this->em->getRepository(ReminderInterface::class);
- $easyadmin = $this->request->attributes->get('easyadmin');
- $entityName = $easyadmin['entity']['name'];
- $id = null;
- if ($easyadmin['item']) $id = $easyadmin['item']->getId();
-
- $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfig($actionName, $entityName, $id));
-
- if ($actionName == 'list') {
- if ($this->filtersForm === null) {
- $options['fields'] = $parameters['fields'];
- $options['method'] = 'get';
- $this->filtersForm = $this->createForm(ListFilterType::class, null, $options);
- }
- $parameters = array_merge(
- $parameters,
- array(
- 'filters_form' => $this->filtersForm->createView()
- )
- );
- }
-
-
- $parameters = array_merge(
- $parameters,
- $this->getTwigExtraParameters(),
- $reminders
- );
-
- return parent::renderTemplate($actionName, $templatePath, $parameters);
- }
-
- public function getTwigExtraParameters()
- {
- $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
- $merchants = $repositoryMerchant->findAll();
-
- $user = $this->security->getUser();
-
- return [
- 'merchants' => $merchants,
- 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
- ];
- }
-
-
- public function listChildrenAction()
- {
- $this->dispatch(EasyAdminEvents::PRE_LIST);
-
- $id = $this->request->query->get('id');
- $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
-
- $easyadmin = $this->request->attributes->get('easyadmin');
- $entity = $easyadmin['item'];
-
- $fields = $this->entity['list']['fields'];
- $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
-
- $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
-
- $parameters = [
- 'paginator' => $paginator,
- 'fields' => $fields,
- 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
- 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
- 'entity' => $entity,
- ];
-
- return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
- }
-
-
- public function sortAction()
- {
-
- $this->dispatch(EasyAdminEvents::PRE_LIST);
- $entity = null;
-
- //Replace this with query builder function, do not use finAll of easyAdmin
- if ($this->request->query->get('id')) {
- $id = $this->request->query->get('id');
- $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
-
- $easyadmin = $this->request->attributes->get('easyadmin');
- $entity = $easyadmin['item'];
- }
-
- if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
- else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
-
- $fields = $this->entity['list']['fields'];
- $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
-
- $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
-
- $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
- ->add('entities', CollectionType::class, array(
- 'required' => true,
- 'allow_add' => true,
- 'entry_type' => AbstractEditPositionType::class,
- ))
- ->getForm();
-
- $positionForm->handleRequest($this->request);
-
- if ($positionForm->isSubmitted() && $positionForm->isValid()) {
- $class = $this->entity['class'];
- $repo = $this->em->getRepository($class);
-
- $latsPos = 0;
- foreach ($positionForm->get('entities')->getData() as $elm) {
- $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
- $entity = $repo->find($elm['id']);
- $entity->setPosition($elm['position']);
- $this->em->persist($entity);
- $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
- $latsPos = $elm['position'];
-
- }
- //die();
- //to do récupérer les élements hors ligne et incrémenter position
- /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
- $latsPos++;
- $offlineEntity->setPosition($latsPos);
- $this->em->persist($offlineEntity);
- }*/
- $this->em->flush();
-
- $this->addFlash('success', 'Position modifié', array(), 'mweb');
-
- return $this->redirectToReferrer();
-
- }
-
- $parameters = [
- 'paginator' => $paginator,
- 'fields' => $fields,
- 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
- 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
- 'postion_form' => $positionForm->createView(),
- 'entity' => $entity,
- 'sortable' => true
- ];
- return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
- }
-
- public function createEntityFormBuilder($entity, $view, $override = true)
- {
-
- $formBuilder = parent::createEntityFormBuilder($entity, $view);
-
- if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
-
- return $formBuilder;
- }
-
- public function overrideFormBuilder($formBuilder, $entity, $view)
- {
- $id = (null !== $entity->getId()) ? $entity->getId() : 0;
-
- if ($entity instanceof SeoInterface) {
- $formBuilder->add('metaTitle', TextType::class, array(
- 'required' => false,
- 'translation_domain' => 'lcshop'
- )
- );
- $formBuilder->add('metaDescription', TextareaType::class, array(
- 'required' => false,
- 'translation_domain' => 'lcshop'
- )
- );
- /*$formBuilder->add('oldUrls', TextareaType::class, array(
- 'required' => false,
- 'translation_domain' => 'lcshop'
- )
- );*/
- }
-
-
- if ($entity instanceof StatusInterface) {
- $formBuilder->add('status', ChoiceType::class, array(
- 'choices' => array(
- 'field.default.statusOptions.offline' => '0',
- 'field.default.statusOptions.online' => '1'
- ),
- 'expanded' => true,
- 'required' => true,
- 'translation_domain' => 'lcshop'
- )
- );
- }
-
- if ($entity instanceof TreeInterface) {
-
- $formBuilder->add('parent', EntityType::class, array(
- 'class' => $this->entity['class'],
- 'query_builder' => function (EntityRepository $repo) use ($id) {
- return $repo->createQueryBuilder('e')
- ->where('e.parent is NULL')
- ->andWhere('e.status >= 0')
- ->orderBy('e.status', "DESC");
- },
- 'required' => false,
- )
- );
- }
-
- $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
- $form = $event->getForm();
- $childrens = $form->all();
- $this->loopFormField($form, $childrens);
- });
- return $formBuilder;
- }
-
- private function loopFormField($form, $childrens)
- {
- foreach ($childrens as $child) {
- $statusInterface = false;
- $treeInterface = false;
- $type = $child->getConfig()->getType()->getInnerType();;
- if ($type instanceof EntityType) {
- $passedOptions = $child->getConfig()->getOptions();
- $classImplements = class_implements($passedOptions['class']);
-
- $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
- $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
-
- if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
-
- if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
- $statusInterface = true;
- }
-
- if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
- $treeInterface = true;
- }
- $propertyMerchant = 'merchant';
- if ($isFilterMultipleMerchantsInterface) {
- $propertyMerchant .= 's';
- }
- $form->add($child->getName(), EntityType::class, array(
- 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
- 'label' => $passedOptions['label'],
- 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
- 'placeholder' => '--',
- 'translation_domain' => 'lcshop',
- 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
- $queryBuilder = $repo->createQueryBuilder('e');
- $propertyMerchant = 'e.' . $propertyMerchant;
-
- if ($passedOptions['class'] == 'App\Entity\PointSale') {
- $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
- } else {
- $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
- }
-
- if ($statusInterface) {
- $queryBuilder->andWhere('e.status >= 0');
- }
- if ($treeInterface && $child->getName() == 'parent') {
- $queryBuilder->andWhere('e.parent is null');
- }
- $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
-
- return $queryBuilder;
- },
- 'choice_label' => function ($choice) {
- if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
- return $choice . ' [hors ligne]';
- }
- return $choice;
-
- },
- 'required' => $passedOptions['required'],
- 'choice_attr' => $passedOptions['choice_attr'],
- )
- );
- }
- } else {
- $subChildrens = $child->all();
- if (count($subChildrens)) {
- $this->loopFormField($child, $subChildrens);
- }
- }
- }
- }
-
- protected function editAction()
- {
- $this->dispatch(EasyAdminEvents::PRE_EDIT);
-
- $id = $this->request->query->get('id');
- $easyadmin = $this->request->attributes->get('easyadmin');
- $entity = $easyadmin['item'];
-
- if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
- $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
- $fieldsMetadata = $this->entity['list']['fields'];
-
- if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
- throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
- }
-
- $this->updateEntityProperty($entity, $property, $newValue);
- $this->utils->addFlash('success', 'success.common.fieldChange');
-
- $response['flashMessages'] = $this->utils->getFlashMessages();
- return new Response(json_encode($response));
- }
-
- $fields = $this->entity['edit']['fields'];
-
- $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
- $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
-
- $editForm->handleRequest($this->request);
- if ($editForm->isSubmitted() && $editForm->isValid()) {
- $this->processUploadedFiles($editForm);
-
- $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
- $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
- $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
-
- return $this->redirectToReferrer();
- }
-
- $this->dispatch(EasyAdminEvents::POST_EDIT);
-
- $parameters = [
- 'form' => $editForm->createView(),
- 'entity_fields' => $fields,
- 'entity' => $entity,
- 'delete_form' => $deleteForm->createView(),
- ];
-
- return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
- }
-
- public function createNewEntity(){
- $idDuplicate = $this->request->query->get('duplicate', null);
- if($idDuplicate){
- $easyadmin = $this->request->attributes->get('easyadmin');
- $entity= $this->em->getRepository($easyadmin['entity']['class'])->find($idDuplicate);
-
- $newProductFamily = clone $entity ;
- $this->em->persist($newProductFamily) ;
- $this->em->flush() ;
- }else{
- $entityFullyQualifiedClassName = $this->entity['class'];
-
- return new $entityFullyQualifiedClassName();
- }
-
- }
-
- public function duplicateAction(){
- $id = $this->request->query->get('id');
- $refererUrl = $this->request->query->get('referer', '');
-
- $easyadmin = $this->request->attributes->get('easyadmin');
-
- $entity= $this->em->getRepository($easyadmin['entity']['class'])->find($id);
-
- $newProductFamily = clone $entity ;
-
- $this->em->persist($newProductFamily) ;
- $this->em->flush() ;
-
- return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' =>$newProductFamily->getId(), 'referer' =>$refererUrl ]) ;
- }
- }
-
|