src/Controller/Finance/InvoiceController.php line 111

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Finance;
  3. use App\Entity\Finance\Invoice;
  4. use App\Entity\Finance\InvoiceProduct;
  5. use App\Entity\Finance\NoInvoice;
  6. use App\Entity\Kernel\Contact;
  7. use App\Form\Finance\InvoiceType;
  8. use App\Form\Finance\InvoiceProfitType;
  9. use App\Form\Finance\InvoiceForContractType;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. use App\Service\Kernel\KernelService;
  16. use App\Entity\Kernel\ListItem;
  17. use App\Entity\Kernel\Setting;
  18. use App\Service\Finance\InvoiceService;
  19. use App\Service\Finance\ContractService;
  20. use App\Entity\CRM\Client;
  21. use App\Service\CRM\ClientService;
  22. use App\Service\Kernel\DMSService;
  23. use App\Service\Kernel\MailService;
  24. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  25. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  26. use Symfony\Component\Form\Extension\Core\Type\FileType;
  27. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  28. use Symfony\Component\Form\FormError;
  29. /**
  30.  * @Route("/{_locale}/invoice")
  31.  */
  32. class InvoiceController extends AbstractController {
  33.     /**
  34.      * @Route("/index/{status?99}/{type?0}/{month?empty}", name="invoice_index", methods={"GET"})
  35.      */
  36.     public function index(int $status = 99, string $month = "",int $type = 0, InvoiceService $invoiceService): Response {
  37.         $classname = explode("\\", get_class($this));
  38.         $arraysize = count($classname);
  39.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  40.         $this->denyAccessUnlessGranted($attribute);
  41.         
  42.         if ($month == "empty")
  43.         {
  44.             $month = "";
  45.         }
  46.         
  47.         /*$entityManager = $this->getDoctrine()
  48.                 ->getManager();
  49.         
  50.         $tempcountersetting = $entityManager->getRepository(Setting::class)->findOneBy(array('identifier' => "tempcounter", 'state' => 0));
  51.         $counter = $tempcountersetting->getValue();
  52.         $invoices = $this->getDoctrine()->getRepository(Invoice::class)->findBy(array('state' => 0), null,500,$counter);
  53.         
  54.         foreach($invoices as $invoice)
  55.         {
  56.             $invoice = $invoiceService->updateProfitInfo($invoice);
  57.             $counter++;
  58.         }
  59.         $tempcountersetting->setIntegerValue($counter);
  60.         $entityManager->persist($tempcountersetting);
  61.         $entityManager->flush(); */
  62.        
  63.         return $this->render('finance/invoice/index.html.twig', [
  64.             'status' => $status,
  65.             'month' => $month,
  66.             'type' => $type,
  67.         ]);
  68.     }
  69.     
  70.     /**
  71.      * @Route("/monthly_follow_up/{type}", name="invoice_monthly_follow_up", methods={"GET"})
  72.      */
  73.     public function monthly_follow_up(int $type = 0, int $status = 99, string $month = ""): Response {
  74.         $classname = explode("\\", get_class($this));
  75.         $arraysize = count($classname);
  76.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  77.         $this->denyAccessUnlessGranted($attribute);
  78.         
  79.         $month = new \DateTime("first day of last month");
  80.         
  81.         return $this->render('finance/invoice/index.html.twig', [
  82.             'status' => 99,
  83.             'month' => $month->format('Y-m-d'),
  84.             'type' => $type,
  85.         ]);
  86.     }
  87.     
  88.     /**
  89.      * @Route("/table/{state}/{status}/{month}/{type}", name="invoice_table", methods={"GET"})
  90.      */
  91.         public function table(int $state, int $status = 99, string $month = "",int $type = 0): Response
  92.     {
  93.         $classname =  explode("\\", get_class($this));
  94.         $arraysize = count($classname);
  95.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  96.         $this->denyAccessUnlessGranted($attribute);
  97.         return $this->render('finance/invoice/table.html.twig', [
  98.             'state' => $state,
  99.             'status' => $status,
  100.             'month' => $month,
  101.             'type' => $type,
  102.         ]);
  103.     }
  104.     /**
  105.      * @Route("/tabledetails/{state}/{status?99}/{month?}/{type?0}", name="invoice_tabledetails", methods={"GET","POST"})
  106.      */
  107.     public function tabledetails(Request $request, int $state, int $status = 99, ?string $month = "",int $type = 0, TranslatorInterface $translator, KernelService $kernelService, DMSService $dmsservice) : Response {
  108.         
  109.         if ($month == null)
  110.         {
  111.             $month="";
  112.         }
  113.         
  114.         $classname =  explode("\\", get_class($this));
  115.         $arraysize = count($classname);
  116.         $attribute = str_replace("Controller", "", $classname[$arraysize-1]) . ":" . str_replace("Action", "", __FUNCTION__);
  117.         $this->denyAccessUnlessGranted($attribute);
  118.         
  119.         $start = $request->get('start');
  120.     $length = $request->get('length');
  121.         
  122.         $em = $this->getDoctrine()->getManager();
  123.         $organization =  $this->getUser()->getOrganization();
  124.         if ($organization == null)
  125.         {
  126.             $organizationid = 0;
  127.         }
  128.         else
  129.         {
  130.             $organizationid = $organization->getId();
  131.         }
  132.         
  133.         
  134.         if ($request->get('search') != null)
  135.         {
  136.             $filter = $request->get('search')['value'];
  137.             $columns = $request->get('columns');
  138.             $order = $request->get('order');
  139.             $orderColumn = $order[0]["column"];
  140.             $orderby = $this->orderColumns($orderColumn); 
  141.             $direction = strtoupper($order[0]["dir"]);
  142.         } else
  143.         {
  144.             $filter = "";
  145.             $orderColumn = "0";
  146.             $orderby = $this->orderColumns($orderColumn); 
  147.             $direction = "desc";
  148.         }
  149.         
  150.         $monthLastDay = null;
  151.         $monthFirstDay = null;
  152.         if (empty($month) != true)
  153.         {
  154.             $param = strtotime($month);
  155.             $monthLastDay = date('Y-m-t', $param);
  156.             $monthFirstDay= date('Y-m-01', $param);
  157.         }         
  158.         $extra = "";
  159.         if ($status != 99)
  160.         {
  161.             if ($status == 98)
  162.             {
  163.                 $extra = " AND (((s.dueDate is not null) AND (s.dueDate < ?3)) AND s.processState != 2)";
  164.             } else
  165.             {
  166.                 $extra = " AND s.processState = " . $status;
  167.             }
  168.         }
  169.         
  170.         if (empty($month) != true)
  171.         {
  172.             $query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
  173.                         . "or (s.organization is null)))) "
  174.                         . "AND ((s.invoiceDate >= '".$monthFirstDay."') "
  175.                         . "AND (s.invoiceDate <= '".$monthLastDay."')) "
  176.                         . $extra. " ORDER BY ".$orderby." ".$direction);
  177.         }
  178.         else
  179.         {
  180.             if(empty($filter) == true){
  181.                 $query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
  182.                         . "or (s.organization is null))))". $extra. " ORDER BY ".$orderby." ".$direction);
  183.             }else{
  184.                 $query = $em->createQuery("SELECT s FROM App\Entity\Finance\Invoice s LEFT JOIN s.contract t LEFT JOIN t.contractsElement u LEFT JOIN t.client v LEFT JOIN t.endClient w LEFT JOIN u.employee x WHERE ((s.state = ?1) AND ((?2 = 0) or ((s.organization = ?2) "
  185.                         . "or (s.organization is null)))) "
  186.                         . "AND ((s.invoiceNumber LIKE '%".$filter."%') "
  187.                         . "or (s.about LIKE '%".$filter."%') "
  188.                         . "or (s.totalWithTaxAmount LIKE '%".$filter."%') "
  189.                         . "or (s.invoiceDate LIKE '%".$filter."%') "
  190.                         . "or (s.clientstring LIKE '%".$filter."%') "
  191.                         . "or (v.company LIKE '%".$filter."%') "
  192.                         . "or (w.company LIKE '%".$filter."%') "
  193.                         . "or (concat(x.firstname,' ', x.lastname) LIKE '%".$filter."%')) "
  194.                         . $extra. " ORDER BY ".$orderby." ".$direction);
  195.             }
  196.         }
  197.         $count = $query->setParameter(2, $organizationid)
  198.                        ->setParameter(1, $state); 
  199.         if ($status == 98)
  200.         {
  201.             $query->setParameter(3, new \DateTime());
  202.         }
  203.         $total = count($count->getResult()); 
  204.         $query = $query->setMaxResults($length)
  205.                        ->setFirstResult($start);
  206.         $invoices = $query->getResult();
  207.         $twig = clone $this->get('twig');
  208.         $timezone = new \DateTimeZone($this->getUser()->getTimezone());
  209.         $datawithlinks = array();
  210.         
  211.         $applicationfolder = $dmsservice->createFolderIfNeeded("System");
  212.         $invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
  213.         
  214.         $totalpayed = 0;
  215.         $totaloutstanding = 0;
  216.         $totalamount = 0;
  217.         $totalcost = 0;
  218.         $totalmonthprofit = 0;
  219.         $currency = "";
  220.         
  221.         foreach($invoices as $row){
  222.             $newrow = array();
  223.             $url = $twig->createTemplate("{{ path('invoice_show', {'id' : id}) }}")->render(array("id" => $row->getId()));
  224.             
  225.             if ($row->getPdf())
  226.             {
  227.                 $urlPDF = $twig->createTemplate("{{ path('kernel_file_version_inline', {'id' : id}) }}")->render(array("id" => $row->getPdf()->getLastKernelFileVersion()->getId()));
  228.                 $urlPDF = "<a href='".$urlPDF ."' type='button' class='btn btn-primary  newwindow' >Invoice</a>";
  229.             } else
  230.             {
  231.                 $urlPDF = "";
  232.             }
  233.             
  234.             $urldocuments = "";
  235.             $folder = $dmsservice->createFolderIfNeeded("".$row->getId(), $invoicefolder);
  236.             foreach($folder->getActiveKernelfiles() as $file)
  237.             {
  238.                 $temp = $twig->createTemplate("{{ path('kernel_file_version_inline', {'id' : id}) }}")->render(array("id" => $file->getLastKernelFileVersion()->getId()));
  239.                 $urldocuments = $urldocuments."<a href='".$temp ."'  type='button' class='btn btn-primary  newwindow' >Timesheet</a>";
  240.             
  241.             }
  242.             
  243.             $urltransaction = "";
  244.             if ($row->getAccounttransaction())
  245.             {
  246.                 $urltransaction = $twig->createTemplate("{{ path('app_account_transaction_show', {'id' : id}) }}")->render(array("id" => $row->getAccounttransaction()->getId()));
  247.                 $urltransaction = "<a href='".$urltransaction ."'  >".$row->getAccounttransaction()."</a>";
  248.             } else
  249.             {
  250.                 $urltransaction = "";
  251.             }
  252.             
  253.             $newrow[0] = "".$row;
  254.             $newrow[1] = $url;
  255.             if ($row->getContract() != null)
  256.             {
  257.                 $element = null;
  258.                 foreach ($row->getContract()->getContractsElement() as $element2)
  259.                 {
  260.                     if ($element2->getState() == 0)
  261.                     {
  262.                         $element =$element2;
  263.                     }
  264.                 }
  265.                 if ($element != null)
  266.                 {
  267.                     $newrow[2] = "".$element->getEmployee(). " - ". $row->getContract()->getClient() ." - ". $row->getContract()->getEndClient();
  268.                 } else
  269.                 {
  270.                     $newrow[2] = "". $row->getContract();
  271.                 }
  272.             } else
  273.             {
  274.                 $newrow[2] = "".$row->getAbout();
  275.             }
  276.             $newrow[3] = $translator->trans($row->getStatusString()); 
  277.             
  278.             if (empty($month) == true)
  279.             {
  280.                 
  281.                     $newrow[4] = "".$row->getClient();
  282.                     $newrow[5] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
  283.                     $newrow[6] = $row->getInvoiceDate()->format('d/m/Y');
  284.                     $newrow[7] = $row->getInvoiceDate()->format('Y-m');
  285.                     $i=8;
  286.                     if( $kernelService->getApplicationInfoValue("Finance.ShowInvoicePDFInOverview") == true)
  287.                     {
  288.                         $newrow[$i] = $urlPDF;
  289.                         $i++;
  290.                     }
  291.                     if( $kernelService->getApplicationInfoValue("Finance.ShowDocumentsInOverview") == true)
  292.                     {
  293.                         $newrow[$i] = $urldocuments;
  294.                         $i++;
  295.                     }
  296.                
  297.                 $organization = $this->getUser()->getOrganization();
  298.                 if ($organization == null)
  299.                 {
  300.                     $newrow[$i] = "".$row->getOrganization();
  301.                 }
  302.             } else
  303.             {
  304.                 if ($type == 0)
  305.                 {
  306.                 $newrow[4] = $urltransaction;
  307.                 $newrow[5] = "".$row->getCurrency()->getString2() . $row->getTotalWithTaxAmount();
  308.                 
  309.                 $payed = 0;
  310.                 if ($row->getProcessState() == 2)
  311.                 {
  312.                      if ($row->getAccounttransaction() == null)
  313.                      {
  314.                          $payed = $row->getTotalWithTaxAmount();
  315.                      }
  316.                      else
  317.                      {
  318.                          if (count($row->getAccounttransaction()->getInvoices()) ==  1)
  319.                          {
  320.                              $payed = $row->getAccounttransaction()->getAmount();
  321.                          }
  322.                          else
  323.                          {
  324.                              $payed = $row->getTotalWithTaxAmount();
  325.                          }
  326.                      }
  327.                 }
  328.                 
  329.                 $totalpayed = $totalpayed + $payed;
  330.                 
  331.                 $topay = $row->getTotalWithTaxAmount() - $payed;
  332.                 
  333.                 $totaloutstanding = $totaloutstanding + $topay;
  334.                 
  335.                 $currency = $row->getCurrency()->getString2();
  336.                         
  337.                 
  338.                 $newrow[6] = "".$row->getCurrency()->getString2() . $payed;
  339.                 $newrow[7] = "".$row->getCurrency()->getString2() . $topay;
  340.                 $i= 8;
  341.                  }
  342.                 else
  343.                 {
  344.                     $difference = 0;
  345.                     $intakeprice = 0;
  346.                     $newrow[3] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
  347.                     
  348.                     $totalamount = $totalamount + $row->getTotalAmount();
  349.         
  350.                     $element = null;
  351.                     
  352.                     /*if ($row->getContract() != null)
  353.                     {
  354.                         
  355.                         foreach ($row->getContract()->getContractsElement() as $element2)
  356.                         {
  357.                             if ($element2->getState() == 0)
  358.                             {
  359.                                 $element =$element2;
  360.                             }
  361.                         }
  362.                         if ($element != null)
  363.                         {
  364.                             $newrow[4] = "".$row->getCurrency()->getString2().$element->getIntakePrice();
  365.                             $newrow[5] = "".$row->getCurrency()->getString2().$element->getUnitPrice();
  366.                             $intakeprice = $element->getIntakePrice();
  367.                             $difference = $element->getUnitPrice() - $element->getIntakePrice();
  368.                             $newrow[6] = "".$row->getCurrency()->getString2().$difference;
  369.                         } else
  370.                         {
  371.                             $newrow[4] = "";
  372.                             $newrow[5] = "";
  373.                             $newrow[6] = "";
  374.                         }
  375.                     } else
  376.                     {
  377.                         $newrow[4] = "";
  378.                         $newrow[5] = "";
  379.                         $newrow[6] = "";
  380.                     }*/
  381.                     $newrow[4] = "" . $row->getCurrency()->getString2() . $row->getIntakeRate();
  382.                     $newrow[5] = "" . $row->getCurrency()->getString2() . $row->getUnitPrice();
  383.                     $intakeprice = $row->getIntakeRate();
  384.                     $difference = $row->getUnitPrice() - $row->getIntakeRate();
  385.                     $newrow[6] = "" . $row->getCurrency()->getString2() . $difference;
  386.                     $days = $row->getDaysInvoiced();
  387.                     $hours = $days*8;
  388.                     /*$hoursproduct = null;
  389.                     foreach ($row->getInvoiceproducts() as $product) {
  390.                         if ($product->getState() == 0) {
  391.                             if ($product->getName() == "Hours")
  392.                             {
  393.                                 $hoursproduct = $product;
  394.                                 $hours = $product->getQuantity();
  395.                             }
  396.                         }
  397.                     }*/
  398.                     
  399.                     //$extrafilter = $extrafilter . " AND ((s.startDate <= '". date ('Y-m-d') . "') AND (s.endDate is null or s.endDate >= '". date ('Y-m-d') . "'))";
  400.                     $invoicetime = new \DateTime($month);
  401.                     $employee = false;
  402.                     if (($row->getProfitCalculationMethod() != null) &&($row->getProfitCalculationMethod()->getName() == "ProfitCalculationMethod.Employee"))
  403.                     {
  404.                         $employee = true;
  405.                     }
  406.                     
  407.                     $workingfactor = $row->getWorkingDaysPerWeek()/5;
  408.                     $newrow[7] = "".$hours;
  409.                     if ($employee)
  410.                     {
  411.                         $extrafactor = 1;
  412.                         if ($invoicetime->format('m') == 6)
  413.                         {
  414.                             $extrafactor = 2;
  415.                         }
  416.                         if ($invoicetime->format('m') == 12)
  417.                         {
  418.                             $extrafactor = 1.92;
  419.                         }
  420.                         $costinvoice =  round($intakeprice*208/13.92*$extrafactor*$workingfactor, 2);
  421.                     } else
  422.                     {    
  423.                         $costinvoice =  round($hours/8*$intakeprice*$workingfactor, 2);
  424.                     }
  425.                     $totalcost = $totalcost + $costinvoice;
  426.                     if ($costinvoice != 0)
  427.                     {
  428.                         $newrow[8] = "".$row->getCurrency()->getString2().$costinvoice;
  429.                         $newrow[9] = "".$row->getCurrency()->getString2() . ($row->getTotalAmount()-$costinvoice);
  430.                         $totalmonthprofit = $totalmonthprofit + ($row->getTotalAmount()-$costinvoice);
  431.                     } else {
  432.                         $newrow[8] = "";
  433.                         $newrow[9] = "".$row->getCurrency()->getString2() . $row->getTotalAmount();
  434.                         $totalmonthprofit = $totalmonthprofit + $row->getTotalAmount();
  435.                     }
  436.                     
  437.                     $i = 10;
  438.                 }
  439.                 
  440.                 $organization = $this->getUser()->getOrganization();
  441.                 if ($organization == null)
  442.                 {
  443.                     $newrow[$i] = "".$row->getOrganization();
  444.                 }
  445.             }
  446.             $datawithlinks[] = $newrow;
  447.         } 
  448.         
  449.         $return = array(
  450.             "draw" => intval($request->get('draw')),
  451.             "recordsTotal" => $total,
  452.             "recordsFiltered" => $total,
  453.             "payed" => "". $currency . number_format($totalpayed,2,",","."),
  454.             "remaining" => "". $currency . number_format($totaloutstanding,2,",","."),
  455.             "totalamount" => "". $currency . number_format($totalamount,2,",","."),
  456.             "totalcost" => "". $currency . number_format($totalcost,2,",","."),
  457.             "totalmonthprofit" => "". $currency . number_format($totalmonthprofit,2,",","."),
  458.             "aaData" => $datawithlinks);
  459.         $return = json_encode($return);
  460.         return new Response($return,200,array('Content-Type' => 'application/json'));
  461.     }
  462.     
  463.     public function orderColumns($orderColumn){
  464.         $orderby = ""; 
  465.         switch($orderColumn){
  466.             case 0:
  467.                 $orderby = "s.invoiceNumber"; // i don't think this works
  468.                 break;
  469.             case 2: 
  470.                 $orderby = "s.about";
  471.                 break;
  472.             case 3:
  473.                 $orderby = "s.processState";
  474.                 break;
  475.             case 4:
  476.                 $orderby = "s.clientstring";
  477.                 break;
  478.             case 5: 
  479.                 $orderby = "s.totalWithTaxAmount"; // total amount don't work 
  480.                 break;
  481.             case 6: 
  482.                 $orderby = "s.invoiceDate"; 
  483.                 break;
  484.                 
  485.         }
  486.         return $orderby;
  487.     }
  488.     
  489.     /**
  490.      * @Route("/new", name="invoice_new", methods={"GET","POST"})
  491.      */
  492.     public function new(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice): 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.         $entityManager = $this->getDoctrine()
  499.                 ->getManager();
  500.         
  501.         $postcodes = array();
  502.         $municipalities = array();
  503.         $organization = $this->getUser()->getOrganization();
  504.         if ($organization != null)
  505.         {
  506.             $organization = $organization->getId();
  507.         }
  508.         else
  509.         {
  510.             $organization = -1;
  511.         }
  512.         if ($request->isMethod('POST'))
  513.         {
  514.             $requestdata = $request->request->all("invoice");
  515.             if (isset($requestdata['postcode']) == true)
  516.             {
  517.                 $postcodeid = $requestdata['postcode'];
  518.                 $postcodeidvalue = $requestdata['postcode'];
  519.                 if (empty($postcodeid) == false)
  520.                 {
  521.                     $type2 = substr($postcodeid, 0, 8);
  522.                     $postcodeidsub = substr($postcodeid, 8);
  523.                     if ($type2 == "INTERNAL")
  524.                     {
  525.                         $item  = $entityManager->getRepository(ListItem::class)->findOneById($postcodeidsub);
  526.                         $postcodeidvalue = $item->getString1();
  527.                     }
  528.                 }
  529.                 $postcodes[$postcodeidvalue] = $postcodeid;
  530.             }
  531.         }
  532.         if ($request->isMethod('POST'))
  533.         {
  534.                 $requestdata = $request->request->all("invoice");
  535.                 if (isset($requestdata['municipality']) == true)
  536.                 {
  537.                     $municipalityid = $requestdata['municipality'];
  538.                     $municipalityidvalue = $requestdata['municipality'];
  539.                     if (empty($municipalityid) == false)
  540.                     {
  541.                         $type2 = substr($municipalityid, 0, 8);
  542.                         $municipalityidsub = substr($municipalityid, 8);
  543.                         if ($type2 == "INTERNAL")
  544.                         {
  545.                                 $item  = $entityManager->getRepository(ListItem::class)->findOneById($municipalityidsub);
  546.                                 $municipalityidvalue = $item->getName();
  547.                         }
  548.                     }
  549.                     $municipalities[$municipalityidvalue] = $municipalityid;
  550.                 }
  551.         }
  552.         
  553.         
  554.         $invoice = new Invoice(); 
  555.         $date = new \DateTime(); 
  556.         $invoice->setInvoiceDate($date); 
  557.         $invoice->setInvoiceNumber($invoiceService->nextInvoiceNumber($date, $this->getUser()->getOrganization()));
  558.         $invoice->setCurrency($kernel_service->getApplicationInfoValue('Kernel.DefaultCurrency'));
  559.         $invoice->setLanguage($this->getUser()->getLocale());
  560.         
  561.         $form = $this->createForm(InvoiceType::class, $invoice,
  562.                 ['postcode' => $postcodes, 'municipality' => $municipalities, 'organization' => $organization,
  563.                     'action' => $this->generateUrl('invoice_new'), 'attr' => ['id' => $this->generateUrl('invoice_new')], 'organization' => $this->getUser()->getOrganization()]);
  564.         if ($this->getUser()->getOrganization() == null) {
  565.             $form->add('organization', null, array('label' => 'Organization',
  566.                 'query_builder' => function ($repository) {
  567.                     return $repository->createQueryBuilder('s')->where("s.state = 0");
  568.                 },
  569.                 'attr' => ['class' => 'select2']));
  570.         }
  571.         $form->handleRequest($request);
  572.         $continue = true;
  573.         if ($form->isSubmitted()) {
  574.             $requestdata = $request->get('invoice');
  575.             if (isset($requestdata['clientselect2']) == false) {
  576.                 $errormessage = $translator->trans('Mandatory');
  577.                 $form->get('clientselect2')->addError(new FormError($errormessage));
  578.                 $continue = false;
  579.             }
  580.         }
  581.         if ($form->isSubmitted() && ($continue == true)) {
  582.             $requestdata = $request->get('invoice'); //dubbel
  583.             if (isset($requestdata['clientselect2']) == true) {
  584.                 $clientselect2 = $requestdata['clientselect2'];
  585.                 $client = null;
  586.                 $clienttype = substr($clientselect2, 0, 2);
  587.                 $clientid = substr($clientselect2, 2);
  588.                 // CASE
  589.                 if ($clienttype == "SU") {
  590.                     $invoice->setClient($entityManager->getRepository(Client::class)->findOneById($clientid));
  591.                 } else {
  592.                     
  593.                     $postcode = null;
  594.                     $municipality = null;
  595.                     $requestdata = $request->request->all("invoice");
  596.                     if (isset($requestdata['postcode']) == true)
  597.                     {
  598.                         $postcodeid = $requestdata['postcode'];
  599.                         if (empty($postcodeid) == false) {
  600.                             $type2 = substr($postcodeid, 0, 8);
  601.                             $postcodeid = substr($postcodeid, 8);
  602.                             if ($type2 == "INTERNAL") {
  603.                                 $item = $entityManager->getRepository(ListItem::class)->findOneById($postcodeid);
  604.                                 $postcode = $item->getString1();
  605.                             } else {
  606.                                 $postcode = $requestdata['postcode'];
  607.                             }
  608.                         }
  609.                     }
  610.                     else
  611.                     {
  612.                         $postcode = "";
  613.                     }
  614.                     if (isset($requestdata['municipality']) == true)
  615.                     {
  616.                         $municipalityid = $requestdata['municipality'];
  617.                         if (empty($municipalityid) == false) {
  618.                             $type2 = substr($municipalityid, 0, 8);
  619.                             $municipalityid = substr($municipalityid, 8);
  620.                             if ($type2 == "INTERNAL") {
  621.                                 $item = $entityManager->getRepository(ListItem::class)->findOneById($municipalityid);
  622.                                 $municipality = $item->getName();
  623.                             } else {
  624.                                 $municipality = $requestdata['municipality'];
  625.                             }
  626.                         }
  627.                     }
  628.                     else
  629.                     {
  630.                         $municipality = "";
  631.                     }
  632.                     
  633.                     
  634.                     if ($clienttype == "NC") {
  635.                         $client = $clientservice->CreateCompany(
  636.                                 $clientid, $requestdata['tax'], null, null, null,$invoice->getLanguage(), $requestdata['street'], $requestdata['housenumber'], $postcode,$municipality, null, null, null, null, null, null, null, null, null, null, null, null,
  637.                                 $invoice->getOrganization()
  638.                         );
  639.                         $invoice->setClient($client);
  640.                     }
  641.                     if ($clienttype == "NI") {
  642.                         $client = $clientservice->CreateIndividual(
  643.                                 $clientid, $requestdata['firstname'], null, null, null, null, $invoice->getLanguage(), $requestdata['street'], $requestdata['housenumber'], $postcode, $municipality, null, null, null, null, null, null, null, null, null, null, null,
  644.                                 $invoice->getOrganization()
  645.                         );
  646.                         $invoice->setClient($client);
  647.                     }
  648.                 }
  649.             }
  650.             if ($this->getUser()->getOrganization() != null) {
  651.                 $invoice->setOrganization($this->getUser()->getOrganization());
  652.             }
  653.             if ($invoiceService->checkForDuplicates($invoice)) {
  654.                 $invoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
  655.                         $invoice->getInvoiceDate()->format('Y-m-d'), $invoice->getInvoiceNumber(),$invoice->getAbout(), $invoice->getNote(),
  656.                         $invoice->getLanguage(),
  657.                         $invoice->getSalesCondition()->getId(), 
  658.                         $invoice->getOrganization());
  659.                 $this->denyAccessUnlessGranted($attribute, $invoice);
  660.                 return $this->redirectToRoute('invoice_show'
  661.                         ,array('id' => $invoice->getId())
  662.                         );
  663.             } else {
  664.                 $this->showErrorMessageMustBeUnique($translator);
  665.             }
  666.         }
  667.         return $this->render('finance/invoice/new.html.twig', [
  668.                     'invoice' => $invoice,
  669.                     'form' => $form->createView(),
  670.         ]);
  671.     }
  672.     
  673.     /**
  674.      * @Route("/newforcontract", name="invoice_newforcontract", methods={"GET","POST"})
  675.      */
  676.     public function newforcontract(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice): Response 
  677.     {
  678.         $classname = explode("\\", get_class($this));
  679.         $arraysize = count($classname);
  680.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  681.         $this->denyAccessUnlessGranted($attribute);
  682.         $entityManager = $this->getDoctrine()
  683.                 ->getManager();
  684.         
  685.         $organization = $this->getUser()->getOrganization();
  686.         $invoice = new Invoice(); 
  687.         $date = new \DateTime(); 
  688.         $invoice->setInvoiceDate($date); 
  689.         $invoice->setInvoiceNumber($invoiceService->nextInvoiceNumber($date, $this->getUser()->getOrganization()));
  690.         $invoice->setCurrency($kernel_service->getApplicationInfoValue('Kernel.DefaultCurrency'));
  691.         $invoice->setLanguage($this->getUser()->getLocale());
  692.         
  693.         $form = $this->createForm(InvoiceForContractType::class, $invoice,
  694.                 [ 'organization' => $organization,
  695.                     'action' => $this->generateUrl('invoice_newforcontract'), 
  696.                     'attr' => ['id' => $this->generateUrl('invoice_newforcontract')], 'organization' => $this->getUser()->getOrganization()]);
  697.         
  698.         $form->handleRequest($request);
  699.         
  700.         if ($form->isSubmitted() && $form->isValid()) {
  701.             
  702.             $invoice->setClient($invoice->getContract()->getClient());
  703.             
  704.             if ($invoiceService->checkForDuplicates($invoice)) {
  705.                 
  706.                 $items = $request->request->get('invoice_for_contract');
  707.                 $input = $request->files->get('invoice_for_contract');
  708.                 
  709.                 $extra = "";
  710.                 foreach ($invoice->getContract()->getContractsElement() as $element)
  711.                 {
  712.                     if ($element->getState() == 0)
  713.                     {
  714.                         if ($invoice->getContract()->getType()->getInteger1() == 2)
  715.                         {
  716.                             $extra = "". $element->getEmployee();
  717.                         }
  718.                     }
  719.                 }
  720.                 
  721.                 $extra2 = "";
  722.                 if (empty($invoice->getContract()->getAttachmentNumber()) == false)
  723.                 {
  724.                     $extra2 = " - " . $invoice->getContract()->getAttachmentNumber();
  725.                 }
  726.                 
  727.                 $contract = $invoice->getContract();
  728.                 $subject = $invoice->getContract()->getContractNumber().$extra2 . " : " . $extra. " - services related to the period " .  $invoice->getInvoiceDate()->format('M Y');
  729.                 $invoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
  730.                     $invoice->getInvoiceDate()->format('Y-m-d'), null,$subject, null,
  731.                     $invoice->getClient()->getLanguage(),
  732.                     $invoice->getContract()->getSalesCondition()->getId(), 
  733.                     $invoice->getContract()->getOrganization(),
  734.                     false);
  735.                 $invoice->setContract($contract);
  736.                 $invoice->setContractNumber($contract->getContractNumber());
  737.                 $invoice->setAttachmentNumber($contract->getAttachmentNumber());
  738.                 $entityManager->persist($invoice);
  739.                 $entityManager->flush();
  740.                 $invoice = $invoiceService->updateProfitInfo($invoice);
  741.                 $product = $kernel_service->getApplicationInfoValue("Finance.DefaultProductForResourceContracts", $contract->getOrganization());
  742.                 $taxrate = $kernel_service->getListItem('Finance.tax', "21%");
  743.                 if ($contract->getClient()->getTaxRate() != null)
  744.                 {
  745.                     $taxrate = $contract->getClient()->getTaxRate();
  746.                 }
  747.                 if ($product)
  748.                 {
  749.                     $price = 0;
  750.                     foreach($contract->getContractsElement() as $element)
  751.                     {
  752.                         if ($element->getState() == 0)
  753.                         {
  754.                             $price = $element->getUnitPrice();
  755.                         }
  756.                     }
  757.                     $invoiceProduct = new InvoiceProduct();
  758.                     $invoiceProduct
  759.                         ->setInvoice($invoice)
  760.                         ->setProduct($product)
  761.                         ->setReference($product->getReference())
  762.                         ->setName($product->getName())
  763.                         ->setUnitPrice($price/8)
  764.                         ->setQuantity(str_replace(',', '.',$items['hours']))
  765.                         ->setTaxrate($taxrate)
  766.                         ->setState(0);
  767.                     $entityManager->persist($invoiceProduct);
  768.                     $entityManager->flush();
  769.                 }
  770.                 $product = $kernel_service->getApplicationInfoValue("Finance.DefaultAdditionalProduct", $contract->getOrganization());
  771.                 $taxrate = $kernel_service->getListItem('Finance.tax', "0%");
  772.                 if ($product)
  773.                 {
  774.                     $extra = str_replace(',', '.',$items['extraamount']);
  775.                     if (empty($extra) == false)
  776.                     {
  777.                         $invoiceProduct = new InvoiceProduct();
  778.                         $invoiceProduct
  779.                             ->setInvoice($invoice)
  780.                             ->setProduct($product)
  781.                             ->setReference($product->getReference())
  782.                             ->setName($product->getName())
  783.                             ->setUnitPrice($extra)
  784.                             ->setQuantity(1)
  785.                             ->setTaxrate($taxrate)
  786.                             ->setState(0);
  787.                         $entityManager->persist($invoiceProduct);
  788.                         $entityManager->flush();
  789.                     }
  790.                 }
  791.                 $invoiceService->calcTotalAmount($invoice, true);
  792.                 $applicationfolder = $dmsservice->createFolderIfNeeded("System");
  793.                 $invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
  794.                 $folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
  795.                 $errorfile = false;
  796.                 try {
  797.                     if ($input != null) {
  798.                         if (array_key_exists('timesheetupload', $input)) {
  799.                             $timesheetfile = $dmsservice->uploadfile($input['timesheetupload'], $folder);
  800.                             $explode = explode(".",$timesheetfile->getName());
  801.                             $extension = end($explode);
  802.                             $timesheetfile->setName("timesheet_". $invoice->getInvoiceNumber(). "." . $extension);
  803.                             $entityManager->persist($timesheetfile);
  804.                             $entityManager->flush();
  805.                         }
  806.                     }
  807.                 } catch (FileException$e) {
  808.                     $errorfile = true;
  809.                 }
  810.                             
  811.                 
  812.                 $this->denyAccessUnlessGranted($attribute, $invoice);
  813.                 return $this->redirectToRoute('invoice_show'
  814.                         ,array('id' => $invoice->getId())
  815.                         );
  816.             } else {
  817.                 $this->showErrorMessageMustBeUnique($translator);
  818.             }
  819.         }
  820.         return $this->render('finance/invoice/newforcontract.html.twig', [
  821.                     'invoice' => $invoice,
  822.                     'form' => $form->createView(),
  823.         ]);
  824.     }
  825.     
  826.     /**
  827.      * @Route("/multinew", name="invoice_multinew", methods={"GET","POST"})
  828.      */
  829.     public function multinew(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice): Response 
  830.     {
  831.         $classname = explode("\\", get_class($this));
  832.         $arraysize = count($classname);
  833.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  834.         $this->denyAccessUnlessGranted($attribute);
  835.         
  836.         $em = $this->getDoctrine()->getManager();
  837.         
  838.         $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Contract t WHERE (t.state = 0) AND ((t.endDate >= ?1) or (t.endDate is null)) AND (t.startDate <= ?2)");
  839.         //new \DateTime('last day of last month')
  840.         $param1 = date("Y-m-d", strtotime("first day of last month"));
  841.         $param2 = date("Y-m-d", strtotime("last day of last month"));
  842.         $query = $query->setParameter(1, $param1);
  843.         $query = $query->setParameter(2, $param2);
  844.         $entities = $query->getResult();
  845.         //$entity = new Invoice();
  846.         //$form   = $this->createForm(new MultiInvoiceType());
  847.         $form = $this->createFormBuilder(null, 
  848.                 ['action' => $this->generateUrl('invoice_multinew'), 
  849.                  'attr' => ['id' => $this->generateUrl('invoice_multinew')]]);
  850.         $entities3 = array();
  851.         foreach ($entities as $entity) {
  852.             $query = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\Invoice t WHERE (t.state = 0) AND (t.invoiceDate >= ?1) AND (t.contract = ?2)");
  853.             //new \DateTime('last day of last month')
  854.             $param = date("Y-m-d", strtotime("first day of last month"));
  855.             $query = $query->setParameter(1, $param);
  856.             $query = $query->setParameter(2, $entity->getId());
  857.             $entities2 = $query->getResult();
  858.             $query2 = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\NoInvoice t WHERE (t.state = 0) AND (t.creationDate >= ?1) AND (t.contract = ?2)");
  859.             $query2 = $query2->setParameter(1, $param);
  860.             $query2 = $query2->setParameter(2, $entity->getId());
  861.             $entities4 = $query2->getResult();
  862.             if (($entities2[0][1] == 0)&& ($entities4[0][1] == 0)) {
  863.                 $form->add('hours' . $entity->getId(), NumberType::class, array('label' => 'Invoice.Hours', 'required' => false));
  864.                 $form->add('extra' . $entity->getId(), NumberType::class, array('label' => 'Invoice.Extra', 'required' => false));
  865.                 $form->add('timesheetupload' . $entity->getId(),  FileType::class, array('label' => 'TimeSheet', 'required' => false, 'mapped' => false));
  866.                 $form->add('action' . $entity->getId(), ChoiceType::class,
  867.                         array('required' => true, 'choices' => array('Invoice.CreateWhenHoursNotZero' => 'invoice', 'Invoice.NoInvoiceNeededThisMonth' => 'noinvoice'), 'preferred_choices' => array('mail')));
  868.                 $entities3[] = $entity;
  869.             }
  870.         }
  871.         
  872.         $form = $form->getForm();
  873.         $form->handleRequest($request);
  874.         if ($form->isSubmitted()) {
  875.             
  876.             $items = $request->request->get('form');
  877.             $input = $request->files->get('form');
  878.             //$this->get('session')->getFlashBag()->add('error', "verzonden");
  879.             $finalarray = array();
  880.             $i = 0;
  881.             $applicationfolder = $dmsservice->createFolderIfNeeded("System");
  882.             $invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
  883.             //$folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
  884.             foreach ($entities as $entity) {
  885.                 $query = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\Invoice t WHERE (t.state = 0) AND (t.invoiceDate >= ?1) AND (t.contract = ?2)");
  886.                 //new \DateTime('last day of last month')
  887.                 $param = date("Y-m-d", strtotime("first day of last month"));
  888.                 $query = $query->setParameter(1, $param);
  889.                 $query = $query->setParameter(2, $entity->getId());
  890.                 $entities2 = $query->getResult();
  891.                 $query2 = $em->createQuery("SELECT COUNT(t.id) FROM App\Entity\Finance\NoInvoice t WHERE (t.state = 0) AND (t.creationDate >= ?1) AND (t.contract = ?2)");
  892.                 $query2 = $query2->setParameter(1, $param);
  893.                 $query2 = $query2->setParameter(2, $entity->getId());
  894.                 $entities4 = $query2->getResult();
  895.                 if (($entities2[0][1] == 0) && ($entities4[0][1] == 0)) {
  896.                     $action = $items['action' . $entity->getId()];
  897.                     if ($action == 'noinvoice') {
  898.                         $noinv = new NoInvoice();
  899.                         $noinv->setContract($entity);
  900.                         $noinv->setCreationDate(new \DateTime('last day of last month'));
  901.                         $noinv->setOrganization($entity->getOrganization());
  902.                         $noinv->setState(0);
  903.                         $em->persist($noinv);
  904.                         $em->flush();
  905.                     } else {
  906.                         if ($items['hours' . $entity->getId()] != 0) {
  907.                             /*$entityinv = new Invoice();
  908.                             $entityinv->setContract($entity);
  909.                             $entityinv->setHours(str_replace(',', '.', $items['hours' . $entity->getId()]));
  910.                             $entityinv->setExtraamount(str_replace(',', '.', $items['extra' . $entity->getId()]));*/
  911.                             
  912.                             $invoicedate = new \DateTime('last day of last month');
  913.                             //Contractnumber ; "-" ; consultantname ; services related to the period ; variable (month , year )
  914.                             $subject = $entity->getSubject();
  915.                             $extra = "";
  916.                             foreach ($entity->getContractsElement() as $element)
  917.                             {
  918.                                 if ($element->getState() == 0)
  919.                                 {
  920.                                     if ($entity->getType()->getInteger1() == 2)
  921.                                     {
  922.                                         $extra = "". $element->getEmployee();
  923.                                     }
  924.                                 }
  925.                             }
  926.                             $extra2 = "";
  927.                             if (empty($entity->getAttachmentNumber()) == false)
  928.                             {
  929.                                 $extra2 = " - " . $entity->getAttachmentNumber();
  930.                             }
  931.                             $subject = $entity->getContractNumber().$extra2 . " : " . $extra. " - services related to the period " .  $invoicedate->format('M Y');
  932.                             $invoice = $invoiceService->createInvoice($entity->getClient()->getId(),
  933.                                 $invoicedate->format('Y-m-d'), null,$subject, null,
  934.                                 $entity->getClient()->getLanguage(),
  935.                                 $entity->getSalesCondition()->getId(), 
  936.                                 $entity->getOrganization(),
  937.                                 false);
  938.                             $invoice->setContract($entity);
  939.                             $invoice->setContractNumber($entity->getContractNumber());
  940.                             $invoice->setAttachmentNumber($entity->getAttachmentNumber());
  941.                             $em->persist($invoice);
  942.                             $em->flush();
  943.                             $invoice = $invoiceService->updateProfitInfo($invoice);
  944.                             
  945.                             
  946.                             $em->persist($invoice);
  947.                             $em->flush();
  948.                             
  949.                             $product = $kernel_service->getApplicationInfoValue("Finance.DefaultProductForResourceContracts", $entity->getOrganization());
  950.                             
  951.                             $taxrate = $kernel_service->getListItem('Finance.tax', "21%");
  952.                             if ($entity->getClient()->getTaxRate() != null)
  953.                             {
  954.                                 $taxrate = $entity->getClient()->getTaxRate();
  955.                             }
  956.                             
  957.                             if ($product)
  958.                             {
  959.                                 $price = 0;
  960.                                 foreach($entity->getContractsElement() as $element)
  961.                                 {
  962.                                     if ($element->getState() == 0)
  963.                                     {
  964.                                         $price = $element->getUnitPrice();
  965.                                     }
  966.                                 }
  967.                                 
  968.                                 $invoiceProduct = new InvoiceProduct();
  969.                                 $invoiceProduct
  970.                                     ->setInvoice($invoice)
  971.                                     ->setProduct($product)
  972.                                     ->setReference($product->getReference())
  973.                                     ->setName($product->getName())
  974.                                     ->setUnitPrice($price/8)
  975.                                     ->setQuantity(str_replace(',', '.',$items['hours' . $entity->getId()]))
  976.                                     ->setTaxrate($taxrate)
  977.                                     ->setState(0);
  978.                                 $em->persist($invoiceProduct);
  979.                                 $em->flush();
  980.                             }
  981.                             
  982.                             $product = $kernel_service->getApplicationInfoValue("Finance.DefaultAdditionalProduct", $entity->getOrganization());
  983.                             $taxrate = $kernel_service->getListItem('Finance.tax', "0%");
  984.                             if ($product)
  985.                             {
  986.                                 $extra = str_replace(',', '.',$items['extra' . $entity->getId()]);
  987.                                 if (empty($extra) == false)
  988.                                 {
  989.                                     $invoiceProduct = new InvoiceProduct();
  990.                                     $invoiceProduct
  991.                                         ->setInvoice($invoice)
  992.                                         ->setProduct($product)
  993.                                         ->setReference($product->getReference())
  994.                                         ->setName($product->getName())
  995.                                         ->setUnitPrice($extra)
  996.                                         ->setQuantity(1)
  997.                                         ->setTaxrate($taxrate)
  998.                                         ->setState(0);
  999.                                     $em->persist($invoiceProduct);
  1000.                                     $em->flush();
  1001.                                 }
  1002.                             }
  1003.                             
  1004.                             $invoiceService->calcTotalAmount($invoice, true);
  1005.                             
  1006.                             $folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
  1007.                             $errorfile = false;
  1008.                             
  1009.                             try {
  1010.                                 if ($input != null) {
  1011.                                     if (array_key_exists('timesheetupload' . $entity->getId(), $input)) {
  1012.                                         
  1013.                                         $timesheetfile = $dmsservice->uploadfile($input['timesheetupload' . $entity->getId()], $folder);
  1014.                                         $explode = explode(".",$timesheetfile->getName());
  1015.                                         $extension = end($explode);
  1016.                                         $timesheetfile->setName("timesheet_". $invoice->getInvoiceNumber(). "." . $extension);
  1017.                                         $em->persist($timesheetfile);
  1018.                                         $em->flush();
  1019.                                     }
  1020.                                 }
  1021.                             } catch (FileException$e) {
  1022.                                 $errorfile = true;
  1023.                             }
  1024.                             $finalarray[] = $invoice;
  1025.                             $i = $i + 1;
  1026.                         }
  1027.                     }
  1028.                 }
  1029.             }
  1030.             $this->get('session')->getFlashBag()->add('succes', $i . " invoice(s) created!");
  1031.             $currenttime = new \DateTime();
  1032.             $filename = $currenttime->format('Y-m-d-H-i-s');
  1033.             return $this->redirect($this->generateUrl('invoice_index'));
  1034.         }
  1035.         return $this->render('finance/invoice/multinew.html.twig', [
  1036.                     
  1037.             'entities' => $entities3,
  1038.             'form' => $form->createView(),
  1039.         ]);
  1040.     }
  1041.     
  1042.     /**
  1043.      * @Route("/listing", name="invoice_listing", methods={"GET","POST"})
  1044.      */
  1045.     public function listing(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice): Response 
  1046.     {
  1047.         $classname = explode("\\", get_class($this));
  1048.         $arraysize = count($classname);
  1049.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1050.         $this->denyAccessUnlessGranted($attribute);
  1051.         $entityManager = $this->getDoctrine()
  1052.                 ->getManager();
  1053.         
  1054.         
  1055.         $em = $this->getDoctrine()->getManager();
  1056.         //$query = $em->createQuery("SELECT t.creationDate  FROM  App\Entity\Finance\Invoice t ORDER BY t.creationDate")->setMaxResults(1);
  1057.        //$entities = $query->getResult();
  1058.     $query2 = $em->createQuery("SELECT DISTINCT(t.invoiceDate) as invoiceDate FROM App\Entity\Finance\Invoice t WHERE t.state = 0 ORDER BY t.invoiceDate DESC");
  1059.        $entities2 = $query2->getResult();
  1060.     $entities3 = array();
  1061.     $prev = "";
  1062.     foreach($entities2 as $entity) {
  1063.         
  1064.         if (substr($entity['invoiceDate'],0,7) != $prev)
  1065.         {
  1066.             $prev = substr($entity['invoiceDate'],0,7);
  1067.             $entities3[$prev] = $prev;
  1068.         }
  1069.     }
  1070.     $form = $this->createFormBuilder(null, array(
  1071.             'attr' => array(
  1072.                 'id' => $this->generateUrl('invoice_listing')
  1073.         )));
  1074.         $form->setAction($this->generateUrl('invoice_listing'));
  1075.         $form->add('month', ChoiceType::class, array('choices' => $entities3, 'label' => 'Month', 'required' => true, 'attr' => array(
  1076.                 'class' => 'select2')));
  1077.     
  1078.         $form = $form->getForm();
  1079.         
  1080.          if ($request->isMethod('POST'))
  1081.          {
  1082.             $items = $request->request->get('form');
  1083.             $selectedmonth = $items['month'];
  1084.             $selecteddate = new \DateTime($selectedmonth . "-15");
  1085.             $firstday = clone $selecteddate->modify('first day of this month');
  1086.             $lastday = $selecteddate->modify('last day of this month');
  1087.             $query = $em->createQuery("SELECT t FROM  App\Entity\Finance\Invoice t WHERE (t.state = 0) AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
  1088.             //new \DateTime('last day of last month')
  1089.             //     $param = date("Y-m-d",strtotime("first day of last month"));
  1090.             //    $param2 = date("Y-m-d",strtotime("first day of last month"));
  1091.             $query = $query->setParameter(1, $firstday);
  1092.             $query = $query->setParameter(2, $lastday);
  1093.             $entities = $query->getResult();
  1094.             
  1095.             $query2 = $em->createQuery("SELECT t FROM  App\Entity\Finance\CreditNote t WHERE (t.state = 0) AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
  1096.             //new \DateTime('last day of last month')
  1097.             //     $param = date("Y-m-d",strtotime("first day of last month"));
  1098.             //    $param2 = date("Y-m-d",strtotime("first day of last month"));
  1099.             $query2 = $query2->setParameter(1, $firstday);
  1100.             $query2 = $query2->setParameter(2, $lastday);
  1101.             $entities2 = $query2->getResult();
  1102.             $result = $invoiceService->multipdf($entities, $selectedmonth,$this->getUser()->getOrganization(), $entities2);
  1103.             return $this->render('finance/invoice/resultlisting.html.twig', [
  1104.                         'selectedmonth' => $lastday->format('Y-m-d'), 'entities' => $entities, 'result' => $result, "f" => $firstday, "l" => $lastday
  1105.             ]);
  1106.         }
  1107.         return $this->render('finance/invoice/listing.html.twig', [
  1108.                     'form' => $form->createView(),
  1109.         ]);
  1110.     }
  1111.     
  1112.     /**
  1113.      * @Route("/accounting", name="invoice_accounting", methods={"GET","POST"})
  1114.      */
  1115.     public function accounting(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, MailService $mailService): Response 
  1116.     {
  1117.         $classname = explode("\\", get_class($this));
  1118.         $arraysize = count($classname);
  1119.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1120.         $this->denyAccessUnlessGranted($attribute);
  1121.         $entityManager = $this->getDoctrine()
  1122.                 ->getManager();
  1123.         
  1124.         
  1125.         $em = $this->getDoctrine()->getManager();
  1126.         //$query = $em->createQuery("SELECT t.creationDate  FROM  App\Entity\Finance\Invoice t ORDER BY t.creationDate")->setMaxResults(1);
  1127.        //$entities = $query->getResult();
  1128.     $query2 = $em->createQuery("SELECT DISTINCT(t.invoiceDate) as invoiceDate FROM App\Entity\Finance\Invoice t WHERE t.state = 0 ORDER BY t.invoiceDate DESC");
  1129.        $entities2 = $query2->getResult();
  1130.     $entities3 = array();
  1131.     $prev = "";
  1132.     foreach($entities2 as $entity) {
  1133.         
  1134.         if (substr($entity['invoiceDate'],0,7) != $prev)
  1135.         {
  1136.             $prev = substr($entity['invoiceDate'],0,7);
  1137.             $entities3[$prev] = $prev;
  1138.         }
  1139.     }
  1140.     $form = $this->createFormBuilder(null, array(
  1141.             'attr' => array(
  1142.                 'id' => $this->generateUrl('invoice_accounting')
  1143.         )));
  1144.         $form->setAction($this->generateUrl('invoice_accounting'));
  1145.         $form->add('resendall', CheckboxType::class, array('mapped' => false, 'label' => 'Resend All', 'required' => false));
  1146.                             
  1147.         $form->add('month', ChoiceType::class, array('choices' => $entities3, 'label' => 'Month', 'required' => true, 'attr' => array(
  1148.                 'class' => 'select2')));
  1149.     
  1150.         $form = $form->getForm();
  1151.         
  1152.          if ($request->isMethod('POST'))
  1153.          {
  1154.             $items = $request->request->get('form');
  1155.             $selectedmonth = $items['month'];
  1156.             $selecteddate = new \DateTime($selectedmonth . "-15");
  1157.             $firstday = clone $selecteddate->modify('first day of this month');
  1158.             $lastday = $selecteddate->modify('last day of this month');
  1159.             
  1160.             if (isset($items['resendall']))
  1161.             {
  1162.                 $query = $em->createQuery("SELECT t FROM  App\Entity\Finance\Invoice t WHERE t.state = 0 AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
  1163.             } else
  1164.             {
  1165.                 $query = $em->createQuery("SELECT t FROM  App\Entity\Finance\Invoice t WHERE (t.state = 0 and t.ublMailToAccountantNeeded = 1) AND ((t.invoiceDate >= ?1) AND (t.invoiceDate <= ?2))");
  1166.             
  1167.             }
  1168.             $query = $query->setParameter(1, $firstday);
  1169.             $query = $query->setParameter(2, $lastday);
  1170.             $entities = $query->getResult();
  1171.             
  1172.             $organization =  $this->getUser()->getOrganization();
  1173.             $emailAccountant = $kernel_service->getApplicationInfoValue("Kernel.AccountantEmail", $organization);
  1174.             $valid = null;
  1175.             foreach (explode(';', $emailAccountant) AS $sEmailAddress) {
  1176.                 if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false) {
  1177.                     if ($valid == null) {
  1178.                         $valid = true;
  1179.                     }
  1180.                 } else {
  1181.                     $valid = false;
  1182.                 }
  1183.             }
  1184.             if ($valid == null) {
  1185.                 $valid = false;
  1186.             }
  1187.             
  1188.             $count = 0;
  1189.             if ($valid == true)
  1190.             {
  1191.                 
  1192.             }
  1193.             
  1194.              foreach ($entities AS $invoice) {
  1195.                 
  1196.                 if ($invoice->getUbl() != null)
  1197.                 {
  1198.                     $files = array(); 
  1199.                     $files[] = $invoice->getUbl();
  1200.                     /*if ($invoice->getPdf() != null)
  1201.                     {
  1202.                         $files[] = $invoice->getPdf();
  1203.                     }*/
  1204.                         
  1205.                     $mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices", $invoice->getOrganization());
  1206.                     $cc = null;
  1207.                     if (empty($mailcc) == false) {
  1208.                         if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
  1209.                             $cc = $mailcc;
  1210.                         }
  1211.                     }
  1212.                         
  1213.                     $mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $invoice->getOrganization());
  1214.                     if (empty($mailfrom) == true) {
  1215.                         $mailfrom = null;
  1216.                     }
  1217.                     
  1218.                    
  1219.                         
  1220.                     $contact = $mailService->createMail($emailAccountant, "Invoice & UBL", "", $files, $cc, $mailfrom, $invoice->getOrganization(), true);
  1221.                     $contact->setInvoice($invoice);
  1222.                     $em->persist($contact);
  1223.                     $invoice->setUblMailToAccountantNeeded(0);
  1224.                     $em->persist($contact);
  1225.                     $em->flush();
  1226.                  
  1227.                     $count++;
  1228.                 }
  1229.              }
  1230.              
  1231.              if (isset($items['resendall']))
  1232.             {
  1233.                 $query = $em->createQuery("SELECT t FROM  App\Entity\Finance\CreditNote t WHERE t.state = 0 AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
  1234.             } else
  1235.             {
  1236.                 $query = $em->createQuery("SELECT t FROM  App\Entity\Finance\CreditNote t WHERE (t.state = 0 and t.ublMailToAccountantNeeded = 1) AND ((t.creditNoteDate >= ?1) AND (t.creditNoteDate <= ?2))");
  1237.             
  1238.             }
  1239.             $query = $query->setParameter(1, $firstday);
  1240.             $query = $query->setParameter(2, $lastday);
  1241.             $entities = $query->getResult();
  1242.             
  1243.             $organization =  $this->getUser()->getOrganization();
  1244.             $emailAccountant = $kernel_service->getApplicationInfoValue("Kernel.AccountantEmail", $organization);
  1245.             $valid = null;
  1246.             foreach (explode(';', $emailAccountant) AS $sEmailAddress) {
  1247.                 if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false) {
  1248.                     if ($valid == null) {
  1249.                         $valid = true;
  1250.                     }
  1251.                 } else {
  1252.                     $valid = false;
  1253.                 }
  1254.             }
  1255.             if ($valid == null) {
  1256.                 $valid = false;
  1257.             }
  1258.             
  1259.             //$count = 0;
  1260.             if ($valid == true)
  1261.             {
  1262.                 
  1263.             }
  1264.             
  1265.              foreach ($entities AS $creditnote) {
  1266.                 
  1267.                 if ($creditnote->getUbl() != null)
  1268.                 {
  1269.                     $files = array(); 
  1270.                     $files[] = $creditnote->getUbl();
  1271.                     /*if ($invoice->getPdf() != null)
  1272.                     {
  1273.                         $files[] = $invoice->getPdf();
  1274.                     }*/
  1275.                         
  1276.                     $mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices", $creditnote->getOrganization());
  1277.                     $cc = null;
  1278.                     if (empty($mailcc) == false) {
  1279.                         if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
  1280.                             $cc = $mailcc;
  1281.                         }
  1282.                     }
  1283.                         
  1284.                     $mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $creditnote->getOrganization());
  1285.                     if (empty($mailfrom) == true) {
  1286.                         $mailfrom = null;
  1287.                     }
  1288.                     
  1289.                    
  1290.                         
  1291.                     $contact = $mailService->createMail($emailAccountant, "Credit Note & UBL", "", $files, $cc, $mailfrom, $creditnote->getOrganization(), true);
  1292.                     $contact->setCreditnote($creditnote);
  1293.                     $em->persist($contact);
  1294.                     $creditnote->setUblMailToAccountantNeeded(0);
  1295.                     $em->persist($contact);
  1296.                     $em->flush();
  1297.                  
  1298.                     $count++;
  1299.                 }
  1300.              }
  1301.             //$result = $invoiceService->multipdf($entities, $selectedmonth,$this->getUser()->getOrganization());
  1302.             $feedback = "". $count . " UBL files have been mailed to the accountant";
  1303.             $this->get('session')->getFlashBag()->add('success', $feedback);
  1304.             
  1305.             return $this->redirect($this->generateUrl('invoice_accounting'));
  1306.             
  1307.         }
  1308.         return $this->render('finance/invoice/accounting.html.twig', [
  1309.                     'form' => $form->createView(),
  1310.         ]);
  1311.     }
  1312.     
  1313.     /**
  1314.      * @Route("/mails", name="invoice_mails", methods={"GET","POST"})
  1315.      */
  1316.     public function mails(Request $request, TranslatorInterface $translator, KernelService $kernel_service, InvoiceService $invoiceService, ClientService $clientservice, DMSService $dmsservice, MailService $mailService): Response 
  1317.     {
  1318.         $classname = explode("\\", get_class($this));
  1319.         $arraysize = count($classname);
  1320.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1321.         $this->denyAccessUnlessGranted($attribute);
  1322.         
  1323.         $em = $this->getDoctrine()->getManager();
  1324.         $query = $em->createQuery("SELECT t FROM App\Entity\Finance\Invoice t LEFT JOIN t.client u WHERE ((t.state = 0) AND  (u.contactByEmail = true))AND  t.processState = 0");
  1325.         $entities = $query->getResult();
  1326.     $form = $this->createFormBuilder(null, 
  1327.                 ['action' => $this->generateUrl('invoice_mails'), 
  1328.                  'attr' => ['id' => $this->generateUrl('invoice_mails')]]);
  1329.         foreach($entities as $entity) {
  1330.             $form->add('action'.$entity->getId(), ChoiceType::class,
  1331.               array('required' => true, 'choices' => array('Invoice.SendMail' => 'mail', 'Invoice.SendMailLater' => 'later', 'Invoice.NoMailRequired' => 'not'), 'preferred_choices' => array('mail')));
  1332.     }
  1333.     
  1334.         $form = $form->getForm();
  1335.         
  1336.         $form->handleRequest($request);
  1337.         if ($form->isSubmitted()) {
  1338.             $items = $request->request->get('form');
  1339.             
  1340.             foreach ($entities as $entity) {
  1341.                 $feedback = "";
  1342.                 $action = $items['action' . $entity->getId()];
  1343.                 if ($action == 'mail') {
  1344.                     
  1345.                     $valid = null;
  1346.                     if (($entity->getContract() != null) and
  1347.                             (empty($entity->getContract()->getInvoiceContactEmail()) == false))
  1348.                     {
  1349.                         if (!filter_var($entity->getContract()->getInvoiceContactEmail(), FILTER_VALIDATE_EMAIL) === false)
  1350.                         {
  1351.                             if ($valid == null)
  1352.                            {
  1353.                                 $valid = true;
  1354.                            }
  1355.                         }
  1356.                     }
  1357.                     else
  1358.                     {
  1359.                     
  1360.                     foreach(explode(';', $entity->getClient()->getEmail()) AS $sEmailAddress) {
  1361.                         if (!filter_var($sEmailAddress, FILTER_VALIDATE_EMAIL) === false)
  1362.                         {
  1363.                            if ($valid == null)
  1364.                            {
  1365.                                 $valid = true;
  1366.                            }
  1367.                         } else
  1368.                         {   
  1369.                             $valid = false;
  1370.                         }
  1371.                     }
  1372.                     if ($valid == null)
  1373.                    {
  1374.                         $valid = false;
  1375.                    }
  1376.                     }
  1377.                     
  1378.                    
  1379.                     //if (!filter_var($entity->getClient()->getEmail(), FILTER_VALIDATE_EMAIL) === false) {
  1380.                     if ($valid == true)   
  1381.                     {
  1382.                         $applicationfolder = $dmsservice->createFolderIfNeeded("System");
  1383.                         $invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
  1384.                         $folder = $dmsservice->createFolderIfNeeded("".$entity->getId(), $invoicefolder);
  1385.                         $files = $folder->getActiveKernelfiles();
  1386.                         $files[] = $entity->getPdf();
  1387.                         
  1388.                         $includeUBLInInvoiceMail = $kernel_service->getApplicationInfoValue("Finance.IncludeUBLInInvoiceMail", $entity->getOrganization());
  1389.                         if ($includeUBLInInvoiceMail == true)
  1390.                         {
  1391.                             $files[] = $entity->getUbl();
  1392.                         }
  1393.                         
  1394.                         $mailcc = $kernel_service->getApplicationInfoValue("Finance.AdditionalCCEmailForInvoices");
  1395.                         $cc = null;
  1396.                         if (empty($mailcc) == false) {
  1397.                             if ((!filter_var($mailcc, FILTER_VALIDATE_EMAIL) === false)) {
  1398.                                 $cc = $mailcc;
  1399.                             }
  1400.                         }
  1401.                         
  1402.                         $mailfrom = $kernel_service->getApplicationInfoValue("Finance.FromEmailForInvoices", $entity->getOrganization());
  1403.                         if (empty($mailfrom) == true)
  1404.                         {
  1405.                             $mailfrom = null;
  1406.                         }
  1407.                         
  1408.                         $to = "";
  1409.                         if (($entity->getContract() != null) and
  1410.                             (empty($entity->getContract()->getInvoiceContactEmail()) == false))
  1411.                         {
  1412.                             $to = $entity->getContract()->getInvoiceContactEmail();
  1413.                         } else
  1414.                         {
  1415.                             $to = explode(';', $entity->getClient()->getEmail());
  1416.                         }
  1417.                         
  1418.                         $contact = $mailService->createMailBasedOnTemplate($to, "TemplateType.NewInvoice", $entity, $entity->getLanguage(), $files, $cc, $mailfrom, $entity->getOrganization());
  1419.                         $contact->setInvoice($entity);
  1420.                         $em->persist($contact);
  1421.                         $entity->setProcessState(1);
  1422.                         $feedback = $feedback . "Invoice " . $entity . " sent";
  1423.                     }
  1424.                             
  1425.                  }
  1426.                 if ($action == 'not') {
  1427.                     $entity->setProcessState(1);
  1428.                     $feedback = $feedback . "Invoice " . $entity . " marked as no longer required to be sent";
  1429.                 }
  1430.                 $em->persist($entity);
  1431.                 $em->flush();
  1432.                 
  1433.                 if (empty($feedback) == false)
  1434.                 {
  1435.                     $this->get('session')->getFlashBag()->add('succes', $feedback);
  1436.                 }
  1437.                 
  1438.             }
  1439.             return $this->redirect($this->generateUrl('invoice_mails'));
  1440.         }
  1441.         return $this->render('finance/invoice/mails.html.twig', [
  1442.             'entities' => $entities,
  1443.             'form'   => $form->createView()
  1444.         ]);
  1445.     }
  1446.     /**
  1447.      * @Route("/{id}", name="invoice_show", methods={"GET"})
  1448.      */
  1449.     public function show(Invoice $invoice, DMSService $dmsservice, InvoiceService $invoiceService): Response {
  1450.         $classname = explode("\\", get_class($this));
  1451.         $arraysize = count($classname);
  1452.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1453.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1454.         
  1455.         $applicationfolder = $dmsservice->createFolderIfNeeded("System");
  1456.         $invoicefolder = $dmsservice->createFolderIfNeeded("Invoice", $applicationfolder);
  1457.         $folder = $dmsservice->createFolderIfNeeded("".$invoice->getId(), $invoicefolder);
  1458.         
  1459.         
  1460.         return $this->render('finance/invoice/show.html.twig', [
  1461.                     'invoice' => $invoice,
  1462.                     'folder' => $folder,
  1463.                     'state' => 0
  1464.         ]);
  1465.     }
  1466.     
  1467.     
  1468.     /**
  1469.      * @Route("/{id}/audit", name="invoice_showaudit", methods={"GET"})
  1470.      */
  1471.     public function showaudit(Invoice $invoice): Response {
  1472.         $classname = explode("\\", get_class($this));
  1473.         $arraysize = count($classname);
  1474.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1475.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1476.         return $this->render('finance/invoice/showaudit.html.twig', [
  1477.                     'invoice' => $invoice,
  1478.         ]);
  1479.     }
  1480.     /**
  1481.      * @Route("/{id}/archive", name="invoice_archive", methods={"GET"})
  1482.      */
  1483.     public function archive(Invoice $invoice, TranslatorInterface $translator, ContractService $contractService): Response {
  1484.         $classname = explode("\\", get_class($this));
  1485.         $arraysize = count($classname);
  1486.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1487.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1488.         $entityManager = $this->getDoctrine()->getManager();
  1489.         $invoice->setState(1);
  1490.         $entityManager->persist($invoice);
  1491.         $entityManager->flush();
  1492.         
  1493.         $contract = $invoice->getContract();
  1494.         if ($contract != null)
  1495.         {
  1496.             $contractService->updateInvoicedDays($contract);
  1497.         }
  1498.         return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1499.     }
  1500.     
  1501.     /**
  1502.      * @Route("/{id}/markassend", name="invoice_markassend", methods={"GET"})
  1503.      */
  1504.     public function markassend(Invoice $invoice): Response {
  1505.         $classname = explode("\\", get_class($this));
  1506.         $arraysize = count($classname);
  1507.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1508.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1509.         
  1510.         $entityManager = $this->getDoctrine()->getManager();
  1511.         $invoice->setProcessState(1);
  1512.         $entityManager->persist($invoice);
  1513.         $entityManager->flush();
  1514.         
  1515.         return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1516.     }
  1517.     
  1518.     /**
  1519.      * @Route("/{id}/markaspayed", name="invoice_markaspayed", methods={"GET"})
  1520.      */
  1521.     public function markaspayed(Invoice $invoice): Response {
  1522.         $classname = explode("\\", get_class($this));
  1523.         $arraysize = count($classname);
  1524.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1525.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1526.         
  1527.         
  1528.         $entityManager = $this->getDoctrine()->getManager();
  1529.         $invoice->setProcessState(2);
  1530.         $entityManager->persist($invoice);
  1531.         $entityManager->flush();
  1532.         
  1533.         return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1534.     }
  1535.     
  1536.     /**
  1537.      * @Route("/{id}/putinnewstatus", name="invoice_putinnewstatus", methods={"GET"})
  1538.      */
  1539.     public function putinnewstatus(Invoice $invoice): Response {
  1540.         $classname = explode("\\", get_class($this));
  1541.         $arraysize = count($classname);
  1542.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1543.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1544.         
  1545.         
  1546.         $entityManager = $this->getDoctrine()->getManager();
  1547.         $invoice->setProcessState(0);
  1548.         $entityManager->persist($invoice);
  1549.         $entityManager->flush();
  1550.         
  1551.         return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1552.     }
  1553.     
  1554.     /**
  1555.      * @Route("/{id}/duplicate", name="invoice_duplicate", methods={"GET"})
  1556.      */
  1557.     public function duplicate(Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
  1558.         $classname = explode("\\", get_class($this));
  1559.         $arraysize = count($classname);
  1560.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1561.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1562.         
  1563.         
  1564.         $entityManager = $this->getDoctrine()->getManager();
  1565.         $datenewinvoice = new \DateTime();
  1566.         $newinvoice = $invoiceService->createInvoice($invoice->getClient()->getId(),
  1567.             $datenewinvoice->format('Y-m-d'), null, $invoice->getAbout(), $invoice->getNote(),
  1568.                         $invoice->getLanguage(),
  1569.                         $invoice->getSalesCondition()->getId(), 
  1570.                         $invoice->getOrganization(),
  1571.                         false);
  1572.         $entityManager = $this->getDoctrine()->getManager();
  1573.         if (is_int($newinvoice) == false)
  1574.         {
  1575.             $newinvoice->setContract($invoice->getContract());
  1576.             $entityManager->persist($newinvoice);
  1577.             $entityManager->flush();
  1578.             
  1579.             foreach($invoice->getInvoiceproducts() as $invoiceproduct) {
  1580.                 $invoiceService->creatInvoiceProduct($invoiceproduct->getReference(), $invoiceproduct->getName(), $invoiceproduct->getUnitPrice(), $invoiceproduct->getQuantity(), $invoiceproduct->getTaxrate()->getName(), $newinvoice->getId(), false, $invoice->getOrganization());
  1581.             }
  1582.         
  1583.             $invoiceService->updatePDF($newinvoice);
  1584.             $this->denyAccessUnlessGranted($attribute, $newinvoice);
  1585.             return $this->redirectToRoute('invoice_show', array('id' => $newinvoice->getId()));
  1586.         } else
  1587.         {
  1588.             $this->get('session')->getFlashBag()->add('error', $translator->trans('Invoice.ReferenceMustBeUnique'));
  1589.             return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1590.         }
  1591.     }
  1592.     
  1593.     /**
  1594.      * @Route("/{id}/createcreditnote", name="invoice_createcreditnote", methods={"GET"})
  1595.      */
  1596.     public function createcreditnote(Invoice $invoice, InvoiceService $invoiceService): Response {
  1597.         $classname = explode("\\", get_class($this));
  1598.         $arraysize = count($classname);
  1599.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1600.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1601.         
  1602.         
  1603.         $entityManager = $this->getDoctrine()->getManager();
  1604.         $datenewinvoice = new \DateTime();
  1605.         $creditnote = $invoiceService->createCreditNote($invoice->getClient()->getId(),
  1606.             $datenewinvoice->format('Y-m-d'), null, $invoice->getAbout(), $invoice->getNote(),
  1607.                         $invoice->getLanguage(),
  1608.                         $invoice->getOrganization(),
  1609.                         false);
  1610.         foreach($invoice->getInvoiceproducts() as $invoiceproduct) {
  1611.             $invoiceService->createCreditNoteProduct($invoiceproduct->getReference(), $invoiceproduct->getName(), $invoiceproduct->getUnitPrice(), $invoiceproduct->getQuantity(), $invoiceproduct->getTaxrate()->getName(), $creditnote->getId(), false);
  1612.         }
  1613.         $invoiceService->updateCreditNotePDF($creditnote);
  1614.         
  1615.         $creditnote->setInvoice($invoice);
  1616.         $entityManager->persist($creditnote);
  1617.         $entityManager->flush();
  1618.         
  1619.         //$this->denyAccessUnlessGranted($attribute, $newinvoice);
  1620.         return $this->redirectToRoute('app_credit_note_show', array('id' => $creditnote->getId()));
  1621.     }
  1622.     /**
  1623.      * @Route("/{id}/restore", name="invoice_restore", methods={"GET"})
  1624.      */
  1625.     public function restore(Invoice $invoice, TranslatorInterface $translator,InvoiceService $invoiceService, ContractService $contractService): Response {
  1626.         $classname = explode("\\", get_class($this));
  1627.         $arraysize = count($classname);
  1628.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1629.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1630.         $entityManager = $this->getDoctrine()->getManager();
  1631.         if ($invoiceService->checkForDuplicates($invoice)) {
  1632.             $invoice->setState(0);
  1633.             $entityManager->persist($invoice);
  1634.             $entityManager->flush();
  1635.             
  1636.             $contract = $invoice->getContract();
  1637.             if ($contract != null)
  1638.             {
  1639.                 $contractService->updateInvoicedDays($contract);
  1640.             }
  1641.             
  1642.         } else {
  1643.             $this->showErrorMessageMustBeUnique($translator);
  1644.         }
  1645.         return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1646.     }
  1647.     /**
  1648.      * @Route("/{id}/delete", name="invoice_logicaldelete", methods={"GET"})
  1649.      */
  1650.     public function logicaldelete(Invoice $invoice, ContractService $contractService): Response {
  1651.         $classname = explode("\\", get_class($this));
  1652.         $arraysize = count($classname);
  1653.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1654.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1655.         $entityManager = $this->getDoctrine()->getManager();
  1656.         $invoice->setState(2);
  1657.         $entityManager->persist($invoice);
  1658.         $entityManager->flush();
  1659.         
  1660.         $contract = $invoice->getContract();
  1661.         if ($contract != null)
  1662.         {
  1663.             $contractService->updateInvoicedDays($contract);
  1664.         }
  1665.         return $this->redirectToRoute('invoice_index');
  1666.     }
  1667.     /**
  1668.      * @Route("/{id}/edit", name="invoice_edit", methods={"GET","POST"})
  1669.      */
  1670.     public function edit(Request $request, Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
  1671.         $classname = explode("\\", get_class($this));
  1672.         $arraysize = count($classname);
  1673.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1674.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1675.         
  1676.         $entityManager = $this->getDoctrine()->getManager();
  1677.         
  1678.         if ($invoice->getClient() != null)
  1679.         {
  1680.             $clients["".$invoice->getClient()] = "SU".$invoice->getClient()->getId();
  1681.             $client = "SU".$invoice->getClient()->getId();
  1682.         }
  1683.         
  1684.         
  1685.        
  1686.         $form = $this->createForm(InvoiceType::class, $invoice,
  1687.                 ['organization' => $invoice->getOrganization(), 'clients' => $clients, 'client' => $client, 'action' => $this->generateUrl('invoice_edit', array('id' => $invoice->getId())),
  1688.                     'attr' => ['id' => $this->generateUrl('invoice_edit', array('id' => $invoice->getId()))]]); 
  1689.         
  1690.         $form->handleRequest($request);
  1691.         $invoice2 = $this->getDoctrine()->getManager()->getRepository(Invoice::class)->findOneBy(array(
  1692.             'invoiceNumber' => $invoice->getInvoiceNumber(),
  1693.             'organization' => $invoice->getOrganization(),
  1694.             'state' => 0));
  1695.         
  1696.         $continue = true;
  1697.         if ($form->isSubmitted())
  1698.         {
  1699.             $requestdata = $request->request->all("invoice");
  1700.             if (isset($requestdata['clientselect2']) == false)
  1701.             {
  1702.                 $errormessage = $translator->trans('Mandatory');
  1703.                 $form->get('clientselect2')->addError(new FormError($errormessage));    
  1704.                 $continue = false;
  1705.             }
  1706.         }
  1707.         if ($form->isSubmitted() && ($continue == true)) {
  1708.             
  1709.             $requestdata = $request->request->all("invoice");
  1710.             if (isset($requestdata['clientselect2']) == true) {
  1711.                 $clientselect2 = $requestdata['clientselect2'];
  1712.                 $client = null;
  1713.                 $clienttype = substr($clientselect2, 0, 2);
  1714.                 $clientid = substr($clientselect2, 2);
  1715.                 if ($clienttype == "SU") {
  1716.                     $invoice->setClient($entityManager->getRepository(Client::class)->findOneById($clientid));
  1717.                 } else {
  1718.                     
  1719.                 }
  1720.             }
  1721.             
  1722.             $invoiceService->copyFieldsFromClientToInvoice($invoice);
  1723.             if ($invoiceService->checkForDuplicates($invoice) or ($invoice2->getId() == $invoice->getId())) {
  1724.                 $invoice->setSalesConditionText($invoice->getSalesCondition()->getTranslatedDescription($invoice->getLanguage()));
  1725.                 
  1726.                 $duedate = clone $invoice->getInvoiceDate();
  1727.                 if ($invoice->getSalesCondition())
  1728.                 {
  1729.                     if ($invoice->getSalesCondition()->getStartCalculationPaymentDueDateFromEndOfMonth())
  1730.                     {
  1731.                         $duedate->modify('last day of this month');
  1732.                     }
  1733.                     
  1734.                     $duedate->add(new \DateInterval('P'.$invoice->getSalesCondition()->getAllowedDaysUntilPayment().'D')); // P1D means a period of 1 day
  1735.                     
  1736.                     $invoice->setDueDate($duedate);
  1737.                 }
  1738.                 
  1739.                 $this->getDoctrine()->getManager()->flush();
  1740.                 $invoiceService->updatePDF($invoice);
  1741.                 
  1742.                 return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1743.             } else {
  1744.                 $this->showErrorMessageMustBeUnique($translator);
  1745.             }
  1746.         }
  1747.        
  1748.         return $this->render('finance/invoice/edit.html.twig', [
  1749.                     'invoice' => $invoice,
  1750.                     'form' => $form->createView(),
  1751.         ]);
  1752.     }
  1753.     
  1754.     /**
  1755.      * @Route("/{id}/editprofitinfo", name="invoice_editprofitinfo", methods={"GET","POST"})
  1756.      */
  1757.     public function editprofitinfo(Request $request, Invoice $invoice, InvoiceService $invoiceService, TranslatorInterface $translator): Response {
  1758.         $classname = explode("\\", get_class($this));
  1759.         $arraysize = count($classname);
  1760.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1761.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1762.         
  1763.         $entityManager = $this->getDoctrine()->getManager();
  1764.         
  1765.        
  1766.        
  1767.         $form = $this->createForm(InvoiceProfitType::class, $invoice,
  1768.                 [ 'action' => $this->generateUrl('invoice_editprofitinfo', array('id' => $invoice->getId())),
  1769.                     'attr' => ['id' => $this->generateUrl('invoice_editprofitinfo', array('id' => $invoice->getId()))]]); 
  1770.         
  1771.         $form->handleRequest($request);
  1772.         
  1773.         if ($form->isSubmitted() && $form->isValid()) {
  1774.             $entityManager = $this->getDoctrine()->getManager();
  1775.             $entityManager->persist($invoice);
  1776.             $entityManager->flush();
  1777.             
  1778.                 
  1779.                 return $this->redirectToRoute('invoice_show', array('id' => $invoice->getId()));
  1780.         }
  1781.        
  1782.         return $this->render('finance/invoice/editprofitinfo.html.twig', [
  1783.                     'invoice' => $invoice,
  1784.                     'form' => $form->createView(),
  1785.         ]);
  1786.     }
  1787.     /**
  1788.      * @Route("/{id}", name="invoice_delete", methods={"DELETE"})
  1789.      */
  1790.     public function delete(Request $request, Invoice $invoice): Response {
  1791.         $classname = explode("\\", get_class($this));
  1792.         $arraysize = count($classname);
  1793.         $attribute = str_replace("Controller", "", $classname[$arraysize - 1]) . ":" . str_replace("Action", "", __FUNCTION__);
  1794.         $this->denyAccessUnlessGranted($attribute, $invoice);
  1795.         if ($this->isCsrfTokenValid('delete' . $invoice->getId(), $request->request->get('_token'))) {
  1796.             $entityManager = $this->getDoctrine()->getManager();
  1797.             $entityManager->remove($invoice);
  1798.             $entityManager->flush();
  1799.         }
  1800.         return $this->redirectToRoute('invoice_index');
  1801.     }
  1802.     public function showErrorMessageMustBeUnique(TranslatorInterface $translator) {
  1803.         $this->get('session')->getFlashBag()->add('error', $translator->trans('Invoice.ReferenceMustBeUnique'));
  1804.     }
  1805.     
  1806. }