src/Controller/SupplierController.php line 1094

Open in your IDE?
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: maloku
  5. * Date: 15.08.2018
  6. * Time: 16:16
  7. */
  8. namespace App\Controller;
  9. use App\Service\Mail;
  10. use App\Service\MailFailedException;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Psr\Log\LoggerInterface;
  13. use App\Entity\AddressSupplier;
  14. use App\Entity\Calculations;
  15. use App\Entity\CompanyRelations;
  16. use App\Entity\Customer;
  17. use App\Entity\CustomerSupplierRelation;
  18. use App\Entity\InvoiceList;
  19. use App\Entity\Process;
  20. use App\Entity\Report;
  21. use App\Entity\ReportData;
  22. use App\Entity\ReportingPeriod;
  23. use App\Entity\ReportRelease;
  24. use App\Entity\Supplier;
  25. use App\Entity\Todos;
  26. use App\Entity\User;
  27. use App\Entity\UserGroups;
  28. use App\Entity\UserRoles;
  29. use App\Entity\UserStatus;
  30. use App\Service\Ajax;
  31. use App\Service\UserPermissionService;
  32. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  33. use Symfony\Component\Config\Definition\Exception\Exception;
  34. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  35. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  36. use Symfony\Component\Form\Extension\Core\Type\TextType;
  37. use Symfony\Component\Form\FormError;
  38. use Symfony\Component\HttpFoundation\JsonResponse;
  39. use Symfony\Component\HttpFoundation\Request;
  40. use Symfony\Component\Security\Core\User\UserInterface;
  41. use Symfony\Contracts\Translation\TranslatorInterface;
  42. use Symfony\Component\Validator\Validator\ValidatorInterface;
  43. use Symfony\Component\Routing\Annotation\Route;
  44. /**
  45. * Supplier controller.
  46. *
  47. * @Route("/supplier")
  48. */
  49. class SupplierController extends AbstractController
  50. {
  51.     private $dbLogger;
  52.     private $doctrine;
  53.     public function __construct(LoggerInterface $dbLoggerManagerRegistry $doctrine)
  54.     {
  55.         $this->dbLogger $dbLogger;
  56.         $this->doctrine $doctrine;
  57.     }
  58.     /**
  59.      * Lists all supplier entities.
  60.      *
  61.      * @Route("/", name="supplier_index", methods={"GET", "POST"})
  62.      */
  63.     public function indexAction(Request $request,
  64.                                 TranslatorInterface $translator,
  65.                                 LoggerInterface $logger,
  66.                                 ValidatorInterface $validator,
  67.                                 UserInterface $user null,
  68.                                 UserPermissionService $userPermissionService,
  69.                                 Ajax $ajax)
  70.     {
  71.         $em $this->doctrine->getManager();
  72.         $helpdesk $em->getRepository(\App\Entity\HelpDesk::class)->findOneBy(["controller" => $request->get('_route'),
  73.             "roles"=>$this->getUser()->getRoles(), "language"=>$request->getLocale()]);
  74.         $user $this->getUser();
  75.         if($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)
  76.         {
  77.             $data $ajax->call($request);
  78.             return new JsonResponse($data);
  79.         }
  80.         return $this->render('supplier/index.html.twig', array(
  81.             'helpdesk' => $helpdesk,
  82.         ));
  83.     }
  84.   /**
  85.   * Creates a new supplier entity.
  86.   *
  87.   * @Route("/new", name="supplier_new", methods={"GET", "POST"})
  88.   */
  89.       public function newAction(
  90.     Request $request,
  91.     TranslatorInterface $translator,
  92.     LoggerInterface $logger,
  93.     ValidatorInterface $validator)
  94.     {
  95.       $em $this->doctrine->getManager();
  96.       $helpdesk $em->getRepository(\App\Entity\HelpDesk::class)->findOneBy(["controller" => $request->get('_route'), "roles"=>$this->getUser()->getRoles(), "language"=>$request->getLocale()]);
  97.       $supplier = new Supplier();
  98.       $user = new User();
  99.       $addressSupplier = new AddressSupplier();
  100.       $invoiceAddress = new AddressSupplier();
  101.       $parentCompanyRelation = new CompanyRelations();
  102.       $subsidiaryCompanyRelation = new CompanyRelations();
  103.       $user->addSupplier($supplier);
  104.       $supplier->addUser($user);
  105.       $supplier->addAddressSupplier($addressSupplier);
  106.       $customersList $em->getRepository(Customer::class)->findAll();
  107.       $form $this->createForm(\App\Form\SupplierType::class, $supplier);
  108.       $invoiceForm $this->createForm(\App\Form\AddressSupplierType::class, $invoiceAddress, ['setRequired' => false]);
  109.       $errors $validator->validate($supplier);
  110.       $form->handleRequest($request);
  111.       $invoiceForm->handleRequest($request);
  112.       //AJAX
  113.       if($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)
  114.       {
  115.         $retval = array();
  116.         $test $request->get("industryid");
  117.         $subindustries $em->getRepository(\App\Entity\SubIndustry::class)->findBy(['industries' => $test]);
  118.         $i 0;
  119.         foreach($subindustries as $subindustry)
  120.         {
  121.           $retval[$i] = array (
  122.             'id' => $subindustry->getId(),
  123.             'name' => $subindustry->getName(),
  124.           );
  125.           $i++;
  126.         }
  127.         return new JsonResponse($retval);
  128.       }
  129.       if ($form->isSubmitted() && $form->isValid()) {
  130.         try {
  131.           $exists $em->getRepository(Supplier::class)->findOneBy(['companyName' => $supplier->getCompanyName()]);
  132.           $addressExists $em->getRepository(AddressSupplier::class)->findOneBy(['street' => $addressSupplier->getStreet(), 'houseNumber' => $addressSupplier->getHouseNumber(),
  133.           'zipCode' => $addressSupplier->getZipCode(), 'city' => $addressSupplier->getCity()]);
  134.           $stop false;
  135.           foreach ($form->get('users')->getData() as $user)
  136.           {
  137.             $userExist $em->getRepository(\App\Entity\User::class)->findBy(['email' => $user->getEmail(), 'active' => 1'supplier' => null]);
  138.             if ($userExist != null)
  139.             {
  140.               $this->addFlash('error''Es gibt bereits einen Benutzer, der einem Kunden zugewiesen ist, mit dieser Email Addresse: ' $user->getEmail());
  141.               //                        $form->get('user')->addError(new FormError('test' . $user->getLastname()));
  142.               $stop true;
  143.             }
  144.           }
  145.           if (strpos($supplier->getCompanyName(), '?') || strpos($supplier->getCompanyName(), '/') ||
  146.           strpos($supplier->getCompanyName(), '\\') || strpos($supplier->getCompanyName(), '^') ||
  147.           strpos($supplier->getCompanyName(), '|') || strpos($supplier->getCompanyName(), ';') !== false )
  148.           {
  149.             $stop true;
  150.             $form->get('companyName')->addError(new FormError($translator->trans('supplier.illegalCharacters')));
  151.           }
  152.           if ($exists != null && $addressExists != null)
  153.           {
  154.             $form->get('companyName')->addError(new FormError($translator->trans('supplier.formDuplicateName')));
  155.             $form->get('addressSupplier')->get('street')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  156.             $form->get('addressSupplier')->get('houseNumber')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  157.             $form->get('addressSupplier')->get('zipCode')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  158.             $form->get('addressSupplier')->get('city')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  159.             $stop true;
  160.           }
  161.           if ($stop)
  162.           {
  163.             // stays on the same page with form errors/warnings
  164.           } else {
  165.               $status $em->getRepository(UserStatus::class)->findOneBy(['id' => UserStatus::STATUS_REGISTERED]);
  166.               $role $em->getRepository(UserRoles::class)->findOneBy(['id' => UserRoles::ROLE_SUPPLIER]);
  167.               $data $supplier->getUser()->getValues();
  168.               foreach ($data as $user)
  169.               {
  170.                   if ($user->getEmail() == null)
  171.                   {
  172.                       $supplier->removeUser($user);
  173.                       $em->remove($user);
  174.                       $em->flush();
  175.                       continue;
  176.                   }
  177.                   $dbUser $em->getRepository(User::class)->findOneBy(['email' => $user->getEmail()]);
  178.                   if ($dbUser != null)
  179.                   {
  180.                       if ($dbUser->getSupplier() != null)
  181.                       {
  182.                           if ($dbUser->getRoles() === null && $dbUser->getUserStatus() === null)
  183.                           {
  184.                               $dbUser->setRoles($role);
  185.                               $dbUser->setUserStatus($status);
  186.                           } else {
  187.                               $em->remove($user);
  188.                               $em->flush();
  189.                           }
  190.                           if ($dbUser->getActive() == null)
  191.                           {
  192.                               $dbUser->setActive(1);
  193.                           }
  194.                           $dbUser->addUserSupplierList($supplier);
  195.                           $em->persist($dbUser);
  196.                           $em->persist($supplier);
  197.                           $em->flush();
  198.                       } else {
  199.                           $this->addFlash('error''Es gibt bereits einen Benutzer mit dieser E-Mail und dieser ist einem Kunden zugewiesen.');
  200.                           throw new Exception('Es gibt bereits einen Benutzer mit dieser E-Mail und dieser ist einem Kunden zugewiesen.');
  201.                       }
  202.                   } else {
  203.                       if ($user->getRoles() === null && $user->getUserStatus() === null)
  204.                       {
  205.                           $user->setRoles($role);
  206.                           $user->setUserStatus($status);
  207.                           $user->setActive(1);
  208.                           $em->persist($user);
  209.                           $em->flush();
  210.                           $user->addUserSupplierList($supplier);
  211.                       }
  212.                   }
  213.               }
  214.               $em->persist($supplier);
  215.               $em->flush();
  216.             $parentCompanys $request->request->get('ParentCompanys');
  217.             if ($parentCompanys != "" || $parentCompanys != null)
  218.             {
  219.               foreach ($parentCompanys as $item)
  220.               {
  221.                 $parentId substr($item1);
  222.                 if(substr($item,0,1) == 'c')
  223.                 {
  224.                   $parent $em->getRepository(Customer::class)->findOneBy(['id' => $parentId]);
  225.                   $exists $em->getRepository(CompanyRelations::class)->findOneBy(['cm' => $parent'ss' => $supplier]);
  226.                   if ($exists == null)
  227.                   {
  228.                     $parentCompanyRelation = new CompanyRelations();
  229.                     $parentCompanyRelation->setCm($em->getRepository(Customer::class)->findOneBy(['id' => $parentId]));
  230.                     $parentCompanyRelation->setSs($supplier);
  231.                     $em->persist($parentCompanyRelation);
  232.                   }
  233.                 }
  234.                 else if(substr($item,0,1) == 's')
  235.                 {
  236.                   $parent $em->getRepository(Supplier::class)->findOneBy(['id' => $parentId]);
  237.                   $exists $em->getRepository(CompanyRelations::class)->findOneBy(['sm' => $parent'ss' => $supplier]);
  238.                   if ($exists == null)
  239.                   {
  240.                     $subsidiaryCompanyRelation = new CompanyRelations();
  241.                     $subsidiaryCompanyRelation->setSm($em->getRepository(Supplier::class)->findOneBy(['id' => $parentId]));
  242.                     $subsidiaryCompanyRelation->setSs($supplier);
  243.                     $em->persist($subsidiaryCompanyRelation);
  244.                   }
  245.                 }
  246.               }
  247.             }
  248.             $subsidiaryCompanys $request->request->get('SubsidiaryCompanys');
  249.             if ($subsidiaryCompanys != "" || $subsidiaryCompanys != null)
  250.             {
  251.               foreach ($subsidiaryCompanys as $item)
  252.               {
  253.                 $subsidiaryId substr($item1);
  254.                 if(substr($item0,1) == 'c')
  255.                 {
  256.                   $subsidiary $em->getRepository(Customer::class)->findOneBy(['id' => $subsidiaryId]);
  257.                   $exists $em->getRepository(CompanyRelations::class)->findOneBy(['cs' => $subsidiary'sm' => $supplier]);
  258.                   if ($exists == null)
  259.                   {
  260.                     $subsidiaryCompanyRelation->setCs($em->getRepository(Customer::class)->findOneBy(['id' => $subsidiaryId]));
  261.                     $subsidiaryCompanyRelation->setSm($supplier);
  262.                     $em->persist($subsidiaryCompanyRelation);
  263.                   }
  264.                 }
  265.                 else if(substr($item0,1) == 's')
  266.                 {
  267.                   $subsidiary $em->getRepository(Customer::class)->findOneBy(['id' => $subsidiaryId]);
  268.                   $exists $em->getRepository(CompanyRelations::class)->findOneBy(['ss' => $subsidiary'sm' => $supplier]);
  269.                   if ($exists == null)
  270.                   {
  271.                     $subsidiaryCompanyRelation->setSs($em->getRepository(Supplier::class)->findOneBy(['id' => $subsidiaryId]));
  272.                     $subsidiaryCompanyRelation->setSm($supplier);
  273.                     $em->persist($subsidiaryCompanyRelation);
  274.                   }
  275.                 }
  276.               }
  277.             }
  278.             $savedCustomers = array();
  279.             $customers $request->request->get('Customers');
  280.             if ($customers != "" || $customers != null)
  281.             {
  282.               foreach ($customers as $customer)
  283.               {
  284.                 $customerDb $em->getRepository(Customer::class)->findOneBy(['id' => $customer]);
  285.                 $exists $em->getRepository(CustomerSupplierRelation::class)->findOneBy(['customer' => $customerDb'supplier' => $supplier]);
  286.                 if ($exists == null)
  287.                 {
  288.                   $customerSupplierRelation = new CustomerSupplierRelation();
  289.                   $customerSupplierRelation->setSupplier($supplier);
  290.                   $customerSupplierRelation->setCustomer($customerDb);
  291.                   $em->persist($customerSupplierRelation);
  292.                 }
  293.               }
  294.             }
  295.             $supplier->getAddressSupplier()->setSupplier($supplier);
  296.             $supplier->getAddressSupplier()->setType('company');
  297.             if ($invoiceAddress->getStreet() == null && $invoiceAddress->getHouseNumber() == null && $invoiceAddress->getZipCode() == null && $invoiceAddress->getCountry() == null)
  298.             {
  299.               $invoiceAddress->setStreet($addressSupplier->getStreet());
  300.               $invoiceAddress->setHouseNumber($addressSupplier->getHouseNumber());
  301.               $invoiceAddress->setZipCode($addressSupplier->getZipCode());
  302.               $invoiceAddress->setCity($addressSupplier->getCity());
  303.               $invoiceAddress->setCountry($addressSupplier->getCountry());
  304.             }
  305.             $invoiceAddress->setSupplier($supplier);
  306.             $invoiceAddress->setType('invoice');
  307.             $supplier->setActive(1);
  308.             $em->persist($supplier);
  309.             $em->persist($invoiceAddress);
  310.             $em->flush();
  311.             //                foreach ($users as $item)
  312.             //                {
  313.             //                    $item->addSupplier($supplier);
  314.             //                    $em->persist($item);
  315.             //                    $em->flush();
  316.             //                }
  317.               $this->dbLogger->info('Create Supplier', [
  318.               'user' => $this->getUser(),
  319.               'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  320.               'supplier' => $supplier,
  321.               'route' => $request->get('_route')
  322.             ]);
  323.             if ($exists != null)
  324.             {
  325.               $this->addFlash('info'$translator->trans('supplier.duplicateName'));
  326.             } elseif ($addressExists != null) {
  327.               $this->addFlash('info'$translator->trans('supplier.duplicateAddress'));
  328.             } else {
  329.               $this->addFlash('success'$translator->trans('supplier.create_success'));
  330.             }
  331.             return $this->redirectToRoute('supplier_index');
  332.           }
  333.         } catch (\Exception $exception) {
  334.           $this->addFlash('error'$translator->trans('supplier.create_error' $exception->getMessage()));
  335.           $logger->error('Error while create Admin Supplier', ['e' => $exception]);
  336.           $this->dbLogger->error('Error when creating Supplier', [
  337.             'user' => $this->getUser(),
  338.             'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  339.             'supplier' => $supplier,
  340.             'route' => $request->get('_route'),
  341.           ]);
  342.         }
  343.       }
  344.       $companys = array();
  345.       $companysList = array();
  346.       array_push($companys$em->getRepository(Customer::class)->findAll());
  347.       array_push($companys$em->getRepository(Supplier::class)->findAll());
  348.       $idx 0;
  349.       //Why used a Foreach $none never used
  350.       foreach($companys as $none)
  351.       {
  352.         foreach($companys[$idx] as $company)
  353.         {
  354.           if($company instanceof Customer)
  355.           {
  356.             $tmp = ['c'.$company->getId(), $company->getcompanyName()];
  357.           }
  358.           else if ($company instanceof Supplier)
  359.           {
  360.             $tmp = ['s'.$company->getId(), $company->getCompanyName()];
  361.           }
  362.           array_push($companysList$tmp);
  363.         }
  364.         $idx++;
  365.       }
  366.       return $this->render('supplier/supplier.html.twig', array(
  367.         'supplier' => $supplier,
  368.         'form' => $form->createView(),
  369.         'errors' => $errors,
  370.         'companys' => $companysList,
  371.         'invoiceForm' => $invoiceForm->createView(),
  372.         'linkedParentCompanys' => array(),
  373.         'linkedSubsidiaryCompanys' => array(),
  374.         'oldCustomers' => array(),
  375.         'customersList' => $customersList,
  376.         'helpdesk' => $helpdesk,
  377.       ));
  378.     }
  379.     /**
  380.     * Update supplier entity.
  381.     *
  382.     * @Route("/edit/{id}", name="supplier_edit", methods={"GET", "POST"})
  383.     */
  384.     public function editAction(
  385.       Request $request,
  386.       Supplier $supplier,
  387.       TranslatorInterface $translator,
  388.       LoggerInterface $logger,
  389.       ValidatorInterface $validator)
  390.       {
  391.         $headerTitle $supplier->getCompanyName();
  392.         $request->attributes->set('headerTitle'$headerTitle);
  393.         $user $this->getUser();
  394.         $em $this->doctrine->getManager();
  395.         $helpdesk $em->getRepository(\App\Entity\HelpDesk::class)->findOneBy(["controller" => $request->get('_route'), "roles"=>$this->getUser()->getRoles(), "language"=>$request->getLocale()]);
  396.         $supplierManagement $em->getRepository(Supplier::class)->findOneBy(['id' => $supplier]);
  397.         $role $em->getRepository(UserRoles::class)->findOneBy(['role' => 'ROLE_SUPPLIER']);
  398.         $status $em->getRepository(UserStatus::class)->findOneBy(['name' => 'registered']);
  399.         $errors $validator->validate($supplierManagement);
  400.         $invoiceAddress $em->getRepository(AddressSupplier::class)->findOneBy(['supplier' => $supplier'type' => 'invoice']);
  401.         if ($invoiceAddress == null)
  402.         {
  403.           $invoiceAddress = new AddressSupplier();
  404.         }
  405.         if ($supplierManagement->getAddressSupplier() == null)
  406.         {
  407.           $addressSupplier = new AddressSupplier();
  408.           $supplierManagement->addAddressSupplier($addressSupplier);
  409.         }
  410.         $tempLinkedParentCompanys $em->getRepository(CompanyRelations::class)->findBy(['ss' => $supplier]);
  411.         $tempLinkedSubsidiaryCompanys $em->getRepository(CompanyRelations::class)->findBy(['sm' => $supplier]);
  412.         $customersDB $em->getRepository(Customer::class)->findAll();
  413.         $oldUsers $supplierManagement->getUsers()->getValues();
  414.         $userGroup $em->getRepository(UserGroups::class)->findOneBy(['id' => 1]);
  415.         $editForm $this->createForm(\App\Form\SupplierType::class, $supplierManagement);
  416.         if ($user->getRole()->getId() != User::ROLE_SUPER_ADMIN && $user->getRole()->getId() != User::ROLE_ADMIN)
  417.         {
  418.           $editForm->remove('customerSupplierRelation');
  419.           $editForm->remove('notice');
  420.         }
  421.         $editForm->handleRequest($request);
  422.         $editInvoiceForm $this->createForm(\App\Form\AddressSupplierType::class, $invoiceAddress, ['setRequired' => false]);
  423.         $editInvoiceForm->handleRequest($request);
  424.         if (!$supplier) {
  425.           $this->addFlash('error'$translator->trans('supplier.not_exist'));
  426.           return $this->redirectToRoute('supplier_index');
  427.         }
  428.         //AJAX
  429.         if($request->isXmlHttpRequest() || $request->query->get('showJson') == 1)
  430.         {
  431.           $retval = array();
  432.           $test $request->get("industryid");
  433.           $subindustries $em->getRepository(\App\Entity\SubIndustry::class)->findBy(['industries' => $test]);
  434.           $i 0;
  435.           foreach($subindustries as $subindustry)
  436.           {
  437.             $retval[$i] = array (
  438.               'id' => $subindustry->getId(),
  439.               'name' => $subindustry->getName(),
  440.             );
  441.             $i++;
  442.           }
  443.           return new JsonResponse($retval);
  444.         }
  445.         $oldCustomers = array();
  446.         foreach ($supplierManagement->getCustomerSupplierRelation()->getValues() as $csRelation)
  447.         {
  448.           array_push($oldCustomers$csRelation->getCustomer());
  449.         }
  450.         $customerList = array();
  451.         foreach ($customersDB as $customer) {
  452.           if (!in_array($customer$oldCustomers)) {
  453.             array_push($customerList$customer);
  454.           }
  455.         }
  456.         $companys = array();
  457.         $companysListWihtoutParent = array();
  458.         $companysListWihtoutSubsidiary = array();
  459.         $companysList = array();
  460.         array_push($companys$em->getRepository(Customer::class)->findAll());
  461.         array_push($companys$em->getRepository(Supplier::class)->findAll());
  462.         $idx 0;
  463.         //Why used a Foreach $none never used
  464.         foreach($companys as $none)
  465.         {
  466.           foreach($companys[$idx] as $company)
  467.           {
  468.             if($company instanceof Customer)
  469.             {
  470.               $tmp = ['c'.$company->getId(), $company->getcompanyName()];
  471.               array_push($companysList$tmp);
  472.             }
  473.             else if ($company instanceof Supplier)
  474.             {
  475.               if ($company !== $supplier)
  476.               {
  477.                 $tmp = ['s'.$company->getId(), $company->getCompanyName()];
  478.                 array_push($companysList$tmp);
  479.               }
  480.             }
  481.           }
  482.           $idx++;
  483.         }
  484.         $oldParents = array();
  485.         $oldSubsidiarys = array();
  486.         $tempRelationCustomer = [array(),array()];
  487.         foreach ($tempLinkedParentCompanys as $relation)
  488.         {
  489.           if($relation->getCm() instanceof Customer)
  490.           {
  491.             array_push($tempRelationCustomer[0], $relation->getCm());
  492.           }
  493.           else if ($relation->getSm() instanceof Supplier)
  494.           {
  495.             array_push($tempRelationCustomer[1], $relation->getSm());
  496.           }
  497.         }
  498.         $tempRelationSubsidiary = [array(),array()];
  499.         foreach ($tempLinkedSubsidiaryCompanys as $relation)
  500.         {
  501.           if($relation->getCs() instanceof Customer)
  502.           {
  503.             array_push($tempRelationSubsidiary[0], $relation->getCs());
  504.           }
  505.           else if ($relation->getSs() instanceof Supplier)
  506.           {
  507.             array_push($tempRelationSubsidiary[1], $relation->getSs());
  508.           }
  509.         }
  510.         for ($i=0;$i<count($companys);$i++)
  511.         {
  512.           foreach ($companys[$i] as $company)
  513.           {
  514.             if($company instanceof Customer)
  515.             {
  516.               if (!in_array($company$tempRelationCustomer[0]))
  517.               {
  518.                 $tmpList = ['c'.$company->getId(), $company->getcompanyName()];
  519.                 array_push($companysListWihtoutParent$tmpList);
  520.               }
  521.               if (!in_array($company$tempRelationSubsidiary[0]))
  522.               {
  523.                 $tmpList = ['c'.$company->getId(), $company->getcompanyName()];
  524.                 array_push($companysListWihtoutSubsidiary$tmpList);
  525.               }
  526.             }
  527.             else if ($company instanceof Supplier)
  528.             {
  529.               if (!in_array($company$tempRelationCustomer[1]))
  530.               {
  531.                 if ($company !== $supplier)
  532.                 {
  533.                   $tmpList = ['s'.$company->getId(), $company->getCompanyName()];
  534.                   array_push($companysListWihtoutParent$tmpList);
  535.                 }
  536.               }
  537.               if (!in_array($company$tempRelationSubsidiary[1]))
  538.               {
  539.                 if ($company !== $supplier)
  540.                 {
  541.                   $tmpList = ['s'.$company->getId(), $company->getCompanyName()];
  542.                   array_push($companysListWihtoutSubsidiary$tmpList);
  543.                 }
  544.               }
  545.             }
  546.           }
  547.         }
  548.         $linkedParentCompanys = array();
  549.         foreach ($tempLinkedParentCompanys as $tempParent)
  550.         {
  551.           if ($tempParent->getCm() != null)
  552.           {
  553.             $tmp = ['c'.$tempParent->getCm()->getId(), $tempParent->getCm()->getcompanyName()];
  554.             $tmpOld $tempParent->getCm();
  555.           }
  556.           if ($tempParent->getSm() != null)
  557.           {
  558.             $tmp = ['s'.$tempParent->getSm()->getId(), $tempParent->getSm()->getCompanyName()];
  559.             $tmpOld $tempParent->getSm();
  560.           }
  561.           array_push($linkedParentCompanys$tmp);
  562.           array_push($oldParents$tmpOld);
  563.         }
  564.         $linkedSubsidiaryCompanys = array();
  565.         foreach ($tempLinkedSubsidiaryCompanys as $tempSubsidiary)
  566.         {
  567.           if ($tempSubsidiary->getCs() != null)
  568.           {
  569.             $tmp = ['c'.$tempSubsidiary->getCs()->getId(), $tempSubsidiary->getCs()->getcompanyName()];
  570.             $tmpOld $tempSubsidiary->getCs();
  571.           }
  572.           if ($tempSubsidiary->getSs() != null)
  573.           {
  574.             $tmp = ['s'.$tempSubsidiary->getSs()->getId(), $tempSubsidiary->getSs()->getCompanyName()];
  575.             $tmpOld $tempSubsidiary->getSs();
  576.           }
  577.           array_push($linkedSubsidiaryCompanys$tmp);
  578.           array_push($oldSubsidiarys$tmpOld);
  579.         }
  580.         if ($editForm->isSubmitted()) {
  581.           try {
  582.             if ($user->getCustomer() != null)
  583.             {
  584.               $system $em->getRepository(\App\Entity\User::class)->findOneBy(['email' => 'scorebox@fra-services.de']);
  585.               $todo $em->getRepository(\App\Entity\Todo::class)->findOneBy(['id' => 5]);
  586.               $processes $em->getRepository(\App\Entity\Processes::class)->findOneBy(['id' => 1]);
  587.               $process = new Process();
  588.               $process->setProcesses($processes);
  589.               $process->setCustomer($user->getCustomer());
  590.               $process->setContactPersonCustomer($user);
  591.               $process->setSupplier($supplier);
  592.               $process->setCreator($system);
  593.               $process->setState(0);
  594.               $em->persist($process);
  595.               $em->flush();
  596.               $todos = new Todos();
  597.               $todos->setTodo($todo);
  598.               $todos->setProcess($process);
  599.               $todos->setState(Todos::STATE_OPEN);
  600.               $todos->setCreator($system);
  601.               $todos->setDue(new \DateTime());
  602.               $editIndustry $supplier->getIndustry() != null $supplier->getIndustry()->getName() : "";
  603.               $editSubIndustry $supplier->getSubIndustry() != null $supplier->getSubIndustry()->getName() : "";
  604.               $notice 'Supplier: ' $supplier->getCompanyName() . "\n" .
  605.               'Straße: ' $supplier->getAddressSupplier()->getStreet() . ' ' $supplier->getAddressSupplier()->getHousenumber() . "\n" .
  606.               'PLZ, Ort: ' $supplier->getAddressSupplier()->getZipCode() . ', ' $supplier->getAddressSupplier()->getCity() . ', ' $supplier->getAddressSupplier()->getCountry() . "\n" .
  607.               'Webseite: ' $supplier->getAddressSupplier()->getWebsite() . "\n" .
  608.               'Notiz: ' $supplier->getNotice() . "\n" .
  609.               'Branche und Subbranche: ' $editIndustry ', ' $editSubIndustry "\n" .
  610.               'Rechnungsadresse: ' $editInvoiceForm->getData()->getStreet() . ', ' $editInvoiceForm->getData()->getHousenumber() . ', ' $editInvoiceForm->getData()->getZipCode() . ', ' .
  611.               $editInvoiceForm->getData()->getCity() . ', ' $editInvoiceForm->getData()->getCountry() . "\n";
  612.               foreach ($supplier->getUser() as $user)
  613.               {
  614.                 $salutation null;
  615.                 if ($user->getSalutation() == 0)
  616.                 {
  617.                   $salutation "Herr";
  618.                 } elseif ($user->getSalutation() == 1) {
  619.                   $salutation "Frau";
  620.                 } elseif ($user->getSalutation() == 2) {
  621.                   $salutation "Divers";
  622.                 }
  623.                 $notice $notice 'Ansprechpartner: ' ' ' $salutation $user->getFirstname() . ' ' $user->getLastname() . ', ' $user->getEmail() . ', ' $user->getPhone() . ', ' $user->getMobile() .
  624.                 ', ' $user->getNotice() . ', ' $user->getFunction() . "\n";
  625.               }
  626.               $todos->setNotice($notice);
  627.               $em->persist($todos);
  628.               $em->flush();
  629.               $this->addFlash('success'$translator->trans('customer.supplier_edit'));
  630.               return $this->redirectToRoute('supplier_index');
  631.             } else {
  632.               $exists $em->getRepository(Supplier::class)->findOneBy(['companyName' => $supplier->getCompanyName()]);
  633.               $addressExists $em->getRepository(AddressSupplier::class)->findOneBy(['street' => $supplier->getAddressSupplier()->getStreet(),
  634.               'houseNumber' => $supplier->getAddressSupplier()->getHouseNumber(), 'zipCode' => $supplier->getAddressSupplier()->getZipCode(),
  635.               'city' => $supplier->getAddressSupplier()->getCity()]);
  636.               if ($exists != null && $addressExists != null && $exists != $supplier)
  637.               {
  638.                 $editForm->get('companyName')->addError(new FormError($translator->trans('supplier.formDuplicateName')));
  639.                 $editForm->get('addressSupplier')->get('street')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  640.                 $editForm->get('addressSupplier')->get('houseNumber')->addError(new FormError(""));
  641.                 $editForm->get('addressSupplier')->get('zipCode')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  642.                 $editForm->get('addressSupplier')->get('city')->addError(new FormError($translator->trans('supplier.formDuplicateAddress')));
  643.               } elseif(strpos($supplier->getCompanyName(), '?') || strpos($supplier->getCompanyName(), '/') ||
  644.               strpos($supplier->getCompanyName(), '\\') || strpos($supplier->getCompanyName(), '^') ||
  645.               strpos($supplier->getCompanyName(), '|') || strpos($supplier->getCompanyName(), ';') !== false ) {
  646.                 $editForm->get('companyName')->addError(new FormError($translator->trans('supplier.illegalCharacters')));
  647.               } else {
  648.                 $data $editForm->get('users')->getData()->getValues();
  649.                 $newUsers = array();
  650.                 foreach ($data as $user)
  651.                 {
  652.                     if ($user->getId() == null)
  653.                     {
  654.                         $dbUser $em->getRepository(User::class)->findOneBy(['email' => $user->getEmail()]);
  655.                         if ($user->getEmail() == null)
  656.                         {
  657.                             $supplier->removeUser($user);
  658.                             $em->remove($user);
  659.                             $em->flush();
  660.                             continue;
  661.                         }
  662.                         if ($dbUser != null)
  663.                         {
  664.                             if ($dbUser->getSupplier() != null)
  665.                             {
  666.                                 $dbUser->addUserSupplierList($supplier);
  667.                                 $em->persist($dbUser);
  668.                                 $em->flush();
  669.                                 $em->remove($user);
  670.                                 $em->flush();
  671.                                 array_push($newUsers$dbUser);
  672.                             } else {
  673.                                 $this->addFlash('error''Es gibt bereits einen Benutzer mit dieser E-Mail und dieser ist einem Kunden zugewiesen. E-Mail: ' $user->getEmail());
  674.                                 throw new Exception();
  675.                             }
  676.                         } else {
  677.                             if ($user->getRoles() === null && $user->getUserStatus() === null)
  678.                             {
  679.                                 $user->setRoles($role);
  680.                                 $user->setUserStatus($status);
  681.                                 $user->setActive(1);
  682.                                 $user->addUserSupplierList($supplier);
  683.                                 $em->persist($user);
  684.                                 array_push($newUsers$user);
  685.                             }
  686.                         }
  687.                     } else {
  688.                         $dbUser $em->getRepository(User::class)->findOneBy(['email' => $user->getEmail()]);
  689.                         if ($dbUser != null && $dbUser->getId() != $user->getId())
  690.                         {
  691.                             if ($dbUser->getSupplier() != null)
  692.                             {
  693.                                 $this->addFlash('error''Es gibt bereits einen Benutzer mit dieser Email, falls das die selben sind, dann bitte hier löschen und neu anlegen. E-Mail: ' $user->getEmail());
  694.                                 throw new Exception();
  695.                             } else {
  696.                                 $this->addFlash('error''Es gibt bereits einen Benutzer mit dieser Email der einem Lieferanten zugeordnet ist, deswegen kann er keinem Kunden zugeordnet werden. E-Mail: ' $user->getEmail());
  697.                                 throw new Exception();
  698.                             }
  699.                         } else {
  700.                             array_push($newUsers$user);
  701.                         }
  702.                     }
  703.                 }
  704.                 $em->flush();
  705.                 $savedRelations = array();
  706.                 $savedSubsidiaryRelations = array();
  707.                 $parentCompanys $request->request->get('ParentCompanys');
  708.                 if ($parentCompanys != "" || $parentCompanys != null)
  709.                 {
  710.                   foreach ($parentCompanys as $item)
  711.                   {
  712.                     $parentId substr($item1);
  713.                     if(substr($item,0,1) == 'c')
  714.                     {
  715.                       $parent $em->getRepository(Customer::class)->findOneBy(['id' => $parentId]);
  716.                       $exists $em->getRepository(CompanyRelations::class)->findOneBy(['cm' => $parent'ss' => $supplier]);
  717.                       if ($exists == null)
  718.                       {
  719.                         $parentCompanyRelation = new CompanyRelations();
  720.                         $parentCompanyRelation->setCm($em->getRepository(Customer::class)->findOneBy(['id' => $parentId]));
  721.                         $parentCompanyRelation->setSs($supplier);
  722.                         $em->persist($parentCompanyRelation);
  723.                       }
  724.                       if (isset($parentCompanyRelation))
  725.                       {
  726.                         array_push($savedRelations$parentCompanyRelation);
  727.                       } elseif ($exists != null) {
  728.                         array_push($savedRelations$exists);
  729.                       }
  730.                     }
  731.                     else if(substr($item,0,1) == 's')
  732.                     {
  733.                       $parent $em->getRepository(Supplier::class)->findOneBy(['id' => $parentId]);
  734.                       $exists $em->getRepository(CompanyRelations::class)->findOneBy(['sm' => $parent'ss' => $supplier]);
  735.                       if ($exists == null)
  736.                       {
  737.                         $subsidiaryCompanyRelation = new CompanyRelations();
  738.                         $subsidiaryCompanyRelation->setSm($em->getRepository(Supplier::class)->findOneBy(['id' => $parentId]));
  739.                         $subsidiaryCompanyRelation->setSs($supplier);
  740.                         $em->persist($subsidiaryCompanyRelation);
  741.                       }
  742.                       if (isset($parentCompanyRelation))
  743.                       {
  744.                         array_push($savedRelations$parentCompanyRelation);
  745.                       } elseif ($exists != null) {
  746.                         array_push($savedRelations$exists);
  747.                       }
  748.                     }
  749.                   }
  750.                 }
  751.                 foreach ($oldParents as $key => $oldParent)
  752.                 {
  753.                   foreach ($savedRelations as $savedRelation)
  754.                   {
  755.                     if ($oldParent instanceof Customer)
  756.                     {
  757.                       if ($savedRelation->getCm() == $oldParent)
  758.                       {
  759.                         unset($oldParents[$key]);
  760.                       }
  761.                     } elseif ($oldParent instanceof Supplier) {
  762.                       if ($savedRelation->getSm() == $oldParent)
  763.                       {
  764.                         unset($oldParents[$key]);
  765.                       }
  766.                     }
  767.                   }
  768.                 }
  769.                 if (!empty($oldParents))
  770.                 {
  771.                   foreach ($oldParents as $oldParent)
  772.                   {
  773.                     if ($oldParent instanceof Customer)
  774.                     {
  775.                       $removeParent $em->getRepository(CompanyRelations::class)->findOneBy(['cm' => $oldParent'ss' => $supplier]);
  776.                       if ($removeParent != null)
  777.                       {
  778.                         $em->remove($removeParent);
  779.                       }
  780.                     } elseif ($oldParent instanceof Supplier) {
  781.                       $removeParent $em->getRepository(CompanyRelations::class)->findOneBy(['sm' => $oldParent'ss' => $supplier]);
  782.                       if ($removeParent != null)
  783.                       {
  784.                         $em->remove($removeParent);
  785.                       }
  786.                     }
  787.                   }
  788.                 }
  789.                 $subsidiaryCompanys $request->request->get('SubsidiaryCompanys');
  790.                 if ($subsidiaryCompanys != "" || $subsidiaryCompanys != null)
  791.                 {
  792.                   foreach ($subsidiaryCompanys as $item)
  793.                   {
  794.                     $subsidiaryId substr($item1);
  795.                     if(substr($item0,1) == 'c')
  796.                     {
  797.                       $subsidiary $em->getRepository(Customer::class)->findOneBy(['id' => $subsidiaryId]);
  798.                       $exists $em->getRepository(CompanyRelations::class)->findOneBy(['cs' => $subsidiary'sm' => $supplier]);
  799.                       if ($exists == null)
  800.                       {
  801.                         $subsidiaryCompanyRelation = new CompanyRelations();
  802.                         $subsidiaryCompanyRelation->setCs($em->getRepository(Customer::class)->findOneBy(['id' => $subsidiaryId]));
  803.                         $subsidiaryCompanyRelation->setSm($supplier);
  804.                         $em->persist($subsidiaryCompanyRelation);
  805.                       }
  806.                       if (isset($subsidiaryCompanyRelation))
  807.                       {
  808.                         array_push($savedSubsidiaryRelations$subsidiaryCompanyRelation);
  809.                       } elseif ($exists != null) {
  810.                         array_push($savedSubsidiaryRelations$exists);
  811.                       }
  812.                     }
  813.                     else if(substr($item0,1) == 's')
  814.                     {
  815.                       $subsidiary $em->getRepository(Supplier::class)->findOneBy(['id' => $subsidiaryId]);
  816.                       $exists $em->getRepository(CompanyRelations::class)->findOneBy(['ss' => $subsidiary'sm' => $supplier]);
  817.                       if ($exists == null)
  818.                       {
  819.                         $subsidiaryCompanyRelation = new CompanyRelations();
  820.                         $subsidiaryCompanyRelation->setSs($em->getRepository(Supplier::class)->findOneBy(['id' => $subsidiaryId]));
  821.                         $subsidiaryCompanyRelation->setSm($supplier);
  822.                         $em->persist($subsidiaryCompanyRelation);
  823.                       }
  824.                       if (isset($subsidiaryCompanyRelation))
  825.                       {
  826.                         array_push($savedSubsidiaryRelations$subsidiaryCompanyRelation);
  827.                       } elseif ($exists != null) {
  828.                         array_push($savedSubsidiaryRelations$exists);
  829.                       }
  830.                     }
  831.                   }
  832.                 }
  833.                 foreach ($oldSubsidiarys as $key => $oldSubsidiary)
  834.                 {
  835.                   foreach ($savedSubsidiaryRelations as $savedRelation)
  836.                   {
  837.                     if ($oldSubsidiary instanceof Customer)
  838.                     {
  839.                       if ($savedRelation->getCs() == $oldSubsidiary)
  840.                       {
  841.                         unset($oldSubsidiarys[$key]);
  842.                       }
  843.                     } elseif ($oldSubsidiary instanceof Supplier) {
  844.                       if ($savedRelation->getSs() == $oldSubsidiary)
  845.                       {
  846.                         unset($oldSubsidiarys[$key]);
  847.                       }
  848.                     }
  849.                   }
  850.                 }
  851.                 if (!empty($oldSubsidiarys))
  852.                 {
  853.                   foreach ($oldSubsidiarys as $oldSubsidiary)
  854.                   {
  855.                     if ($oldSubsidiary instanceof Customer)
  856.                     {
  857.                       $removeSubsidiary $em->getRepository(CompanyRelations::class)->findOneBy(['cs' => $oldSubsidiary'sm' => $supplier]);
  858.                       if ($removeSubsidiary != null)
  859.                       {
  860.                         $em->remove($removeSubsidiary);
  861.                       }
  862.                     } elseif ($oldSubsidiary instanceof Supplier) {
  863.                       $removeSubsidiary $em->getRepository(CompanyRelations::class)->findOneBy(['ss' => $oldSubsidiary'sm' => $supplier]);
  864.                       if ($removeSubsidiary != null)
  865.                       {
  866.                         $em->remove($removeSubsidiary);
  867.                       }
  868.                     }
  869.                   }
  870.                 }
  871.                 $savedCustomers = array();
  872.                 $customers $request->request->get('Customers');
  873.                 if ($customers != "" || $customers != null)
  874.                 {
  875.                   foreach ($customers as $customer)
  876.                   {
  877.                     $customerDb $em->getRepository(Customer::class)->findOneBy(['id' => $customer]);
  878.                     $exists $em->getRepository(CustomerSupplierRelation::class)->findOneBy(['customer' => $customerDb'supplier' => $supplier]);
  879.                     if ($exists == null)
  880.                     {
  881.                       $customerSupplierRelation = new CustomerSupplierRelation();
  882.                       $customerSupplierRelation->setSupplier($supplier);
  883.                       $customerSupplierRelation->setCustomer($customerDb);
  884.                       $em->persist($customerSupplierRelation);
  885.                     }
  886.                     if (isset($customerSupplierRelation))
  887.                     {
  888.                       array_push($savedCustomers$customerSupplierRelation);
  889.                     } elseif ($exists != null) {
  890.                       array_push($savedCustomers$exists);
  891.                     }
  892.                   }
  893.                 }
  894.                 foreach ($oldCustomers as $key => $oldCustomer)
  895.                 {
  896.                   foreach ($savedCustomers as $savedCustomer)
  897.                   {
  898.                     if ($savedCustomer->getCustomer() == $oldCustomer)
  899.                     {
  900.                       unset($oldCustomers[$key]);
  901.                     }
  902.                   }
  903.                 }
  904.                 if (!empty($oldCustomers))
  905.                 {
  906.                   foreach ($oldCustomers as $oldCustomer)
  907.                   {
  908.                     $removeCustomer $em->getRepository(CustomerSupplierRelation::class)->findOneBy(['customer' => $oldCustomer'supplier' => $supplier]);
  909.                     if ($removeCustomer != null)
  910.                     {
  911.                       $em->remove($removeCustomer);
  912.                     }
  913.                   }
  914.                 }
  915.                 $supplier->setUpdatedAt(new \DateTime());
  916.                 $supplier->getAddressSupplier()->setUpdatedAt(new \DateTime());
  917.                 foreach ($oldUsers as $key => $oldUser)
  918.                 {
  919.                   foreach ($newUsers as $newUser)
  920.                   {
  921.                     if ($newUser == $oldUser)
  922.                     {
  923.                       unset($oldUsers[$key]);
  924.                     }
  925.                   }
  926.                 }
  927.                 if (!empty($oldUsers))
  928.                 {
  929.                   $deactivatedStatus $em->getRepository(\App\Entity\UserStatus::class)->findOneBy(['id' => 4]);
  930.                   foreach ($oldUsers as $oldUser)
  931.                   {
  932.                     $tmpUser $em->getRepository(\App\Entity\User::class)->findOneBy(['id' => $oldUser->getId()]);
  933.                     $csr $tmpUser->getCsr();
  934.                     foreach ($csr as $item)
  935.                     {
  936.                         $tmpUser->removeCsr($item);
  937.                     }
  938.                     if (count($tmpUser->getUserSupplierList()->getValues()) <= 1)
  939.                     {
  940.                         if ($tmpUser != null)
  941.                         {
  942.                             $tmpUser->setActive(0);
  943.                             $tmpUser->setNotice($tmpUser->getNotice() . "\n" "E-mail: " $tmpUser->getEmail() . "\n" .
  944.                                 "Supplier: " $supplier->getCompanyName() . "\n" "Supplier-ID: " $supplier->getId());
  945.                             $tmpUser->setEmail(NULL);
  946.                             $tmpUser->setUserStatus($deactivatedStatus);
  947.                             $tmpUser->setSupplier(null);
  948.                             $tmpUser->removeUserSupplierList($supplier);
  949.                         }
  950.                     } else {
  951.                         if ($tmpUser->getSupplier() == $supplier)
  952.                         {
  953.                             $tmpUser->setSupplier(null);
  954.                         }
  955.                         $tmpUser->removeUserSupplierList($supplier);
  956.                     }
  957.                     $em->persist($tmpUser);
  958.                     $em->flush();
  959.                   }
  960.                 }
  961.                 if ($invoiceAddress->getStreet() == null && $invoiceAddress->getHouseNumber() == null && $invoiceAddress->getZipCode() == null && $invoiceAddress->getCity() == null)
  962.                 {
  963.                   $invoiceAddress->setStreet($supplier->getAddressSupplier()->getStreet());
  964.                   $invoiceAddress->setHouseNumber($supplier->getAddressSupplier()->getHouseNumber());
  965.                   $invoiceAddress->setZipCode($supplier->getAddressSupplier()->getZipCode());
  966.                   $invoiceAddress->setCity($supplier->getAddressSupplier()->getCity());
  967.                   $invoiceAddress->setCountry($supplier->getAddressSupplier()->getCountry());
  968.                 }
  969.                 if ($supplier->getAddressSupplier()->getSupplier() == null)
  970.                 {
  971.                   $supplier->getAddressSupplier()->setSupplier($supplier);
  972.                 }
  973.                 $supplier->getAddressSupplier()->setType('company');
  974.                 if ($invoiceAddress->getSupplier() == null)
  975.                 {
  976.                   $invoiceAddress->setSupplier($supplier);
  977.                 }
  978.                 $invoiceAddress->setUpdatedAt(new \DateTime());
  979.                 $invoiceAddress->setType('invoice');
  980.                 $this->doctrine->getManager()->flush();
  981.                 $em->persist($invoiceAddress);
  982.                 $em->flush();
  983.                 $this->addFlash('success'$translator->trans('supplier.update_success'));
  984.                 $this->dbLogger->info('Edit Supplier', [
  985.                   'other' => $supplier,
  986.                   'route' => $request->get('_route')
  987.                 ]);
  988.                 return $this->redirectToRoute('supplier_index');
  989.               }
  990.             }
  991.           } catch (\Exception $exception) {
  992.               if ($exception->getMessage() === "")
  993.               {
  994.               } else {
  995.                   $this->addFlash('error'$translator->trans('supplier.update_error'));
  996.                   $logger->error('Error while Admin edit Supplier', ['e' => $exception]);
  997.                   //                $this->dbLogger->error('Error when editing supplier', [
  998.                   //                    'other' => $supplier,
  999.                   //                    'route' => $request->get('_route'),
  1000.                   //                ]);
  1001.               }
  1002.           }
  1003.         }
  1004.         return $this->render('supplier/supplier.html.twig', array(
  1005.           'supplier' => $supplier,
  1006.           'form' => $editForm->createView(),
  1007.           'errors' => $errors,
  1008.           'companys' => $companysList,
  1009.           'invoiceForm' => $editInvoiceForm->createView(),
  1010.           'linkedParentCompanys' => $linkedParentCompanys,
  1011.           'linkedSubsidiaryCompanys' => $linkedSubsidiaryCompanys,
  1012.           'companysListWihtoutParent' => $companysListWihtoutParent,
  1013.           'companysListWihtoutSubsidiary' => $companysListWihtoutSubsidiary,
  1014.           'oldCustomers' => $oldCustomers,
  1015.           'customersList' => $customerList,
  1016.           'helpdesk' => $helpdesk,
  1017.         ));
  1018.       }
  1019.     /**
  1020.      * @Route("/view/{id}", name="supplier_view")
  1021.      * @param $supplier
  1022.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  1023.      */
  1024.     public function viewAction(
  1025.         TranslatorInterface $translator,
  1026.         Supplier $supplier null,
  1027.         Request $request,
  1028.         UserPermissionService $userPermissionService
  1029.     )
  1030.     {
  1031.         $headerTitle $supplier->getCompanyName();
  1032.         $request->attributes->set('headerTitle'$headerTitle);
  1033.         if (!$supplier) {
  1034.             $this->addFlash('error'$translator->trans('supplier.not_exist'));
  1035.             return $this->redirectToRoute('supplier_index');
  1036.         }
  1037.         $em $this->doctrine->getManager();
  1038.         $helpdesk $em->getRepository(\App\Entity\HelpDesk::class)->findOneBy(["controller" => $request->get('_route'), "roles"=>$this->getUser()->getRoles(), "language"=>$request->getLocale()]);
  1039.         if ($userPermissionService->checkSupplierPermission('view_suppliers'$this->getUser(), $supplier));
  1040.         else if ($userPermissionService->checkUserPermission('view_all_suppliers'$this->getUser()) );
  1041.         else {
  1042.             $this->addFlash('error'$translator->trans('not_permitted'));
  1043.             return $this->redirectToRoute('supplier_index');
  1044.         }
  1045.         $address $em->getRepository(AddressSupplier::class)->findOneBy(['supplier' => $supplier'type' => 'company']);
  1046.         $invoiceAddress $em->getRepository(AddressSupplier::class)->findOneBy(['supplier' => $supplier'type' => 'invoice']);
  1047.         $reportPeriod $em->getRepository(ReportingPeriod::class)->findBy(['supplier' => $supplier]);
  1048.         $customer_supplier $em->getRepository(CustomerSupplierRelation::class)->findBy(['supplier' => $supplier]);
  1049.         $customer $em->getRepository(Customer::class)->findBy(['id' => $customer_supplier]);
  1050. //        $user = $em->getRepository(User::class)->findBy(['supplier' => $supplier, 'active' => 1]);
  1051.         $user $supplier->getUsers()->getValues();
  1052.         $reportReleases $em->getRepository(ReportRelease::class)->findBy(['supplier' => $supplier]);
  1053.         $invoicelist = array();
  1054.         $parentCompanys $em->getRepository(CompanyRelations::class)->findBy(['ss' => $supplier]);
  1055.         $subsidiaryCompanys $em->getRepository(CompanyRelations::class)->findBy(['sm' => $supplier]);
  1056.         $existScRelation null;
  1057.         $existCustomer $this->getUser()->getCustomer();
  1058.         if ($existCustomer != null)
  1059.         {
  1060.             $existScRelation $em->getRepository(\App\Entity\CustomerSupplierRelation::class)->findOneBy(['supplier' => $supplier'customer' => $existCustomer]);
  1061.         }
  1062.         if ($existScRelation == null && ($this->getUser()->getRole()->getId() != User::ROLE_SUPER_ADMIN && $this->getUser()->getRole()->getId() != User::ROLE_ADMIN) && $supplier != $this->getUser()->getSupplier())
  1063.         {
  1064.             $this->addFlash('warning'$translator->trans('error.not_permitted'));
  1065.             return $this->redirectToRoute('supplier_index');
  1066.         } else {
  1067.             foreach ($reportReleases as $release)
  1068.             {
  1069.                 for ($i=1;$i<=5;$i++)
  1070.                 {
  1071.                     $func 'getYear'.$i;
  1072.                     if ($release->getReport()->$func() == null && $i 0//last year!!!!!!
  1073.                     {
  1074.                         $invoice $em->getRepository(InvoiceList::class)->findOneBy(['reportrelease' => $release]);
  1075.                         if ($invoice != null)
  1076.                         {
  1077.                             array_push($invoicelist$invoice);
  1078.                             break;
  1079.                         }
  1080.                     }
  1081.                 }
  1082.             }
  1083.             $calculations = array();
  1084.             $reportPeriods = array();
  1085.             foreach ($reportPeriod as $item) {
  1086.                 $calculation $em->getRepository(Calculations::class)->findOneBy(['reportPeriodId' => $item->getId()]);
  1087.                 if ($calculation != null)
  1088.                 {
  1089.                     array_push($calculations$calculation);
  1090.                     if ($calculation->getAnalysis() != null) {
  1091.                         if ($calculation->getAnalysis()->getCommentAndOutlook() != null && $calculation->getAnalysis()->getCommentAndOutlookDe() != null) {
  1092.                             array_push($reportPeriods, [$item"calc" => true'analysis' => "en/de"]);
  1093.                         } else {
  1094.                             if ($calculation->getAnalysis()->getCommentAndOutlook() != null) {
  1095.                                 array_push($reportPeriods, [$item"calc" => true'analysis' => "en"]);
  1096.                             } elseif ($calculation->getAnalysis()->getCommentAndOutlookDe() != null) {
  1097.                                 array_push($reportPeriods, [$item"calc" => true'analysis' => "de"]);
  1098.                             } else {
  1099.                                 array_push($reportPeriods, [$item"calc" => true'analysis' => ""]);
  1100.                             }
  1101.                         }
  1102.                     }else {
  1103.                         array_push($reportPeriods, [$item"calc" => true'analysis' => false]);
  1104.                     }
  1105.                 } else {
  1106.                     array_push($reportPeriods, [$item,"calc" => false'analysis' => false]);
  1107.                 }
  1108.             }
  1109.             // Get all Report from the supplier
  1110.             $reports $em->getRepository(Report::class)->findBy(['supplier' => $supplier'active' => 1]);
  1111.             $test = array();
  1112.             foreach ($reportPeriod as $data)
  1113.             {
  1114.                 $test[$data->getId()] = $data->getId();
  1115.             }
  1116.             //        for ($i = 0; $i < count($reportPeriod); $i++)
  1117.             //        {
  1118.             //            array_push($test, $reportPeriod[$i]->getId());
  1119.             //        }
  1120.             $oldCSRs = array();
  1121.             $tmpTest null;
  1122.             $newUserList = array();
  1123.             foreach ($user as $item)
  1124.             {
  1125.                 $tmpOldCsr = array();
  1126.                 $oldCustomers = array();
  1127.                 $customerList = array();
  1128.                 $csrForOldCustomers = array();
  1129.                 foreach ($item->getCsr() as $oldCSR)
  1130.                 {
  1131.                     if ($oldCSR->getSupplier() == $supplier)
  1132.                     {
  1133.                         array_push($csrForOldCustomers$oldCSR);
  1134.                     }
  1135.                 }
  1136.                 foreach ($item->getCsr()->getValues() as $tmpItem)
  1137.                 {
  1138.                     array_push($tmpOldCsr$tmpItem);
  1139.                 }
  1140.                 foreach ($csrForOldCustomers as $csrForOldCustomer)
  1141.                 {
  1142.                     array_push($oldCustomers$csrForOldCustomer->getCustomer());
  1143.                 }
  1144.                 foreach ($customer_supplier as $key => $csRelation)
  1145.                 {
  1146.                     if (!in_array($csRelation->getCustomer(), $customerList) && !in_array($csRelation->getCustomer(), $oldCustomers))
  1147.                     {
  1148.                         array_push($customerList$csRelation->getCustomer());
  1149.                     }
  1150.                 }
  1151.                 if ($this->getUser()->getRole()->getId() == User::ROLE_CUSTOMER)
  1152.                 {
  1153.                     if (in_array($item$existScRelation->getUsers()->getValues()))
  1154.                     {
  1155.                         array_push($newUserList, [$item$tmpOldCsr$oldCustomers$customerList]);
  1156.                     }
  1157.                 } else {
  1158.                     array_push($newUserList, [$item$tmpOldCsr$oldCustomers$customerList]);
  1159.                 }
  1160.             }
  1161.             $formBuilderCustomer $this->get('form.factory')->createNamedBuilder('addCustomer');
  1162.             if ($this->getUser()->getRole()->getId() == User::ROLE_SUPER_ADMIN || $this->getUser()->getRole()->getId() == User::ROLE_ADMIN)
  1163.             {
  1164.                 foreach ($user as $item)
  1165.                 {
  1166.                     $formBuilderCustomer->add('submit'.$item->getId(), SubmitType::class,['label' => 'submit']);
  1167.                 }
  1168.             }
  1169.             $formCustomer $formBuilderCustomer->getForm();
  1170.             $formCustomer->handleRequest($request);
  1171.             $formBuilder $this->createFormBuilder();
  1172.             foreach ($reportPeriods as $item)
  1173.             {
  1174.                 $formBuilder->add('reportPeriod'.$item[0]->getId(), CheckboxType::class, ['required' => false'data' => false'value' => $item[0]->getId(), 'label' => false]);
  1175.             }
  1176.             $formBuilder->add('submitReportPeriod'SubmitType::class,['label' => 'supplier.newReportPeriod']);
  1177.             $formBuilder->add('editReportPeriod'SubmitType::class,['label' => 'supplier.editReportPeriod']);
  1178.             $formBuilder->add('viewReportPeriod'SubmitType::class,['label' => 'supplier.viewReportPeriod']);
  1179.             $formBuilder->add('submitCalculation'SubmitType::class,['label' => 'supplier.submitCalculation']);
  1180.             $formBuilder->add('submitReport'SubmitType::class,['label' => 'supplier.createReport']);
  1181.             $form $formBuilder->getForm();
  1182.             $form->handleRequest($request);
  1183.             $scRelationFormBuilder $this->createFormBuilder();
  1184.             foreach ($customer_supplier as $item)
  1185.             {
  1186.                 if($item->getCustomer() != null)
  1187.                 {
  1188.                     $scRelationFormBuilder->add('supplierNumber'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getSupplierNumber()]);
  1189.                     $scRelationFormBuilder->add('purchaseVolume'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getPurchaseVolume()]);
  1190.                     $scRelationFormBuilder->add('status'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getStatus()]);
  1191.                     $scRelationFormBuilder->add('productGroups'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getProductGroups()]);
  1192.                     $scRelationFormBuilder->add('openField1'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getOpenfield1()]);
  1193.                     $scRelationFormBuilder->add('openField2'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getOpenfield2()]);
  1194.                     $scRelationFormBuilder->add('openField3'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getOpenfield3()]);
  1195.                     $scRelationFormBuilder->add('openField4'.$item->getCustomer()->getId(), TextType::class, ['required' => false'data' => $item->getOpenfield4()]);
  1196.                     $scRelationFormBuilder->add('submit'.$item->getCustomer()->getId(), SubmitType::class,['label' => 'submit']);
  1197.                 }
  1198.             }
  1199.             $scRelationForm $scRelationFormBuilder->getForm();
  1200.             $scRelationForm->handleRequest($request);
  1201.             if($form->isSubmitted() && $form->isValid())
  1202.             {
  1203.                 if ($form->getClickedButton()->getName() == 'submitCalculation')
  1204.                 {
  1205.                     $ids = array();
  1206.                     $i 1;
  1207.                     $uri "";
  1208.                     $data $form->all();
  1209.                     foreach ($data as $item) {
  1210.                         if (substr($item->getName(), 012) == 'reportPeriod')
  1211.                         {
  1212.                             if ($item->getData() == true)
  1213.                             {
  1214.                                 $ids['id'.$i] = $item->getViewData();
  1215.                                 $i++;
  1216.                             }
  1217.                         } elseif (substr($item->getName(), 011) == 'calculation')
  1218.                         {
  1219.                         }
  1220.                     }
  1221.                     return $this->redirectToRoute('calculation_edit'$ids);
  1222.                 } elseif ($form->getClickedButton()->getName() == 'submitReport')
  1223.                 {
  1224.                     try {
  1225.                         $requestedLanguage $request->get('reportLanguage');
  1226.                         $data $form->getData();
  1227.                         $i 1;
  1228.                         $points = array();
  1229.                         $newReport = new Report();
  1230.                         //Sorty by Year
  1231.                         foreach ($reportPeriod as $key => $row)
  1232.                         {
  1233. //                    $sortedReportPeriods[$key] = $row->getYear();
  1234.                             $sortedReportPeriods[$key] = $row->getDeadline();
  1235.                         }
  1236.                         array_multisort($sortedReportPeriodsSORT_ASC$reportPeriod);
  1237.                         foreach ($reportPeriod as $key => $item)
  1238.                         {
  1239.                             if ($data['reportPeriod' $item->getId()] == true)
  1240.                             {
  1241.                                 $calculationDB $em->getRepository(\App\Entity\Calculations::class)->findOneBy(['reportPeriodId' => $item]);
  1242.                                 if ($calculationDB === null) {
  1243.                                     continue;
  1244.                                 }
  1245.                                 $reportData = new ReportData();
  1246.                                 $reportData->setNetSales($item->getNetSales());
  1247.                                 $reportData->setAmortizationOfAvIncludingGoodwill($item->getAmortizationOfAvIncludingGoodwill());
  1248.                                 $reportData->setInterestIncome($item->getInterestIncome());
  1249.                                 $reportData->setInterestExpenses($item->getInterestExpenses());
  1250.                                 $reportData->setTaxesOnIncomeAndEarnings($item->getTaxesOnIncomeAndEarnings());
  1251.                                 $reportData->setProfitAfterTax($item->getProfitAfterTax());
  1252.                                 $reportData->setExtraordinaryIncome($item->getExtraordinaryIncome());
  1253.                                 $reportData->setCheckoutBank($item->getCheckoutBank());
  1254.                                 $reportData->setTradeReceivables($item->getTradeReceivables());
  1255.                                 $reportData->setInventory($item->getInventory());
  1256.                                 $reportData->setReceivablesToShareholders($item->getReceivablesToShareholders());
  1257.                                 $reportData->setReceivablesAffiliatedCompaniesParticipating($item->getReceivablesAffiliatedCompaniesParticipating());
  1258.                                 $reportData->setOtherCurrentAssets($item->getOtherCurrentAssets());
  1259.                                 $reportData->setCurrentAssets($item->getCurrentAssets());
  1260.                                 $reportData->setPropertyPlantAndEquipment($item->getPropertyPlantAndEquipment());
  1261.                                 $reportData->setGoodwill($item->getGoodwill());
  1262.                                 $reportData->setOtherIntangibleAssets($item->getOtherIntangibleAssets());
  1263.                                 $reportData->setSharesAffiliatedCompaniesParticipations($item->getSharesAffiliatedCompaniesParticipations());
  1264.                                 $reportData->setLoansAffiliatedCompaniesParticipations($item->getLoansAffiliatedCompaniesParticipations());
  1265.                                 $reportData->setOtherNonCurrentAssets($item->getOtherNonCurrentAssets());
  1266.                                 $reportData->setTradePayables($item->getTradePayables());
  1267.                                 $reportData->setOtherCurrentLiabilities($item->getOtherCurrentLiabilities());
  1268.                                 $reportData->setAdvancePaymentsReceivedForOrders($item->getAdvancePaymentsReceivedForOrders());
  1269.                                 $reportData->setCurrentShareholderLoans($item->getCurrentShareholderLoans());
  1270.                                 $reportData->setLiabilitiesAffiliatedCompaniesParticipations($item->getLiabilitiesAffiliatedCompaniesParticipations());
  1271.                                 $reportData->setCurrentBankDebt($item->getCurrentBankDebt());
  1272.                                 $reportData->setCurrentLiabilities($item->getCurrentLiabilities());
  1273.                                 $reportData->setNonCurrentBankDebt($item->getNonCurrentBankDebt());
  1274.                                 $reportData->setNonCurrentShareholderLoans($item->getNonCurrentShareholderLoans());
  1275.                                 $reportData->setNonCurrentLiabilitiesAffiliatedCompaniesParticipations($item->getNonCurrentLiabilitiesAffiliatedCompaniesParticipations());
  1276.                                 $reportData->setAccrualsForPensions($item->getAccrualsForPensions());
  1277.                                 $reportData->setOtherProvisions($item->getOtherProvisions());
  1278.                                 $reportData->setOtherNonCurrentLiabilities($item->getOtherNonCurrentLiabilities());
  1279.                                 $reportData->setNonCurrentLiabilities($item->getNonCurrentLiabilities());
  1280.                                 $reportData->setEquity($item->getEquity());
  1281.                                 $reportData->setYear($item->getYear());
  1282.                                 $reportData->setChangeInInventories($item->getChangeInInventories());
  1283.                                 $reportData->setReturnOnSales($calculationDB->getReturnOnSales());
  1284.                                 $reportData->setGearing($calculationDB->getGearing());
  1285.                                 $reportData->setLiquidity3Grade($calculationDB->getLiquidity3Grade());
  1286.                                 if ($calculationDB->getOperativeCf() != null )
  1287.                                 {
  1288.                                     $reportData->setOperativeCf($calculationDB->getOperativeCf());
  1289.                                 }
  1290.                                 $reportData->setEbitdaMarge($calculationDB->getEbitdaMarge());
  1291.                                 $reportData->setDso($calculationDB->getDso());
  1292.                                 $reportData->setFinanceVerbQuote($calculationDB->getFinanceVerbQuote());
  1293.                                 $reportData->setBankDebtInPercent($calculationDB->getBankDebtInPercent());
  1294.                                 $reportData->setLiabilitiesToShareholderInPercent($calculationDB->getVerbSocietyIn());
  1295.                                 $reportData->setLiabilitiesAffiliatedCompaniesParticipationsInPercent($calculationDB->getLiabilitiesAffiliatedCompaniesParticipationsInPercent());
  1296.                                 $reportData->setInterestCoverage($calculationDB->getInterestCoverage());
  1297.                                 $reportData->setPropertyPlantAndIntensity($calculationDB->getPropertyPlantAndIntensity());
  1298.                                 $reportData->setAssetCoverage($calculationDB->getAssetCoverage());
  1299.                                 $reportData->setInventoryIntensity($calculationDB->getInventoryIntensity());
  1300.                                 $reportData->setWorkingCapitalRatio($calculationDB->getWorkingCapitalRatio());
  1301.                                 $reportData->setTradeWorkingCapital($calculationDB->getTradeWorkingCapital());
  1302.                                 $reportData->setGoodwillCoverageEk($calculationDB->getGoodwillCoverageEk());
  1303.                                 $reportData->setEbitda($calculationDB->getEbitda());
  1304.                                 $reportData->setEbitMarge($calculationDB->getEbitMarge());
  1305.                                 $reportData->setEbtMarge($calculationDB->getEbtMarge());
  1306.                                 $reportData->setBalanceSheet($calculationDB->getBalanceSheet());
  1307.                                 $reportData->setShareholderLoanAndGroup($calculationDB->getShareholderLoanAndGroup());
  1308.                                 if ($calculationDB->getNotationForReport() != null)
  1309.                                 {
  1310.                                     $reportData->setRiskGrade($calculationDB->getNotationForReport());
  1311.                                 } else {
  1312.                                     $reportData->setRiskGrade($calculationDB->getRiskRating());
  1313.                                 }
  1314.                                 if ($calculationDB->getNotationGFDForReport() != null)
  1315.                                 {
  1316.                                     $reportData->setRiskGradeZf($calculationDB->getNotationGFDForReport());
  1317.                                 } else {
  1318.                                     $reportData->setRiskGradeZf($calculationDB->getZfRiskRating());
  1319.                                 }
  1320.                                 $reportData->setRiskGradeGfd($calculationDB->getRiskNoteWithGFD());
  1321.                                 $reportData->setRiskGradeZfGfd($calculationDB->getZfGFDRiskRating());
  1322.                                 $reportData->setSupplier($supplier);
  1323.                                 $reportData->setEquityRatio($calculationDB->getEquityRatio());
  1324.                                 $reportData->setVerbSocietyIn($calculationDB->getVerbSocietyIn());
  1325.                                 $reportData->setVerbInterCompany($calculationDB->getVerbInterCompany());
  1326.                                 $reportData->setOtherLiabilities($calculationDB->getOtherLiabilities());
  1327.                                 $reportData->setBankLiabilitiesIn($calculationDB->getBankLiabilitiesIn());
  1328.                                 $reportData->setNetDebtToEbitda($calculationDB->getNetDebtToEbitda());
  1329.                                 $reportData->setDih($calculationDB->getDih());
  1330.                                 $reportData->setDpoMaterialCost($calculationDB->getDpoMaterialCost());
  1331.                                 $reportData->setNetInvestments($calculationDB->getNetInvestments()!=null $calculationDB->getNetInvestments() : 0);
  1332.                                 $reportData->setDepreciation($calculationDB->getDepreciation());
  1333.                                 $period null;
  1334.                                 if ($item->getPeriodFrom() == 1)
  1335.                                 {
  1336.                                     $period $translator->trans('reportingPeriod.jan');
  1337.                                 } elseif ($item->getPeriodFrom() == 2) {
  1338.                                     $period $translator->trans('reportingPeriod.feb');
  1339.                                 } elseif ($item->getPeriodFrom() == 3) {
  1340.                                     $period $translator->trans('reportingPeriod.mar');
  1341.                                 } elseif ($item->getPeriodFrom() == 4) {
  1342.                                     $period $translator->trans('reportingPeriod.apr');
  1343.                                 } elseif ($item->getPeriodFrom() == 5) {
  1344.                                     $period $translator->trans('reportingPeriod.may');
  1345.                                 } elseif ($item->getPeriodFrom() == 6) {
  1346.                                     $period $translator->trans('reportingPeriod.jun');
  1347.                                 } elseif ($item->getPeriodFrom() == 7) {
  1348.                                     $period $translator->trans('reportingPeriod.jul');
  1349.                                 } elseif ($item->getPeriodFrom() == 8) {
  1350.                                     $period $translator->trans('reportingPeriod.aug');
  1351.                                 } elseif ($item->getPeriodFrom() == 9) {
  1352.                                     $period $translator->trans('reportingPeriod.sep');
  1353.                                 } elseif ($item->getPeriodFrom() == 10) {
  1354.                                     $period $translator->trans('reportingPeriod.oct');
  1355.                                 } elseif ($item->getPeriodFrom() == 11) {
  1356.                                     $period $translator->trans('reportingPeriod.nov');
  1357.                                 } elseif ($item->getPeriodFrom() == 12) {
  1358.                                     $period $translator->trans('reportingPeriod.dec');
  1359.                                 }
  1360.                                 if ($item->getPeriodUntil() == 1)
  1361.                                 {
  1362.                                     $period $period " - " $translator->trans('reportingPeriod.jan');
  1363.                                 } elseif ($item->getPeriodUntil() == 2) {
  1364.                                     $period $period " - " $translator->trans('reportingPeriod.feb');
  1365.                                 } elseif ($item->getPeriodUntil() == 3) {
  1366.                                     $period $period " - " $translator->trans('reportingPeriod.mar');
  1367.                                 } elseif ($item->getPeriodUntil() == 4) {
  1368.                                     $period $period " - " $translator->trans('reportingPeriod.apr');
  1369.                                 } elseif ($item->getPeriodUntil() == 5) {
  1370.                                     $period $period " - " $translator->trans('reportingPeriod.may');
  1371.                                 } elseif ($item->getPeriodUntil() == 6) {
  1372.                                     $period $period " - " $translator->trans('reportingPeriod.jun');
  1373.                                 } elseif ($item->getPeriodUntil() == 7) {
  1374.                                     $period $period " - " $translator->trans('reportingPeriod.jul');
  1375.                                 } elseif ($item->getPeriodUntil() == 8) {
  1376.                                     $period $period " - " $translator->trans('reportingPeriod.aug');
  1377.                                 } elseif ($item->getPeriodUntil() == 9) {
  1378.                                     $period $period " - " $translator->trans('reportingPeriod.sep');
  1379.                                 } elseif ($item->getPeriodUntil() == 10) {
  1380.                                     $period $period " - " $translator->trans('reportingPeriod.oct');
  1381.                                 } elseif ($item->getPeriodUntil() == 11) {
  1382.                                     $period $period " - " $translator->trans('reportingPeriod.nov');
  1383.                                 } elseif ($item->getPeriodUntil() == 12) {
  1384.                                     $period =  $period " - " $translator->trans('reportingPeriod.dec');
  1385.                                 }
  1386.                                 $reportData->setPeriod($period);
  1387.                                 $reportData->setActive(1);
  1388.                                 $em->persist($reportData);
  1389.                                 $em->flush();
  1390.                                 if ($calculationDB->getOverridePoint() != null)
  1391.                                 {
  1392.                                     $points[$i] = $calculationDB->getOverridePoint();
  1393.                                 } else {
  1394.                                     $points[$i] = $calculationDB->getPoint();
  1395.                                 }
  1396.                                 if ($points[$i] != null)
  1397.                                 {
  1398.                                     if ($i != 1)
  1399.                                     {
  1400.                                         $trend = ($points[$i] - $points[$i-1]) / $points[$i-1];
  1401.                                         if ($trend != null)
  1402.                                         {
  1403.                                             $newReport->setTrend($trend);
  1404.                                         }
  1405.                                     }
  1406.                                 }
  1407.                                 $func "setYear" $i;
  1408.                                 $newReport->$func($reportData);
  1409.                                 $newReport->setYear($reportData->getYear());
  1410.                                 $newReport->setRiskGrade($reportData->getRiskGrade());
  1411.                                 $newReport->setRiskGradeZf($reportData->getRiskGradeZf());
  1412.                                 $newReport->setSupplier($supplier);
  1413.                                 $newReport->setMonths($item->getMonths());
  1414.                                 $newReport->setReferenceDate($item->getDeadline());
  1415.                                 $newReport->setComment($item->getComment());
  1416.                                 $newReport->setEvaluationDate(new \DateTime());
  1417.                                 $analyst $em->getRepository(\App\Entity\User::class)->findOneBy(['short' => $item->getAnalyst()]);
  1418.                                 $newReport->setAnalyst($analyst);
  1419.                                 $newReport->setAccountingStandard($item->getAccountingStandard());
  1420.                                 $newReport->setQuality($item->getQuality());
  1421.                                 $newReport->setUnit($item->getUnit());
  1422.                                 $newReport->setSalesClass($item->getSalesClass());
  1423.                                 $newReport->setPublicityMandatory($supplier->getPublicityMandatory());
  1424.                                 $newReport->setDocument($item->getDocument());
  1425.                                 $newReport->setEmployees($item->getEmployees());
  1426.                                 $newReport->setCurrency($item->getCurrency());
  1427.                                 $newReport->setActive(1);
  1428.                                 $newReport->setVersion(1);
  1429.                                 $i++;
  1430.                             }
  1431.                         }
  1432.                         if ($calculationDB->getAnalysis() != null)
  1433.                         {
  1434.                             $analysis $em->getRepository(\App\Entity\Analysis::class)->findOneBy(['id' => $calculationDB->getAnalysis()]);
  1435.                             if ($requestedLanguage == 0)
  1436.                             {
  1437.                                 $newReport->setCommentAndOutlookAnalysis($analysis->getCommentAndOutlook());
  1438.                                 $newReport->setBalanceSheetRelationsAnalysis($analysis->getBalanceSheetRelations());
  1439.                                 $newReport->setMarketPositionAndGrowthAnalysis($analysis->getMarketPositionAndGrowth());
  1440.                                 $newReport->setDebtRatioAnalysis($analysis->getDebtRatio());
  1441.                                 $newReport->setTradeWorkingCapitalAnalysis($analysis->getTradeWorkingCapital());
  1442.                                 $newReport->setInvestmentPpeAnalysis($analysis->getInvestmentPpe());
  1443.                                 $newReport->setLanguage(0);
  1444.                             } elseif ($requestedLanguage == 1) {
  1445.                                 $newReport->setCommentAndOutlookAnalysis($analysis->getCommentAndOutlookDe());
  1446.                                 $newReport->setBalanceSheetRelationsAnalysis($analysis->getBalanceSheetRelationsDe());
  1447.                                 $newReport->setMarketPositionAndGrowthAnalysis($analysis->getMarketPositionAndGrowthDe());
  1448.                                 $newReport->setDebtRatioAnalysis($analysis->getDebtRatioDe());
  1449.                                 $newReport->setTradeWorkingCapitalAnalysis($analysis->getTradeWorkingCapitalDe());
  1450.                                 $newReport->setInvestmentPpeAnalysis($analysis->getInvestmentPpeDe());
  1451.                                 $newReport->setLanguage(1);
  1452.                             }
  1453.                         }
  1454.                         $em->persist($newReport);
  1455.                         $em->flush();
  1456.                         $this->addFlash('success''Bericht wurde erfolgreich erstellt');
  1457.                         return $this->redirectToRoute('supplier_view', ['id'=>$supplier->getId()]);
  1458.                     }  catch (\Exception $exception) {
  1459.                         $this->addFlash('error'"No Calc for periods");
  1460.                     }
  1461.                 } elseif ($form->getClickedButton()->getName() == 'submitReportPeriod') {
  1462.                     $ids = array();
  1463.                     $i 1;
  1464.                     $data $form->all();
  1465.                     $ids['supplierId'] = $supplier->getId();
  1466.                     foreach ($data as $item) {
  1467.                         if (substr($item->getName(), 012) == 'reportPeriod')
  1468.                         {
  1469.                             if ($item->getData() == true)
  1470.                             {
  1471.                                 $ids['reportPeriodId'.$i] = $item->getViewData();
  1472.                                 $i++;
  1473.                             }
  1474.                         } elseif (substr($item->getName(), 011) == 'calculation')
  1475.                         {
  1476.                         }
  1477.                     }
  1478.                     return $this->redirectToRoute('reportperiod_new'$ids);
  1479.                 } elseif ($form->getClickedButton()->getName() == 'editReportPeriod') {
  1480.                     $ids = array();
  1481.                     $i 1;
  1482.                     $uri "";
  1483.                     $data $form->all();
  1484.                     foreach ($data as $item) {
  1485.                         if (substr($item->getName(), 012) == 'reportPeriod')
  1486.                         {
  1487.                             if ($item->getData() == true)
  1488.                             {
  1489.                                 $ids['id'.$i] = $item->getViewData();
  1490.                                 $i++;
  1491.                             }
  1492.                         } elseif (substr($item->getName(), 011) == 'calculation')
  1493.                         {
  1494.                         }
  1495.                     }
  1496.                     return $this->redirectToRoute('reportperiod_edit'$ids);
  1497.                 } elseif ($form->getClickedButton()->getName() == 'viewReportPeriod') {
  1498.                     $ids = array();
  1499.                     $i 1;
  1500.                     $uri "";
  1501.                     $data $form->all();
  1502.                     foreach ($data as $item) {
  1503.                         if (substr($item->getName(), 012) == 'reportPeriod')
  1504.                         {
  1505.                             if ($item->getData() == true)
  1506.                             {
  1507.                                 $ids['id'.$i] = $item->getViewData();
  1508.                                 $i++;
  1509.                             }
  1510.                         } elseif (substr($item->getName(), 011) == 'calculation')
  1511.                         {
  1512.                         }
  1513.                     }
  1514.                     return $this->redirectToRoute('reportperiod_view'$ids);
  1515.                 }
  1516.             }
  1517.             if ($scRelationForm->isSubmitted())
  1518.             {
  1519.                 try {
  1520.                     $number substr($scRelationForm->getClickedButton()->getName(), 6);
  1521.                     $scRelationForm->getData();
  1522.                     foreach ($customer_supplier as $item)
  1523.                     {
  1524.                         if ($item->getCustomer()->getId() == $number)
  1525.                         {
  1526.                             $item->setSupplierNumber($scRelationForm->get('supplierNumber'.$item->getCustomer()->getId())->getNormData());
  1527.                             $item->setPurchaseVolume($scRelationForm->get('purchaseVolume'.$item->getCustomer()->getId())->getNormData());
  1528.                             $item->setStatus($scRelationForm->get('status'.$item->getCustomer()->getId())->getNormData());
  1529.                             $item->setProductGroups($scRelationForm->get('productGroups'.$item->getCustomer()->getId())->getNormData());
  1530.                             $item->setOpenfield1($scRelationForm->get('openField1'.$item->getCustomer()->getId())->getNormData());
  1531.                             $item->setOpenfield2($scRelationForm->get('openField2'.$item->getCustomer()->getId())->getNormData());
  1532.                             $item->setOpenfield3($scRelationForm->get('openField3'.$item->getCustomer()->getId())->getNormData());
  1533.                             $item->setOpenfield4($scRelationForm->get('openField4'.$item->getCustomer()->getId())->getNormData());
  1534.                             $em->persist($item);
  1535.                             $em->flush();
  1536.                         }
  1537.                     }
  1538.                     $this->addFlash('success'$translator->trans('supplier.csr_update_success'));
  1539.                     return $this->redirectToRoute('supplier_view', ['id' => $supplier->getId()]);
  1540.                 } catch (Exception $exception) {
  1541.                     $this->addFlash('error'$translator->trans('customer.csr_update_error'));
  1542.                 }
  1543.             }
  1544.             $documents $em->getRepository(\App\Entity\DocumentUser::class)->findBy(['supplier' => $supplier]);
  1545.             $fraDatasheets $em->getRepository(\App\Entity\FraDataSheet::class)->findBy(['supplier' => $supplier]);
  1546.             if ($this->getUser()->getCustomer() != null)
  1547.             {
  1548.                 $releases $em->getRepository(\App\Entity\ReportRelease::class)->customerViewSupplierReportsGrouped($this->getUser()->getCustomer()->getId(), $supplier->getId());
  1549.                 $reportsCustomerData = array();
  1550.                 foreach ($releases as $release)
  1551.                 {
  1552.                     if ($release['supplier'] == $supplier->getId())
  1553.                     {
  1554.                         if ($userPermissionService->checkSupplierPermission('view_reports'$this->getUser(), $release['supplier']))
  1555.                         {
  1556.                             array_push($reportsCustomerData$release);
  1557.                         } else if ($userPermissionService->checkUserPermission('view_all_reports'$this->getUser()))
  1558.                         {
  1559.                             array_push($reportsCustomerData$release);
  1560.                         } else {
  1561.                         }
  1562.                     }
  1563.                 }
  1564.             } else {
  1565.                 $reportsCustomerData null;
  1566.             }
  1567.             $supplierCustomerRelation null;
  1568.             if ($this->getUser()->getCustomer() != null)
  1569.             {
  1570.                 $userCustomer $this->getUser()->getCustomer();
  1571.                 $supplierCustomerRelation $em->getRepository(\App\Entity\CustomerSupplierRelation::class)->findOneBy(['customer' => $userCustomer'supplier' => $supplier]);
  1572.             }
  1573.             $savedCustomers = array();
  1574.             if ($formCustomer->isSubmitted())
  1575.             {
  1576.                 try
  1577.                 {
  1578.                     $number substr($formCustomer->getClickedButton()->getName(), 6);
  1579.                     $changedUser $em->getRepository(\App\Entity\User::class)->findOneBy(['id' => $number]);
  1580.                     $customers $request->request->get('Customers' $changedUser->getId());
  1581.                     $savedCSRs = array();
  1582.                     if ($customers != null)
  1583.                     {
  1584.                         foreach ($customers as $item)
  1585.                         {
  1586.                             $newCustomer $em->getRepository(\App\Entity\Customer::class)->findOneBy(['id' => $item]);
  1587.                             $changedCsRelation $em->getRepository(\App\Entity\CustomerSupplierRelation::class)->findOneBy(['customer' => $newCustomer'supplier' => $supplier]);
  1588.                             $changedUser->addCsr($changedCsRelation);
  1589.                             $em->persist($changedUser);
  1590.                             $em->flush();
  1591.                             array_push($savedCSRs$changedCsRelation);
  1592.                         }
  1593.                         foreach ($oldCSRs as $key => $oldCSR)
  1594.                         {
  1595.                             foreach ($savedCSRs as $item)
  1596.                             {
  1597.                                 if ($item == $oldCSR)
  1598.                                 {
  1599.                                     unset($oldCSRs[$key]);
  1600.                                 }
  1601.                             }
  1602.                         }
  1603.                         if (!empty($oldCSRs))
  1604.                         {
  1605.                             foreach ($oldCSRs as $oldCSR)
  1606.                             {
  1607.                                 $changedUser->removeCsr($oldCSR);
  1608.                                 $em->persist($changedUser);
  1609.                                 $em->flush($changedUser);
  1610.                             }
  1611.                         }
  1612.                     } else {
  1613.                         foreach ($changedUser->getCsr() as $item)
  1614.                         {
  1615.                             $changedUser->removeCsr($item);
  1616.                         }
  1617.                     }
  1618.                     $em->persist($changedUser);
  1619.                     $em->flush();
  1620.                     $this->addFlash('success'$translator->trans('supplier.addCustomer_success'));
  1621.                     return $this->redirectToRoute('supplier_view', ['id' => $supplier->getId()]);
  1622.                 } catch (\Exception $exception) {
  1623.                     $this->addFlash('error'$translator->trans('supplier.addCustomer_error'));
  1624.                 }
  1625.             }
  1626.         }
  1627.         return $this->render('supplier/view.html.twig', [
  1628.             'supplier' => $supplier,
  1629.             'reportPeriods' => $reportPeriods,
  1630.             'customers' => $customer,
  1631.             'form' => $form->createView(),
  1632.             'address' => $address,
  1633.             'contactPerson' => $newUserList,
  1634.             'scRelations' => $customer_supplier,
  1635.             'scRelationForm' => $scRelationForm->createView(),
  1636.             'calculations' => $calculations,
  1637.             'invoiceAddress' => $invoiceAddress,
  1638.             'documents' => $documents,
  1639.             'fradatasheets' => $fraDatasheets,
  1640.             'invoiceList' => $invoicelist,
  1641.             'parentCompanys' => $parentCompanys,
  1642.             'subsidiaryCompanys' => $subsidiaryCompanys,
  1643.             'reportsCustomerData' => $reportsCustomerData,
  1644.             'reports' => $reports,
  1645.             'supplierCustomerRelation' => $supplierCustomerRelation,
  1646.             'helpdesk' => $helpdesk,
  1647.             'formCustomer' => $formCustomer->createView(),
  1648.         ]);
  1649.     }
  1650.       /**
  1651.       * @Route("/deactivate/{id}", name="supplier_deactivate")
  1652.       * @param $customer
  1653.       * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  1654.       */
  1655.       public function deactivateAction(TranslatorInterface $translatorLoggerInterface $logger$idRequest $request)
  1656.       {
  1657.         $em $this->doctrine->getManager();
  1658.         $supplier $em->getRepository(Supplier::class)->findOneBy(['id' => $id]);
  1659.         if (!$supplier) {
  1660.           $this->addFlash('error'$translator->trans('supplier.not_exist'));
  1661.           return $this->redirectToRoute('supplier_index');
  1662.         }
  1663.         try {
  1664.           $supplier->setActive(0);
  1665.           $em->persist($supplier);
  1666.           $em->flush();
  1667.           $this->addFlash('success'$translator->trans('supplier.deactivate_success'));
  1668.           $this->dbLogger->info('Deactivate supplier', [
  1669.             'user' => $this->getUser(),
  1670.             'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  1671.             'supplier' => $this->getUser()->getSupplier() != null ?: $this->getUser()->getSupplier(),
  1672.             'other' => $supplier,
  1673.             'route' => $request->get('_route')
  1674.           ]);
  1675.         } catch (\Exception $exception) {
  1676.           $this->addFlash('error'$translator->trans('supplier.deactivate_error'));
  1677.           $logger->error('Error while deactivate Supplier', ['e' => $exception]);
  1678.           $this->dbLogger->error('Error when deactivating supplier', [
  1679.             'user' => $this->getUser(),
  1680.             'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  1681.             'supplier' => $this->getUser()->getSupplier() != null ?: $this->getUser()->getSupplier(),
  1682.             'other' => $supplier,
  1683.             'route' => $request->get('_route'),
  1684.             'error' => $exception
  1685.           ]);
  1686.         }
  1687.         return $this->redirectToRoute('supplier_index');
  1688.       }
  1689.       /**
  1690.       * @Route("/activate/{id}", name="supplier_activate")
  1691.       * @param $customer
  1692.       * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  1693.       */
  1694.       public function activateAction(TranslatorInterface $translatorLoggerInterface $logger$idRequest $request)
  1695.       {
  1696.         $em $this->doctrine->getManager();
  1697.         $supplier $em->getRepository(Supplier::class)->findOneBy(['id' => $id]);
  1698.         if (!$supplier) {
  1699.           $this->addFlash('error'$translator->trans('supplier.not_exist'));
  1700.           return $this->redirectToRoute('supplier_index');
  1701.         }
  1702.         // if ($supplier->getTemporary() == 1) // TODO we should talk about this
  1703.         // {
  1704.         //   $contactPersons = $supplier->getUser()->getValues();
  1705.         //   foreach ($contactPersons as $contactPerson)
  1706.         //   {
  1707.         //     $userAlreadyExist = $em->getRepository(\App\Entity\User::class)->findOneBy(['email' => $contactPerson->getEmail()]);
  1708.         //     $this->addFlash('error', $translator->trans('supplier.user_already_exist') . $userAlreadyExist->getEmail());
  1709.         //   }
  1710.         //   return $this->redirectToRoute('supplier_index');
  1711.         // }
  1712.         try {
  1713.           $supplier->setActive(1);
  1714.           $supplier->setTemporary(0);
  1715.           $em->persist($supplier);
  1716.           $em->flush();
  1717.           $this->addFlash('success'$translator->trans('supplier.activate_success'));
  1718.           $this->dbLogger->info('Activate supplier', [
  1719.             'user' => $this->getUser(),
  1720.             'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  1721.             'supplier' => $this->getUser()->getSupplier() != null ?: $this->getUser()->getSupplier(),
  1722.             'other' => $supplier,
  1723.             'route' => $request->get('_route')
  1724.           ]);
  1725.         } catch (\Exception $exception) {
  1726.           $this->addFlash('error'$translator->trans('supplier.activate_error'));
  1727.           $logger->error('Error while activate Supplier', ['e' => $exception]);
  1728.           $this->dbLogger->error('Error when activating supplier', [
  1729.             'user' => $this->getUser(),
  1730.             'customer' => $this->getUser()->getCustomer() != null ?: $this->getUser()->getCustomer(),
  1731.             'supplier' => $this->getUser()->getSupplier() != null ?: $this->getUser()->getSupplier(),
  1732.             'other' => $supplier,
  1733.             'route' => $request->get('_route'),
  1734.             'error' => $exception
  1735.           ]);
  1736.         }
  1737.         return $this->redirectToRoute('supplier_index');
  1738.       }
  1739.       /**
  1740.       * @Route("/changeAllocatedSupplier", name="supplier_changeAllocatedSupplier", methods={"POST"})
  1741.       * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  1742.       */
  1743.       public function changeAllocatedSupplier(Request $requestTranslatorInterface $translator)
  1744.       {
  1745.           $this->denyAccessUnlessGranted('ROLE_SUPPLIER'null$translator->trans('error.not_permitted'));
  1746.           $em $this->doctrine->getManager();
  1747.           $selectedSupplier $em->getRepository(Supplier::class)->findOneBy(['id' => $request->get('supplier')]);
  1748.           $user $this->getUser();
  1749.           if (in_array($selectedSupplier$user->getUserSupplierList()->getValues()))
  1750.           {
  1751.               $user->setSupplier($selectedSupplier);
  1752.               $em->persist($user);
  1753.               $em->flush();
  1754.           } else {
  1755.               $this->addFlash('warning'$translator->trans('not_permitted'));
  1756.           }
  1757.           return $this->redirectToRoute('homepage');
  1758.       }
  1759.     }