src/Controller/Finance/ContractController.php line 142

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Finance;
  3. use App\Entity\Finance\Contract;
  4. use App\Entity\Finance\ContractElement;
  5. use App\Entity\HR\Employee;
  6. use App\Entity\Kernel\User;
  7. use App\Form\Finance\ContractType;
  8. use App\Form\Finance\ContractAdminType;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use App\Service\Kernel\KernelService;
  15. use App\Service\Finance\ContractService;
  16. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  17. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  18. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  19. use Symfony\Component\Form\Extension\Core\Type\DateType;
  20. /**
  21.  * @Route("/{_locale}/contract")
  22.  */
  23. class ContractController extends AbstractController
  24. {
  25.     
  26.     /**
  27.      * @Route("/ownerpercentage", name="contract_ownerpercentage", methods={"GET"})
  28.      */
  29.     public function ownerpercentage(KernelService $kernelservice): Response
  30.     {
  31.         $classname =  explode("\\", get_class($this));
  32.         $arraysize = count($classname);
  33.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  34.         $this->denyAccessUnlessGranted($attribute); 
  35.         
  36.         $organization =  $this->getUser()->getOrganization();
  37.         $marginproduct = $kernelservice->getApplicationInfoValue("Finance.DefaultProductForResourceContracts", $organization);
  38.         
  39.         $em = $this->getDoctrine()->getManager();
  40.         
  41.         $query = $em->createQuery("SELECT  s.id as id FROM App\Entity\Finance\Contract t JOIN t.owner s  WHERE (t.endDate >= ?1) AND (t.startDate <= ?2) GROUP BY s");
  42.         
  43.     $param1 = date("Y-m-d",strtotime("first day of last month"));
  44.         $param2 = date("Y-m-d",strtotime("last day of last month"));
  45.     $query = $query->setParameter(1, $param1);
  46.         $query = $query->setParameter(2, $param2);
  47.         $recruiters = $query->getResult();
  48.         
  49.         $result = array();
  50.         foreach ($recruiters as $recruiter) {
  51.             $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Contract t JOIN t.owner s WHERE ((t.endDate >= ?1) AND (t.startDate <= ?2)) AND (s.id = ?3)");
  52.             $param1 = date("Y-m-d", strtotime("first day of last month"));
  53.             $param2 = date("Y-m-d", strtotime("last day of last month"));
  54.             $param3 = $recruiter;
  55.             $query = $query->setParameter(1, $param1);
  56.             $query = $query->setParameter(2, $param2);
  57.             $query = $query->setParameter(3, $param3);
  58.             $entities = $query->getResult();
  59.             foreach ($entities as $contract) {
  60.                 $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t WHERE (t.invoiceDate >= ?1) AND (t.contract = ?2)");
  61.                 $param = date("Y-m-d", strtotime("first day of last month"));
  62.                 $query = $query->setParameter(1, $param);
  63.                 $query = $query->setParameter(2, $contract->getId());
  64.                 $entities2 = $query->getResult();
  65.                 $newitem = array();
  66.                 $newitem['owner'] = $contract->getOwner();
  67.                 $newitem['contract'] = $contract;
  68.                 $newitem['invoice'] = null;
  69.                 foreach ($entities2 as $invoice) {
  70.                     $newitem['invoice'] = $invoice;
  71.                 }
  72.                 $result[] = $newitem;
  73.             }
  74.         }
  75.         $query = $em->createQuery("SELECT  s.id as id FROM App\Entity\Finance\Contract t JOIN t.secondaryOwner s  WHERE (t.endDate >= ?1) AND (t.startDate <= ?2) GROUP BY s");
  76.         $param1 = date("Y-m-d", strtotime("first day of last month"));
  77.         $param2 = date("Y-m-d", strtotime("last day of last month"));
  78.         $query = $query->setParameter(1, $param1);
  79.         $query = $query->setParameter(2, $param2);
  80.         $recruiters = $query->getResult();
  81.         $result2 = array();
  82.         foreach ($recruiters as $recruiter) {
  83.             $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Contract t JOIN t.secondaryOwner s WHERE ((t.endDate >= ?1) AND (t.startDate <= ?2)) AND (s.id = ?3)");
  84.             $param1 = date("Y-m-d", strtotime("first day of last month"));
  85.             $param2 = date("Y-m-d", strtotime("last day of last month"));
  86.             $param3 = $recruiter;
  87.             $query = $query->setParameter(1, $param1);
  88.             $query = $query->setParameter(2, $param2);
  89.             $query = $query->setParameter(3, $param3);
  90.             $entities = $query->getResult();
  91.             foreach ($entities as $contract) {
  92.                 $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t WHERE (t.invoiceDate >= ?1) AND (t.contract = ?2)");
  93.                 $param = date("Y-m-d", strtotime("first day of last month"));
  94.                 $query = $query->setParameter(1, $param);
  95.                 $query = $query->setParameter(2, $contract->getId());
  96.                 $entities2 = $query->getResult();
  97.                 $newitem = array();
  98.                 $newitem['secondaryowner'] = $contract->getSecondaryowner();
  99.                 $newitem['contract'] = $contract;
  100.                 $newitem['invoice'] = null;
  101.                 foreach ($entities2 as $invoice) {
  102.                     $newitem['invoice'] = $invoice;
  103.                 }
  104.                 $result2[] = $newitem;
  105.             }
  106.         }
  107.         return $this->render('finance/contract/ownerpercentage.html.twig', [
  108.                     'result' => $result,
  109.                     'result2' => $result2,
  110.             'marginproduct' => $marginproduct]);
  111.     }
  112.     /**
  113.      * @Route("/index/{state?0}/{open?2}/{my?0}/{user?0}/{action?0}/{month?empty}", name="contract_index", methods={"GET"})
  114.      */
  115.     public function index(int $state, int $open=2, int $my=0, int $user=0, int $action=0, string $month = "", ContractService $contractService): Response
  116.     {
  117.         $classname =  explode("\\", get_class($this));
  118.         $arraysize = count($classname);
  119.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  120.         $this->denyAccessUnlessGranted($attribute);  
  121.         
  122.         
  123.         if ($month == "empty")
  124.         {
  125.             $month = "";
  126.         }
  127.         
  128.         /*$contracts = $this->getDoctrine()->getRepository(Contract::class)->findAll();
  129.         foreach($contracts as $contract)
  130.         {
  131.             $contractService->updateInvoicedDays($contract);
  132.         }*/
  133.         //
  134.  
  135.         
  136.         return $this->render('finance/contract/index.html.twig',[
  137.            'state' => $state, 
  138.            'open' => $open,
  139.            'my' => $my,
  140.            'user' => $user,
  141.            'action' => $action,
  142.            'month' => $month
  143.         ]);
  144.     }
  145.     
  146.     /**
  147.      * @Route("/table/{state}/{open}/{my}/{user}/{action}/{month}", name="contract_table", methods={"GET"})
  148.      */
  149.     public function table(int $state, int $open, int $my, int $user = 0, int $action=0, string $month = ""): Response
  150.     {
  151.         $classname =  explode("\\", get_class($this));
  152.         $arraysize = count($classname);
  153.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  154.         $this->denyAccessUnlessGranted($attribute);
  155.         
  156.         $username = "";
  157.         if ($my != 0)
  158.         {
  159.             $username = " - " . $this->getUser();
  160.         }
  161.         if ($user != 0)
  162.         {
  163.             $username = " - " . $this->getDoctrine()->getRepository(User::class)->findOneById($user);
  164.         }
  165.         
  166.         if (empty($month))
  167.         {
  168.             $month = strtotime("now");
  169.             $month = date('Y-m-01', $month);
  170.         }
  171.     
  172.         $contracts = $this->getDoctrine()
  173.             ->getRepository(Contract::class)
  174.             ->findBy(array('state' => $state));
  175.         $button = $state + 3*$open + 9*$my + 18*$action;
  176.         return $this->render('finance/contract/table.html.twig', [
  177.             'button' => $button, 'state' => $state, 'open' => $open, 'my' => $my, 'user' => $user, 'action' => $action,
  178.             'month' => $month,
  179.            'username' => $username
  180.         ]);
  181.     }
  182.     
  183.     /**
  184.      * @Route("/tabledetails/{state}/{open}/{my}/{user}/{action}/{month}", name="contract_tabledetails", methods={"GET","POST"})
  185.      */
  186.     public function tabledetails(Request $request, int $state,int $open,int $my,int $user=0, int $action=0, string $month = "",TranslatorInterface $translator) : Response {
  187.         $classname = explode("\\", get_class($this));
  188.         $arraysize = count($classname);
  189.         $attribute = str_replace("Controller", "", $classname[$arraysize -1]) . ":" . str_replace("Action", "", __FUNCTION__);
  190.         $this->denyAccessUnlessGranted($attribute);
  191.         $start = $request->get('start');
  192.     $length = $request->get('length');
  193.         
  194.         $usermargin = 0;
  195.     
  196.         $em = $this->getDoctrine()->getManager();
  197.         $organization =  $this->getUser()->getOrganization();
  198.         if ($organization == null)
  199.         {
  200.             $organizationid = 0;
  201.         }
  202.         else
  203.         {
  204.             $organizationid = $organization->getId();
  205.         }
  206.         $filter = "";
  207.         if ($request->get('search'))
  208.         {
  209.     $filter = $request->get('search')['value'];
  210.         }
  211.         
  212.         if (empty($month) != true)
  213.         {
  214.             $param = strtotime($month);
  215.             $monthLastDay = date('Y-m-t', $param);
  216.             $monthFirstDay= date('Y-m-01', $param);
  217.         } else
  218.         {
  219.             $param = strtotime("now");
  220.             $monthLastDay =   date('Y-m-t', $param);
  221.             $monthFirstDay= date('Y-m-01', $param);
  222.         }
  223.                 
  224.         
  225.         
  226.        
  227.         $columns = $request->get('columns');
  228.         $orderColumn = 0;
  229.        
  230.         $order = $request->get('order');
  231.          if ($order) {
  232.         $orderColumn = $order[0]["column"];
  233.          }
  234.         $orderby = $this->orderColumns($orderColumn);
  235.         $direction = "DESC";
  236.         if ($order) {
  237.         $direction = strtoupper($order[0]["dir"]);
  238.         }
  239.         $queryString = "SELECT s FROM App\Entity\Finance\Contract s JOIN s.contractsElement t JOIN t.employee u WHERE ((s.state = ?1) ";
  240.         if($open != 2){
  241.             $queryString = $queryString . "AND ((s.endDate >= ?7 or s.endDate is null) AND (s.startDate <= ?6))";
  242.             
  243.             /*$query = $em->createQuery("SELECT s.firstName as owner, s.id as id, COUNT(t.id) as total FROM App\Entity\Finance\Contract t JOIN t.owner s WHERE (t.state = 0) AND (((t.endDate >= ?1) OR (t.endDate is null))AND (t.startDate <= ?2)) AND t.state = 0  GROUP BY s");
  244.             $param = date("Y-m-d");
  245.             $query = $query->setParameter(1, $lastmonthFirstDay);
  246.             $query = $query->setParameter(2, $lastmonthLastDay);
  247.             $activecontracts = $query->getResult();*/
  248.         }
  249.         if($my == 1){
  250.             $queryString = $queryString . "AND ((s.owner = ?4 ) or (s.secondaryOwner = ?4)) ";
  251.         }
  252.         if($user != 0){
  253.             if($action != 0){
  254.                 $queryString = $queryString . "AND (s.owner = ?4 ) ";
  255.             }
  256.             else
  257.             {
  258.                 $queryString = $queryString . "AND ((s.owner = ?4 ) or (s.secondaryOwner = ?4)) ";
  259.             }
  260.         }
  261.         if($action != 0){
  262.             $queryString = $queryString . "AND (((s.endDate <= ?5) OR (s.invoicedDays + 20 >= s.maxDays)) AND (s.noExtension = false)) ";
  263.         }
  264.         $queryString = $queryString ."AND ((?2 = 0) or ((s.organization = ?2) or (s.organization is null)))) ";
  265.         if(!empty($filter) == true){
  266.             $queryString = $queryString ."AND ((s.subject LIKE '%".$filter."%') ";
  267.             $queryString = $queryString ."OR (concat(u.firstname,' ', u.lastname) LIKE '%".$filter."%')) ";
  268.         } 
  269.         $queryString = $queryString ."ORDER BY ".$orderby." ".$direction;
  270.         $query = $em->createQuery($queryString);
  271.         $count = $query->setParameter(2, $organizationid)
  272.                        ->setParameter(1, $state); 
  273.         /*if($open != 2){
  274.             $count->setParameter(3, $open);
  275.         }*/
  276.         if($my == 1){
  277.              $count->setParameter(4, $this->getUser());
  278.         }
  279.         if($open != 2){
  280.             $count->setParameter(7, $monthFirstDay);
  281.             $count->setParameter(6, $monthLastDay);
  282.         }
  283.         if($user != 0){
  284.              $count->setParameter(4, $user);
  285.         }
  286.         if($action != 0){
  287.             $count->setParameter(5, date("Y-m-d", strtotime("+1 month")));
  288.         }
  289.         $total = count($count->getResult());
  290.         $query->setMaxResults($length)
  291.               ->setFirstResult($start);
  292.         $proposals = $query->getResult();
  293.         $twig = clone $this->get('twig');
  294.         
  295.         $datawithlinks = array();
  296.         foreach($proposals as $row){
  297.             $i = 0;
  298.             $newrow = array();
  299.             
  300.             $element = null;
  301.             foreach ($row->getContractsElement() as $element2)
  302.             {
  303.                 if ($element2->getState() == 0)
  304.                 {
  305.                     $element =$element2;
  306.                 }
  307.             }
  308.             
  309.             $url = $twig->createTemplate("{{ path('contract_show', {'id': id })  }}")->render(array("id" => $row->getId()));
  310.             $newrow[$i] = "".$row->getId();
  311.             $i++;
  312.             $newrow[$i] = $url;
  313.             $i++;
  314.             if ($row->getProposal() != null)
  315.             {
  316.                 //$link = "<a href='".$twig->createTemplate("{{ path('proposal_show', {'id': id })  }}")->render(array("id" => $row->getProposal()->getId()))."'>".$row->getProposal()->getId()."</a>";
  317.                 $newrow[$i] = "".$row->getProposal()->getId(); 
  318.                 //;
  319.                 $i++;
  320.             }
  321.             else
  322.             {
  323.                 $newrow[$i] = "";
  324.                 $i++;
  325.             }
  326.             if ($element != null)
  327.             {
  328.                 $newrow[$i] = "".$element->getEmployee();
  329.                 $i++;
  330.                 $newrow[$i] = "".$element->getIntakePrice();
  331.                 $i++;
  332.                 $newrow[$i] = "".$element->getUnitPrice();
  333.                 $i++;
  334.             } else
  335.             {
  336.                 $newrow[$i] = "";
  337.                 $i++;
  338.                 $newrow[$i] = "";
  339.                 $i++;
  340.                 $newrow[$i] = "";
  341.                 $i++;
  342.             }
  343.             $newrow[$i] = $row->getSubject();
  344.             $i++;
  345.             if ($row->getendDate() != null)
  346.             {
  347.                 $newrow[$i] = "".$row->getendDate()->format('d/m/Y');
  348.             }
  349.             else
  350.             {
  351.                 $newrow[$i] = "";
  352.             }
  353.             $i++;
  354.             $infodays = "";
  355.             
  356.             if ($row->getMaxDays() != null) {
  357.                 if ($row->getInvoicedDays() != null) {
  358.                     $infodays = $row->getInvoicedDays() . "";
  359.                 } else
  360.                 {
  361.                     $infodays = "0";
  362.                 }
  363.                 $infodays = $infodays . "/" . $row->getMaxDays();
  364.             }
  365.             $newrow[$i] = $infodays;
  366.             $i++;
  367.             $newrow[$i] = "".$row->getClient();
  368.             $i++;
  369.             $newrow[$i] = "".$row->getEndClient();
  370.             $i++;
  371.             if($open != 2){
  372.                 $margin = 0;
  373.                 
  374.                 if ((($row->getOwner() != null) && ($this->getUser()->getId() == $row->getOwner()->getId())) ||
  375.                 ($this->getUser()->getUserfunction()->getAuthorizationtype()->getName() != 'Authorizationtype.Default'))
  376.                 {
  377.                     foreach ($row->getInvoices() as $invoice)
  378.                     {
  379.                         if ($monthFirstDay == $invoice->getInvoiceDate()->format('Y-m-01'))
  380.                         {
  381.                             $margin += $invoice->getMarginowner();
  382.                             if ($row->getOwner())
  383.                             {
  384.                                 if ($row->getOwner()->getId() == $user)
  385.                                 {
  386.                                     $usermargin += $margin;
  387.                                 }
  388.                             }
  389.                         }
  390.                     }
  391.                 }
  392.                 if ($margin > 0)
  393.                 {
  394.                     $margin = " / " . $margin;
  395.                 } else
  396.                 {
  397.                     $margin = "";
  398.                 }
  399.                 $newrow[$i] = "".$row->getOwner() . $margin;
  400.                 $i++;
  401.                 $margin = 0;
  402.                 if ((($row->getSecondaryOwner() != null) && ($this->getUser()->getId() == $row->getSecondaryOwner()->getId())) ||
  403.                 ($this->getUser()->getUserfunction()->getAuthorizationtype()->getName() != 'Authorizationtype.Default'))
  404.                 {
  405.                     foreach ($row->getInvoices() as $invoice)
  406.                     {
  407.                         if ($monthFirstDay == $invoice->getInvoiceDate()->format('Y-m-01'))
  408.                         {
  409.                             $margin += $invoice->getSecondarymarginowner();
  410.                             if ($row->getSecondaryOwner() != null)
  411.                             {
  412.                                 if ($row->getSecondaryOwner()->getId() == $user)
  413.                                 {
  414.                                     $usermargin += $margin;
  415.                                 }
  416.                             }
  417.                         }
  418.                     }
  419.                 }
  420.                 if ($margin > 0)
  421.                 {
  422.                     $margin = " / " . $margin;
  423.                 } else
  424.                 {
  425.                     $margin = "";
  426.                 }
  427.                 $newrow[$i] = "".$row->getSecondaryOwner() . $margin;
  428.                 $i++;
  429.             }
  430.             $newrow[$i] = "".$row->getOrganization();
  431.             $i++;
  432.             $datawithlinks[] = $newrow;
  433.         }
  434.         $return = array(
  435.             "draw" => intval($request->get('draw')),
  436.             "recordsTotal" => $total,
  437.             "recordsFiltered" => $total,
  438.             "aaData" => $datawithlinks,
  439.             "margin" => $usermargin
  440.         );
  441.         $return = json_encode($return);
  442.         return new Response($return,200,array('Content-type' => 'application/json')); 
  443.     }
  444.     
  445.     
  446.     
  447.     
  448.         public function orderColumns($orderColumn){
  449.         $orderby = ""; 
  450.         switch($orderColumn){
  451.             case 0:
  452.                 $orderby = "s.id"; // i don't think this works
  453.                 break;
  454.             case 2: 
  455.                 $orderby = "s.proposal";
  456.                 break;
  457.             case 3:
  458.                 $orderby = "s.id";
  459.                 break;
  460.             case 4:
  461.                 $orderby = "s.id";
  462.                 break;
  463.             case 5:
  464.                 $orderby = "s.id";
  465.                 break;
  466.             case 6: 
  467.                 $orderby = "s.subject"; // total amount don't work 
  468.                 break;
  469.             case 7: 
  470.                 $orderby = "s.endDate"; 
  471.                 break;
  472.             case 8:
  473.                 $orderby = "s.client";
  474.                 break;
  475.             case 9:
  476.                 $orderby = "s.endClient";
  477.                 break;
  478.             case 10:
  479.                 $orderby = "s.owner";
  480.                 break;
  481.             case 11:
  482.                 $orderby = "s.organization";
  483.                 break;       
  484.         }
  485.         return $orderby;
  486.     }
  487.     
  488.     
  489.      /**
  490.      * @Route("/showopen", name="contract_showopen", methods={"GET"})
  491.      */
  492.     public function showopen() : Response
  493.     {
  494.         $classname =  explode("\\", get_class($this));
  495.         $arraysize = count($classname);
  496.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  497.         $this->denyAccessUnlessGranted($attribute);
  498.          $contracts = $this->getDoctrine()
  499.             ->getManager()
  500.             ->createQuery('SELECT c FROM App\Entity\Finance\Contract c '
  501.                     . 'WHERE c.state = 0 and (c.endDate >= CURRENT_DATE() or c.endDate is null)')->getResult();       
  502.         return $this->render('finance/contract/table.html.twig', ['contracts' => $contracts]); //vervangen door index soort filter optie
  503.             
  504.     }
  505.     /**
  506.      * @Route("/showMy", name="contract_showMy", methods={"GET"})
  507.      */
  508.     public function showMy() : Response
  509.     {
  510.         $classname =  explode("\\", get_class($this));
  511.         $arraysize = count($classname);
  512.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  513.         $this->denyAccessUnlessGranted($attribute);
  514.         $contracts = $this->getDoctrine()
  515.             ->getRepository(Contract::class)
  516.             ->findBy(array('owner' => $this->getUser(),'state' => 0 ));
  517.         return $this->render('finance/contract/table.html.twig',['contracts' => $contracts] );
  518.     }
  519.     /**
  520.      * @Route("/showMyOpen", name="contract_showMyOpen", methods={"GET"})
  521.      */
  522.     public function showMyOpen() : Response
  523.     {
  524.         $classname =  explode("\\", get_class($this));
  525.         $arraysize = count($classname);
  526.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  527.         $this->denyAccessUnlessGranted($attribute);
  528.          $contracts = $this->getDoctrine()
  529.             ->getManager()
  530.             ->createQueryBuilder()->select(array('c'))->from('App\Entity\Finance\Contract' ,'c')
  531.                  ->where('c.owner =' . $this->getUser()->getId())
  532.                  ->andWhere('c.state = 0')
  533.                  ->andWhere('(c.endDate >= CURRENT_DATE() or c.endDate is null)')
  534.                  ->getQuery()->getResult();
  535.         return $this->render('finance/contract/table.html.twig',['contracts' => $contracts] );
  536.     }
  537.     /**
  538.      * @Route("/new", name="contract_new", methods={"GET","POST"})
  539.      */
  540.     public function new(Request $request, TranslatorInterface $translator, KernelService $kernelservice): Response
  541.     {
  542.         $classname =  explode("\\", get_class($this));
  543.         $arraysize = count($classname);
  544.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" 
  545.                 . str_replace("Action", "", __FUNCTION__);
  546.         $this->denyAccessUnlessGranted($attribute);
  547.         $contract = new Contract();
  548.         $date = new \DateTime();
  549.         $contract->setStartDate($date);
  550.         $contract->setEndDate($date);
  551.         $contract->setContractCreated($date);
  552.         $contract->setOwner($this->getUser());
  553.         $contract->setSend2signedCopies(false);
  554.         $contract->setReceivedCounterSigned(false);
  555.         $organization= $this->getUser()->getOrganization();
  556.         $contract->setOrganization($organization);
  557.         $endDateMandatoryForContract = $kernelservice->getApplicationInfoValue("Finance.EndDateMandatoryForContract");
  558.         $form = $this->createForm(ContractType::class, $contract, 
  559.                 ['organization' => $organization, 'endDateMandatoryForContract' => $endDateMandatoryForContract,
  560.                  'action' => $this->generateUrl('contract_new'), 
  561.                  'attr' => ['id' => $this->generateUrl('contract_new')]]);
  562.         $simpleProposals = $kernelservice->getApplicationInfoValue("Sales.SimpleProposals");
  563.         if($simpleProposals)
  564.         {
  565.             $employees = array();
  566.             $employee = "";
  567.             $unitPrice = 0;
  568.             $intakePrice = 0;
  569.             $required = true;
  570.             $form->add('employeeselect2',ChoiceType::class, array('priority' => 10, 'label' => 'Contract.Employee',
  571.                     'required' => true,
  572.                     'multiple' => false,
  573.                     'mapped' => false,
  574.                     'data' => $employee, 
  575.                     'choices' => $employees,
  576.                     'attr' => array('class' => 'selectemployee')
  577.                 ));
  578.             $form->add('intakePrice', NumberType::class, array('priority' => 2, 'data' => $intakePrice, 'mapped' => false, 'label' => 'IntakePrice','required' => $required));
  579.             $form->add('unitPrice', NumberType::class, array('priority' => 1, 'data' => $unitPrice, 'mapped' => false, 'label' => 'Contract.UnitPrice','required' => $required));
  580.         }
  581.         if ($organization == null) {
  582.         $form->add('organization', null, array('label' => 'Organization',
  583.                 'query_builder' => function ($repository) {
  584.                     return $repository->createQueryBuilder('s')
  585.                             ->where("s.state = 0");
  586.                 },
  587.                 'attr' => ['class' => 'select2']));
  588.         }
  589.         $form->handleRequest($request);
  590.         if ($form->isSubmitted()) {// && $form->isValid()) {
  591.             if($contract->getEndDate() >= $contract->getStartDate() || $contract->getEndDate() == null){
  592.                 $entityManager = $this->getDoctrine()->getManager();
  593.                 
  594.                                 
  595.                 $contract->setState(0);
  596.                 if ($this->getUser()->getOrganization() != null) {
  597.                     $contract->setOrganization($this->getUser()->getOrganization());
  598.                 }
  599.                 $entityManager->persist($contract);
  600.                 
  601.                 if($simpleProposals)
  602.                 {
  603.                     $element =  new ContractElement();
  604.                     $element->setQuantity(1);
  605.                     $element->setReceivedBack(false);
  606.                     $element->setSendCounterSigned(false);
  607.                     $element->setContractSendToConsultant(false);
  608.                     $element->setState(0);
  609.                     $element->setContract($contract);
  610.                     $requestdata = $request->request->all("contract");
  611.                     if (isset($requestdata['unitPrice']) == true)
  612.                     {
  613.                         $element->setUnitPrice(str_replace(',', '.',$requestdata['unitPrice']));
  614.                     }
  615.                     if (isset($requestdata['intakePrice']) == true)
  616.                     {
  617.                         $element->setIntakePrice(str_replace(',', '.',$requestdata['intakePrice']));
  618.                     }
  619.                     if (isset($requestdata['employeeselect2']) == true) {
  620.                         $employeeselect2 = $requestdata['employeeselect2'];
  621.                         $employee = null;
  622.                         $entityManager = $this->getDoctrine()->getManager();
  623.                         $employeetype = substr($employeeselect2, 0, 2);
  624.                         $employeeid = substr($employeeselect2, 2);
  625.                         if ($employeetype == "SU") {
  626.                             $element
  627.                                     ->setEmployee(
  628.                                        $entityManager->getRepository(Employee::class)
  629.                                             ->findOneById($employeeid));
  630.                         }
  631.                     }
  632.                     $entityManager->persist($element);        
  633.                 }
  634.                 
  635.                 $entityManager->flush();
  636.                 $this->denyAccessUnlessGranted($attribute, $contract);
  637.                 return $this->redirectToRoute('contract_index');
  638.             }else{
  639.                  $this->get('session')->getFlashBag()->add('error', 
  640.                          $translator->trans('Contract.startdatecannotbeafterenddate'));
  641.             }
  642.             
  643.         }
  644.         return $this->render('finance/contract/new.html.twig', [
  645.             'contract' => $contract,
  646.             'form' => $form->createView(),
  647.         ]);
  648.     }
  649.     /**
  650.      * @Route("/{id}", name="contract_show", methods={"GET"})
  651.      */
  652.     public function show(Contract $contract, KernelService $kernelservice): Response
  653.     {
  654.         $classname =  explode("\\", get_class($this));
  655.         $arraysize = count($classname);
  656.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  657.         $this->denyAccessUnlessGranted($attribute, $contract);  
  658.         
  659.         $simpleProposals = $kernelservice->getApplicationInfoValue("Sales.SimpleProposals");
  660.         
  661.         return $this->render('finance/contract/show.html.twig', [
  662.             'contract' => $contract,
  663.             'simpleProposals' => $simpleProposals
  664.         ]);
  665.     }
  666.     
  667.     /**
  668.      * @Route("/{id}/audit", name="contract_showaudit", methods={"GET"})
  669.      */
  670.     public function showaudit(Contract $contract): Response
  671.     {
  672.         $classname =  explode("\\", get_class($this));
  673.         $arraysize = count($classname);
  674.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  675.         $this->denyAccessUnlessGranted($attribute, $contract);  
  676.         
  677.         return $this->render('finance/contract/showaudit.html.twig', [
  678.             'contract' => $contract,
  679.         ]);
  680.     }
  681.     
  682.     /**
  683.      * @Route("/{id}/archive", name="contract_archive", methods={"GET"})
  684.      */
  685.     public function archive(Contract $contract): Response
  686.     {
  687.         $classname =  explode("\\", get_class($this));
  688.         $arraysize = count($classname);
  689.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  690.         $this->denyAccessUnlessGranted($attribute, $contract); 
  691.         
  692.                 
  693.         $entityManager = $this->getDoctrine()->getManager();
  694.         $contract->setState(1);
  695.         $entityManager->persist($contract);
  696.         $entityManager->flush();
  697.         
  698.         return $this->redirectToRoute('contract_show', array('id' => $contract->getId()));
  699.     }
  700.     
  701.     /**
  702.      * @Route("/{id}/restore", name="contract_restore", methods={"GET"})
  703.      */
  704.     public function restore(Contract $contract): Response
  705.     {
  706.         $classname =  explode("\\", get_class($this));
  707.         $arraysize = count($classname);
  708.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  709.         $this->denyAccessUnlessGranted($attribute, $contract); 
  710.         
  711.                 
  712.         $entityManager = $this->getDoctrine()->getManager();
  713.         $contract->setState(0);
  714.         $entityManager->persist($contract);
  715.         $entityManager->flush();
  716.         
  717.         return $this->redirectToRoute('contract_show', array('id' => $contract->getId()));
  718.     }
  719.     
  720.     /**
  721.      * @Route("/{id}/delete", name="contract_logicaldelete", methods={"GET"})
  722.      */
  723.     public function logicaldelete(Contract $contract): Response
  724.     {
  725.         $classname =  explode("\\", get_class($this));
  726.         $arraysize = count($classname);
  727.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  728.         $this->denyAccessUnlessGranted($attribute, $contract); 
  729.         
  730.                 
  731.         $entityManager = $this->getDoctrine()->getManager();
  732.         $contract->setState(2);
  733.         $entityManager->persist($contract);
  734.         $entityManager->flush();
  735.         
  736.         return $this->redirectToRoute('contract_index');
  737.     }
  738.     /**
  739.      * @Route("/{id}/edit", name="contract_edit", methods={"GET","POST"})
  740.      */
  741.     public function edit(Request $request, Contract $contract, KernelService $kernelservice): Response
  742.     {
  743.         $classname =  explode("\\", get_class($this));
  744.         $arraysize = count($classname);
  745.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  746.         $this->denyAccessUnlessGranted($attribute, $contract); 
  747.     
  748.         $endDateMandatoryForContract = $kernelservice->getApplicationInfoValue("Finance.EndDateMandatoryForContract");
  749.         if ($this->getUser()->getUserfunction()->getAuthorizationtype()->getName() != 'Authorizationtype.Default')
  750.         {
  751.             $form = $this->createForm(ContractAdminType::class, $contract, 
  752.                 ['organization' => $contract->getOrganization(), 'endDateMandatoryForContract' => $endDateMandatoryForContract,
  753.                     'action' => $this->generateUrl('contract_edit', array('id' => $contract->getId())), 
  754.                     'attr' => ['id' => $this->generateUrl('contract_edit', array('id' => $contract->getId()))]]);
  755.         }
  756.         else
  757.         {
  758.             $form = $this->createForm(ContractType::class, $contract, 
  759.                 ['organization' => $contract->getOrganization(), 'endDateMandatoryForContract' => $endDateMandatoryForContract,
  760.                     'action' => $this->generateUrl('contract_edit', array('id' => $contract->getId())), 
  761.                     'attr' => ['id' => $this->generateUrl('contract_edit', array('id' => $contract->getId()))]]);
  762.         }
  763.         
  764.         $simpleProposals = $kernelservice->getApplicationInfoValue("Sales.SimpleProposals");
  765.         if($simpleProposals)
  766.         {
  767.             $employees = array();
  768.             $employee = "";
  769.             $unitPrice = 0;
  770.             $intakePrice = 0;
  771.             $contractSendToConsultant = false;
  772.             $contractSendDate = null;
  773.             $receivedBack = false;
  774.             $sendCounterSigned = false;
  775.             
  776.             if ($contract->getContractsElement()->isEmpty() == false) {
  777.                 $element =  $contract->getContractsElement()->first();
  778.                 $employee = $element->getEmployee();
  779.                 $unitPrice = $element->getUnitPrice();
  780.                 $intakePrice = $element->getIntakePrice();
  781.                 $contractSendToConsultant = $element->getContractSendToConsultant();
  782.                 $contractSendDate = $element->getContractSendDate();
  783.                 $receivedBack = $element->getReceivedBack();
  784.                 $sendCounterSigned = $element->getSendCounterSigned();
  785.                 
  786.                 if ($element->getEmployee() != null)
  787.                 {
  788.                     $employees["".$element->getEmployee()] 
  789.                             = "SU".$element->getEmployee()->getId();
  790.                     $employee = "SU".$element->getEmployee()->getId();
  791.                 }
  792.             }
  793.             
  794.             $required = true;
  795.             $form->add('employeeselect2',ChoiceType::class, array('priority' => 3, 'label' => 'Employee',
  796.                     'required' => true,
  797.                     'multiple' => false,
  798.                     'mapped' => false,
  799.                     'data' => $employee, 
  800.                     'choices' => $employees,
  801.                     'attr' => array('class' => 'selectemployee')
  802.                 ));
  803.             $form->add('intakePrice', NumberType::class, array('priority' => 2, 'data' => $intakePrice, 'mapped' => false, 'label' => 'IntakePrice','required' => $required));
  804.             $form->add('unitPrice', NumberType::class, array('priority' => 1, 'data' => $unitPrice, 'mapped' => false, 'label' => 'UnitPrice','required' => $required));
  805.             
  806.             //$form->add('contractSendToConsultant', CheckboxType::class, array('data' => $contractSendToConsultant, 'mapped' => false, 'label' => 'ContractElement.ContractSendToConsultant','required' =>false));
  807.             //$form->add('contractSendDate', DateType::class, array('data' => $contractSendDate,'label' => 'ContractElement.ContractSendDate','mapped' => false,'required' =>false,'widget' => 'single_text', 'attr' => array('class' => 'date')));
  808.             //$form->add('receivedBack', CheckboxType::class, array('data' => $receivedBack, 'mapped' => false, 'label' => 'ContractElement.ReceivedBack','required' =>false));
  809.             //$form->add('sendCounterSigned', CheckboxType::class, array('data' => $sendCounterSigned, 'mapped' => false, 'label' => 'ContractElement.SendCounterSigned','required' =>false));
  810.             
  811.         }
  812.         
  813.         $form->handleRequest($request);
  814.         if ($form->isSubmitted()) { // && $form->isValid()) {
  815.             
  816.             if($simpleProposals)
  817.             {
  818.                 if ($contract->getContractsElement()->isEmpty() == false) {
  819.                     $element =  $contract->getContractsElement()->first();
  820.                     $requestdata = array_merge($request->request->all("contract"), $request->request->all("contract_admin"));
  821.                     if (isset($requestdata['contractSendToConsultant']) == true)
  822.                     {
  823.                         $element->setContractSendToConsultant(true);
  824.                     }
  825.                     else
  826.                     {
  827.                         $element->setContractSendToConsultant(false);
  828.                     }
  829.                     if (isset($requestdata['contractSendDate']) == true)
  830.                     {
  831.                         $element->setContractSendDate(new \DateTime($requestdata['contractSendDate']));
  832.                     }
  833.                     if (isset($requestdata['receivedBack']) == true)
  834.                     {
  835.                         $element->setReceivedBack(true);
  836.                     }
  837.                     else
  838.                     {
  839.                         $element->setReceivedBack(false);
  840.                     }
  841.                     if (isset($requestdata['sendCounterSigned']) == true)
  842.                     {
  843.                         $element->setSendCounterSigned(true);
  844.                     }
  845.                     else
  846.                     {
  847.                         $element->setSendCounterSigned(false);
  848.                     }
  849.                     if (isset($requestdata['unitPrice']) == true)
  850.                     {
  851.                         $element->setUnitPrice(str_replace(',', '.',$requestdata['unitPrice']));
  852.                     }
  853.                     if (isset($requestdata['intakePrice']) == true)
  854.                     {
  855.                         $element->setIntakePrice(str_replace(',', '.',$requestdata['intakePrice']));
  856.                     }
  857.                     if (isset($requestdata['employeeselect2']) == true) {
  858.                         $employeeselect2 = $requestdata['employeeselect2'];
  859.                         $employee = null;
  860.                         $entityManager = $this->getDoctrine()->getManager();
  861.                         $employeetype = substr($employeeselect2, 0, 2);
  862.                         $employeeid = substr($employeeselect2, 2);
  863.                         if ($employeetype == "SU") {
  864.                             $element
  865.                                     ->setEmployee(
  866.                                        $entityManager->getRepository(Employee::class)
  867.                                             ->findOneById($employeeid));
  868.                         }
  869.                     }
  870.                     
  871.                     $this->getDoctrine()->getManager()->persist($element);
  872.                     $this->getDoctrine()->getManager()->flush();
  873.                 }           
  874.             }
  875.             
  876.             $this->getDoctrine()->getManager()->flush();
  877.             return $this->redirectToRoute('contract_show', array('id' => $contract->getId()));
  878.         }
  879.         return $this->render('finance/contract/edit.html.twig', [
  880.             'contract' => $contract,
  881.             'form' => $form->createView(),
  882.         ]);
  883.     }
  884.     /**
  885.      * @Route("/{id}", name="contract_delete", methods={"DELETE"})
  886.      */
  887.     public function delete(Request $request, Contract $contract): Response
  888.     {
  889.         $classname =  explode("\\", get_class($this));
  890.         $arraysize = count($classname);
  891.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  892.         $this->denyAccessUnlessGranted($attribute, $contract); 
  893.     
  894.         if ($this->isCsrfTokenValid('delete'.$contract->getId(), $request->request->get('_token'))) {
  895.             $entityManager = $this->getDoctrine()->getManager();
  896.             $entityManager->remove($contract);
  897.             $entityManager->flush();
  898.         }
  899.         return $this->redirectToRoute('contract_index');
  900.     }    
  901. }