src/StartPlatz/Bundle/RheinlandPitchBundle/Controller/ApplyController.php line 498

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\StartPlatz\Bundle\RheinlandPitchBundle\Controller;
  3. /**
  4.  * CRITICAL DEPENDENCY WARNING - EVENT REGISTRATION SYSTEM
  5.  * 
  6.  * This controller is heavily used by the EventBundle for event registrations.
  7.  * Event registration is the MOST IMPORTANT registration method for events.
  8.  * 
  9.  * DO NOT modify this controller without thoroughly testing event registration functionality.
  10.  * 
  11.  * Key dependencies from EventBundle:
  12.  * - EventBundle/Controller/EventRegistrationController uses this for all internal event registrations
  13.  * - Event registration forms are rendered using templates from this bundle
  14.  * - Application workflow (validation, status management) is shared with events
  15.  * 
  16.  * Critical methods used by events:
  17.  * - applyAction() - Main registration form handling
  18.  * - Form validation and submission logic
  19.  * - Email validation workflows (validateEmail/validateLogin)
  20.  * - Application status management
  21.  * 
  22.  * Templates used by events:
  23.  * - Apply/_edit.registration.event.widget.html.twig
  24.  * - Apply/_edit.registration.widget.html.twig
  25.  * - Apply/apply.default.html.twig (for anonymous access)
  26.  * 
  27.  * IMPORTANT: Event registrations depend on:
  28.  * - Application entity structure
  29.  * - Form field definitions in ApplicationType
  30.  * - Validation logic and error handling
  31.  * - Email confirmation workflows
  32.  * - Member/Team assignment logic
  33.  * 
  34.  * See also:
  35.  * - EventBundle/Controller/EventRegistrationController.php (registration logic, extracted from DefaultController)
  36.  * - StartupBundle/Entity/ApplicationRepository.php (for data operations)
  37.  * - Documentation: /doc/claude-files/application-process.md#event-integration
  38.  */
  39. use App\StartPlatz\Bundle\EventBundle\Entity\Event;
  40. use App\StartPlatz\Bundle\MailmanBundle\ConfirmationMailService;
  41. use App\StartPlatz\Bundle\MailmanBundle\Entity\MailTemplate;
  42. use App\StartPlatz\Bundle\MemberBundle\Entity\Member;
  43. use App\StartPlatz\Bundle\MemberBundle\Entity\MemberTeam;
  44. use App\StartPlatz\Bundle\MemberBundle\Entity\Option;
  45. use App\StartPlatz\Bundle\MemberBundle\Entity\Product;
  46. use App\StartPlatz\Bundle\MemberBundle\Entity\Team;
  47. use App\StartPlatz\Bundle\MetaBundle\Entity\Attribute;
  48. use App\StartPlatz\Bundle\MonsumBundle\Entity\Customer;
  49. use App\StartPlatz\Bundle\StartupBundle\Entity\Reminder;
  50. use App\StartPlatz\Bundle\StartupBundle\Entity\Startup;
  51. use App\StartPlatz\Bundle\WebsiteBundle\MenuTranslationService;
  52. use DateTime;
  53. use Doctrine\ORM\EntityManagerInterface;
  54. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  55. use Speicher210\CloudinaryBundle\Cloudinary\Api;
  56. use Symfony\Component\Mailer\MailerInterface;
  57. use Symfony\Component\Mime\Email;
  58. use Symfony\Component\Routing\Annotation\Route;
  59. use App\StartPlatz\Bundle\FeedbackBundle\CallbackService;
  60. use App\StartPlatz\Bundle\FeedbackBundle\Form\ContentPlainEditorFormType;
  61. use App\StartPlatz\Bundle\StartupBundle\Entity\Application;
  62. use App\StartPlatz\Bundle\StartupBundle\Entity\Batch;
  63. use App\StartPlatz\Bundle\StartupBundle\Entity\Program;
  64. use App\StartPlatz\Bundle\StartupBundle\Form\ApplicationType;
  65. use App\StartPlatz\Bundle\UserBundle\Entity\User;
  66. use App\StartPlatz\Bundle\UserBundle\Form\SetPasswordFormType;
  67. use App\StartPlatz\Bundle\UserBundle\LoginService;
  68. use App\StartPlatz\Bundle\WebsiteBundle\Utility\Utility;
  69. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  70. use Symfony\Component\HttpFoundation\Request;
  71. use Symfony\Component\HttpFoundation\Response;
  72. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  73. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  74. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  75. use Symfony\Component\Stopwatch\Stopwatch;
  76. use Symfony\Component\Validator\Constraints as Assert;
  77. use Symfony\Component\Validator\Validation;
  78. use Twig\Environment;
  79. use Twig\Loader\ArrayLoader;
  80. class ApplyController extends AbstractController
  81. {
  82.     public function __construct(
  83.         private readonly SessionInterface             $session,
  84.         private readonly MailerInterface              $mailer,
  85.         private readonly CallbackService              $callbackService,
  86.         private readonly LoginService                 $loginService,
  87.         private readonly UserPasswordEncoderInterface $encoder,
  88.         private readonly MenuTranslationService       $menuTranslationService,
  89.         private readonly ConfirmationMailService      $confirmationMailService,
  90.         private readonly Api                          $cloudinary,
  91.         private readonly Stopwatch                    $stopwatch,
  92.         private readonly EntityManagerInterface       $entityManager,
  93.     ) {
  94.     }
  95.     /*
  96.      * this page uses a collection of bootstrap4 pages
  97.      * https://colorlib.com/wp/template/meetup/
  98.      */
  99.     #[Route('/apply/action/allmeda_application_set-application-done/{applicationId}'name'allmeda_application_set-application-done')]
  100.     /**
  101.      * @IsGranted("ROLE_ADMIN")
  102.      */
  103.     public function setApplicationDoneAction(Request $request$applicationId)
  104.     {
  105.         $em $this->entityManager;
  106.         if (!$redirect json_decode(base64_decode($request->get('redirect')))) {
  107.             $redirect json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template''parameters' => []]));
  108.         }
  109.         $application $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
  110.         $application $em->getRepository(Application::class)->setApplicationDone($application);
  111.         $application $em->getRepository(Application::class)->setApplication($application);
  112.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  113.     }
  114.     #[Route('/apply/action/allmeda_application_set-error-validate-email/{applicationId}'name'allmeda_application_set-error-validate-email')]
  115.     /**
  116.      * @IsGranted("ROLE_ADMIN")
  117.      */
  118.     public function setErrorValidateEmailAction(Request $request$applicationId)
  119.     {
  120.         $em $this->entityManager;
  121.         if (!$redirect json_decode(base64_decode($request->get('redirect')))) {
  122.             $redirect json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template''parameters' => []]));
  123.         }
  124.         $application $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
  125.         $application $em->getRepository(Application::class)->setApplicationStarted($application);
  126.         $application $em->getRepository(Application::class)->setErrorValidateEmail($application);
  127.         $application $em->getRepository(Application::class)->setApplication($application);
  128.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  129.     }
  130.     #[Route('/apply/action/allmeda_application_set-error-validate-login/{applicationId}'name'allmeda_application_set-error-validate-login')]
  131.     /**
  132.      * @IsGranted("ROLE_ADMIN")
  133.      */
  134.     public function setErrorValidateLoginAction(Request $request$applicationId)
  135.     {
  136.         $em $this->entityManager;
  137.         if (!$redirect json_decode(base64_decode($request->get('redirect')))) {
  138.             $redirect json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template''parameters' => []]));
  139.         }
  140.         $application $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
  141.         $application $em->getRepository(Application::class)->setApplicationStarted($application);
  142.         $application $em->getRepository(Application::class)->setErrorValidateLogin($application);
  143.         $application $em->getRepository(Application::class)->setApplication($application);
  144.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  145.     }
  146.     #[Route('/apply/action/list-tests'name'allmeda_startups_batches_test')]
  147.     public function listTestsAction(Request $request)
  148.     {
  149.         /*
  150.          * Program Slug: rheinland-pitch // Batch Slug:
  151.          * Program Slug: startup-tools // Batch Slug: 01-twilio-sms-voice-whatsapp
  152.          * Program Slug: online-circle-sales // Batch Slug: 05-session
  153.          * Program Slug: startplatz-aob // Batch Slug: 01-interesse-an-effzeh-karten
  154.          * Program Slug: feedback-zu-deiner-startup-idee // Batch Slug: 19-sondersitzung-woche-13
  155.          * Program Slug: rheinland-pitch-zuschauer // Batch Slug: 100-jubilaeum
  156.          * Program Slug: membership // Batch Slug: 17041-test-startup-membership
  157.          */
  158.         $tests = [
  159.             'Rheinland-Pitch' => ['batchId' => 283'programSlug' => 'rheinland-pitch''batchSlug' => ''],
  160.             'Feedback' => ['batchId' => 298'programSlug' => 'feedback-zu-deiner-startup-idee''batchSlug' => ''],
  161.             'Startup Tools' => ['batchId' => 269'programSlug' => 'startup-tools''batchSlug' => '01-twilio-sms-voice-whatsapp'],
  162.             'Startup Tools AWS' => ['batchId' => 188'programSlug' => 'startup-tools''batchSlug' => '01-aws'],
  163.             'Online Circle' => ['batchId' => 386'programSlug' => 'online-circle-sales''batchSlug' => 'session-11'],
  164.             'OC Gründerstip.' => ['batchId' => 305'programSlug' => 'online-circle-gruenderstipendium''batchSlug' => '03-session'],
  165.             'RPitch-Zuschauer' => ['batchId' => 123'programSlug' => 'rheinland-pitch-zuschauer''batchSlug' => '100-jubilaeum'],
  166.             'Membership' => ['batchId' => 208'programSlug' => 'membership''batchSlug' => '17041-test-startup-membership'],
  167.             'Membership Trial' => ['batchId' => 360'programSlug' => 'membership''batchSlug' => '16017-cgn-trial-community-membership'],
  168.             'Event' => ['batchId' => 357'programSlug' => 'businessclub-politischer-dialog''batchSlug' => 'spd-08-07-2021'],
  169.             'Sign Up Mentor' => ['batchId' => 391'programSlug' => 'sign-up''batchSlug' => 'mentor-registration-01'],
  170.         ];
  171.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/list-tests.html.twig', [
  172.             'tests' => $tests,
  173.             'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
  174.         ]);
  175.     }
  176.     #[Route('/apply/action/run-workflow/{applicationId}'name'apply_action_run-workflow')]
  177.     public function runWorkflow(Request $request$applicationId)
  178.     {
  179.         $em $this->entityManager;
  180.         $responseContent "";
  181.         $application $em->getRepository(Application::class)->find($applicationId);
  182.         $message $em->getRepository(Application::class)->runApplicationDoneWorkflow($application);
  183.         $responseContent "workflow set for application with id={$applicationId} and {$message}";
  184.         $this->session->getFlashBag()->add('notice'$responseContent );
  185.         return $this->redirect($this->generateUrl("allmeda_applications_home", ['filter'=>"batchId:{$application->getBatchId()}"]));
  186.     }
  187.     #[Route('/apply/settings'defaults: ['program' => 'example''batch' => 'batch11'])]
  188.     #[Route('/apply/{program}/settings'defaults: ['batch' => 'general'])]
  189.     #[Route('/apply/{program}/{batch}/settings'name'apply_settings')]
  190.     /**
  191.      * @IsGranted("ROLE_ADMIN")
  192.      */
  193.     public function setSettingsAction(Request $request$program$batch)
  194.     {
  195.         $em $this->entityManager;
  196.         $now = new datetime();
  197.         $metaName "settings.program.{$program}.{$batch}";
  198.         if (!$settingsProgram $em->getRepository(Option::class)->getOptionMetaValue($metaName)) {
  199.             if (!$settingsProgram $em->getRepository(Option::class)->getOptionMetaValue($metaName)) {
  200.                 $settingsProgram $this->getSettingsProgramDefault();
  201.                 $em->getRepository(Option::class)->setOptionMetaValueJsonEncoded($metaName"settingsProgram"$settingsProgram);
  202.             }
  203.         }
  204.         $content Utility::transformArrayAssocIntoCsvString($settingsProgram);
  205.         $data['content'] = $content;
  206.         $form $this->createForm(ContentPlainEditorFormType::class, $data);
  207.         $form->handleRequest($request);
  208.         if ($form->isSubmitted() && $form->isValid()) {
  209.             $data $form->getData();
  210.             $importString $data['content'];
  211.             $rows explode(PHP_EOL, (string) $importString);
  212.             foreach ($rows as $row) {
  213.                 $parts str_getcsv($row"\t");
  214.                 $settingsProgram[$parts[0]] = $parts[1];
  215.             }
  216.             $metaName "settings.program.{$settingsProgram['programSlug']}.{$settingsProgram['batchSlug']}";
  217.             $em->getRepository(Option::class)->setOptionMetaValueJsonEncoded($metaNamenull$settingsProgram);
  218.             $this->session->getFlashBag()->add('notice''SUCCESS data saved');
  219.             $this->redirect($this->generateUrl('apply_settings', ['program' => $settingsProgram['programSlug'], 'batch' => $settingsProgram['batchSlug']]));
  220.         }
  221.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/settings.html.twig', [
  222.             'settings' => $settingsProgram,
  223.             'event' => $em->getRepository(Event::class)->findOneBy(['id' => '4982']),
  224.             'form' => $form->createView(),
  225.             'redirectUrl' => base64_encode(json_encode(['path' => 'apply_settings''parameters' => []])),
  226.         ]);
  227.     }
  228.     #[Route('/apply/'name'apply_home')]
  229.     public function indexAction(Request $request)
  230.     {
  231.         $em $this->entityManager;
  232.         $batches $em->getRepository(Batch::class)->findOpenApplications(['programId' => ['1''3''8'], 'visibility' => 'public']);
  233.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/index.html.twig', [
  234.             'batches' => $batches,
  235.             'redirectUrl' => base64_encode(json_encode(['path' => 'apply_home''parameters' => []])),
  236.         ]);
  237.     }
  238.     #[Route('/apply/{programSlug}'name'apply_program_redirect-to-next-open-application')]
  239.     public function findNextOpenApplicationAction(Request $request$programSlug)
  240.     {
  241.         $em $this->entityManager;
  242.         $test $request->get('test');
  243.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  244.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  245.             return $this->redirect($this->generateUrl('apply_home', []));
  246.         }
  247.         $sorry "Sorry, no open application for {$program->getName()} right now";
  248.         if ($batch $em->getRepository(Batch::class)->findOpenApplicationsByProgram($program)) {
  249.             if ($test) {
  250.                 return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batch->getSlug(), 'test' => $test]));
  251.             } else {
  252.                 return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batch->getSlug()]));
  253.             }
  254.         } else {
  255.             $this->session->getFlashBag()->add('notice''ERROR ' $sorry);
  256.             return $this->redirect($this->generateUrl('apply_home', []));
  257.         }
  258.     }
  259.     #[Route('/apply/{programSlug}/{batchSlug}/{id}/monsum-checkout'name'apply_program_monsum-checkout')]
  260.     public function checkoutAction(Request $request$programSlug$batchSlug$id)
  261.     {
  262.         $em $this->entityManager;
  263.         $now = new datetime();
  264.         /** @var User $user */
  265.         $user $this->getUser();
  266.         $em->getRepository(User::class)->writeActivity($user);
  267.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  268.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  269.             return $this->redirect($this->generateUrl('apply_home', []));
  270.         }
  271.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug'program' => $program])) {
  272.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no batch found');
  273.             return $this->redirect($this->generateUrl('apply_home', []));
  274.         }
  275.         if ($customerHash $request->get('customerId')) {
  276.             $customer $em->getRepository(Customer::class)->findOneBy(['hash' => $customerHash]);
  277.             $teamId $customer->getTeamId();
  278.             $team $em->getRepository(Team::class)->findOneBy(['id' => $teamId]);
  279.         }
  280.         $settings $em->getRepository(Application::class)->getSettingsProgram($program$batch);
  281.         $productNumber $batch->getBatchNumber();
  282.         $account $this->getAccountBySlug($batchSlug);
  283.         $accountHash $em->getRepository(Customer::class)->getAccountHashByAccount($account);
  284.         $promocode $request->get('promocode') ? $request->get('promocode') : '';
  285.         if (isset($settings['isFrame']) and $settings['isFrame']) {
  286.             return $this->render('@StartPlatzRheinlandPitchBundle/Apply/monsum.checkout.html.twig', [
  287.                 'accountHash' => $accountHash,
  288.                 'customerHash' => $customerHash,
  289.                 'productNumber' => $productNumber,
  290.                 'settings' => $settings,
  291.                 'redirectUrl' => base64_encode(json_encode(['path' => 'rheinland-pitch_apply_home''parameters' => []])),
  292.                 'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
  293.             ]);
  294.         } else {
  295.             if ($promocode) {
  296.                 return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&promocode={$promocode}&x_applicationId={$id}");
  297.             } else {
  298.                 return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&x_applicationId={$id}");
  299.             }
  300.             /* Gerrit stash membership 11.4.23
  301.             if ($promocode) {
  302.                 return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&promocode={$promocode}&x_applicationId={$id}&success_url={$successUrl}");
  303.             } else {
  304.                 return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&x_applicationId={$id}&success_url={$successUrl}");
  305.             }
  306.             */
  307.         }
  308.         /*
  309.         Rückgabe von Monsum auf
  310.         https://www.startplatz.de/x/membership/receipt-monsum/17048?customerId=6a982bbfe539c9cb0ba1ca967210e0cc&subscriptionId=83add62a2825deabc141b278bd7f1fe3
  311.          */
  312.     }
  313.     private function getAccountBySlug($slug)
  314.     {
  315.         $accountShortName explode('-'$slug)[1];
  316.         $accounts = [
  317.             "cgn" => "SP-CGN",
  318.             "dus" => "SP-DUS",
  319.             "test" => "TESTPLATZ",
  320.         ];
  321.         return $accounts[$accountShortName];
  322.     }
  323.     #[Route('/access/startup-membership/{programSlug}/{batchSlug}/'name'access_startup-membership')]
  324.     /**
  325.      * @IsGranted("ROLE_USER")
  326.      */
  327.     public function hasStartupMembershipAction(Request $request$programSlug$batchSlug)
  328.     {
  329.         $em $this->entityManager;
  330.         /** @var User $user */
  331.         $user $this->getUser();
  332.         $em->getRepository(User::class)->writeActivity($user);
  333.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  334.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  335.             return $this->redirect($this->generateUrl('apply_home', []));
  336.         }
  337.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug'program' => $program])) {
  338.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no batch found');
  339.             return $this->redirect($this->generateUrl('apply_home', []));
  340.         }
  341.         $settings = [
  342.             'bgImage' => 'https://res.cloudinary.com/startplatz/image/upload/v1610197223/applications/backgrounds/friendly-coworking.png',
  343.         ];
  344.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/checkHasStartupMembership.html.twig', [
  345.             'program' => $program,
  346.             'batch' => $batch,
  347.             'settings' => $settings,
  348.             'product' => ['name' => 'test'],
  349.             'action' => 'default',
  350.             'application' => ['websiteUrl' => ''],
  351.             'redirectUrl' => base64_encode(json_encode(['path' => 'rheinland-pitch_apply_home''parameters' => []])),
  352.             'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
  353.         ]);
  354.     }
  355.     #[Route('/apply/rheinland-pitch/startup-academy-pitch-night-bewerbungen-00'name'redirect_applications')]
  356.     public function redirectApplicationAction()
  357.     {
  358.         return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => 'event''batchSlug' => 'startup-academy-pitch-night-bewerbungen-01''id' => 'start']));
  359.     }
  360.     private function getExtraFieldsAttributes($settings)
  361.     {
  362.         if (!isset($settings['extraFields'])) {
  363.             return $settings;
  364.         }
  365.         $em $this->entityManager;
  366.         $extraFields $settings['extraFields'];
  367.         $i 0;
  368.         foreach ($extraFields as $extraField) {
  369.             if ($extraField['type'] == 'choice') {
  370.                 $choices = [];
  371.                 if (isset($extraField['arr'])) {
  372.                     $choices $em->getRepository(Attribute::class)->findCodesByAttributeName($extraField['arr']);
  373.                 }
  374.                 $settings['extraFields'][$i]['choices'] = $choices;
  375.             }
  376.             $i++;
  377.         }
  378.         return $settings;
  379.     }
  380.     private function getExtraFieldsData(Application $application$settings$form)
  381.     {
  382.         $extraFields $settings['extraFields'];
  383.         $data = [];
  384.         $i 0;
  385.         foreach ($extraFields as $extraField) {
  386.             $data[$extraField['field']] = $form->get($extraField['field'])->getData();
  387.             $i++;
  388.         }
  389.         if ($data) {
  390.             $application->setExtraFields(json_encode($data)) ;
  391.         }
  392.         return $application;
  393.     }
  394.     #[Route('/schnuppermitgliedschaft-buchen/welcome/{id}'name'schnuppermitgliedschaft_buchen_welcome_de')]
  395.     #[Route('/schnuppermitgliedschaft-buchen/{id}'name'schnuppermitgliedschaft_buchen_de')]
  396.     #[Route('/schnuppermitgliedschaft-team-buchen/welcome/{id}'name'schnuppermitgliedschaft_team_buchen_welcome_de')]
  397.     #[Route('/schnuppermitgliedschaft-team-buchen/{id}'name'schnuppermitgliedschaft_team_buchen_de')]
  398.     #[Route('/startup-academy-test-mitgliedschaft-buchen/{id}'name'startup-academy-test-mitgliedschaft_buchen_de')]
  399.     #[Route('/trial-membership-register/{id}'name'schnuppermitgliedschaft_buchen_en')]
  400.     #[Route('/trial-membership-register/{id}'name'schnuppermitgliedschaft_buchen_en')]
  401.     #[Route('/free-token/{id}'name'free-token')]
  402.     #[Route('/apply/{programSlug}/{batchSlug}/{id}'name'apply_program_home')]
  403.     #[Route('/{lang}/apply/{programSlug}/{batchSlug}/{id}'name'apply_program_home_lang')]
  404.     public function applyAction(Request $request$programSlug 'undef'$batchSlug 'undef'$id 'start'$lang null)
  405.     {
  406.         ##apply
  407.         $em $this->entityManager;
  408.         $now = new datetime();
  409.         $pathInfo $request->getPathInfo();
  410.         $host $request->getHost();
  411.         $test $request->get('test');
  412.         $routeName $request->get('_route');
  413.         $routeParameters $request->get('_route_params');
  414.         $isMemberloggedIn false;
  415.         $isEmailRegistered false;
  416.         $product null;
  417.         $landingPageContent "";
  418.         $landingPageTwig "";
  419.         $lang strtoupper($lang ?? 'DE');
  420.         $priceAndDiscount = [];
  421.         $settings = []; // array contains specific definitions in relation to program, batch and template
  422.         // Retrieve the UTM parameters from the URL
  423.         $utmParameters = [
  424.             'utmSource'   => $request->query->get('utm_source'),
  425.             'utmMedium'   => $request->query->get('utm_medium'),
  426.             'utmCampaign' => $request->query->get('utm_campaign'),
  427.             'utmTerm'     => $request->query->get('utm_term'),
  428.             'utmContent'  => $request->query->get('utm_content'),
  429.         ];
  430.         if ($routeName != 'apply_program_home' && $routeName != 'apply_program_home_lang') {
  431.             ## evaluate special routes like 'schnuppermitgliedschaft_buchen_en' ########################
  432.             if (!$response $this->evaluateAliasSlug($routeName)) {
  433.                 $this->session->getFlashBag()->add('notice''ERROR url is invalid');
  434.                 return $this->redirect($this->generateUrl('apply_home', []));
  435.             } else {
  436.                 /** @var Program $program */
  437.                 $program $response['data']['program'];
  438.                 /** @var Batch $batch */
  439.                 $batch $response['data']['batch'];
  440.                 $batchSlug $batch->getSlug();
  441.                 $programSlug $program->getSlug();
  442.             }
  443.             ## end of route evaluation
  444.         } else {
  445.             ## find program and batch by the default way ############
  446.             /** @var Program $program */
  447.             if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  448.                 $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  449.                 return $this->redirect($this->generateUrl('apply_home', []));
  450.             }
  451.             if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug'program' => $program])) {
  452.                 $this->session->getFlashBag()->add('notice''ERROR Sorry, no batch found');
  453.                 return $this->redirect($this->generateUrl('apply_home', []));
  454.             }
  455.         }
  456.         if ($program->getSlug() == 'membership') {
  457.             $productNumber $batch->getBatchNumber();
  458.             $account $this->getAccountBySlug($batchSlug);
  459.             // find product by productNumber, account and agent == monsum
  460.             $product $em->getRepository(Product::class /*Product Member*/)->findOneBy(['account' => $account'productNumber' => $productNumber'agent' => 'monsum']);
  461.         }
  462.         ##-- now we know program and batch (and product if membership) --##
  463.         // check if application is still open
  464.         if ($batch->getStatus() == 'inactive') {
  465.             $this->session->getFlashBag()->add('notice''ERROR Sorry, application is currently not active');
  466.             return $this->redirect($this->generateUrl('apply_home', []));
  467.         }
  468.         ## is application open
  469.         ##toBeTested
  470.         $response $em->getRepository(Batch::class)->isApplicationOpen($batch);
  471.         if ($response['status'] == 'error') {
  472.             $this->session->getFlashBag()->add('notice'$response['message']);
  473.             return $this->redirect($this->generateUrl('apply_home', []));
  474.         }
  475.         // check if settings contains necessary setters
  476.         $batch $em->getRepository(Batch::class)->checkLegacyData($batch);
  477.         // settings for program and batch will be merged
  478.         $settings $em->getRepository(Application::class)->getSettingsProgram($program$batch);
  479.         // check LoginStatus
  480.         /** @var User $user */
  481.         if ($user $this->getUser()) {
  482.             ## user is logged in. this will be the default case ############
  483.             $adminEmail $user->getEmail();
  484.             $em->getRepository(User::class)->writeActivity($user);
  485.             /** @var Member $member */
  486.             $member $em->getRepository(Member::class)->find($user->getMemberId());
  487.             $isMemberloggedIn true;
  488.         } else {
  489.             ## if user is not logged in - kick her out except it is allowed to access batch without being logged in
  490.             if ($batch->getAccess() != 'anonymous') {
  491.                 // Pass the UTM parameters along with other necessary arguments to the createApplicationByApplyForm method
  492.                 $application $em->getRepository(Application::class)->createApplicationByApplyForm(
  493.                     $program,
  494.                     $batch,
  495.                     $lang,
  496.                     $priceAndDiscount,
  497.                     $utmParameters  // This is the array you created earlier
  498.                 );
  499.                 return $this->render('@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig', [
  500.                     'settings' => $settings,
  501.                     'program' => $program,
  502.                     'batch' => $batch,
  503.                     'test' => $test,
  504.                     'application' => $application,
  505.                     'applicationId' => $id,
  506.                     'phrases' => $em->getRepository(Option::class)->getApplicationPhrases($program$batch$product$lang),
  507.                     'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang''parameters' => ['id' => $id'programSlug' => $programSlug'batchSlug' => $batchSlug], 'lang' => strtolower($lang)])),
  508.                     'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
  509.                 ]);
  510.             }
  511.             $member $em->getRepository(Member::class)->setEmptyMemberAccount();
  512.         }
  513.         $settings['isMemberloggedIn'] = $isMemberloggedIn;
  514.         if ($isMemberloggedIn) {
  515.             // check access conditions
  516.             if ($batch->getAccess() == 'hasStartupMembership') {
  517.                 $team $em->getRepository(Team::class)->findOneBy(['id' => $user->getTeamId()]);
  518.                 if (!$team->getHasStartupMembership()) {
  519.                     return $this->redirect($this->generateUrl('access_startup-membership', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $id]));
  520.                 }
  521.             }
  522.             // check is missing if Community Membership
  523.         }
  524.         ## -- settings -- #############
  525.         // important distinction - is it necessary to bind this application to a team
  526.         // or is it okay to bind it with a person only
  527.         // event are normally person only, applications for accelerator need a team
  528.         // it can be defined via batch (isMultipleApplicationsPerTeam)
  529.         // but in every case an application need to be tied to a member and at least a virtual team
  530.         // we need to keep track is a member team relationship has been set
  531.         // because either member or team can be created during application process
  532.         $_isMemberTeamRelationSet 0;
  533.         // for memberships we need the product type
  534.         $settings['productType'] = 'Applicant';
  535.         if ($product) {
  536.             $settings['productType'] = $product->getType();
  537.         }
  538.         // we set an virtual team as fallback if no new allmeda team is needed to process the request
  539.         $virtualTeam array_key_exists('virtualTeam'$settings) ? $settings['virtualTeam'] : 'applicants';
  540.         // access the relevant virtual team or create that team if it does not exists
  541.         $applicantsTeam $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
  542.         $adminEmail $user $user->getEmail() : "";
  543.         $application null;
  544.         // find application or create new one if id = start
  545.         if ($id == 'start') {
  546.             if ($teamId $request->get('teamId') and $user and $teamId 0) {
  547.                 if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($user->getMemberId(), $teamId)) {
  548.                     $this->session->getFlashBag()->add('notice''ERROR 01 no access to team');
  549.                     return $this->redirect($this->generateUrl('apply_program_home_lang', ['id' => $id'programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => strtolower($lang)]));
  550.                 }
  551.                 if ($application $em->getRepository(Application::class)->findOneBy(['teamId' => $teamId'programSlug' => $programSlug'batchSlug' => $batchSlug])) {
  552.                     $this->session->getFlashBag()->add('notice''SUCCESS application for your team found');
  553.                     return $this->redirect($this->generateUrl('apply_program_home_lang', ['id' => $application->getId(), 'programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => strtolower($lang)]));
  554.                 }
  555.             }
  556.             if ($batch->isMultipleApplicationsPerTeam() and $user) {
  557.                 // look up application of that member
  558.                 $application $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $user->getMemberId()]);
  559.             } elseif ($user) {
  560.                 if (!$batch->isMultipleApplicationsPerMember()) {
  561.                     // look up application of that team
  562.                     if (!$application $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'teamId' => $user->getTeamId()])) {
  563.                         // if there is no application bound with the primary team of the member look for an application bound with that member directly
  564.                         $application $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $user->getMemberId()]);
  565.                     }
  566.                 }
  567.             }
  568.             if ($application) {
  569.                 $member $em->getRepository(Member::class)->find($application->getMemberId());
  570.                 $teamId $request->get('teamId') ? $request->get('teamId') : $application->getTeamId();
  571.                 $team $this->setTeam($member$settings$teamId$applicantsTeam);
  572.             } else { // create new application
  573.                 // Pass the UTM parameters along with other necessary arguments to the createApplicationByApplyForm method
  574.                 $application $em->getRepository(Application::class)->createApplicationByApplyForm(
  575.                     $program,
  576.                     $batch,
  577.                     $lang,
  578.                     $priceAndDiscount,
  579.                     $utmParameters  // This is the array you created earlier
  580.                 );
  581.                 if ($program->getSlug() == 'membership') {
  582.                     if ($memberId $request->get('w')) {
  583.                         if ($werber $em->getRepository(Member::class)->find($memberId)) {
  584.                             $application->setRecommendedBy($werber->getEmail());
  585.                         }
  586.                     }
  587.                 }
  588.                 $member $em->getRepository(Application::class)->setMember($program$batch$applicantsTeam$user);
  589.                 $application $em->getRepository(Application::class)->updateApplicationByMember($application$member);
  590.                 if ($request->get('teamId')) {
  591.                     $teamId $request->get('teamId');
  592.                 } elseif ($user) {
  593.                     if ($settings['createAlwaysNewTeam']) {
  594.                         $teamId 0;
  595.                     } else {
  596.                         $teamId $user->getTeamId();
  597.                     }
  598.                 } else {
  599.                     $teamId 0;
  600.                 }
  601.                 $team $this->setTeam($member$settings$teamId$applicantsTeam);
  602.                 if ($settings['isTeamNeeded']) {
  603.                     $application $this->updateApplicationByTeam($application$team);
  604.                 } else {
  605.                     $teamId $applicantsTeam->getId();
  606.                     $application->setTeamId($teamId);
  607.                 }
  608.             }
  609.         } else {
  610.             if (!$application $em->getRepository(Application::class)->find($id)) {
  611.                 $this->session->getFlashBag()->add('notice''ERROR apply:01 - Application could not be found. You can create a new one');
  612.                 return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => 'start''lang' => strtolower($lang)]));
  613.             }
  614.             if ($application->getProgramSlug() != $programSlug or $application->getBatchSlug() != $batchSlug) {
  615.                 $this->session->getFlashBag()->add('notice''ERROR apply:011 - Application could not be found. You can create a new one');
  616.                 return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => 'start''lang' => strtolower($lang)]));
  617.             }
  618.             $canPassWithoutLogin = [
  619.                 "error:validateLogin",
  620.                 "error:validateEmail",
  621.             ];
  622.             if (!in_array($application->getEditStatus(), $canPassWithoutLogin)) {
  623.                 if (!$user) {
  624.                     $this->session->getFlashBag()->add('notice''ERROR apply:021 - Please Login first');
  625.                     return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => 'start''lang' => strtolower($lang)]));
  626.                 } else {
  627.                     if ($application->getMemberId() != $user->getMemberId() and $user) {
  628.                         $this->session->getFlashBag()->add('notice''ERROR apply:012 - Application could not be found. You can create a new one');
  629.                         return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => 'start''lang' => strtolower($lang)]));
  630.                     }
  631.                 }
  632.             }
  633.             if ($user) {
  634.                 if ($application->getMemberId() != $user->getMemberId()) {
  635.                     if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($user->getMemberId(), $application->getTeamId())) {
  636.                         $this->session->getFlashBag()->add('notice''ERROR apply:013 - No access to this application. You can create a new one');
  637.                         return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => 'start''lang' => strtolower($lang)]));
  638.                     }
  639.                 }
  640.             }
  641.             $teamId $request->get('teamId') ? $request->get('teamId') : $application->getTeamId();
  642.             $team $this->setTeam($member$settings$teamId$applicantsTeam);
  643.         }
  644.         ## now in every case there is an application
  645.         ## we need to check the language
  646.         if ($lang) {
  647.             if ($lang != $application->getLang()) {
  648.                 $application->setLang($lang);
  649.             }
  650.         } else {
  651.             $lang $application->getLang() ? $application->getLang() : $batch->getLang();
  652.         }
  653.         ## now in every case the variable $lang is set
  654.         // checkAccessRight for team if found by external teamId
  655.         if ($request->get('teamId') > and !$teamMember $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team'member' => $member])) {
  656.             $this->session->getFlashBag()->add('notice''ERROR 02 no access to team');
  657.             return $this->redirect($this->generateUrl('apply_home'));
  658.         }
  659.         if ($adminEmail) {
  660.             $application->setLastChangeUser($adminEmail);
  661.         }
  662.         $action $request->get('action');
  663.         // action can be only set to 'finish' internally
  664.         if ($action == "finish") {
  665.             $action "";
  666.         }
  667.         if ($action == "changeName") {
  668.             $application->setStartupName("copy of " $application->getStartupName());
  669.             $application->setEditStatus("open");
  670.             $action "start";
  671.         }
  672.         if ($action == "shortenIdeaPitch") {
  673.             $application->setEditStatus("open");
  674.             $action "start";
  675.         }
  676.         if (str_contains(strtolower($application->getEditStatus() ?? ''), "error")   and $action and $user) {
  677.             // Zuordnung memberTeam checken bzw. erstellen - falls validate Login - falls keine Zuordnung und isTeamNeeded GF sonst MA
  678.             $response $em->getRepository(Application::class)->validateApplication($application$member$team$settings$action$request->get('code'));
  679.             /** @var Application $application */
  680.             $application $response['data']['application'];
  681.             $action $response['action'];
  682.             /* Gerrit stash membership 11.4.23
  683.             $application = $em->getRepository(Application::class)->setProcessGoToMonsum($application);
  684.             */
  685.             /*
  686.             if ($response['status'] == "success") {
  687.                 $application = $this->setApplicationStatusByTemplate($application);
  688.                 $action = $this->setActionByProgramSlug($application);
  689.             }*/
  690.             /** @var Member $member */
  691.             $member $response['data']['member'];
  692.             /** @var Team $team */
  693.             $team $response['data']['team'];
  694.             $teamId $team->getId();
  695.             if (!$user->getTeamId()) {
  696.                 $em->getRepository(Member::class)->setPrimaryTeam($member$team$this->getUser()->getEmail());
  697.             }
  698.             /*  Gerrit stash membership 11.4.23
  699.              } elseif ($program->getSlug() == 'membership' and $application->getEditStatus() == "success:applied" and $user) {
  700.                  $action = "goToMonsum"; */
  701.         } elseif ($application->getEditStatus() == "success:applied" and $user) {
  702.             //todo find another status for people that have applied long before
  703.             $action "finish";
  704.         } elseif ($application->getEditStatus() == "success:confirmationMailSent" and $user) {
  705.             $action "done";
  706.         } elseif (($application->getEditStatus() == "success:validatedLogin" or $application->getEditStatus() == "success:validatedEmail" or $application->getEditStatus() == "validated") and $user) {
  707.             $action $this->setActionByProgramSlug($application);
  708.         } elseif ($application->getApplicationStatus() == "started" and $user) {
  709.             $action "continue";
  710.         } elseif ($application->getApplicationStatus() == "applied" and $user) {
  711.             if (in_array($application->getTemplate(), ['accelerator''rheinland-pitch'])) {
  712.                 $action "reopen";
  713.             } else {
  714.                 $action "finish";
  715.             }
  716.         }
  717.         $_isMemberTeamRelationSet $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team'member' => $member]) ? 0;
  718.         $form $this->createForm(ApplicationType::class, $application, ['settings' => $settings'program' => $program'batch' => $batch]);
  719.         $form->handleRequest($request);
  720.         ##############################################################
  721.         ##   form validation starts here                            ##
  722.         ##############################################################
  723.         if ($form->isSubmitted() && $form->isValid()) {
  724.             // make email lower case
  725.             $application->setEmail(strtolower($application->getEmail()));
  726.             if (!$application->getPerson() and $application->getFirstName()) {
  727.                 $application->setPerson("{$application->getFirstName()} {$application->getLastName()}");
  728.             }
  729.             if (!$adminEmail) {
  730.                 $adminEmail $application->getEmail();
  731.             }
  732.             if (isset($settings['extraFields'])) {
  733.                 $application $this->getExtraFieldsData($application$settings$form);
  734.             }
  735.             // now we can check if the email of the form already registered within startplatz
  736.             $isEmailRegistered $em->getRepository(Member::class)->isEmailRegistered($application->getEmail());
  737.             if ($isMemberloggedIn or !$isEmailRegistered) {
  738.                 // if settings[isTeamNeeded] is set a corporate team is created otherwise a person team
  739.                 if ($teamId == 'create' or !$team->getId()) {
  740.                     $team $em->getRepository(Team::class)->createTeamByApplication($application$settings$member);
  741.                     $application->setTeamId($team->getId());
  742.                     $teamId $team->getId();
  743.                 }
  744.             }
  745.             ##email validation - only relevant if access == anonymous or login
  746.             $response $this->evaluateApplicationEmail($application$member$team$settings$user);
  747.             $application $response['data']['application'];
  748.             $member $response['data']['member'];
  749.             $hasExistingApplication $response['hasExistingApplication'];
  750.             $_isMemberTeamRelationSet $teamMember $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team'member' => $member]) ? 0;
  751.             // Do we allow multiple applications?
  752.             $allowMultiple $settings['isTeamNeeded']
  753.                 ? $settings['isMultipleApplicationsPerTeam']
  754.                 : $settings['isMultipleApplicationsPerMember'];
  755.             if (!$allowMultiple
  756.                 && $hasExistingApplication
  757.                 && $application->getApplicationStatus() == 'applied'
  758.                 && $program->getSlug() == 'membership'
  759.             ) {
  760.                 $targetUrl strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  761.                 $loginLink $this->generateUrl('login', ['targetPath' => $targetUrl]);
  762.                 $this->session->getFlashBag()->add('notice'"ERROR: You already applied for this membership with your email address. <a title=\"Login page\" href=\"$loginLink\">You can login here</a>.");
  763.                 $routeParameters['action'] = "";
  764.                 return $this->redirect($targetUrl);
  765.             }
  766.             if (!$application->getApplicationStatus()) {
  767.                 $application->setApplicationStatus('started');
  768.             }
  769.             $application $em->getRepository(Application::class)->setApplication($application);
  770.             // at this point application is set and stored in database
  771.             // and member is set and team is set - now we can do last changes to team
  772.             if ($response['status'] == 'error') {
  773.                 /*
  774.                     $status  = "error";
  775.                     $todo    = "validateLogin";
  776.                  */
  777.                 $routeParameters = [
  778.                     'programSlug' => $programSlug,
  779.                     'batchSlug' => $batchSlug,
  780.                     'id' => $application->getId(),
  781.                     'lang' => $lang,
  782.                     'action' => 'validate'
  783.                 ];
  784.                 if ($test) {
  785.                     $routeParameters['test'] = $test;
  786.                 }
  787.                 if ($response['todo'] == "validateLogin") {
  788.                     $targetPath strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  789.                     $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  790.                     $mailTemplate $em->getRepository(MailTemplate::class)->getValidateLoginMailTemplateByBatch($batch$application$loginLink);
  791.                     $feedback Utility::sendAlertMailPerZapier($mailTemplate['recipientEmail'], $mailTemplate['mailText'], $mailTemplate['mailSubject'], $mailTemplate['replyToEmail'], $mailTemplate['fromName'], $mailTemplate['bodyType']);
  792.                     $feedback json_decode($feedback);
  793.                     if ($feedback->status == "success") {
  794.                         $routeParameters['action'] = "needsLoginValidation";
  795.                         $targetUrl strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  796.                         return $this->redirect($targetUrl);
  797.                     } else {
  798.                         $this->session->getFlashBag()->add('notice''ERROR email is invalid please check your email address!');
  799.                         $routeParameters['action'] = "";
  800.                         $targetUrl strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  801.                         return $this->redirect($targetUrl);
  802.                     }
  803.                 }
  804.                 if ($response['todo'] == "validateEmail") {
  805.                     $targetPath strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  806.                     $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  807.                     $mailTemplate $em->getRepository(MailTemplate::class)->getValidateEmailMailTemplateByBatch($batch$application$loginLink);
  808.                     $em->persist($application);
  809.                     $em->flush();
  810.                     $feedback Utility::sendAlertMailPerZapier($mailTemplate['recipientEmail'], $mailTemplate['mailText'], $mailTemplate['mailSubject'], $mailTemplate['replyToEmail'], $mailTemplate['fromName'], $mailTemplate['bodyType']);
  811.                     $feedback json_decode($feedback);
  812.                     if ($feedback->status == "success") {
  813.                         $routeParameters['action'] = "needsEmailVerification";
  814.                         $targetUrl strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  815.                         return $this->redirect($targetUrl);
  816.                     } else {
  817.                         $this->session->getFlashBag()->add('notice''ERROR email is invalid please check your email adress!');
  818.                         $routeParameters['action'] = "";
  819.                         $targetUrl strtolower($this->generateUrl('apply_program_home_lang'$routeParameters));
  820.                         return $this->redirect($targetUrl);
  821.                     }
  822.                 }
  823.                 if ($test) {
  824.                     return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'test' => $test'lang' => strtolower($lang)]));
  825.                 } else {
  826.                     return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'lang' => strtolower($lang)]));
  827.                 }
  828.             }
  829.             $response $this->checkPlausibility($application$member$team$settings);
  830.             $application $response['data']['application'];
  831.             $application $em->getRepository(Application::class)->setApplication($application);
  832.             if (!$user) {
  833.                 switch ($program->getSlug()) {
  834.                     case "rheinland-pitch":
  835.                     case "accelerator":
  836.                         // make applicant a guest member and login
  837.                         $guestTeam $em->getRepository(Team::class)->getVirtualTeamByName("Guest Membership");
  838.                         $memberTeam $em->getRepository(Member::class)->setTeamAssignment($member$guestTeam"MA"$adminEmail);
  839.                         break;
  840.                     case "nft":
  841.                         // make applicant a guest member and login
  842.                         if (!$isEmailRegistered) {
  843.                             $guestTeam $em->getRepository(Team::class)->getVirtualTeamByName("Guest Membership");
  844.                             $memberTeam $em->getRepository(Member::class)->setTeamAssignment($member$guestTeam"MA"$adminEmail);
  845.                         }
  846.                         $user $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
  847.                         break;
  848.                     default:
  849.                         break;
  850.                 }
  851.             }
  852.             if ($response['status'] == 'error') {
  853.                 if (!$user) {
  854.                     $targetPath $this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), $action => 'validate']);
  855.                     $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  856.                     return $this->redirect($loginLink);
  857.                 } else {
  858.                     return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), $action => 'validate']));
  859.                 }
  860.             }
  861.             if ($settings['isPitchDeckRequired']) {
  862.                 if ($form->get('uploadImage')->isClicked()) {
  863.                     $uploadTag "application/{$application->getId()}";
  864.                     if ($application->getLinkPitchDeck()) {
  865.                         $application->setLinkPitchDeck('');
  866.                         $application->setPublicIdPitchDeck('');
  867.                         $application $em->getRepository(Application::class)->setApplication($application);
  868.                         $result $this->cloudinary->delete_resources_by_tag($uploadTag);
  869.                     }
  870.                     return $this->redirect($this->generateUrl('apply_program_uploadPitchDeck', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'teamId' => $application->getTeamId(), 'memberId' => $application->getMemberId()]));
  871.                 }
  872.             }
  873.             if ($form->get('finish')->isClicked()) {
  874.                 $action "finish";
  875.                 if ($application->getPhone() and !$member->getPhone()) {
  876.                     $member $em->getRepository(Member::class)->setPhone($member$application->getPhone(), $adminEmail);
  877.                 }
  878.                 // relevant only for membership applicants - all applications for membership exit here
  879.                 if ($program->getSlug() == 'membership') {
  880.                     $settings['routeName'] = $routeName;
  881.                     $settings['monsumArticleNumber'] = $product->getMonsumArticleNumber();
  882.                     /* Gerrit stash membership 11.4.23 - exchange with next line
  883.                     return $this->redirect($this->generateUrl('x_membership_monsum-checkout', ['productId' => $product->getProductNumber()]));
  884.                     */
  885.                     return $this->goToMonsum($program$batch$settings$application$member$team$applicantsTeam$user);
  886.                 }
  887.                 // make applicant member of additional virtual team specified in settings
  888.                 $applicantsTeamMember $em->getRepository(Member::class)->setTeamAssignment($member$applicantsTeam"MA"$adminEmail);
  889.                 // final plausibility checks - brauchen wir die überhaupt noch? oder sind das finale Anpassungen der application
  890.                 switch ($program->getSlug()) {
  891.                     case "rheinland-pitch":
  892.                     case "accelerator":
  893.                         if (!$application->getLinkPitchDeck()) {
  894.                             $this->session->getFlashBag()->add('notice''ERROR - Your application will not be processed unless you upload a pitch deck!');
  895.                         } else {
  896.                             $wordsCount str_word_count($application->getIdeaPitch() ?? '');
  897.                             if ($wordsCount 1500) {
  898.                                 $this->session->getFlashBag()->add('notice'"ERROR - Your idea pitch contains {$wordsCount} words, please reduce the length of your idea pitch!");
  899.                             } else {
  900.                                 $action "finish";
  901.                                 $application->setApplicationStatus('applied');
  902.                                 if ($application->getVotesRegistered() == 0) {
  903.                                     $application->setVotesRegistered($settings['initialVotes']);
  904.                                 }
  905.                                 $em->persist($application);
  906.                                 $em->flush();
  907.                             }
  908.                         }
  909.                         break;
  910.                     default:
  911.                         $application $em->getRepository(Application::class)->setApplicationApplied($application);
  912.                         break;
  913.                 }
  914.             } // end of validation of submit button (finish)
  915.             if ($action != "finish") {
  916.                 $this->session->getFlashBag()->add('notice''SUCCESS data saved');
  917.                 if ($id != $application->getId()) {
  918.                     if (!$user) {
  919.                         $targetPath $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'lang' => strtolower($lang)]);
  920.                         $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  921.                         return $this->redirect($loginLink);
  922.                     } else {
  923.                         return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'lang' => strtolower($lang)]));
  924.                     }
  925.                 } else {
  926.                     $id $application->getId();
  927.                 }
  928.             }
  929.         } // end of form validation
  930.         else {
  931.             $errorString $form->getErrors(truefalse);
  932.             // @todo: $errorString ist ein Array -> StringCast in der nächsten Zeile anders behandeln
  933.             if (str_contains((string) $errorString'ERROR:')) {
  934.                 $this->session->getFlashBag()->add('notice''ERROR - Data have not been saved, reason: ' $errorString);
  935.             }
  936.         }
  937.         if ($action == "goToMonsum") {
  938.             $settings['routeName'] = $routeName;
  939.             $settings['monsumArticleNumber'] = $product->getMonsumArticleNumber();
  940.             return $this->goToMonsum($program$batch$settings$application$member$team$applicantsTeam$user);
  941.         }
  942.         if ($action == "finish") {
  943.             $batch $em->getRepository(Batch::class)->updateNumbers($batch);
  944.             ##final actions and good bye messages
  945.             switch ($batch->getTemplate()) {
  946.                 case "accelerator":
  947.                 case "rheinland-pitch":
  948.                     $this->session->getFlashBag()->add('notice''SUCCESS Thank you for your application. We have sent you a confirmation mail with additional information.');
  949.                     break;
  950.                 case "registration":
  951.                 case "businessclub":
  952.                 case "event":
  953.                     if ($batch->getAccess() == "anonymous") {
  954.                         if (!$user and $member->getId()) {
  955.                             $targetPath $this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $application->getId(), 'action' => 'finish']);
  956.                             $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  957.                             $user $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
  958.                             $this->sendConfirmationMailToApplicant($user$settings$application$batch);
  959.                             return $this->redirect($loginLink);
  960.                         }
  961.                     }
  962.                     break;
  963.                 case "speed-networking":
  964.                     break;
  965.                 case "sign-up":
  966.                     // what follow up should be done after
  967.                     if ($batch->getGoToPage() == 'editMentorsProfile') {
  968.                         $targetPath $this->generateUrl('connect_mentor_edit_profile', ['id' => $member->getId()]);
  969.                         if (!$user and $member->getId()) {
  970.                             $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  971.                             return $this->redirect($loginLink);
  972.                         } else {
  973.                             return $this->redirect($targetPath);
  974.                         }
  975.                     }
  976.                     break;
  977.                 case "startup-tools":
  978.                     $this->session->getFlashBag()->add('notice''SUCCESS Thank you for your application. We will come back to you soon');
  979.                     break;
  980.                 default:
  981.                     $view '@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig';
  982.                     break;
  983.             }
  984.             //$this->session->getFlashBag()->add('notice', 'MESSAGE sendConfirmationMailToApplicant($user, $settings, $application, $batch)');
  985.             if (!$user){
  986.                 $user $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
  987.             }
  988.             $this->sendConfirmationMailToApplicant($user$settings$application$batch);
  989.             if ($programSlug == 'ai-hub'){
  990.                 $application->setEditStatus("success:confirmationMailSent");
  991.                 $application $em->getRepository(Application::class)->setApplicationDoneWithoutWorkflow($application);
  992.             }
  993.             // additional actions for specific programs
  994.             switch ($batch->getTemplate()) {
  995.                 case "accelerator":
  996.                     // Podio integration removed
  997.                     break;
  998.                 case "rheinland-pitch":
  999.                     break;
  1000.             }
  1001.             if ($batch->getLandingPageTwig()) {
  1002.                 $loader = new ArrayLoader([
  1003.                     'landingPageTwig' => $batch->getLandingPageTwig(),
  1004.                 ]);
  1005.                 $twig = new Environment($loader);
  1006.                 //$landingPageTwig = $twig->render('landingPageTwig', ['member' => $member]);
  1007.             }
  1008.         }
  1009.         $editWidget $this->setEditWidgetByTemplate($batch->getTemplate());
  1010.         $phrases $em->getRepository(Option::class)->getApplicationPhrases($program$batch$product$lang);
  1011.         $_isMemberTeamRelationSet $teamMember $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team'member' => $member]) ? 0;
  1012.         $showFooter true// Default to showing the footer
  1013.         if ($request->query->get('iframe') === 'true') {
  1014.             // If the 'iframe' parameter is 'true', always hide the footer
  1015.             $showFooter false;
  1016.         } elseif (isset($settings['showFooter']) && $settings['showFooter'] == 0) {
  1017.             // If the 'iframe' parameter is not 'true' and $setting['showFooter'] exists and is 0, hide the footer
  1018.             $showFooter false;
  1019.         }
  1020.         // Auswahl des Twig-Templates basierend auf programId
  1021.         switch ($batch->getProgramId()) {
  1022.             case 1:
  1023.             case 3:
  1024.             default:
  1025.                 // Fallback auf das zentrale Template, falls programId unbekannt ist
  1026.                 $view '@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig';
  1027.                 break;
  1028.         }
  1029.         $landingPageContent $batch->getLandingPageContent();
  1030.         ##view-apply
  1031.         // render specific application form or show landing page
  1032.         return $this->render($view, [
  1033.             'id' => $id,
  1034.             'settings' => $settings,
  1035.             'programSlug' => $programSlug,
  1036.             'batchSlug' => $batchSlug,
  1037.             'program' => $program,
  1038.             'phrases' => $phrases,
  1039.             'batch' => $batch,
  1040.             'lang' => $lang,
  1041.             'product' => $product,
  1042.             'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
  1043.             'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
  1044.             'test' => $test,
  1045.             'host' => $host,
  1046.             'pathInfo' => $pathInfo,
  1047.             'view' => $view,
  1048.             'editWidget' => $editWidget,
  1049.             'showFooter' => $showFooter,
  1050.             'member' => $member,
  1051.             'team' => $team,
  1052.             'teamId' => $teamId,
  1053.             'application' => $application,
  1054.             'applicationId' => $id,
  1055.             'form' => $form->createView(),
  1056.             'action' => $action,
  1057.             'landingPageContent' => $landingPageContent,
  1058.             'landingPageTwig' => $landingPageTwig,
  1059.             'targetPathEN' => $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => 'en']),
  1060.             'targetPathDE' => $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => 'de']),
  1061.             'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang''parameters' => ['id' => $id'programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => strtolower($lang)]])),
  1062.             'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI'), $lang),
  1063.         ]);
  1064.     }
  1065.     private function goToMonsum($programBatch $batch$settingsApplication $application$member$team$applicantsTeam$user)
  1066.     {
  1067.         $em $this->entityManager;
  1068.         if ($program->getSlug() == 'membership') {
  1069.             // assume that everything went right
  1070.             // save member, assign member to team, save application
  1071.             $data['email'] = $application->getEmail();
  1072.             $data['name'] = $application->getPerson();
  1073.             $adminEmail $application->getEmail();
  1074.             if (!$user) {
  1075.                 $member $em->getRepository(Member::class)->createGuestMemberIfNotExists($data$team$adminEmail);
  1076.             } else {
  1077.                 $applicantsTeamMember $em->getRepository(Member::class)->setTeamAssignment($member$applicantsTeam"MA"$adminEmail);
  1078.             }
  1079.             $account $this->getAccountBySlug($batch->getSlug());
  1080.             if (!$customer $em->getRepository(Customer::class)->findPrimaryMonsumAccount($member$account)) {
  1081.                 $team $em->getRepository(Team::class)->createTeamByMembershipApplicant($member);
  1082.                 $customer $this->setMonsumAccountIfNotExists($member$team$application$account);
  1083.             }
  1084.             $productNumber $batch->getBatchNumber();
  1085.             $customer $em->getRepository(Customer::class)->setCheckoutData($customer$account$productNumber$member->getId());
  1086.             if ($batch->getTemplate() == 'membership-per-api') {
  1087.                 $login $em->getRepository(Customer::class)->getLoginByAccount($customer->getAccount());
  1088.                 $payload json_encode([
  1089.                     'SERVICE' => "subscription.create",
  1090.                     'DATA' => [
  1091.                         'CUSTOMER_ID' => "{$customer->getCustomerId()}",
  1092.                         'ARTICLE_NUMBER' => $settings['monsumArticleNumber'],
  1093.                     ],
  1094.                 ]);
  1095.                 $feedback $this->callbackService->curl_get_monsum_all($payload$login);
  1096.                 $feedback json_decode($feedback);
  1097.                 if (isset($feedback->RESPONSE->STATUS) and $feedback->RESPONSE->STATUS == "success") {
  1098.                     $subscriptionId $feedback->RESPONSE->SUBSCRIPTION_ID;
  1099.                     $application->setEditStatus("sucess:subscriptionId=={$subscriptionId}");
  1100.                     $application $em->getRepository(Application::class)->setHistory($application$application->getEditMessage());
  1101.                     $application->setApplicationStatus('applied');
  1102.                     $em->persist($application);
  1103.                     $em->flush();
  1104.                     ## assign to team ##
  1105.                     $virtualTeam array_key_exists('virtualTeam'$settings) ? $settings['virtualTeam'] : 'applicants';
  1106.                     $funnelTeam $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
  1107.                     $memberTeam $em->getRepository(Member::class)->setTeamAssignment($member$funnelTeam"MA"$adminEmail);
  1108.                     $action "finish";
  1109.                     if ($settings['routeName'] != 'apply_program_home' && $settings['routeName'] != 'apply_program_home_lang') {
  1110.                         $route $settings['routeName'];
  1111.                         if ($route == "schnuppermitgliedschaft_buchen_de") {
  1112.                             $route "schnuppermitgliedschaft_buchen_welcome_de";
  1113.                         } elseif ($route == "schnuppermitgliedschaft_team_buchen_de") {
  1114.                             $route "schnuppermitgliedschaft_team_buchen_welcome_de";
  1115.                         }
  1116.                         $targetPath $this->generateUrl($route, ['id' => $application->getId()]);
  1117.                     } else {
  1118.                         $targetPath $this->generateUrl('apply_program_home', ['programSlug' => $application->getProgramSlug(), 'batchSlug' => $application->getBatchSlug(), 'id' => $application->getId()]);
  1119.                     }
  1120.                     if (!$user) {
  1121.                         $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  1122.                         return $this->redirect($loginLink);
  1123.                     } else {
  1124.                         return $this->redirect($targetPath);
  1125.                     }
  1126.                 } else {
  1127.                     $application->setEditStatus("error:monsum-purchase-failed");
  1128.                     $em->persist($application);
  1129.                     $em->flush();
  1130.                     $action "error";
  1131.                 }
  1132.             } else {
  1133.                 $application $em->getRepository(Application::class)->setProcessGoToMonsum($application);
  1134.                 $application $em->getRepository(Application::class)->setHistory($application$application->getEditMessage());
  1135.                 $application->setApplicationStatus('applied');
  1136.                 $em->persist($application);
  1137.                 $em->flush();
  1138.                 $promocode $application->getRecommendedBy() ? 'welcome-startplatz' '';
  1139.                 return $this->redirect($this->generateUrl('apply_program_monsum-checkout', [
  1140.                     'id' => $application->getId(),
  1141.                     'programSlug' => $program->getSlug(),
  1142.                     'batchSlug' => $batch->getSlug(),
  1143.                     'customerId' => $customer->getHash(),
  1144.                     'promocode' => $promocode,
  1145.                 ]));
  1146.             }
  1147.         }
  1148.     }
  1149.     private function setEditWidgetByTemplate($template)
  1150.     {
  1151.         switch ($template) {
  1152.             case "accelerator":
  1153.                 $editWidget '@StartPlatzRheinlandPitchBundle/Apply/_edit.accelerator.widget.html.twig';
  1154.                 break;
  1155.             case "membership":
  1156.                 $editWidget '@StartPlatzRheinlandPitchBundle/Apply/_edit.membership.widget.html.twig';
  1157.                 break;
  1158.             case "registration":
  1159.             case "businessclub":
  1160.             case "event":
  1161.             case "speed-networking":
  1162.             case "sign-up":
  1163.                 $editWidget '@StartPlatzRheinlandPitchBundle/Apply/_edit.registration.widget.html.twig';
  1164.                 break;
  1165.             case "nft":
  1166.                 $editWidget '@StartPlatzRheinlandPitchBundle/Apply/_edit.nft.widget.html.twig';
  1167.                 break;
  1168.             default:
  1169.                 $editWidget '@StartPlatzRheinlandPitchBundle/Apply/_edit.default.widget.html.twig';
  1170.                 break;
  1171.         }
  1172.         /*
  1173.         these templates are implemented as of 19.10.2021
  1174.         accelerator 25
  1175.         businessclub 8
  1176.         effzeh 1
  1177.         event 37
  1178.         feedback-zu-deiner-startup-idee 46
  1179.         membership 13
  1180.         membership-per-api 2
  1181.         registration 18
  1182.         rheinland-pitch 122
  1183.         sign-up 2
  1184.         speed-networking 161
  1185.         startup-tools 19
  1186.         */
  1187.         return $editWidget;
  1188.     }
  1189.     private function getLandingPageDescription($type)
  1190.     {
  1191.         if ($type == 'default-de') {
  1192.             $description "
  1193.                     <section>
  1194.                         <ul>
  1195.                             <li>Du m&ouml;chtest wissen, wie Du am STARTPLATZ Mitglied werden kannst?
  1196.                             <ul>
  1197.                                 <li>=> <a href=\/tarife/\">Dann informiere Dich auf unserer Mitgliedschafts-Seite</a></li>
  1198.                             </ul>
  1199.                             </li>
  1200.                             <li>Du m&ouml;chtest wissen, welche Konferenzr&auml;ume Du am STARTPLATZ buchen kannst?
  1201.                             <ul>
  1202.                                 <li>=> Dann informiere Dich zu den <a href=\"/koeln-tagungsraeume-und-konferenzraeume/\">Konferenzr&auml;umen in K&ouml;ln</a> oder zu den <a href=\"/duesseldorf-tagungsraeume-und-konferenzraeume/\">Konferenzr&auml;umen in D&uuml;sseldorf</a></li>
  1203.                             </ul>
  1204.                             </li>
  1205.                             <li>Du m&ouml;chtest wissen, welche Workshops oder Events am STARTPLATZ stattfinden?
  1206.                             <ul>
  1207.                                 <li>=> <a href=\"/events/list\">Dann informiere Dich auf unseren Event-Seiten</a></li>
  1208.                             </ul>
  1209.                             </li>
  1210.                         </ul>
  1211.                     </section>
  1212.                     ";
  1213.         } else {
  1214.             $description "
  1215.                     <ul>
  1216.                         <li>Do you want to explore more options within STARTPLATZ?
  1217.                         <ul>
  1218.                             <li>=> <a href=\/tarife/\">go to our Membership Page</a></li>
  1219.                         </ul>
  1220.                         </li>
  1221.                         <li>Do you want to book additional conference rooms at STARTPLATZ?
  1222.                         <ul>
  1223.                             <li>=> Go to <a href=\"/koeln-tagungsraeume-und-konferenzraeume/\">Konferenzr&auml;umen in K&ouml;ln</a> or go to <a href=\"/duesseldorf-tagungsraeume-und-konferenzraeume/\">Konferenzr&auml;umen in D&uuml;sseldorf</a></li>
  1224.                         </ul>
  1225.                         </li>
  1226.                         <li>Do you want to know more about current events at STARTPLATZ?
  1227.                         <ul>
  1228.                             <li>=> <a href=\"/events/list\">Go to our events page</a></li>
  1229.                         </ul>
  1230.                         </li>
  1231.                     </ul>
  1232.                     ";
  1233.         }
  1234.         return $description;
  1235.     }
  1236.     private function setActionByProgramSlug(Application $application)
  1237.     {
  1238.         switch ($application->getTemplate()) {
  1239.             case "rheinland-pitch":
  1240.             case "rheinland-pitch-web3":
  1241.             case "accelerator":
  1242.                 $action "continue";
  1243.                 break;
  1244.             case "membership":
  1245.                 $action "goToMonsum";
  1246.                 break;
  1247.             default:
  1248.                 $action "finish";
  1249.                 break;
  1250.         }
  1251.         // only in case of membership the program slug counts more
  1252.         if ($application->getProgramSlug() == 'membership') {
  1253.             $action "goToMonsum";
  1254.         }
  1255.         return $action;
  1256.     }
  1257.     private function setApplicationStatusByTemplate(Application $application)
  1258.     {
  1259.         $em $this->entityManager;
  1260.         switch ($application->getTemplate()) {
  1261.             case "rheinland-pitch":
  1262.             case "rheinland-pitch-web3":
  1263.             case "accelerator":
  1264.                 $application $em->getRepository(Application::class)->setApplicationStarted($application);
  1265.                 break;
  1266.             default:
  1267.                 $application $em->getRepository(Application::class)->setApplicationApplied($application);
  1268.                 break;
  1269.         }
  1270.         return $application;
  1271.     }
  1272.     private function updateApplicationByTeam(Application $applicationTeam $team)
  1273.     {
  1274.         $em $this->entityManager;
  1275.         $application->setTeamId($team->getId());
  1276.         $application->setStartupName($team->getShortName());
  1277.         $application->setCity($team->getAddressCity());
  1278.         $application->setTeamSize($team->getNEmployees());
  1279.         $application->setWebsiteUrl($team->getHomepage());
  1280.         if ($team->getStartupId()) {
  1281.             $startup $em->getRepository(Startup::class)->find($team->getStartupId());
  1282.             $application->setIdeaPitch($startup->getOneSentencePitch());
  1283.             $application->setIndustry($startup->getIndustry());
  1284.             $application->setStartupId($team->getStartupId());
  1285.         }
  1286.         return $application;
  1287.     }
  1288.     /**
  1289.      * Snapshot member data at registration time for historical analysis.
  1290.      * Captures tags, membership status, UTM source, and KI-Kompetenz at the moment of registration.
  1291.      */
  1292.     private function setMemberSnapshotAtRegistration(Application $applicationMember $member): void
  1293.     {
  1294.         // Capture member tags at registration
  1295.         $application->setMemberTagsAtRegistration($member->getTags());
  1296.         // Capture community membership status
  1297.         $application->setWasCommunityMemberAtRegistration($member->getHasCommunityMembership() ?? false);
  1298.         // Check if member was a physical/coworking member at registration time
  1299.         $isPhysicalMember $member->getPhysicalMembershipStarted() !== null
  1300.             && ($member->getPhysicalMembershipEnded() === null
  1301.                 || $member->getPhysicalMembershipEnded() > new \DateTime());
  1302.         $application->setWasPhysicalMemberAtRegistration($isPhysicalMember);
  1303.         // Capture member's original UTM source (first touch attribution)
  1304.         $application->setMemberUtmSourceAtRegistration($member->getUtmSource());
  1305.         // Capture member's KI-Kompetenz level at registration
  1306.         $application->setKiKompetenzAtRegistration($member->getKiKompetenz());
  1307.     }
  1308.     private function setTeam($member$settings$teamIdTeam $applicantsTeam)
  1309.     {
  1310.         $em $this->entityManager;
  1311.         if ($settings['isTeamNeeded']) {
  1312.             if ($teamId == 'create' or $teamId == 0) {
  1313.                 $team $em->getRepository(Team::class)->setNewTeamForApplication($member$settings);
  1314.             } else {
  1315.                 if ($settings['isSignUp']) {
  1316.                     // in this case virtual teams are okay
  1317.                     $team $em->getRepository(Team::class)->find($teamId);
  1318.                 } else {
  1319.                     $virtualTeams $em->getRepository(Team::class)->findKeysOfVirtualTeams();
  1320.                     if (in_array($member->getTeamId(), $virtualTeams)) {
  1321.                         $team $em->getRepository(Team::class)->setNewTeamForApplication($member$settings);
  1322.                     } else {
  1323.                         $team $em->getRepository(Team::class)->find($teamId);
  1324.                     }
  1325.                 }
  1326.             }
  1327.         } else {
  1328.             // in this case we need only the virtual team related with that batch
  1329.             $team $applicantsTeam;
  1330.         }
  1331.         return $team;
  1332.     }
  1333.     private function evaluateAliasSlug($routeName)
  1334.     {
  1335.         $em $this->entityManager;
  1336.         $status "";
  1337.         $message "";
  1338.         $todo "";
  1339.         $data = ['program' => false'batch' => false];
  1340.         $programSlug 'membership';
  1341.         switch ($routeName) {
  1342.             case "startup-academy-test-mitgliedschaft_buchen_de":
  1343.                 $batchSlug '16127-test-trial-startup-academy-community-membership';
  1344.                 break;
  1345.             case "schnuppermitgliedschaft_buchen_de":
  1346.             case "schnuppermitgliedschaft_buchen_welcome_de":
  1347.             case "schnuppermitgliedschaft_buchen_en":
  1348.                 $batchSlug '16017-cgn-trial-community-membership';
  1349.                 break;
  1350.             case "schnuppermitgliedschaft_team_buchen_de":
  1351.             case "schnuppermitgliedschaft_team_buchen_welcome_de":
  1352.                 $batchSlug '17047-cgn-trial-startup-membership';
  1353.                 break;
  1354.             case "free-token":
  1355.                 $batchSlug 'free-to-own-token-meetup-24112022';
  1356.                 break;
  1357.             default:
  1358.                 $batchSlug '16017-cgn-trial-community-membership';
  1359.                 break;
  1360.         }
  1361.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
  1362.             return false;
  1363.         } else {
  1364.             $status "success";
  1365.             $data = ['batch' => $batch'program' => $batch->getProgram()];
  1366.             $response = [
  1367.                 'status' => $status,
  1368.                 'todo' => $todo,
  1369.                 'message' => $message,
  1370.                 'data' => $data,
  1371.             ];
  1372.             return $response;
  1373.         }
  1374.     }
  1375.     private function evaluateApplicationEmail(Application $application$memberTeam $team$settings$user)
  1376.     {
  1377.         $em $this->entityManager;
  1378.         $status "";
  1379.         $message "";
  1380.         $todo "";
  1381.         $data = ['application' => $application'member' => $member];
  1382.         $isEmailRegistered $em->getRepository(Member::class)->isEmailRegistered($application->getEmail());
  1383.         $isMemberloggedIn $user true false;
  1384.         $existingApplication false;
  1385.         if ($isEmailRegistered) {
  1386.             $existingMember $em->getRepository(Member::class)->findOneBy(['email' => $application->getEmail()]);
  1387.             $existingApplication $this->checkForMultipleApplications($team$existingMember$settings);
  1388.         }
  1389.         // ['Anonymous' => 'anonymous', 'Login' => 'login', 'Community Membership'=>'hasCommunityMembership', 'Startup Membership'=>'hasStartupMembership'],'required'=> false])
  1390.         switch ($settings['access']) {
  1391.             case "anonymous":
  1392.                 if ($isEmailRegistered == false and $isMemberloggedIn == false) {
  1393.                     if ($settings['isNeedsEmailValidation']) {
  1394.                         $status "error";
  1395.                         $todo "validateEmail";
  1396.                         $message "Email is not yet registered. Email needs to be validated";
  1397.                         $application $em->getRepository(Application::class)->setErrorValidateEmail($application);
  1398.                     } else {
  1399.                         $status "process";
  1400.                         $todo "notValidatedEmail";
  1401.                         $message "Email will be registered without being validated";
  1402.                         $application $em->getRepository(Application::class)->setEditStatus($application$status$todo$message);
  1403.                     }
  1404.                     $data['email'] = $application->getEmail();
  1405.                     $data['firstName'] = $application->getFirstName();
  1406.                     $data['lastName'] = $application->getLastName();
  1407.                     $data['name'] = $application->getPerson();
  1408.                     $adminEmail $application->getEmail();
  1409.                     if ($settings['isTeamNeeded']) {
  1410.                         $memberType "GF";
  1411.                     } else {
  1412.                         $memberType "MA";
  1413.                     }
  1414.                     $member $em->getRepository(Member::class)->createGuestMemberIfNotExists($data$team$adminEmail$memberType);
  1415.                     $application->setMemberId($member->getId());
  1416.                     $this->setMemberSnapshotAtRegistration($application$member);
  1417.                     $application->setTeamId($team->getId());
  1418.                     $data = ['application' => $application'member' => $member];
  1419.                 }
  1420.                 if ($isEmailRegistered == false and $isMemberloggedIn == true) {
  1421.                     $status "error";
  1422.                     $todo "check2ndAccount";
  1423.                     $message "You are registered at STARTPLATZ with another email address.";
  1424.                     $application->setSecondaryEmail($application->getEmail());
  1425.                     $application->setEmail($member->getEmail());
  1426.                     $data = ['application' => $application'member' => $member];
  1427.                 }
  1428.                 if ($isEmailRegistered == true and $isMemberloggedIn == false) {
  1429.                     // "error"; "validateLogin";
  1430.                     /** @var Member $existingMember */
  1431.                     $isAdmin false;
  1432.                     if ($existingMember) {
  1433.                         // check if member is admin
  1434.                         $user $em->getRepository(User::class)->findOneBy(['memberId' => $existingMember->getId()]);
  1435.                         if ($user->getIsAdmin()) {
  1436.                             $isAdmin true;
  1437.                         }
  1438.                     }
  1439.                     if ($settings['isNeedsLoginValidation'] or $isAdmin) {
  1440.                         $status "error";
  1441.                         $todo "validateLogin";
  1442.                         $message "This email address is already in use. Please login to make your application valid.";
  1443.                     } else {
  1444.                         $status "process";
  1445.                         $todo "notValidatedLogin";
  1446.                         $message "This email address is already in use. Application will be processed without login being validated";
  1447.                     }
  1448.                     if (!$existingApplication) {
  1449.                         $message "This email address is already in use. Please login to make your application valid.";
  1450.                         $application->setMemberId($existingMember->getId());
  1451.                         $this->setMemberSnapshotAtRegistration($application$existingMember);
  1452.                         if (!$team->getId()) {
  1453.                             if ($settings['createAlwaysNewTeam']) {
  1454.                                 $team $em->getRepository(Team::class)->createTeamByApplication($application$settings$member);
  1455.                                 $application->setTeamId($team->getId());
  1456.                                 $em->getRepository(Member::class)->setTeamAssignment($existingMember$team'GF'$application->getEmail());
  1457.                             } else {
  1458.                                 $application->setTeamId($existingMember->getTeamId());
  1459.                             }
  1460.                         }
  1461.                     } else {
  1462.                         $message "This email address is already in use and there is already an application of your team. Please login to edit your application.";
  1463.                         $application $existingApplication;
  1464.                     }
  1465.                     $application $em->getRepository(Application::class)->setEditStatus($application$status$todo$message);
  1466.                     $data = ['application' => $application'member' => $existingMember];
  1467.                 }
  1468.                 if ($isEmailRegistered == true and $isMemberloggedIn == true) {
  1469.                     if ($user->getEmail() != $application->getEmail()) {
  1470.                         // "error"; "validateLogin";
  1471.                         $status "error";
  1472.                         $todo "validateLogin";
  1473.                         $application $em->getRepository(Application::class)->setErrorValidateLogin($application);
  1474.                     } else {
  1475.                         if ($application->getProgramSlug() == "membership") {
  1476.                             $status "process";
  1477.                             $todo "goToMonsum";
  1478.                             $message "You need to check out";
  1479.                         } else {
  1480.                             $status "success";
  1481.                             $todo "loggedIn";
  1482.                             $message "We will register your application";
  1483.                         }
  1484.                         $data = ['application' => $application'member' => $member];
  1485.                     }
  1486.                 }
  1487.                 $application->setEditStatus("{$status}:{$todo}");
  1488.                 $application->setEditMessage($message);
  1489.                 break;
  1490.             case "login":
  1491.             case "hasCommunityMembership":
  1492.             case "hasStartupMembership":
  1493.                 if ($existingApplication) {
  1494.                     $data['application'] = $existingApplication;
  1495.                 }
  1496.                 break;
  1497.             default:
  1498.                 break;
  1499.         }
  1500.         $response = [
  1501.             'status' => $status,
  1502.             'todo' => $todo,
  1503.             'message' => $message,
  1504.             'data' => $data,
  1505.             'hasExistingApplication' => !!$existingApplication,
  1506.         ];
  1507.         return $response;
  1508.     }
  1509.     private function checkForMultipleApplications(Team $teamMember $member$settings)
  1510.     {
  1511.         $em $this->entityManager;
  1512.         $application null;
  1513.         if (!$settings['isMultipleApplicationsPerTeam'] and $team->getId()) {
  1514.             $application $em->getRepository(Application::class)->findOneBy(['teamId' => $team->getId(), 'batchId' => $settings['batchId']]);
  1515.         } else {
  1516.             if (!$settings['isMultipleApplicationsPerMember']) {
  1517.                 $application $em->getRepository(Application::class)->findOneBy(['memberId' => $member->getId(), 'batchId' => $settings['batchId']]);
  1518.             }
  1519.         }
  1520.         return $application;
  1521.     }
  1522.     private function checkPlausibility(Application $applicationMember $memberTeam $team$settings)
  1523.     {
  1524.         $em $this->entityManager;
  1525.         $status "";
  1526.         $message "";
  1527.         $todo "";
  1528.         $data = ['application' => $application];
  1529.         switch ($settings['programSlug']) {
  1530.             case "rheinland-pitch":
  1531.             case "accelerator":
  1532.                 // plausibility checks
  1533.                 if ($em->getRepository(Application::class)->findByCriteriaButNotTeam(['programSlug' => $application->getProgramSlug(), 'batchSlug' => $application->getBatchSlug(), 'startupName' => $application->getStartupName()], $team)) {
  1534.                     $status "error";
  1535.                     $todo "changeName";
  1536.                     $message "An Application with this name already exists. Please change name!";
  1537.                 }
  1538.                 if (!$application->getIdeaPitch()) {
  1539.                     $status "error";
  1540.                     $todo "fillOutIdeaPitch";
  1541.                     $message "Please specify your idea pitch!";
  1542.                 }
  1543.                 $wordsCount str_word_count($application->getIdeaPitch() ?? '');
  1544.                 if ($wordsCount 150) {
  1545.                     $status "error";
  1546.                     $todo "shortenIdeaPitch";
  1547.                     $message "Your idea pitch contains {$wordsCount} words, max words is 150, please reduce the length of your idea pitch!";
  1548.                 }
  1549.                 break;
  1550.             default:
  1551.                 break;
  1552.         }
  1553.         if ($status "") {
  1554.             $application->setEditStatus("{$status}:{$todo}");
  1555.             $application->setEditMessage($message);
  1556.             $data = ['application' => $application];
  1557.         }
  1558.         $response = [
  1559.             'status' => $status,
  1560.             'todo' => $todo,
  1561.             'message' => $message,
  1562.             'data' => $data,
  1563.         ];
  1564.         return $response;
  1565.     }
  1566.     private function setMonsumAccountIfNotExists(Member $memberTeam $teamApplication $application$account)
  1567.     {
  1568.         $em $this->entityManager;
  1569.         $adminEmail $member->getEmail();
  1570.         $responseContent = [];
  1571.         $teamId $team->getId();
  1572.         $customer null;
  1573.         $monsumCustomer null;
  1574.         $settings = [
  1575.             'adminEmail' => $adminEmail,
  1576.             'location' => $em->getRepository(Customer::class)->getLocationByAccount($account),
  1577.             'account' => $account,
  1578.             'accountHash' => $em->getRepository(Customer::class)->getAccountHashByAccount($account),
  1579.         ];
  1580.         $login $em->getRepository(Customer::class)->getLoginByAccount($account);
  1581.         $payload json_encode([
  1582.             'SERVICE' => "customer.get",
  1583.             'FILTER' => [
  1584.                 'CUSTOMER_EXT_UID' => "{$team->getId()}",
  1585.             ],
  1586.         ]);
  1587.         $feedback $this->callbackService->curl_get_monsum_all($payload$login);
  1588.         $feedback json_decode($feedback);
  1589.         if (isset($feedback->RESPONSE->CUSTOMERS[0])) {
  1590.             $responseContent[] = "Team {$teamId} has already account in Monsum";
  1591.             $customer $feedback->RESPONSE->CUSTOMERS[0];
  1592.         } else {
  1593.             $responseContent[] = "New account will be created for team {$teamId} in Monsum";
  1594.             $customerSettings $em->getRepository(Customer::class)->getCustomerSettingsByTeamAndMember($team$member);
  1595.             $payload json_encode([
  1596.                 'SERVICE' => "customer.create",
  1597.                 'DATA' => $customerSettings,
  1598.             ]);
  1599.             $feedback $this->callbackService->curl_get_monsum_all($payload$login);
  1600.             $feedback json_decode($feedback);
  1601.             $monsumResponse $feedback->RESPONSE;
  1602.             if (isset($monsumResponse->ERRORS)) {
  1603.                 $responseContent[] = "ERROR ======== ERROR";
  1604.                 $responseContent[] = $monsumResponse->ERRORS;
  1605.                 $responseContent[] = $feedback;
  1606.             } else {
  1607.                 $responseContent[] = $monsumResponse;
  1608.                 if ($monsumResponse->STATUS == "success") {
  1609.                     $customerId $monsumResponse->CUSTOMER_ID;
  1610.                     $payload $em->getRepository(Customer::class)->getPayloadSingleCustomerByCustomerId($customerId);
  1611.                     $feedback $this->callbackService->curl_get_monsum_all($payload$login);
  1612.                     if ($feedback json_decode($feedback)) {
  1613.                         $customer $feedback->RESPONSE->CUSTOMERS[0];
  1614.                     } else {
  1615.                         $responseContent[] = "ERROR: could not decode feedback from monsum";
  1616.                         $responseContent[] = $feedback;
  1617.                     }
  1618.                 }
  1619.             }
  1620.         }
  1621.         if ($customer) {
  1622.             $monsumCustomer $em->getRepository(Customer::class)->createOrUpdateMonsumCustomerByTeam($customer$settings$team);
  1623.         }
  1624.         return $monsumCustomer;
  1625.     }
  1626.     #[Route('/apply-add-application/{memberId}/{batchId}/'name'apply_add-application')]
  1627.     public function addApplicationAction(Request $request$batchId$memberId)
  1628.     {
  1629.         $em $this->entityManager;
  1630.         $redirect Utility::getRedirectTarget($request);
  1631.         $now = new datetime();
  1632.         $batch $em->getRepository(Batch::class)->findOneBy(['id' => $batchId]);
  1633.         $program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['id' => $batch->getProgramId()]);
  1634.         $member $em->getRepository(Member::class)->findOneBy(['id' => $memberId]);
  1635.         // check if settings contains necessary setters
  1636.         $batch $em->getRepository(Batch::class)->checkLegacyData($batch);
  1637.         $settings $em->getRepository(Application::class)->getSettingsProgram($program$batch);
  1638.         /** @var User $user */
  1639.         $user $this->getUser();
  1640.         $adminEmail $user->getEmail();
  1641.         $em->getRepository(User::class)->writeActivity($user);
  1642.         // falls member Mitglied in mehreren teams ist, auswählen lassen, ob für bestehendes team einreichen oder für neues team
  1643.         $virtualTeam array_key_exists('virtualTeam'$settings) ? $settings['virtualTeam'] : 'applicants';
  1644.         $applicantsTeam $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
  1645.         // check if $member is part of specified - virtual team
  1646.         if (!$applicantsTeamMember $em->getRepository(MemberTeam::class)->findOneBy(['team' => $applicantsTeam'member' => $member])) {
  1647.             $em->getRepository(Member::class)->setTeamAssignmentByUser($user$member->getId(), $applicantsTeam->getId());
  1648.         }
  1649.         $id $member->getTeamId();
  1650.         $team $em->getRepository(Team::class)->findOneBy(['id' => $id]);
  1651.         $teamMember $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team'member' => $member]);
  1652.         $teamId $team->getId();
  1653.         if ($batch->getIsMultipleApplicationsPerTeam()) {
  1654.             if (!$application $em->getRepository(Application::class)->findOneBy(['programSlug' => $program->getSlug(), 'batchSlug' => $batch->getSlug(), 'memberId' => $member->getId()])) {
  1655.                 $application $em->getRepository(Application::class)->createApplicationIfNotExists($program$batch$team$member$adminEmail);
  1656.             }
  1657.         } else {
  1658.             if (!$application $em->getRepository(Application::class)->findOneBy(['programSlug' => $program->getSlug(), 'batchSlug' => $batch->getSlug(), 'teamId' => $teamId])) {
  1659.                 $application $em->getRepository(Application::class)->createApplicationIfNotExists($program$batch$team$member$adminEmail);
  1660.             }
  1661.         }
  1662.         $application->setBatchStatus('applicant');
  1663.         $application->setApplicationStatus('applied');
  1664.         $em->persist($application);
  1665.         $em->flush();
  1666.         $batch $em->getRepository(Batch::class)->updateNumbers($batch);
  1667.         $this->session->getFlashBag()->add('notice''SUCCESS ' "Application created for member {$member->getName()} and batch {$batch->getName()}");
  1668.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  1669.     }
  1670.     #[Route('/apply/{programSlug}/{batchSlug}/action/get-access'name'apply_program_get_access')]
  1671.     public function getAccessAction(Request $request$programSlug$batchSlug)
  1672.     {
  1673.         $em $this->entityManager;
  1674.         $data $request->request->all();
  1675.         if (!($data['email'] and $data['firstName'] and $data['lastName'])) {
  1676.             $this->session->getFlashBag()->add('notice''ERROR Please fill in your data');
  1677.             return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1678.         }
  1679.         // https://symfony.com/doc/4.4/validation/raw_values.html
  1680.         $validator Validation::createValidator();
  1681.         $constraint = new Assert\Collection([
  1682.             // the keys correspond to the keys in the input array
  1683.             'firstName' => new Assert\Length(['min' => 3]),
  1684.             'lastName' => new Assert\Length(['min' => 3]),
  1685.             'email' => new Assert\Email(),
  1686.         ]);
  1687.         if ($violations $validator->validate($data$constraint)) {
  1688.             $error false;
  1689.             foreach ($violations as $violation) {
  1690.                 $this->session->getFlashBag()->add('notice''ERROR ' $violation->getMessage());
  1691.                 $error true;
  1692.             }
  1693.             if ($error) {
  1694.                 return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1695.             }
  1696.         }
  1697.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  1698.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  1699.             return $this->redirect($this->generateUrl('apply_home', []));
  1700.         }
  1701.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
  1702.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no batch found');
  1703.             return $this->redirect($this->generateUrl('apply_home', []));
  1704.         }
  1705.         $settingsProgram $em->getRepository(Application::class)->getSettingsProgram($program$batch);
  1706.         //$adminEmail = $data['email'];
  1707.         $userEmail $data['email'];
  1708.         $adminEmail "support@startplatz.de";
  1709.         // check if there is the defined virtual team
  1710.         $virtualTeam array_key_exists('virtualTeam'$settingsProgram) ? $settingsProgram['virtualTeam'] : 'applicants';
  1711.         $team $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
  1712.         $member $em->getRepository(Member::class)->createGuestMemberIfNotExists($data$team$userEmail);
  1713.         $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1714.         $mailSubject "{$settingsProgram['programName']} - Access Code - Application Area";
  1715.         $mailText $this->renderView(
  1716.             '@StartPlatzRheinlandPitchBundle/Apply/_mail.get.access.txt.twig',
  1717.             [
  1718.                 'member' => $member,
  1719.                 'loginLink' => $loginLink,
  1720.                 'settings' => $settingsProgram,
  1721.             ]
  1722.         );
  1723.         $this->callbackService->sendAlertMailPerZapier("{$member->getEmail()}"$mailText$mailSubject$adminEmail);
  1724.         $mailText "
  1725. Es gibt eine Anmeldung von {$data['firstName']} {$data['lastName']}   
  1726. Bewerber im Program {$settingsProgram['programName']} mit der E-Mail-Adresse {$data['email']}
  1727. und der Bitte um Zugang zum internen Bereich
  1728.         ";
  1729.         $this->callbackService->sendAlertMailPerZapier($adminEmail$mailText"{$settingsProgram['programName']} - Registration internal Area"$userEmail);
  1730.         $this->callbackService->setSlackMonitoring($mailText);
  1731.         $this->session->getFlashBag()->add('notice''SUCCESS Thank you for your message; we have sent you an access code');
  1732.         return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1733.     }
  1734.     #[Route('/apply/{programSlug}/{batchSlug}/action/feedback'name'apply_program_feedback')]
  1735.     public function receiveFeedbackAction(Request $request$programSlug$batchSlug)
  1736.     {
  1737.         $em $this->entityManager;
  1738.         $data $request->request->all();
  1739.         if (!array_key_exists('context'$data)) {
  1740.             $data['context'] = "Application Platform";
  1741.         }
  1742.         if (!$data['email']) {
  1743.             $this->session->getFlashBag()->add('notice''ERROR Please specify your email address');
  1744.             return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1745.         }
  1746.         $mailText "
  1747. Es gibt eine Nachricht von {$data['name']}        
  1748. mit der E-Mail-Adresse {$data['email']}
  1749. und dem Betreff: {$data['subject']}
  1750. und dem Inhalt:
  1751. {$data['message']}
  1752.         ";
  1753.         $this->callbackService->sendAlertMailPerZapier("lorenz.graef@startplatz.de"$mailText$data['context'] . ": " $data['subject'], "support@startplatz.de");
  1754.         $this->callbackService->setSlackMonitoring($mailText);
  1755.         $this->session->getFlashBag()->add('notice''SUCCESS Thank you for your message');
  1756.         return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1757.     }
  1758.     #[Route('/apply/{programSlug}/{batchSlug}/{id}/account'name'apply_program_account')]
  1759.     /**
  1760.      * @IsGranted("ROLE_USER")
  1761.      */
  1762.     public function accountAction(Request $request$programSlug$batchSlug$id)
  1763.     {
  1764.         $em $this->entityManager;
  1765.         if (!$user $this->getUser()) {
  1766.             return $this->redirect($this->generateUrl('apply_home', []));
  1767.         }
  1768.         $em->getRepository(User::class)->writeActivity($user);
  1769.         $form $this->createForm(SetPasswordFormType::class);
  1770.         $form->handleRequest($request);
  1771.         if ($form->isSubmitted() && $form->isValid()) {
  1772.             /** @var User $user */
  1773.             $user $this->getUser();
  1774.             $data $form->getData();
  1775.             $password $data['new_password'];
  1776.             $encodedPassword $this->encoder->encodePassword($user$password);
  1777.             $user->setPassword($encodedPassword);
  1778.             $em->getRepository(User::class)->add($user);
  1779.             $message = new Email();
  1780.             $message->to($user->getEmail());
  1781.             $message->from('info@startplatz.de');
  1782.             $message->subject('Your password for startplatz.de has been changed');
  1783.             $message->text(
  1784.                 $this->renderView(
  1785.                     '@StartPlatzUserBundle/Mails/passwordChangeAlert.txt.twig',
  1786.                     [
  1787.                         'email' => $user->getEmail(),
  1788.                         'password' => $password,
  1789.                     ]
  1790.                 )
  1791.             );
  1792.             $this->mailer->send($message);
  1793.             $this->session->getFlashBag()->add('notice''SUCCESS ' "Passwort has been set");
  1794.             return $this->redirect($this->generateUrl('apply_program_home', ['id' => $id'programSlug' => $programSlug'batchSlug' => $batchSlug]));
  1795.         }
  1796.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/account.html.twig', [
  1797.             'form' => $form->createView(),
  1798.             'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home''parameters' => ['programSlug' => $programSlug'batchSlug' => $batchSlug]])),
  1799.         ]);
  1800.     }
  1801.     #[Route('/apply/{programSlug}/{batchSlug}/{id}/uploadPitchDeck'name'apply_program_uploadPitchDeck')]
  1802.     public function uploadPitchDeckAction(Request $request$programSlug$batchSlug$id)
  1803.     {
  1804.         $em $this->entityManager;
  1805.         $now = new datetime();
  1806.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
  1807.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no program found');
  1808.             return $this->redirect($this->generateUrl('apply_home', []));
  1809.         }
  1810.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
  1811.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no batch found');
  1812.             return $this->redirect($this->generateUrl('apply_home', []));
  1813.         }
  1814.         $settings $em->getRepository(Application::class)->getSettingsProgram($program$batch);
  1815.         /** @var User $user */
  1816.         if ($user $this->getUser()) {
  1817.             $em->getRepository(User::class)->writeActivity($user);
  1818.         }
  1819.         $isAdminUpload $request->get('isAdminUpload');
  1820.         if (!$application $em->getRepository(Application::class)->findOneBy(['programSlug' => $programSlug'batchSlug' => $batchSlug'id' => $id])) {
  1821.             $this->session->getFlashBag()->add('notice''ERROR no application found ');
  1822.             return $this->redirect($this->generateUrl('apply_home', []));
  1823.         }
  1824.         if (!$teamId $application->getTeamId()) {
  1825.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no team found');
  1826.             return $this->redirect($this->generateUrl('apply_home', []));
  1827.         }
  1828.         if (!$memberId $application->getMemberId()) {
  1829.             $this->session->getFlashBag()->add('notice''ERROR Sorry, no member found');
  1830.             return $this->redirect($this->generateUrl('apply_home', []));
  1831.         }
  1832.         if (!$isAdminUpload) {
  1833.             if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($memberId$teamId)) {
  1834.                 $this->session->getFlashBag()->add('notice''ERROR Sorry, we found a problem with the team access rights');
  1835.                 return $this->redirect($this->generateUrl('apply_home', []));
  1836.             }
  1837.         }
  1838.         $publicId $request->get('PublicId');
  1839.         $uploadTag "application/{$application->getId()}";
  1840.         if (!$isAdminUpload) {
  1841.             $redirectTargetUrl $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => strtolower($application->getLang())]);
  1842.         } else {
  1843.             $redirectTargetUrl $this->generateUrl('allmeda_application_edit', ['id' => $application->getId()]);
  1844.         }
  1845.         return $this->render('@StartPlatzRheinlandPitchBundle/Apply/uploadPitchDeck.html.twig', [
  1846.             'application' => $application,
  1847.             'settings' => $settings,
  1848.             'programSlug' => $programSlug,
  1849.             'batchSlug' => $batchSlug,
  1850.             'program' => $program,
  1851.             'batch' => $batch,
  1852.             'uploadTag' => $uploadTag,
  1853.             'publicId' => $publicId,
  1854.             'isAdminUpload' => $isAdminUpload,
  1855.             'teamId' => $teamId,
  1856.             'memberId' => $memberId,
  1857.             'redirect' => $redirectTargetUrl,
  1858.             'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang''parameters' => ['programSlug' => $programSlug'batchSlug' => $batchSlug'lang' => strtolower($application->getLang())]])),
  1859.         ]);
  1860.     }
  1861.     #[Route('/apply/{programSlug}/{batchSlug}/{id}/add-images-by-tag/'name'apply_program_add_images_by_tag')]
  1862.     public function addImagesByTagAction(Request $request$programSlug$batchSlug$id)
  1863.     {
  1864.         $time_start microtime(true);
  1865.         $tag $request->request->get('tag');
  1866.         $redirect Utility::getRedirectTarget($request);
  1867.         $em $this->entityManager;
  1868.         $now = new DateTime();
  1869.         if (!$application $em->getRepository(Application::class)->findOneBy(['id' => $id])) {
  1870.             $response = new Response();
  1871.             $response->setContent(json_encode('ERROR no application found'));
  1872.             $response->headers->set('Content-Type''application/json');
  1873.             return $response;
  1874.         }
  1875.         $result $this->cloudinary->resources_by_tag($tag);
  1876.         $resources $result['resources'];
  1877.         foreach ($resources as $resource) {
  1878.             $publicId $resource['public_id'];
  1879.             $secureUrl $resource['secure_url'];
  1880.             $application->setLinkPitchDeck($secureUrl);
  1881.             $application->setPublicIdPitchDeck($publicId);
  1882.             $application->setEditStatus("feedback:pitchdeckUploaded");
  1883.             $application->setEditMessage("Thank you for uploading your pitch deck.");
  1884.             $em->persist($application);
  1885.             $em->flush();
  1886.         }
  1887.         $response = new Response();
  1888.         $response->setContent(json_encode($result));
  1889.         $response->headers->set('Content-Type''application/json');
  1890.         return $response;
  1891.     }
  1892.     private function getSettingsProgramDefault()
  1893.     {
  1894.         return [
  1895.             "programName" => "Example",
  1896.             "programSlug" => "example",
  1897.             "batchName" => "Batch11",
  1898.             "batchSlug" => "batch11",
  1899.             "applicationStart" => "2019-11-11",
  1900.             "programStart" => "2019-12-11",
  1901.             "programEnd" => "2019-12-11",
  1902.             "applicationStages" => "applied,approved",
  1903.             "programStages" => "applicant,participant,alumni,drop-out,rejected",
  1904.             "programTag" => "example-batch11-participant",
  1905.             "eventId" => "4982",
  1906.             "bgImage" => "https://res.cloudinary.com/startplatz/image/upload/v1573496116/rheinland-pitch/impressions/final-koeln-2017_audience_manor-lux.jpg",
  1907.             "virtualTeam" => "example-team",
  1908.             "status" => "test",
  1909.         ];
  1910.     }
  1911.     #[Route('/apply/administration/batch/test-confirmation-mail/{batchId}'name'apply_test_confirmation-mail')]
  1912.     /**
  1913.      * @IsGranted("ROLE_ADMIN")
  1914.      */
  1915.     public function sendConfirmationTestMail(Request $request$batchId)
  1916.     {
  1917.         $redirect Utility::getRedirectTarget($request);
  1918.         $em $this->entityManager;
  1919.         $reminder null;
  1920.         $sendReminderMail $request->get('sendReminderMail');
  1921.         /** @var User $user */
  1922.         $user $this->getUser();
  1923.         $em->getRepository(User::class)->writeActivity($user);
  1924.         if ($sendReminderMail){
  1925.             $reminder $em->getRepository(Reminder::class)->find($batchId);
  1926.             $batchId $reminder->getBatchId();
  1927.         }
  1928.         /** @var Batch $batch */
  1929.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['id' => $batchId])) {
  1930.             $this->session->getFlashBag()->add('notice''ERROR batch not found');
  1931.             return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  1932.         }
  1933.         $member $em->getRepository(Member::class)->find($user->getMemberId());
  1934.         if (!$application $em->getRepository(Application::class)->findOneBy(['memberId'=>$member->getId(), 'batchId'=>$batch->getId()])){
  1935.             $application $em->getRepository(Application::class)->getTemporaryApplicationByBatchAndMember($batch$member);
  1936.             $application $em->getRepository(Application::class)->setApplicationDone($application);
  1937.         }
  1938.         $application->setApplicationStatus('applied');
  1939.         // Start timing
  1940.         $this->stopwatch->start('confirmation_mail');
  1941.         $response $this->sendConfirmationMailToApplicant($user, [], $application$batch$reminder);
  1942.         // Stop timing
  1943.         $stopwatchEvent $this->stopwatch->stop('confirmation_mail');
  1944.         // Get duration and memory usage
  1945.         $duration $stopwatchEvent->getDuration();
  1946.         $memory round($stopwatchEvent->getMemory() / (1024 1024), 2); // Convert to MB and round to 2 decimal places
  1947.         $this->addFlash('notice'"SUCCESS via service: A test confirmation mail has been sent to {$user->getEmail()}. Time: {$duration}ms, Memory: {$memory} MB");
  1948.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  1949.     }
  1950.     #[Route('/apply/administration/batch/test-confirmation-mail-service/{batchId}'name'apply_test_confirmation-mail_service')]
  1951.     /**
  1952.      * @IsGranted("ROLE_ADMIN")
  1953.      */
  1954.     public function sendConfirmationTestMailViaService(Request $request$batchId)
  1955.     {
  1956.         $redirect Utility::getRedirectTarget($request);
  1957.         $em $this->entityManager;
  1958.         $reminder null;
  1959.         $sendReminderMail $request->get('sendReminderMail');
  1960.         /** @var User $user */
  1961.         $user $this->getUser();
  1962.         $em->getRepository(User::class)->writeActivity($user);
  1963.         if ($sendReminderMail){
  1964.             $reminder $em->getRepository(Reminder::class)->find($batchId);
  1965.             $batchId $reminder->getBatchId();
  1966.         }
  1967.         /** @var Batch $batch */
  1968.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['id' => $batchId])) {
  1969.             $this->session->getFlashBag()->add('notice''ERROR batch not found');
  1970.             return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  1971.         }
  1972.         $member $em->getRepository(Member::class)->find($user->getMemberId());
  1973.         if (!$application $em->getRepository(Application::class)->findOneBy(['memberId'=>$member->getId(), 'batchId'=>$batch->getId()])){
  1974.             $application $em->getRepository(Application::class)->getTemporaryApplicationByBatchAndMember($batch$member);
  1975.             $application $em->getRepository(Application::class)->setApplicationDone($application);
  1976.         }
  1977.         $application->setApplicationStatus('applied');
  1978.         // Start timing
  1979.         $this->stopwatch->start('confirmation_mail');
  1980.         $result $this->confirmationMailService->sendConfirmationMailToApplicant($user$member, [], $application$batch$reminder);
  1981.         // Stop timing
  1982.         $stopwatchEvent $this->stopwatch->stop('confirmation_mail');
  1983.         // Get duration and memory usage
  1984.         $duration $stopwatchEvent->getDuration();
  1985.         $memory round($stopwatchEvent->getMemory() / (1024 1024), 2); // Convert to MB and round to 2 decimal places
  1986.         // Verarbeiten der Nachrichten aus dem Service
  1987.         foreach ($result['messages'] as $message) {
  1988.             $this->addFlash('notice'$message);
  1989.         }
  1990.         // Zusätzliche Flash-Nachricht für Leistungsinformationen
  1991.         $this->addFlash('notice'"Service execution: Time: {$duration}ms, Memory: {$memory} MB");
  1992.         // Status-basierte Nachricht
  1993.         if ($result['status'] === 'success') {
  1994.             $this->addFlash('notice''SUCCESS: Mail sent successfully via service');
  1995.         } else {
  1996.             $this->addFlash('notice''ERROR: Failed to send mail via service');
  1997.         }
  1998.         return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
  1999.     }
  2000.     private function sendConfirmationMailToApplicant(User $user$settingsApplication $applicationBatch $batchReminder $reminder null)
  2001.     {
  2002.         $em $this->entityManager;
  2003.         if (!$settings) {
  2004.             $application->setStartupName("Test Startup");
  2005.             $application->setEmail($user->getEmail());
  2006.         }
  2007.         $program $batch->getProgram();
  2008.         $routeParameters = [
  2009.             'programSlug' => $program->getSlug(),
  2010.             'batchSlug' => $batch->getSlug(),
  2011.         ];
  2012.         if (isset($reminder) && $reminder->getType() == 'feedbackMail' && $batch->getSurveyId() > ''){
  2013.             $loginPath = ['path'=>'survey_proceed','parameters'=>['id'=>$batch->getSurveyId(), 'slug'=>"{$program->getSlug()}-{$batch->getSlug()}"]];
  2014.             //$mailTemplate->setLoginPath(json_encode($loginPath));
  2015.             $targetPath $this->generateUrl($loginPath['path'], $loginPath['parameters']);
  2016.         } else {
  2017.             $targetPath $this->generateUrl('apply_program_home'$routeParameters);
  2018.         }
  2019.         $loginLink $this->loginService->getLoginLinkByTargetPath($application->getEmail(), $targetPath);
  2020.         $metaName $batch->getMailDesignTemplate();
  2021.         $designTemplate $em->getRepository(Option::class)->getOptionMetaValuePlain($metaName);
  2022.         if ($reminder){
  2023.             $content $reminder->getReminderMailContent();
  2024.             $subject $reminder->getReminderMailSubject();
  2025.         } else {
  2026.             $content $batch->getConfirmationMailContent();
  2027.             $subject $batch->getConfirmationMailSubject();
  2028.         }
  2029.         $loader = new ArrayLoader([
  2030.             'mailBase' => $designTemplate,
  2031.             'content' => $content,
  2032.             'subject' => $subject,
  2033.         ]);
  2034.         // create new twig object with all twig templates
  2035.         $twig = new Environment($loader);
  2036.         $viewBase 'mailBase';
  2037.         $viewContent 'content';
  2038.         $viewSubject 'subject';
  2039.         $renderedSubject $twig->render(
  2040.             $viewSubject,
  2041.             [
  2042.                 'userId' => $user->getId(),
  2043.                 'loginLink' => $loginLink,
  2044.                 'batch' => $batch,
  2045.                 'program' => $program,
  2046.                 'application' => $application,
  2047.                 'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
  2048.                 'dateDE' => $batch->getPitchDate()->format('d.m.y'),
  2049.                 'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
  2050.                 'timeDE' => $batch->getPitchTime()->format('H:i'),   // German 24-hour format
  2051.                 'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
  2052.             ]
  2053.         );
  2054.         $renderedContent $twig->render(
  2055.             $viewContent,
  2056.             [
  2057.                 'userId' => $user->getId(),
  2058.                 'name' => $application->getPerson(),
  2059.                 'firstName' => $application->getFirstName(),
  2060.                 'loginLink' => $loginLink,
  2061.                 'batch' => $batch,
  2062.                 'program' => $program,
  2063.                 'application' => $application,
  2064.                 'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
  2065.                 'dateDE' => $batch->getPitchDate()->format('d.m.y'),
  2066.                 'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
  2067.                 'timeDE' => $batch->getPitchTime()->format('H:i'),   // German 24-hour format
  2068.                 'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
  2069.                 'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
  2070.                 'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
  2071.             ]
  2072.         );
  2073.         $html $twig->render(
  2074.             $viewBase,
  2075.             [
  2076.                 'userId' => $user->getId(),
  2077.                 'name' => $application->getPerson(),
  2078.                 'firstName' => $application->getFirstName(),
  2079.                 'loginLink' => $loginLink,
  2080.                 'batch' => $batch,
  2081.                 'program' => $program,
  2082.                 'application' => $application,
  2083.                 'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
  2084.                 'dateDE' => $batch->getPitchDate()->format('d.m.y'),
  2085.                 'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
  2086.                 'timeDE' => $batch->getPitchTime()->format('H:i'),   // German 24-hour format
  2087.                 'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
  2088.                 'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
  2089.                 'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
  2090.                 'content' => $renderedContent,
  2091.             ]
  2092.         );
  2093.         $feedback Utility::sendAlertMailPerZapier($application->getEmail(), $html$renderedSubject$batch->getSenderMail(), $batch->getFromName(), 'html');
  2094.         $this->session->getFlashBag()->add('notice'"SUCCESS Confirmation Mail has been sent via Zapier to {$application->getEmail()} with feedback=" print_r($feedbacktrue));
  2095.         $mailSubject "{$batch->getProgram()->getName()} - Application submitted by {$application->getStartupName()}";
  2096.         $mailText $this->renderView(
  2097.             '@StartPlatzRheinlandPitchBundle/Apply/_mail.altert.admin.application.txt.twig',
  2098.             [
  2099.                 'user' => $user,
  2100.                 'batch' => $batch,
  2101.                 'application' => $application,
  2102.             ]
  2103.         );
  2104.         $feedback $this->callbackService->sendAlertMailPerZapier($batch->getRecipientMonitoringMail(), $mailText$mailSubject$application->getEmail());
  2105.         $this->session->getFlashBag()->add('notice'"SUCCESS Confirmation Mail has been sent via Zapier to {$application->getEmail()} with feedback=" print_r($feedbacktrue));
  2106.         if ($batch->getSkoolWebhook() > ''){
  2107.             $feedback $this->callbackService->sendPostRequest($batch->getSkoolWebhook(), $application->getEmail());
  2108.             $this->session->getFlashBag()->add('notice'"SUCCESS Skool Webhook has been posted with email= {$application->getEmail()} and feedback=" print_r($feedbacktrue));
  2109.         }
  2110.         if ($batch->getZapierWebhook() > ''){
  2111.             $payload json_encode($em->getRepository(Event::class)->setPayloadSingleApplicationAndBatch($application$batch));
  2112.             $callbackUrl $batch->getZapierWebhook();
  2113.             $feedback $this->callbackService->curl_callback($callbackUrl$payload);
  2114.             $this->session->getFlashBag()->add('notice'"SUCCESS Zapier webhook {$batch->getZapierWebhook()} called with feedback=" print_r($feedback,true));
  2115.         }
  2116.         if ($reminder && $reminder->getSkoolWebhook() > ''){
  2117.             $feedback $this->callbackService->sendPostRequest($reminder->getSkoolWebhook(), $application->getEmail());
  2118.             $this->session->getFlashBag()->add('notice'"SUCCESS Skool Webhook has been posted with email= {$application->getEmail()} and feedback=" print_r($feedbacktrue));
  2119.         }
  2120.         if ($reminder && $reminder->getZapierWebhook() > ''){
  2121.             $payload json_encode($em->getRepository(Event::class)->setPayloadSingleApplicationAndBatch($application$batch));
  2122.             $callbackUrl $reminder->getZapierWebhook();
  2123.             $feedback $this->callbackService->curl_callback($callbackUrl$payload);
  2124.             $this->session->getFlashBag()->add('notice'"SUCCESS Zapier webhook {$reminder->getZapierWebhook()} called with feedback=" print_r($feedback,true));
  2125.         }
  2126.         return true;
  2127.     }
  2128. }