src/Controller/CompanyController.php line 163

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CompanyAssociation;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  11. use Symfony\Component\HttpFoundation\File\UploadedFile;
  12. use Symfony\Component\HttpFoundation\File\File;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use FOS\UserBundle\Model\UserManagerInterface;
  17. use FOS\UserBundle\Util\TokenGeneratorInterface;
  18. use FOS\UserBundle\Mailer\MailerInterface;
  19. //Form element
  20. use Symfony\Component\Form\Extension\Core\Type\TextType;
  21. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  22. use Symfony\Component\Form\Extension\Core\Type\DateType;
  23. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  24. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  25. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  26. use Symfony\Component\Form\Extension\Core\Type\MoneyType;
  27. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  28. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  29. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  30. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  31. use App\Form\CompanyType;
  32. use App\Form\CompanyDepositType;
  33. use App\Form\CompanyPaymentType;
  34. use App\Form\CompanyDefaultShippingType;
  35. use App\Form\CompanySubscriptionType;
  36. use App\Form\CompanyLocationType;
  37. use App\Form\UserType;
  38. use App\Service\UserService;
  39. use App\Service\ProductService;
  40. use App\Service\ImageService;
  41. use App\Service\CompanyService;
  42. use App\Service\PaymentService;
  43. use App\Service\VariableService;
  44. use App\Entity\User;
  45. use App\Entity\Product;
  46. use App\Entity\CartProduct;
  47. use App\Entity\Company;
  48. use App\Entity\Category;
  49. use App\Entity\CompanyPayment;
  50. use App\Entity\CompanyDefaultShipping;
  51. use App\Entity\CompanyLocation;
  52. use App\Entity\CompanySubscription;
  53. use App\Entity\CompanyDeposit;
  54. use App\Entity\CustomOrder;
  55. use App\Entity\FinancialLog;
  56. use App\Entity\UserViewedProduct;
  57. use App\Entity\Variable;
  58. use App\Service\StripeService;
  59. class CompanyController extends AbstractController
  60. {
  61.     private $imageServ;
  62.     function __construct(ImageService $imageServ){
  63.         $this->imageServ $imageServ;
  64.     }
  65.     function createFastCompanyForm($data false){
  66.         if(!$data)
  67.             $data = ['message' => 'Type your message here'];
  68.         $form $this->createFormBuilder($data)
  69.             ->add('user'UserType::class, [
  70.                 'label' => false
  71.             ])
  72.             ->add('company'CompanyType::class, [
  73.                 'label' => false
  74.             ])
  75.             ->add('payment'CompanyPaymentType::class, [
  76.                 'label' => false
  77.             ])
  78.             ->add('subscription'CompanySubscriptionType::class, [
  79.                 'label' => false
  80.             ])
  81.             ->add('storeMadeByMaturin'ChoiceType::class, array(
  82.                 'required' => true,
  83.                 'placeholder' => 'Choisir...',
  84.                 'choices' => array(
  85.                     'Oui, faites le montage pour nous' => true,
  86.                     'Non, nous ferons le montage nous-même' => false
  87.                 )
  88.             ))
  89.             ->add('submit'SubmitType::Class,
  90.             array(
  91.                 'label' => 'Enregistrer',
  92.                 'attr' => [
  93.                     'class' => 'pull-right'
  94.                 ]
  95.             )
  96.         )
  97.         ;
  98.         $form->get('user')
  99.             ->remove('displayName')
  100.             ->remove('phone')
  101.             ->remove('locale')
  102.             ->remove('profileImage')
  103.             ->remove('settingsReceiveMessageNotification')
  104.             ->remove('shippingAddresses')
  105.             ->remove('save');
  106.         $form->get('payment')->remove('save');
  107.         $form->get('subscription')->remove('save');
  108.         $form->get('company')->get('mainLocation')
  109.             ->remove('country')
  110.             ->remove('province')
  111.             ->remove('mobilePhone')
  112.             ->remove('email')
  113.             ->remove('pickUp')
  114.             ->remove('notesForBuyer')
  115.             ->remove('name')
  116.             ->remove('defaultShipping')
  117.             ->remove('showPublic')
  118.             ;
  119.         $form->get('company')
  120.             ->remove('submit')
  121.             ->remove('conditionsCancel')
  122.             ->remove('conditionsReturn')
  123.             ->remove('conditionsShipping')
  124.             ->remove('customSaleConditions')
  125.             ->remove('speciality')
  126.             ->remove('banner')
  127.             ->remove('image')
  128.             ->remove('otherLocations')
  129.             ->remove('description')
  130.             ->remove('website')
  131.             //->remove('termsAcceptance')
  132.             ->remove('defaultShipping')
  133.         ->remove('customUrl')
  134.             ;
  135.         return $form->getForm();
  136.     }
  137.     /**
  138.      * @Route({
  139.      *          "fr": "/go",
  140.      *          "en": "/go",
  141.      *      },
  142.      *      name="fastCompanyInscription")
  143.      *
  144.      * @Template("frontend/fastCompanyInscription.html.twig")
  145.      */
  146.     public function fastCompanyInscription(EntityManagerInterface $emRequest $requestUserManagerInterface $userManagerPaymentService $paymentServUserService $userServ){
  147.         $twigData = array();
  148.         $twigData['hideSideMenu'] = true;
  149.         $twigData['forceFooter']=true;
  150.         $company = new Company();
  151.         $form $this->createFastCompanyForm();
  152.         $twigData['form']=$form->createView();
  153.         $form->handleRequest($request);
  154.         if($form->isSubmitted() && $form->isValid()){
  155.             //Ok we got the entire form, let's proceed step by step
  156.             /*
  157.              * Creation of the user
  158.              */
  159.             $user $form->get('user')->getData();
  160.             $user->setUsername($user->getEmail());
  161.             $user->setEmailCanonical($user->getEmail());
  162.             $user->setPhone($form->get('company')->get('mainLocation')->get('phone')->getData());
  163.             $user->setDisplayName($user->getFirstName());
  164.             $user->setEnabled(true);
  165.             $em->persist($user);
  166.             /*
  167.              * User done, let's do the Company
  168.              */
  169.             $company $form->get('company')->getData();
  170.             $testName $em->getRepository(Company::class)->findOneBy(
  171.                 [
  172.                     'name' => $company->getName()
  173.                 ]
  174.             );
  175.             if(!empty($testName)){
  176.                 //Check if this company name exist
  177.                 $this->addFlash('error''Ce nom de boutique est déja existant.');
  178.                 $form $this->createFastCompanyForm($form->getData());
  179.                 $twigData['form']=$form->createView();
  180.                 return $twigData;
  181.             }else{
  182.                 $company->addUsersAdmin($user);
  183.                 $company->setExportColabor(false);
  184.                 $em->persist($company);
  185.             }
  186.             
  187.             /*
  188.              * Ok Company done let's do the payment
  189.              */
  190.             $payment $form->get('payment')->getData();
  191.             $company->addPayment($payment);
  192.             $paymentServ->testOnly true;
  193.             $stripe $paymentServ->getPaymentAccount($company);
  194.             if($stripe){
  195.                 $em->persist($payment);
  196.             }else{
  197.                 $this->addFlash('error'"Votre carte de crédit n'est pas valide");
  198.                 $form $this->createFastCompanyForm($form->getData());
  199.                 $twigData['form']=$form->createView();
  200.                 return $twigData;
  201.             }
  202.             /*
  203.              * Subscribtion
  204.              */
  205.             $subscription $form->get('subscription')->getData();
  206.             $company->addSubscription($subscription);
  207.             $em->persist($subscription);
  208.             $paymentServ->testOnly false;
  209.             $paymentServ->subscribeToPlan($company$subscription);
  210.             /*
  211.              * Ok time to check for the store at 125$
  212.              * @NOTE mettre a jour aussi le template d'email!
  213.              */
  214.             $store $form->get('storeMadeByMaturin')->getData();
  215.             if($store){
  216.                 if($paymentServ->collectFromCompany(275$company)){
  217.                     $company->setStoreMadeByMaturin(true);
  218.                     $userServ->sendEmail('Paiement recu pour creation boutique de la compagnie: '.$company->getName(), false'Recu un paiement de 275$ pour la compagnie Id:'.$company->getName().' via le formulaire /go''support@maturin.ca');
  219.                 }
  220.             }
  221.             $this->addFlash('success''Merci, votre compte a été créé avec succès!');
  222.             $email =  $this->get('twig')->render('emails/newCompany.html.twig', array('company' => $company'user' => $user));
  223.             $userServ->sendEmail('Bienvenue chez Maturin'$emailfalse$user->getEmail());
  224.             $userServ->sendEmail('Maturin: Nouvelle compagnie via le formulare go '.$company->getName(), false'La compagnie '.$company->getName().' vient de remplir le formulaire /go''support@maturin.ca');
  225.             $em->persist($company);
  226.             $em->flush();
  227.             return $this->redirectToRoute('companyStore', array('id' => $company->getId(), 'urlname' => $company->getUrlName()));
  228.         }else if($form->isSubmitted() && !$form->isValid()){
  229.             foreach($form->getErrors(true) as $error){
  230.                 $this->addFlash('error'$error->getMessage());
  231.             }
  232.             $form $this->createFastCompanyForm($form->getData());
  233.             $twigData['form']=$form->createView();
  234.         }
  235.         return $twigData;
  236.     }
  237.     /**
  238.      * @Route({
  239.      *          "fr": "/epicerie/liste",
  240.      *          "en": "/compagnie/liste",
  241.      *      },
  242.      *      name="CompanyList")
  243.      *
  244.      * @Template("frontend/companies.html.twig")
  245.      */
  246.     public function companyList(EntityManagerInterface $em){
  247.         $twigData = array();
  248.         $twigData['companies'] =
  249.             $em
  250.             ->getRepository(Company::class)
  251.             ->findAllValid();
  252.         return $twigData;
  253.     }
  254.     /**
  255.      * @Route({
  256.      *          "fr": "/vendeur/controle/{id}",
  257.      *          "en": "/seller/dashboard/{id}",
  258.      *      },
  259.      *      defaults={
  260.      *          "id" = false
  261.      *      },
  262.      *      name="dashboardCompany")
  263.      *
  264.      * @Security("has_role('ROLE_ADMIN')")
  265.      * @Template("admin/dashboardCompany.html.twig")
  266.      */
  267.     public function dashboard(Company $company=nullCompanyService $companyServEntityManagerInterface $emUserService $userServ){
  268.         $twigData = array();
  269.         $user $userServ->getUser();
  270.         if(empty($company)){
  271.             $companies $user->getCompanies();
  272.             if(count($companies) > 1){
  273.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  274.                 return $this->redirectToRoute('dashboard');
  275.             }else{
  276.                 $company $companies->get(0);
  277.             }
  278.         }
  279.         if(empty($company)){
  280.             $this->addFlash('error'"Nous n'arrivons pas a trouver votre boutique, utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  281.             return $this->redirectToRoute('dashboard');
  282.         }
  283.         if(!$companyServ->allowedToModify($company)){
  284.             $this->addFlash('error'"Vous n'avez pas accès a cette commpagnie");
  285.             return $this->redirectToRoute('dashboard');
  286.         }
  287.         $twigData['company'] = $company;
  288.         $twigData['maturinOrders'] = $em->getRepository(CartProduct::class)->findMaturinOrdersOf($company5);
  289.         $twigData['customOrders'] = $em->getRepository(CustomOrder::class)->findCustomOrdersOf($company5);
  290.         $twigData['visitors'] = $em->getRepository(UserViewedProduct::class)->findVisitorsOnProducer($company);
  291.         $twigData['totalSales'] = $em->getRepository(CartProduct::class)->findTotalSalesForCompany($company);
  292.         $twigData['totalSalesLast7days'] = $em->getRepository(CartProduct::class)->findTotalSalesLastXDaysForCompany($company7);
  293.         return $twigData;
  294.     }
  295.     /**
  296.      * @Route({
  297.      *      "fr": "/vendeur/nouveau",
  298.      *      "en": "/seller/new"
  299.      *      },
  300.      *      name="adminCompanyNew"
  301.      * )
  302.      * @Security("has_role('ROLE_ADMIN')")
  303.      * @Template("admin/company/new.html.twig")
  304.      */
  305.     public function adminCompanyNew(Request $requestUserService $userServUrlGeneratorInterface $router)
  306.     {
  307.         $twigData = array();
  308.         $imageServ $this->imageServ;
  309.         $em $this->getDoctrine()->getManager();
  310.         $company = new Company();
  311.         $mainLocation = new CompanyLocation();
  312.         $mainLocation->setPickUp(false);
  313.         $company->setMainLocation($mainLocation);
  314.         $form $this->createForm(CompanyType::class, $company);
  315.         /*
  316.          * Default shipping
  317.          if(empty($company->getDefaultShipping())){
  318.              $defaultShipping = new CompanyDefaultShipping();
  319.     }else
  320.         $defaultShipping = $company->getDefaultShipping();
  321.     $formDefaultShipping = $this->createForm(CompanyDefaultShippingType::class, $defaultShipping);
  322.     $twigData['entity']['defaultShipping'] = $defaultShipping;
  323.     $twigData['forms']['defaultShipping'] = $formDefaultShipping->createView();
  324.          */
  325.         $form->handleRequest($request);
  326.         if($form->isSubmitted() && $form->isValid()){
  327.             $company $form->getData();
  328.             $user $userServ->getUser();
  329.             //Bind the association right away if it's that kind of users
  330.             if($user->getIsAllowedToMakeCompanyForAssociation() && $user->getMakeCompanyForAssociation()){
  331.                 $company->addAssociation($user->getMakeCompanyForAssociation());
  332.             }
  333.             //Let's check if the custom Url exist
  334.             $routeIsAvailable false;
  335.             try {
  336.                 if($company->getCustomUrl()){
  337.                     $route $router->match'/' $company->getCustomUrl());
  338.                     //To avoid taking url of another company
  339.                     if($route['_route']== 'companyStore' && $route['id']== $company->getId())
  340.                         $routeIsAvailable true;
  341.                 }
  342.             } catch ( ResourceNotFoundException $e ) {
  343.                 // If the url didn't match any route at all
  344.                 $testUrl $em->getRepository(Company::class)->findOneByCustomUrl($company->getCustomUrl());
  345.                 if(empty($testUrl))
  346.                     $routeIsAvailable true;
  347.             }
  348.             //Bad route
  349.             if(!$routeIsAvailable){
  350.                 $this->addFlash('error'"Ce lien maturin n'est pas disponible");
  351.                 $company->setCustomUrl(null);
  352.             }
  353.             $newShippings $request->request->get('newShipping');
  354.             if($newShippings){
  355.                 foreach($newShippings as $ship){
  356.                     if($ship == 'main'){
  357.                         $company->getDefaultshipping()->addLocation($company->getMainLocation());
  358.                     }else{
  359.                         //Ok we receive this one as urlencode(name)||zipCode
  360.                         $rawValues explode('||'$ship);
  361.                         if(count($rawValues) == 2){
  362.                             //We can't use the entity repository has it's not been recorded yet
  363.                             //So we go through the otherLocations
  364.                             foreach($company->getOtherLocations() as $location){
  365.                                 if($location->getName() == urldecode($rawValues[0]) && $location->getZipCode() == $rawValues[1])
  366.                                     $company->getDefaultshipping()->addLocation($location);
  367.                             }
  368.                         }
  369.                     }
  370.                 }
  371.             }
  372.             //As this user created the company, it's a Admin per default
  373.             $company->addAdminUser($userServ->getUser());
  374.             //@TODO change to FormType Image and remove this
  375.             if(!empty($company->getImage())){
  376.                 $file = new File($company->getImage());
  377.                 $image $imageServ->saveUploadedFile($file'company_image'false);
  378.                 if($image)
  379.                     $company->setImage($image);
  380.                 else
  381.                     $company->setImage('reset');
  382.             }
  383.             if(!empty($company->getBanner())){
  384.                 $file = new File($company->getBanner());
  385.                 $banner $imageServ->saveUploadedFile($file'company_banner'false);
  386.                 if($banner)
  387.                     $company->setBanner($banner);
  388.                 else
  389.                     $company->setBanner('reset');
  390.             }
  391.             $company->setExportColabor(false);
  392.             try {
  393.                 $em->persist($company);
  394.                 $em->flush();
  395.                 $this->addFlash('success''Votre boutique a été créé avec succès.');
  396.                 //Let's send it to the support team
  397.                 $link $router->generate('companyStore', array('urlname' => $company->getUrlName(), 'id' => $company->getId()));
  398.                 $userServ->sendEmail('Maturin: Nouvelle boutique '.$company->getName(), "Cette boutique vien d'être créé sur Maturin, vous pouvez la voir a : ".$link false'support@maturin.ca');
  399.                 return $this->redirectToRoute('adminNewProduct', array('id' => $company->getId()));
  400.             } catch (\Exception $e ){
  401.                 if(stristr($e->getMessage(), 'duplicate'))
  402.                     $this->addFlash('error''Ce nom de boutique est pris.');
  403.                 else{
  404.                     $this->addFlash('error''Une erreur est survenu, veuillez contacter notre support.');
  405.                     $this->addFlash('error'$e->getMessage());
  406.                 }
  407.             }
  408.         }else{
  409.             foreach($form->getErrors(true) as $error){
  410.                 $this->addFlash('error'$error->getMessage());
  411.             }
  412.         }
  413.         $twigData['company'] = $company;
  414.         $twigData['addNewForm'] = $form->createView();
  415.         $twigData['companyForm']= true;
  416.         return $twigData;
  417.     }
  418.     /**
  419.      * @Route({
  420.      *      "fr": "/vendeur/paiement/{id}",
  421.      *      "en": "/seller/payment/{id}"
  422.      *      },
  423.      *      defaults={
  424.      *          "id" = false
  425.      *      },
  426.      *      name="companyPayment"
  427.      * )
  428.      * @Security("has_role('ROLE_ADMIN')")
  429.      * @Template("admin/company/payment.html.twig")
  430.      */
  431.     public function companyPayment(Request $requestPaymentService $paymentServUserService $userServCompany $company=nullCompanyService $companyServ){
  432.         $twigData = array();
  433.         $user $userServ->getUser();
  434.         if(empty($company)){
  435.             $companies $user->getCompanies();
  436.             if(count($companies) > 1){
  437.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  438.                 return $this->redirectToRoute('dashboard');
  439.             }else{
  440.                 $company $companies->get(0);
  441.             }
  442.         }
  443.         if(empty($company)){
  444.             $this->addFlash('error'"Nous n'arrivons pas a trouver votre boutique, utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  445.             return $this->redirectToRoute('dashboard');
  446.         }
  447.         if(!$companyServ->allowedToModify($company)){
  448.             $this->addFlash('error'"Vous n'avez pas accès a cette commpagnie");
  449.             return $this->redirectToRoute('dashboard');
  450.         }
  451.         $twigData['company'] = $company;
  452.         /*
  453.          * Buy a already made store
  454.          */
  455.         $formCreateStore $this->createFormBuilder($company)
  456.             ->add('storeMadeByMaturin'CheckboxType::class, array(
  457.                 'label' => 'Oui je voudrais que Maturin configure ma boutique et produits',
  458.                 'required' => true,
  459.             ))
  460.             ->add('extra'TextareaType::class, array(
  461.                 'label' => 'Information supplémentaire',
  462.                 'mapped' => false,
  463.                 'required' => false
  464.             ))
  465.             ->add('save'SubmitType::class, array('label' => 'Commander'))
  466.             ->getForm();
  467.         $twigData['forms']['createStore'] = $formCreateStore->createView();
  468.         $formCreateStore->handleRequest($request);
  469.         if($formCreateStore->isSubmitted() && $formCreateStore->isValid()){
  470.             if($paymentServ->collectFromCompany(275$company)){
  471.                 $em $this->getDoctrine()->getManager();
  472.                 $extra $formCreateStore->get('extra')->getData();
  473.                 $userServ->sendEmail('Paiement recu pour creation boutique de la compagnie: '.$company->getName(), false'Recu un paiement de 275$ pour la compagnie Id:'.$company->getId().' la compagnie a entré comme texte extra:'.$extra'support@maturin.ca');
  474.                 $this->addFlash('success''Merci, votre demande a été envoyé a notre équipe!');
  475.                 $userServ->addNotification('success''Achat création boutique''Merci, votre demande a été envoyé a notre équipe!');
  476.                 return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
  477.             }else{
  478.                 $company->setStoreMadeByMaturin(false);
  479.                 $this->addFlash('error''Une erreur est survenue lors de votre paiement');
  480.             }
  481.             $em->persist($company);
  482.             $em->flush();
  483.         }
  484.         /*
  485.          * Payment Form
  486.          */
  487.         if($company->hasPayment())
  488.             $payment $company->getCurrentPayment();
  489.         else
  490.             $payment = new CompanyPayment();
  491.         $formPayment $this->createForm(CompanyPaymentType::class, $payment);
  492.         $formPayment->handleRequest($request);
  493.         if($formPayment->isSubmitted() && $formPayment->isValid()){
  494.             $em $this->getDoctrine()->getManager();
  495.             //Let's test with Stripe see if it's a valid card
  496.             $company->addPayment($payment);
  497.             $stripe $paymentServ->getPaymentAccount($company);
  498.             if($stripe){
  499.                 $em->persist($payment);
  500.                 $em->persist($company);
  501.                 $em->flush();
  502.                 $this->addFlash('success''Informations enregistré avec succès');
  503.                 $this->addFlash('focus''form[name="company_payment"]');
  504.                 return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
  505.             }else{
  506.                 $company->removePayment($payment);
  507.                 $em->persist($company);
  508.                 $em->flush();
  509.                 //Repopulate the form with the previous information
  510.                 $p $formPayment->getData();
  511.                 $p->forceDisplayNumbers true;
  512.                 $formPayment $this->createForm(CompanyPaymentType::class, $p);
  513.             }
  514.         }
  515.         $twigData['forms']['payments'] = $formPayment->createView();
  516.         /*
  517.          * Subscriptions
  518.          */
  519.         $subscription = new CompanySubscription();
  520.         $twigData['subscriptions']=$company->getSubscriptions();
  521.         $formSubscription $this->createForm(CompanySubscriptionType::class, $subscription);
  522.         $twigData['forms']['subscription'] = $formSubscription->createView();
  523.         $formSubscription->handleRequest($request);
  524.         if($formSubscription->isSubmitted() && $formSubscription->isValid()){
  525.             $subscription $formSubscription->getData();
  526.             $subscription->setCompany($company);
  527.             $em $this->getDoctrine()->getManager();
  528.             $em->persist($subscription);
  529.             $company->addSubscription($subscription);
  530.             $em->persist($company);
  531.             $em->flush();
  532.             if(count($company->getPayments()) == 0){
  533.                 $this->addFlash('error'"Votre n'avez pas de carte de crédit à votre compte");
  534.                 $userServ->addNotification('error''Votre abonnement'"Votre compte n'a pas de carte de crédit configuré, donc la facturation a échoué.");
  535.                 $this->addFlash('focus''form[name="company_subscription"]');
  536.             }else{
  537.                 $paymentServ->subscribeToPlan($company$subscription);
  538.                 $this->addFlash('success''Informations enregistré avec succès');
  539.                 $this->addFlash('focus''form[name="company_subscription"]');
  540.             }
  541.             return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
  542.         }
  543.         return $twigData;
  544.     }
  545.     /**
  546.      * @Route({
  547.      *      "fr": "/vendeur/depot/{id}",
  548.      *      "en": "/seller/deposit/{id}"
  549.      *      },
  550.      *      defaults={
  551.      *          "id" = false
  552.      *      },
  553.      *      name="adminCompanySettings"
  554.      * )
  555.      * @Security("has_role('ROLE_ADMIN')")
  556.      * @Template("admin/company/settings.html.twig")
  557.      */
  558.     public function adminCompanySettings(Company $company=nullRequest $requestProductService $prodServPaymentService $paymentServUserService $userServCompanyService $companyServ,StripeService $stripeService){
  559.         $user $userServ->getUser();
  560.         if(empty($company)){
  561.             $companies $user->getCompanies();
  562.             if(count($companies) > 1){
  563.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  564.                 return $this->redirectToRoute('dashboard');
  565.             }else{
  566.                 $company $companies->get(0);
  567.             }
  568.         }
  569.         if(!$companyServ->allowedToModify($company)){
  570.                 $this->addFlash('error'"Vous n'avez pas accès a cette boutique");
  571.                     return $this->redirectToRoute('dashboard');
  572.         }
  573.         $twigData = array(
  574.             'company' => $company,
  575.             'amountOfProducts' => $prodServ->countProducts($company->getId())
  576.         );
  577.         $formSettings $this->createFormBuilder($company)
  578.             ->add('taxeTPS'TextType::class, array(
  579.                 'label' => 'Numéro de TPS',
  580.                 'required' => false
  581.             ))
  582.             ->add('taxeTVX'TextType::class, array(
  583.                 'label'=>'Numéro de TVP ou TVH',
  584.                 'required' => false
  585.             ))
  586.             ->add('companyNumber'TextType::class, array('label' => "Numéro d'entreprise : ARC ou NEQ"))
  587.             ->add('saleId'TextType::class, array(
  588.                 'label' => 'Numéro de vendeur',
  589.                 'disabled' =>true,
  590.                 'empty_data' => uniqid(),
  591.                 'required' => false
  592.             ))
  593.             ->add('numberOfSales'NumberType::class, array(
  594.                 'label' => 'Nombre de vente',
  595.                 'disabled' => true,
  596.                 'empty_data' => '0',
  597.                 'required' => false
  598.             ))
  599.             ->add('totalSalesInDollars'MoneyType::class, array(
  600.                 'label' => 'Total en vente',
  601.                 'disabled' => true,
  602.                 'empty_data' => '0',
  603.                 'required' => false
  604.             ))
  605.             ->add('save'SubmitType::class, array('label' => 'Enregistrer'))
  606.             ->getForm();
  607.             $twigData['forms']['settings'] = $formSettings->createView();
  608.             $formSettings->handleRequest($request);
  609.             if($formSettings->isSubmitted() && $formSettings->isValid()){
  610.                 $newCompany $formSettings->getData();
  611.                 $em $this->getDoctrine()->getManager();
  612.                 $em->persist($newCompany);
  613.                 $em->flush();
  614.                 $this->addFlash('success''Informations enregistré avec succès');
  615.                 $this->addFlash('focus''form[name="form"]');
  616.                 return $this->redirectToRoute('adminCompanySettings', array('id' => $newCompany->getId()));
  617.             }
  618.         /*
  619.          * Deposit
  620.          */
  621.         if (empty($company->getDeposit()))
  622.             $deposit = new CompanyDeposit();
  623.         else
  624.             $deposit $company->getDeposit();
  625.         $acct false;
  626.         if ($deposit)
  627.             $acct $this->retriveCompanyStripeAccount($deposit,$company,$userServ,$stripeService);
  628.         //We leave standard and express account as they are  They dont have property verification
  629.         if ( $acct && !($acct->type == "standard") && !($acct->type == "express") ) {
  630.             $accountStatus=$acct->legal_entity->verification->status;
  631.             $twigData['accountStatus'] = $accountStatus;
  632.     
  633.            
  634.             $accountLink $this->getAccountLink($deposit,$company,$userServ);
  635.             if ($accountLink)
  636.                 $twigData['accountLink'] = $accountLink->url;
  637.             else
  638.                 $twigData['accountLink'] = false;
  639.           
  640.             
  641.             $verificationList$this->getErrorsVerificationArray($acct,$stripeService);
  642.             $twigData['verificationList'] = $verificationList;
  643.             $twigData['forms']['deposit'] = false;
  644.         } else {
  645.             //Prefill the address with the one we have in the database.
  646.             if (!empty($company->getMainLocation()) && empty($deposit->getLegalStreetName())) {
  647.                 $deposit->setLegalCivicNumber($company->getMainLocation()->getCivicNumber());
  648.                 $deposit->setLegalStreetName($company->getMainLocation()->getStreetName());
  649.                 $deposit->setLegalCity($company->getMainLocation()->getCity());
  650.                 $deposit->setLegalProvince($company->getMainLocation()->getProvince());
  651.                 $deposit->setLegalZipCode($company->getMainLocation()->getZipCode());
  652.             }
  653.             $formDeposit $this->createForm(CompanyDepositType::class, $deposit);
  654.             $twigData['forms']['deposit'] = $formDeposit->createView();
  655.             $formDeposit->handleRequest($request);
  656.             if ($formDeposit->isSubmitted() && $formDeposit->isValid()) {
  657.                 $deposit $formDeposit->getData();
  658.                 $otherOwnersFirst $request->get('otherOwnersFirst');
  659.                 $otherOwnersLast $request->get('otherOwnersLast');
  660.                 $otherOwners = array();
  661.                 foreach ($otherOwnersFirst as $k => $o) {
  662.                     if (!empty($o)) {
  663.                         $otherOwners[] = array(
  664.                             'first_name' => $o,
  665.                             'last_name' => $otherOwnersLast[$k]
  666.                         );
  667.                     }
  668.                 }
  669.                 if (!empty($otherOwners))
  670.                 $deposit->setCompanyOwners($otherOwners);
  671.                 $em $this->getDoctrine()->getManager();
  672.                 $em->persist($deposit);
  673.                 $company->setDeposit($deposit);
  674.                 $em->persist($company);
  675.                 $em->flush();
  676.                 //Ok let's update the Stripe Account for deposit while at it
  677.                 $paymentServ->updateAccount($company);
  678.                 $this->addFlash('success''Informations enregistré avec succès');
  679.                 $this->addFlash('focus''form[name="company_deposit"]');
  680.                 return $this->redirectToRoute('adminCompanySettings', array('id' => $company->getId()));
  681.             } else {
  682.                 foreach ($formDeposit->getErrors(true) as $error) {
  683.                     $this->addFlash('error'$error->getMessage());
  684.                 }
  685.             }
  686.         }
  687.         return $twigData;
  688.     }
  689.     
  690.     public function getErrorsVerificationArray($acct,StripeService $stripeService){
  691.         $verificationList=[];
  692.         //Get the document  verification needed for the company
  693.         $errorsCode $acct->verification->errors;
  694.         if($errorsCode){
  695.             foreach ($errorsCode as $code) {
  696.                 $verificationCode$stripeService->getErrorsCodeType($code->code);
  697.                 array_push($verificationList$verificationCode);
  698.             }
  699.         }
  700.         return $verificationList;
  701.     }
  702.     public function getAccountLink(CompanyDeposit $companyDeposit,Company $company,UserService $userServ){
  703.         $log = new FinancialLog();
  704.         $log->setCompanyReceiving($company);
  705.         $log->setMethod('Get Company Account Link');
  706.         try {
  707.             $account_links = \Stripe\AccountLink::create([
  708.                 'account' => $companyDeposit->getStripeAccountId(),
  709.                 'refresh_url' => 'https://www.maturin.ca/vendeur/depot/'.$company->getId(),
  710.                 'return_url' => 'https://www.maturin.ca/vendeur/depot/'.$company->getId(),
  711.                 'type' => 'account_update',
  712.             ]);
  713.             return $account_links;
  714.         } catch (\Exception $e) {
  715.             $log->setStripeRawResponse($e->getMessage());
  716.             $log->setStatus(false);
  717.             //$this->saveLog($log);
  718.             $userServ->addFlash('error'$e->getMessage());
  719.             return false;
  720.         }
  721.         return false;
  722.     }
  723.     public function retriveCompanyStripeAccount(CompanyDeposit $companyDeposit,Company $company,UserService $userServ,StripeService $stripeService){
  724.           $log = new FinancialLog();
  725.           $log->setCompanyReceiving($company);
  726.           $log->setMethod('Company stripe account ');
  727.           try{
  728.             $acct = \Stripe\Account::retrieve($companyDeposit->getStripeAccountId());
  729.             return $acct;
  730.                
  731.           } catch (\Exception $e){
  732.                 $log->setStripeRawResponse($e->getMessage());
  733.                 $log->setStatus(false);
  734.                 //$this->saveLog($log);
  735.                 $userServ->addFlash('error'$e->getMessage());
  736.         }
  737.         return false;
  738.     }
  739.     /**
  740.      * @Route({
  741.      *      "fr": "/vendeur/profile/{id}",
  742.      *      "en": "/seller/profil/{id}"
  743.      *      },
  744.      *      defaults={
  745.      *          "id" = false
  746.      *      },
  747.      *      name="adminCompanyProfile"
  748.      * )
  749.      * @Security("has_role('ROLE_ADMIN')")
  750.      * @Template("admin/company/new.html.twig")
  751.      */
  752.     public function adminCompanyProfile(Request $requestUserService $userServImageService $imageServCompany $company nullUrlGeneratorInterface $router)
  753.     {
  754.         if(empty($company)){
  755.             $user $userServ->getUser();
  756.             $companies $user->getCompanies();
  757.             if(count($companies) > 1){
  758.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  759.                 return $this->redirectToRoute('dashboard');
  760.             }else{
  761.                 $company $companies->get(0);
  762.             }
  763.         }
  764.         $twigData = array();
  765.         $em $this->getDoctrine()->getManager();
  766.         $pass false;
  767.         foreach($userServ->getUser()->getCompanies() as $userAllowed){
  768.             if($userAllowed->getId() == $company->getId()){
  769.                 $pass true;
  770.                 break;
  771.             }
  772.         }
  773.         if(!$pass){
  774.             $this->redirectToRoute('dashboardCompany', array('id' => $company->getId()));
  775.         }
  776.         $tmpImage $company->getImage();
  777.         $tmpBanner $company->getBanner();
  778.         $form $this->createForm(CompanyType::class, $company);
  779.         $twigData['entity']['defaultShipping'] = $company->getDefaultShipping();
  780.         $form->handleRequest($request);
  781.         if($form->isSubmitted() && $form->isValid()){
  782.             //Let's check if the custom Url exist
  783.             $routeIsAvailable false;
  784.             try {
  785.                 if($company->getCustomUrl()){
  786.                     $route $router->match'/' $company->getCustomUrl());
  787.                     //To avoid taking url of another company
  788.                     if($route['_route']== 'companyStore' && $route['id']== $company->getId())
  789.                         $routeIsAvailable true;
  790.                 }
  791.             } catch ( ResourceNotFoundException $e ) {
  792.                 // If the url didn't match any route at all
  793.                 $testUrl $em->getRepository(Company::class)->findOneByCustomUrl($company->getCustomUrl());
  794.                 if(empty($testUrl) || $testUrl->getId() == $company->getId())
  795.                     $routeIsAvailable true;
  796.             }
  797.             //Bad route
  798.             if(!$routeIsAvailable){
  799.                 $this->addFlash('error'"Ce lien maturin n'est pas disponible");
  800.                 $company->setCustomUrl(null);
  801.             }
  802.             $banner $request->files->get('company')['banner'];
  803.             $image $request->files->get('company')['image'];
  804.             if(!empty($image)){
  805.                 //$file = new File($company->getImage());
  806.                 $imgImage $imageServ->saveUploadedFile($image'company_image'false);
  807.                 if($imgImage)
  808.                     $company->setImage($imgImage);
  809.                 else
  810.                     $company->setImage('reset');
  811.             }elseif($tmpImage){
  812.                 //The Image wasn'T updated, fall back on the old one
  813.                 if($tmpImage)
  814.                     $company->setImage($tmpImage);
  815.             }
  816.             if(!empty($banner)){
  817.                 //$file = new File($company->getBanner());
  818.                 $imgBanner $imageServ->saveUploadedFile($banner'company_banner'false);
  819.                 if($imgBanner){
  820.                     $company->setBanner($imgBanner);
  821.                 }else{
  822.                     $company->setBanner('reset');
  823.                 }
  824.             }elseif($tmpBanner){
  825.                 //Banner wasn'T updated, let's use the old one
  826.                 if($tmpBanner)
  827.                     $company->setBanner($tmpBanner);
  828.             }
  829.             $em->persist($company);
  830.             $em->flush();
  831.             $this->addFlash('success''Informations enregistré avec succès');
  832.             return $this->redirectToRoute('adminCompanyProfile', array('id' => $company->getId()));
  833.         }else{
  834.             foreach($form->getErrors(true) as $error){
  835.                 $this->addFlash('error'$error->getMessage());
  836.             }
  837.         }
  838.         $twigData['company'] = $company;
  839.         $twigData['addNewForm'] = $form->createView();
  840.         $twigData['companyForm']= true;
  841.         /*
  842.          * Default shipping
  843.          */
  844.         /*
  845.         if(empty($company->getDefaultShipping())){
  846.             $defaultShipping = new CompanyDefaultShipping();
  847.             $defaultShipping->setCompany($company);
  848.         }else
  849.             $defaultShipping = $company->getDefaultShipping();
  850.         $formDefaultShipping = $this->createForm(CompanyDefaultShippingType::class, $defaultShipping);
  851.         $twigData['forms']['defaultShipping'] = $formDefaultShipping->createView();
  852.         $formDefaultShipping->handleRequest($request);
  853.         if($formDefaultShipping->isSubmitted() && $formDefaultShipping->isValid()){
  854.             die('GOOD');
  855.             $em = $this->getDoctrine()->getManager();
  856.             $em->persist($defaultShipping);
  857.             $em->flush();
  858.             $this->addFlash('success', 'Informations enregistré avec succès');
  859.             $this->addFlash('focus', 'form[name="company_default_shipping"]');
  860.             return $this->redirectToRoute('adminCompanyProfile', array('id' => $company->getId()));
  861.         }else{
  862.             foreach($formDefaultShipping->getErrors(true) as $error){
  863.                 $this->addFlash('error', $error->getMessage());
  864.                 echo $error->getMessage();
  865.             }
  866.             if($formDefaultShipping->isSubmitted())
  867.                 die('Valid');
  868.             die('bad');
  869.         }
  870.          */
  871.         return $twigData;
  872.     }
  873.     /**
  874.      * @route({
  875.      *          "fr": "/groupe/{groupurlname}/producteur/{urlname}/{id}",
  876.      *          "en": "/group/{groupurlname}/producer/{urlname}/{id}"
  877.      *      },
  878.      *      options = {
  879.      *          "expose" = true
  880.      *      },
  881.      *      name="viewCompanyInGroup")
  882.      * @Template("frontend/company.html.twig")
  883.      */
  884.     public function companyIn($groupurlname$urlname $idProductService $prodServEntityManagerInterface $emUserService $userServ){
  885.         $company $em->getRepository(Company::class)->find((int)$id);
  886.         $assocation=$em->getRepository(CompanyAssociation::class)
  887.             ->findOneBy([
  888.                 'urlName' => $groupurlname
  889.             ]);
  890.         if ($assocation && $assocation != $userServ->getAssociationUserIsBrowsing()){
  891.             $userServ->setAssociationUserIsBrowsing($assocation->getId());
  892.             //$this->addFlash('success');
  893.         }
  894.         return $this->company($urlname$company$prodServ$em);
  895.     }
  896.     /**
  897.      * @route({
  898.      *          "fr": "/producteur/{urlname}/{id}",
  899.      *          "en": "/producer/{urlname}/{id}"
  900.      *      },
  901.      *      options = {
  902.      *          "expose" = true
  903.      *      },
  904.      *      name="companyStore")
  905.      * @Template("frontend/company.html.twig")
  906.      */
  907.     public function company($urlnameCompany $companyProductService $prodServEntityManagerInterface $emRequest $request ){
  908.         $twigData = array();
  909.         $twigData['link'] = $request->getPathInfo();
  910.         if (!$company->getShowPublicly() /*&& !$CompanyServ->allowedToModify($company)*/){
  911.             $this->addFlash('error''Cette compagnie n\'est pas disponible ');
  912.             $referer null;//$request->headers->get('referer');
  913.             return $this->redirect($referer != null $referer '/'307);
  914.         }
  915.         $order "DESC";
  916.         if ($request->get("order")) {
  917.           $order $request->get("order");
  918.         }
  919.         $twigData['order']= $order;
  920.         $sorting "date";
  921.         // $sorting = null;
  922.         if ($request->get("sorting")) {
  923.           $sorting $request->get("sorting");
  924.         }
  925.         $twigData['sorting']= $sorting;
  926.         $twigData['company'] = $company;
  927.         $twigData['noPagination'] = true;
  928.         $twigData['companyTotalProducts'] = $em->getRepository(Product::class)->getTotalProducts($company);
  929.         if($request->get('filter')){
  930.             $filter $request->get('filter');
  931.             $category $em->getRepository(Category::class)->findBy(['id' => $filter]);
  932.             $twigData['availableProducts'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId(), $sorting$order$category[0]);
  933.             $twigData['amountProductsPerCategories'] = count($twigData['availableProducts']);
  934.         }else{
  935.             $twigData['availableProducts'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId(), $sorting$order);
  936.             $twigData['amountProductsPerCategories'] = count($twigData['availableProducts']);
  937.         }
  938.         $twigData['amountProductsTotal'] = array(
  939.             'total' => $prodServ->countProducts($company->getId())
  940.         );
  941.         $categories $prodServ->getAllUsedCategories($company->getId());
  942.         $twigData['productCategories'] = array();
  943.         foreach($categories as $key => $cat){
  944.             $twigData['productCategories'][] =
  945.                 array(
  946.                     'id' => $key,
  947.                     'name' => $cat,
  948.                     'amount' => $prodServ->countProducts($company->getId(), $key)
  949.                 );
  950.         }
  951.         $twigData['totalSales'] = $em->getRepository(CartProduct::class)->findAmountSalesForCompany($company);
  952.         //$twigData['totalproduit'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId());
  953.         $twigData['orderDates ']= $em->getRepository(Product::class)->findBy(
  954.             [
  955.                 'company' => $company,
  956.                 'available' => true
  957.             ],[
  958.                 'creationDate' => 'DESC'
  959.             ]
  960.         );
  961.         $twigData['imagesGallery'] = $prodServ->getGalleryImages($company20);
  962.         return $twigData;
  963.     }
  964.     /**
  965.      * @Route({
  966.      *      "fr": "/vendeur/usagers/{id}",
  967.      *      "en": "/seller/users/{id}"
  968.      *      },
  969.      *      options = {
  970.      *          "expose" = true
  971.      *      },
  972.      *      name="adminCompanyListUsers"
  973.      * )
  974.      * @Security("has_role('ROLE_ADMIN')")
  975.      * @Template("admin/company/userList.html.twig")
  976.      */
  977.     public function adminCompanyListUsers(Company $companyCompanyService $companyServ)
  978.     {
  979.     if(!$companyServ->allowedToModify($company)){
  980.             $this->addFlash('error'"Vous n'avez pas accès a cette boutique");
  981.                 return $this->redirectToRoute('dashboard');
  982.     }
  983.         $twigData = array();
  984.         $twigData['company']=$company;
  985.         $twigData['companyUsers'] = $company->getAdminUsers();
  986.         return $twigData;
  987.     }
  988.     /**
  989.      * @Route({
  990.      *      "fr": "/vendeur/usagers/nouveau/{id}",
  991.      *      "en": "/seller/users/new/{id}"
  992.      *      },
  993.      *      name="adminCompanyUsers"
  994.      * )
  995.      * @Security("has_role('ROLE_ADMIN')")
  996.      * @Template("admin/company/user.html.twig")
  997.      */
  998.     public function adminCompanyUsers(Company $company)
  999.     {
  1000.         $twigData = array();
  1001.         return $twigData;
  1002.     }
  1003.     /**
  1004.      * @Route({
  1005.      *      "fr": "/vendeur/usagers/effacer/{companyId}/{userId}",
  1006.      *      "en": "/seller/users/delete/{companyId}/{userId}"
  1007.      *      },
  1008.      *      options = {
  1009.      *          "expose" = true
  1010.      *      },
  1011.      *      name="adminCompanyDeleteUser"
  1012.      * )
  1013.      * @Security("has_role('ROLE_ADMIN')")
  1014.      * @Entity("company", expr="repository.find(companyId)")
  1015.      * @Entity("user", expr="repository.find(userId)")
  1016.      */
  1017.     public function adminCompanyDeleteUsers(Company $companyUser $userUserService $UserServCompanyService $CompanyServEntityManagerInterface $em)
  1018.     {
  1019.         $return = array(
  1020.             'status' => false
  1021.         );
  1022.         //Little bit of security here
  1023.         $currentUser $UserServ->getUser();
  1024.         if(!$CompanyServ->allowedToModify($company))
  1025.             die('Not allowed');
  1026.         else{
  1027.             $company->removeAdminUser($user);
  1028.             $em->persist($company);
  1029.             $em->flush();
  1030.             $return['status'] = true;
  1031.         }
  1032.         $jsonResponse = new JsonResponse();
  1033.         $jsonResponse->setData($return);
  1034.         return $jsonResponse;
  1035.     }
  1036.     /**
  1037.      * @Route({
  1038.      *      "fr": "/admin/compagnie/{companyId}/usagers/{userEmail}/ajouter",
  1039.      *      "en": "/admin/company/{companyId}/users/{userEmail}/add"
  1040.      *      },
  1041.      *      options = {
  1042.      *          "expose" = true
  1043.      *      },
  1044.      *      name="adminCompanyAddUser"
  1045.      * )
  1046.      * @Security("has_role('ROLE_ADMIN')")
  1047.      * @Entity("company", expr="repository.find(companyId)")
  1048.      * @Entity("user", options={"mapping": {"userEmail": "email"}})
  1049.      */
  1050.     public function adminCompanyAddUser(Company $companyUser $user=NULLUserService $UserServCompanyService $CompanyServEntityManagerInterface $em)
  1051.     {
  1052.         $return = array(
  1053.             'status' => false,
  1054.             'message' => ''
  1055.         );
  1056.         if(empty($user)){
  1057.             $return['message']='User not found';
  1058.         }else{
  1059.             //Little bit of security here
  1060.             $currentUser $UserServ->getUser();
  1061.             if(!$CompanyServ->allowedToModify($company))
  1062.                 $return['message'] = 'You are not allowed';
  1063.             else{
  1064.                 $company->addAdminUser($user);
  1065.                 $em->persist($company);
  1066.                 $em->flush();
  1067.                 $return['status'] = true;
  1068.             }
  1069.         }
  1070.         $jsonResponse = new JsonResponse();
  1071.         $jsonResponse->setData($return);
  1072.         return $jsonResponse;
  1073.     }
  1074.     /**
  1075.      * @Route(
  1076.      *      "/vendeur/conditions/{id}",
  1077.      *      options = {
  1078.      *          "expose" = true
  1079.      *      },
  1080.      *      name="acceptCompanyTerms"
  1081.      * )
  1082.      * @Security("has_role('ROLE_ADMIN')")
  1083.      */
  1084.     public function acceptTerms(Company $companyEntityManagerInterface $emCompanyService $CompanyServ)
  1085.     {
  1086.         $return = array(
  1087.             'status' => false,
  1088.             'message' => ''
  1089.         );
  1090.         if(!$CompanyServ->allowedToModify($company))
  1091.             $return['message'] = 'You are not allowed';
  1092.         else{
  1093.             $company->setTermsAcceptance(true);
  1094.             $em->persist($company);
  1095.             $em->flush();
  1096.             $return['message'] = 'Terms Accepted';
  1097.             $return['status'] = true;
  1098.         }
  1099.         $jsonResponse = new JsonResponse();
  1100.         $jsonResponse->setData($return);
  1101.         return $jsonResponse;
  1102.     }
  1103.     /**
  1104.      * @Route({
  1105.      *      "fr": "/vendeur/variableCompagnie/liste/{id}",
  1106.      *      "en": "/seller/variableCompany/list/{id}"
  1107.      *      },
  1108.      *      defaults={
  1109.      *          "id" = false
  1110.      *      },
  1111.      *      name="companyVariableList"
  1112.      * )
  1113.      * @Security("has_role('ROLE_ADMIN')")
  1114.      * @Template("admin/company/listVariables.html.twig")
  1115.      */
  1116.     public function companyVariableList(Company $company=nullUserService $userServRequest $requestEntityManagerInterface $emCompanyService $companyServVariableService $variableServ){
  1117.         if(empty($company)){
  1118.             $user $userServ->getUser();
  1119.             $companies $user->getCompanies();
  1120.             if(count($companies) > 1){
  1121.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  1122.                 return $this->redirectToRoute('dashboard');
  1123.             }else{
  1124.                 $company $companies->get(0);
  1125.             }
  1126.         }
  1127.         if(!$companyServ->allowedToModify($company)){
  1128.                 $this->addFlash('error'"Vous n'avez pas accès a cette boutique");
  1129.                     return $this->redirectToRoute('dashboard');
  1130.         }
  1131.         $twigData = array();
  1132.         $twigData['company']= $company;
  1133.         $twigData['schedule_available_hours'] = [
  1134.           '00h00',
  1135.           '00h30',
  1136.           '01h00',
  1137.           '01h30',
  1138.           '02h00',
  1139.           '02h30',
  1140.           '03h00',
  1141.           '03h30',
  1142.           '04h00',
  1143.           '04h30',
  1144.           '05h00',
  1145.           '05h30',
  1146.           '06h00',
  1147.           '06h30',
  1148.           '07h00',
  1149.           '07h30',
  1150.           '08h00',
  1151.           '08h30',
  1152.           '09h00',
  1153.           '09h30',
  1154.           '10h00',
  1155.           '10h30',
  1156.           '11h00',
  1157.           '11h30',
  1158.           '12h00',
  1159.           '12h30',
  1160.           '13h00',
  1161.           '13h30',
  1162.           '14h00',
  1163.           '14h30',
  1164.           '15h00',
  1165.           '15h30',
  1166.           '16h00',
  1167.           '16h30',
  1168.           '17h00',
  1169.           '17h30',
  1170.           '18h00',
  1171.           '18h30',
  1172.           '19h00',
  1173.           '19h30',
  1174.           '20h00',
  1175.           '20h30',
  1176.           '21h00',
  1177.           '21h30',
  1178.           '22h00',
  1179.           '22h30',
  1180.           '23h00',
  1181.           '23h30',
  1182.         ];
  1183.           $twigData['schedule_available_days'] = [
  1184.           => 'Lundi',
  1185.           => 'Mardi',
  1186.           => 'Mercredi',
  1187.           => 'Jeudi',
  1188.           => 'Vendredi',
  1189.           => 'Samedi',
  1190.           => 'Dimanche',
  1191.           ];
  1192.           $variables = [
  1193.           'orders.canPackUp' => '0',
  1194.           'orders.canPickUp' => '0',
  1195.           'orders.pickUpSchedule' => [],
  1196.           'orders.pickUpScheduleTimes' => [],
  1197.           'orders.pickUpScheduleDurations' => [],
  1198.           'orders.pickUpScheduleSlotLimits' => [],
  1199.           'orders.pickUpScheduleDaysChecked' => [],
  1200.           'orders.pickUpAdress' => '',
  1201.           'orders.prepareDelay' => '0',
  1202.           'orders.packingFixedFee' => '0',
  1203.           ];
  1204.           $action $request->get('action');
  1205.           if ($action == "save_variables") {
  1206.             $orders_packingFixedFee $request->get('orders_packingFixedFee');
  1207.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1208.               $twigData['company'],
  1209.               'Frais fixe de montage d\'une commande (cueillette)',
  1210.               'orders.packingFixedFee',
  1211.               $orders_packingFixedFee
  1212.             );
  1213.             $orders_prepareDelay $request->get('orders_prepareDelay');
  1214.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1215.               $twigData['company'],
  1216.               'Delais de preparation d\'une commande en jours',
  1217.               'orders.prepareDelay',
  1218.               $orders_prepareDelay
  1219.             );
  1220.             $orders_canPickUp $request->get('orders_canPickUp');
  1221.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1222.               $twigData['company'],
  1223.               'Ramassage possible',
  1224.               'orders.canPickUp',
  1225.               $orders_canPickUp
  1226.             );
  1227.             $orders_canPackUp $request->get('orders_canPackUp');
  1228.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1229.               $twigData['company'],
  1230.               'Option de montage des commandes',
  1231.               'orders.canPackUp',
  1232.               $orders_canPackUp
  1233.             );
  1234.             $orders_pickUpAdress $request->get('orders_pickUpAdress');
  1235.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1236.               $twigData['company'],
  1237.               'Adresse de ramassage',
  1238.               'orders.pickUpAdress',
  1239.               $orders_pickUpAdress
  1240.             );
  1241.             $orders_pickUpSchedule $request->get('orders_pickUpSchedule');
  1242.             $orders_pickUpScheduleDaysChecked $request->get('orders_pickUpScheduleDaysChecked');
  1243.             $orders_pickUpScheduleDuration $request->get('orders_pickUpScheduleDuration');
  1244.             $orders_pickUpScheduleSlotLimits $request->get('orders_pickUpScheduleSlotLimits');
  1245.             $pickUpSchedule = [];
  1246.             $pickUpScheduleDurations = [];
  1247.             $pickUpScheduleSlotLimits = [];
  1248.             foreach($twigData['schedule_available_days'] as $day_idx => $day_name) {
  1249.               if (isset($orders_pickUpScheduleDaysChecked[$day_idx])) {
  1250.                 if ($orders_pickUpScheduleDaysChecked[$day_idx] == "on") {
  1251.                   $pickUpSchedule[$day_idx] = [];
  1252.                   $time_start strtotime(date("Y-m-d ").str_replace("h"":"$orders_pickUpSchedule[$day_idx][0]));
  1253.                   $time_stop strtotime(date("Y-m-d ").str_replace("h"":"$orders_pickUpSchedule[$day_idx][1]));
  1254.                   $minutes 30;
  1255.                   if ($orders_pickUpScheduleDuration[$day_idx] == "30") {
  1256.                     $minutes 30;
  1257.                   }
  1258.                   if ($orders_pickUpScheduleDuration[$day_idx] == "60") {
  1259.                     $minutes 60;
  1260.                   }
  1261.                   $pickUpScheduleDurations[$day_idx] = $minutes;
  1262.                   $pickUpScheduleSlotLimits[$day_idx] = $orders_pickUpScheduleSlotLimits[$day_idx];
  1263.                   $current_time_start $time_start;
  1264.                   while ( true ) {
  1265.                     $current_time_stop $current_time_start + ( $minutes 60 );
  1266.                     $pickUpSchedule[$day_idx][] = [date("H\hi"$current_time_start), date("H\hi"$current_time_stop)];
  1267.                     if ( $current_time_stop >= $time_stop ) {
  1268.                       break;
  1269.                     }
  1270.                     $current_time_start $current_time_start + ( $minutes 60 );
  1271.                   }
  1272.                 }
  1273.               }
  1274.             }
  1275.             $pickUpSchedule json_encode($pickUpSchedule);
  1276.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1277.               $twigData['company'],
  1278.               'Horaire de ramassage',
  1279.               'orders.pickUpSchedule',
  1280.               $pickUpSchedule
  1281.             );
  1282.             $pickUpScheduleDurations json_encode($pickUpScheduleDurations);
  1283.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1284.               $twigData['company'],
  1285.               'Durée des plages horaires',
  1286.               'orders.pickUpScheduleDurations',
  1287.               $pickUpScheduleDurations
  1288.             );
  1289.             $pickUpScheduleSlotLimits json_encode($pickUpScheduleSlotLimits);
  1290.             $em->getRepository(Variable::class)->saveVariableForCompany(
  1291.               $twigData['company'],
  1292.               'Limite de personnes des plages horaires',
  1293.               'orders.pickUpScheduleSlotLimits',
  1294.               $pickUpScheduleSlotLimits
  1295.             );
  1296.             $this->addFlash('success'"Vos paramètres on été mise à jour");
  1297.           }
  1298.           $company_variables $twigData["company"]->getVariables();
  1299.           foreach($company_variables as $company_variable) {
  1300.             $codeName $company_variable->getCodeName();
  1301.             if (isset($variables[$codeName])) {
  1302.               $variables[$codeName] = $company_variable->getValue();
  1303.               if (
  1304.                 $codeName == "orders.pickUpSchedule" ||
  1305.                 $codeName == "orders.pickUpScheduleDurations" ||
  1306.                 $codeName == "orders.pickUpScheduleSlotLimits"
  1307.               ) {
  1308.                 $variables[$codeName] = json_decode($variables[$codeName], true);
  1309.               }
  1310.             }
  1311.           }
  1312.           /* set default values */
  1313.           foreach($twigData['schedule_available_days'] as $x => $day) {
  1314.             if (!isset($variables["orders.pickUpSchedule"][$x])) {
  1315.               $variables["orders.pickUpScheduleTimes"][$x]["time_start"] = "00h00";
  1316.               $variables["orders.pickUpScheduleTimes"][$x]["time_stop"] = "00h00";
  1317.               $variables["orders.pickUpScheduleDaysChecked"][$x] = false;
  1318.             } else {
  1319.               $variables["orders.pickUpScheduleDaysChecked"][$x] = true;
  1320.               $time_start "23h59";
  1321.               $time_stop "00h00";
  1322.               foreach($variables["orders.pickUpSchedule"][$x] as $times) {
  1323.                 if ($times[0] < $time_start) {
  1324.                   $time_start $times[0];
  1325.                 }
  1326.                 if ($times[1] > $time_stop) {
  1327.                   $time_stop $times[1];
  1328.                 }
  1329.               }
  1330.               $variables["orders.pickUpScheduleTimes"][$x]["time_start"] = $time_start;
  1331.               $variables["orders.pickUpScheduleTimes"][$x]["time_stop"] = $time_stop;
  1332.             }
  1333.           }
  1334.           $twigData["variables"] = $variables;
  1335.         // //If that simple form was submitted
  1336.         // $testVar = $request->get('var');
  1337.         // if($testVar){
  1338.         //     foreach($testVar as $id => $value){
  1339.         //         //Validation and security
  1340.         //         $cv = $em->getRepository(Variable::class)->findOneBy(
  1341.         //             [
  1342.         //                 'id' => $id
  1343.         //             ]
  1344.         //         );
  1345.         //         if($cv && $cv->getIsEditableByTarget()){
  1346.         //             $variableServ->setVariableById($id, $value);
  1347.         //         }
  1348.         //     }
  1349.         //     $this->addFlash('success', "Vos paramètres on été mise à jour");
  1350.         // }
  1351.         return $twigData;
  1352.     }
  1353.     /**
  1354.      * @Route({
  1355.      *          "fr": "/SupprimeAdresse/{id}",
  1356.      *          "en": "/removeProduct/{id}",
  1357.      *      },
  1358.      *      name="removeProduct")
  1359.      *
  1360.      */
  1361.     public function removeProduct(Request $request$id){
  1362.         $em $this->getDoctrine()->getManager();
  1363.         $productCompany $em->getRepository(Product::class)->findOneBy(["id"=>$id]);
  1364.         if ($productCompany->getQtyReadyToShip() == ){
  1365.             $productCompany->setProductDelete(1);
  1366.             $productCompany->setAvailable(0);
  1367.         }else{
  1368.             $this->addFlash('error'"Vous ne pouvez pas supprimer ce produit car ça quantité est supérieure a 0.");
  1369.             return $this->redirectToRoute('adminListProducts', [
  1370.                 'id' => $productCompany->getCompany()->getId()
  1371.             ]); 
  1372.         }
  1373.         
  1374.       
  1375.         $em->persist($productCompany);
  1376.         $em->flush();
  1377.         $this->addFlash('success'"Le produit " $productCompany ." a bien été mis à jour.");
  1378.         return $this->redirectToRoute('adminListProducts', [
  1379.             'id' => $productCompany->getCompany()->getId()
  1380.         ]); 
  1381.                   
  1382.      }
  1383. }