<?php declare(strict_types=1);
namespace App\StartPlatz\Bundle\RheinlandPitchBundle\Controller;
/**
* CRITICAL DEPENDENCY WARNING - EVENT REGISTRATION SYSTEM
*
* This controller is heavily used by the EventBundle for event registrations.
* Event registration is the MOST IMPORTANT registration method for events.
*
* DO NOT modify this controller without thoroughly testing event registration functionality.
*
* Key dependencies from EventBundle:
* - EventBundle/Controller/DefaultController uses this for all internal event registrations
* - Event registration forms are rendered using templates from this bundle
* - Application workflow (validation, status management) is shared with events
*
* Critical methods used by events:
* - applyAction() - Main registration form handling
* - Form validation and submission logic
* - Email validation workflows (validateEmail/validateLogin)
* - Application status management
*
* Templates used by events:
* - Apply/_edit.registration.event.widget.html.twig
* - Apply/_edit.registration.widget.html.twig
* - Apply/apply.default.html.twig (for anonymous access)
*
* IMPORTANT: Event registrations depend on:
* - Application entity structure
* - Form field definitions in ApplicationType
* - Validation logic and error handling
* - Email confirmation workflows
* - Member/Team assignment logic
*
* See also:
* - EventBundle/Controller/DefaultController.php (lines 763-1000+ for registration logic)
* - StartupBundle/Entity/ApplicationRepository.php (for data operations)
* - Documentation: /doc/claude-files/application-process.md#event-integration
*/
use App\StartPlatz\Bundle\EventBundle\Entity\Event;
use App\StartPlatz\Bundle\MailmanBundle\ConfirmationMailService;
use App\StartPlatz\Bundle\MailmanBundle\Entity\MailTemplate;
use App\StartPlatz\Bundle\MemberBundle\Entity\Member;
use App\StartPlatz\Bundle\MemberBundle\Entity\MemberTeam;
use App\StartPlatz\Bundle\MemberBundle\Entity\Option;
use App\StartPlatz\Bundle\MemberBundle\Entity\Product;
use App\StartPlatz\Bundle\MemberBundle\Entity\Team;
use App\StartPlatz\Bundle\MetaBundle\Entity\Attribute;
use App\StartPlatz\Bundle\MonsumBundle\Entity\Customer;
use App\StartPlatz\Bundle\StartupBundle\Entity\Reminder;
use App\StartPlatz\Bundle\StartupBundle\Entity\Startup;
use App\StartPlatz\Bundle\WebsiteBundle\MenuTranslationService;
use DateTime;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Speicher210\CloudinaryBundle\Cloudinary\Api;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use App\StartPlatz\Bundle\FeedbackBundle\CallbackService;
use App\StartPlatz\Bundle\FeedbackBundle\Form\ContentPlainEditorFormType;
use App\StartPlatz\Bundle\StartupBundle\Entity\Application;
use App\StartPlatz\Bundle\StartupBundle\Entity\Batch;
use App\StartPlatz\Bundle\StartupBundle\Entity\Program;
use App\StartPlatz\Bundle\StartupBundle\Form\ApplicationType;
use App\StartPlatz\Bundle\UserBundle\Entity\User;
use App\StartPlatz\Bundle\UserBundle\Form\SetPasswordFormType;
use App\StartPlatz\Bundle\UserBundle\LoginService;
use App\StartPlatz\Bundle\WebsiteBundle\Utility\Utility;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
class ApplyController extends AbstractController
{
public function __construct(
private readonly SessionInterface $session,
private readonly MailerInterface $mailer,
private readonly CallbackService $callbackService,
private readonly LoginService $loginService,
private readonly UserPasswordEncoderInterface $encoder,
private readonly MenuTranslationService $menuTranslationService,
private readonly ConfirmationMailService $confirmationMailService,
private readonly Api $cloudinary,
private readonly Stopwatch $stopwatch,
) {
}
/*
* this page uses a collection of bootstrap4 pages
* https://colorlib.com/wp/template/meetup/
*/
/**
* @Route("/apply/action/allmeda_application_set-application-done/{applicationId}", name="allmeda_application_set-application-done" )
* @Security("is_granted('ROLE_ADMIN')")
*/
public function setApplicationDoneAction(Request $request, $applicationId)
{
$em = $this->getDoctrine()->getManager();
if (!$redirect = json_decode(base64_decode($request->get('redirect')))) {
$redirect = json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template', 'parameters' => []]));
}
$application = $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
$application = $em->getRepository(Application::class)->setApplicationDone($application);
$application = $em->getRepository(Application::class)->setApplication($application);
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
/**
* @Route("/apply/action/allmeda_application_set-error-validate-email/{applicationId}", name="allmeda_application_set-error-validate-email" )
* @Security("is_granted('ROLE_ADMIN')")
*/
public function setErrorValidateEmailAction(Request $request, $applicationId)
{
$em = $this->getDoctrine()->getManager();
if (!$redirect = json_decode(base64_decode($request->get('redirect')))) {
$redirect = json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template', 'parameters' => []]));
}
$application = $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
$application = $em->getRepository(Application::class)->setApplicationStarted($application);
$application = $em->getRepository(Application::class)->setErrorValidateEmail($application);
$application = $em->getRepository(Application::class)->setApplication($application);
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
/**
* @Route("/apply/action/allmeda_application_set-error-validate-login/{applicationId}", name="allmeda_application_set-error-validate-login" )
* @Security("is_granted('ROLE_ADMIN')")
*/
public function setErrorValidateLoginAction(Request $request, $applicationId)
{
$em = $this->getDoctrine()->getManager();
if (!$redirect = json_decode(base64_decode($request->get('redirect')))) {
$redirect = json_decode(json_encode(['path' => 'allmeda_doku_twig-render-mail-from-template', 'parameters' => []]));
}
$application = $em->getRepository(Application::class)->findOneBy(['id' => $applicationId]);
$application = $em->getRepository(Application::class)->setApplicationStarted($application);
$application = $em->getRepository(Application::class)->setErrorValidateLogin($application);
$application = $em->getRepository(Application::class)->setApplication($application);
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
/**
* @Route("/apply/action/list-tests", name="allmeda_startups_batches_test")
*/
public function listTestsAction(Request $request)
{
/*
* Program Slug: rheinland-pitch // Batch Slug:
* Program Slug: startup-tools // Batch Slug: 01-twilio-sms-voice-whatsapp
* Program Slug: online-circle-sales // Batch Slug: 05-session
* Program Slug: startplatz-aob // Batch Slug: 01-interesse-an-effzeh-karten
* Program Slug: feedback-zu-deiner-startup-idee // Batch Slug: 19-sondersitzung-woche-13
* Program Slug: rheinland-pitch-zuschauer // Batch Slug: 100-jubilaeum
* Program Slug: membership // Batch Slug: 17041-test-startup-membership
*/
$tests = [
'Rheinland-Pitch' => ['batchId' => 283, 'programSlug' => 'rheinland-pitch', 'batchSlug' => ''],
'Feedback' => ['batchId' => 298, 'programSlug' => 'feedback-zu-deiner-startup-idee', 'batchSlug' => ''],
'Startup Tools' => ['batchId' => 269, 'programSlug' => 'startup-tools', 'batchSlug' => '01-twilio-sms-voice-whatsapp'],
'Startup Tools AWS' => ['batchId' => 188, 'programSlug' => 'startup-tools', 'batchSlug' => '01-aws'],
'Online Circle' => ['batchId' => 386, 'programSlug' => 'online-circle-sales', 'batchSlug' => 'session-11'],
'OC Gründerstip.' => ['batchId' => 305, 'programSlug' => 'online-circle-gruenderstipendium', 'batchSlug' => '03-session'],
'RPitch-Zuschauer' => ['batchId' => 123, 'programSlug' => 'rheinland-pitch-zuschauer', 'batchSlug' => '100-jubilaeum'],
'Membership' => ['batchId' => 208, 'programSlug' => 'membership', 'batchSlug' => '17041-test-startup-membership'],
'Membership Trial' => ['batchId' => 360, 'programSlug' => 'membership', 'batchSlug' => '16017-cgn-trial-community-membership'],
'Event' => ['batchId' => 357, 'programSlug' => 'businessclub-politischer-dialog', 'batchSlug' => 'spd-08-07-2021'],
'Sign Up Mentor' => ['batchId' => 391, 'programSlug' => 'sign-up', 'batchSlug' => 'mentor-registration-01'],
];
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/list-tests.html.twig', [
'tests' => $tests,
'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
]);
}
/**
* @Route("/apply/action/add-to-podio/{batchId}/{applicationId}", name="apply_action_add-to-podio")
*/
public function triggerPodioAction(Request $request, $batchId, $applicationId)
{
$em = $this->getDoctrine()->getManager();
$responseContent = "";
$action = $request->get('action');
$batch = $em->getRepository(Batch::class)->find($batchId);
$application = $em->getRepository(Application::class)->find($applicationId);
if ($batch->getProgram()->getSlug() == 'accelerator') {
$responseContent = $this->addApplicationToPodioByZapier($application, $batch, $action);
} else {
$responseContent = $this->addApplicationToPodioByZapierSwitch($application, $batch);
}
$response = new Response();
$response->setContent(json_encode($responseContent));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/apply/action/run-workflow/{applicationId}", name="apply_action_run-workflow")
*/
public function runWorkflow(Request $request, $applicationId)
{
$em = $this->getDoctrine()->getManager();
$responseContent = "";
$application = $em->getRepository(Application::class)->find($applicationId);
$message = $em->getRepository(Application::class)->runApplicationDoneWorkflow($application);
$responseContent = "workflow set for application with id={$applicationId} and {$message}";
$this->session->getFlashBag()->add('notice', $responseContent );
return $this->redirect($this->generateUrl("allmeda_applications_home", ['filter'=>"batchId:{$application->getBatchId()}"]));
}
/**
* @Route("/apply/action/update-from-podio/{applicationId}", name="apply_action_update-from-podio")
*/
public function triggerPodioUpdateAction(Request $request, $applicationId)
{
$em = $this->getDoctrine()->getManager();
$responseContent = "";
$application = $em->getRepository(Application::class)->find($applicationId);
$payload = json_encode([
'applicationId' => $application->getId(),
'podioId' => $application->getPodioId() ? $application->getPodioId() : "",
'podioItemId' => $application->getPodioItemId() ? $application->getPodioItemId() : "",
'startupName' => $application->getStartupName(),
]);
if ($application->getPodioItemId()) {
$callbackUrl = "https://hooks.zapier.com/hooks/catch/1872803/bxkn68s/";
} else {
$callbackUrl = "https://hooks.zapier.com/hooks/catch/1872803/bxkn68s/";
}
$responseContent = $this->callbackService->curl_callback($callbackUrl, $payload);
$response = new Response();
$response->setContent(json_encode($responseContent));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/apply/action/podio-to-allmeda", name="apply_action_podio-to-allmeda")
*/
public function podioToAllmedaAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$parameters = $request->getContent();
$response = new Response();
$response->setContent(json_encode(["status" => "success"]));
$apikey = $request->headers->get('apikey');
if ($apikey != '50670') {
$response->setContent(json_encode(["status" => "error"]));
}
$parameters = json_decode($parameters);
$applicationId = $parameters->applicationId;
$podioId = $parameters->podioId;
$podioItemId = $parameters->podioItemId;
$podioUrl = $parameters->podioUrl;
if ($application = $em->getRepository(Application::class)->find($applicationId)) {
$application->setPodioId($podioId);
$application->setPodioItemId($podioItemId);
$application->setPodioUrl($podioUrl);
$em->persist($application);
$em->flush();
}
$response->headers->set('Content-Type', 'application/json');
return $response;
}
/**
* @Route("/apply/settings", defaults={"program" = "example", "batch" = "batch11"})
* @Route("/apply/{program}/settings", defaults={"batch" = "general"})
* @Route("/apply/{program}/{batch}/settings", name="apply_settings")
* @Security("is_granted('ROLE_ADMIN')")
*/
public function setSettingsAction(Request $request, $program, $batch)
{
$em = $this->getDoctrine()->getManager();
$now = new datetime();
$metaName = "settings.program.{$program}.{$batch}";
if (!$settingsProgram = $em->getRepository(Option::class)->getOptionMetaValue($metaName)) {
if (!$settingsProgram = $em->getRepository(Option::class)->getOptionMetaValue($metaName)) {
$settingsProgram = $this->getSettingsProgramDefault();
$em->getRepository(Option::class)->setOptionMetaValueJsonEncoded($metaName, "settingsProgram", $settingsProgram);
}
}
$content = Utility::transformArrayAssocIntoCsvString($settingsProgram);
$data['content'] = $content;
$form = $this->createForm(ContentPlainEditorFormType::class, $data);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$importString = $data['content'];
$rows = explode(PHP_EOL, (string) $importString);
foreach ($rows as $row) {
$parts = str_getcsv($row, "\t");
$settingsProgram[$parts[0]] = $parts[1];
}
$metaName = "settings.program.{$settingsProgram['programSlug']}.{$settingsProgram['batchSlug']}";
$em->getRepository(Option::class)->setOptionMetaValueJsonEncoded($metaName, null, $settingsProgram);
$this->session->getFlashBag()->add('notice', 'SUCCESS data saved');
$this->redirect($this->generateUrl('apply_settings', ['program' => $settingsProgram['programSlug'], 'batch' => $settingsProgram['batchSlug']]));
}
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/settings.html.twig', [
'settings' => $settingsProgram,
'event' => $em->getRepository(Event::class)->findOneBy(['id' => '4982']),
'form' => $form->createView(),
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_settings', 'parameters' => []])),
]);
}
/**
* @Route("/apply/", name="apply_home")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$batches = $em->getRepository(Batch::class)->findOpenApplications(['programId' => ['1', '3', '8'], 'visibility' => 'public']);
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/index.html.twig', [
'batches' => $batches,
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_home', 'parameters' => []])),
]);
}
/**
* @Route("/apply/{programSlug}", name="apply_program_redirect-to-next-open-application")
*/
public function findNextOpenApplicationAction(Request $request, $programSlug)
{
$em = $this->getDoctrine()->getManager();
$test = $request->get('test');
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
$sorry = "Sorry, no open application for {$program->getName()} right now";
if ($batch = $em->getRepository(Batch::class)->findOpenApplicationsByProgram($program)) {
if ($test) {
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batch->getSlug(), 'test' => $test]));
} else {
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batch->getSlug()]));
}
} else {
$this->session->getFlashBag()->add('notice', 'ERROR ' . $sorry);
return $this->redirect($this->generateUrl('apply_home', []));
}
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/{id}/monsum-checkout", name="apply_program_monsum-checkout")
*/
public function checkoutAction(Request $request, $programSlug, $batchSlug, $id)
{
$em = $this->getDoctrine()->getManager();
$now = new datetime();
/** @var User $user */
$user = $this->getUser();
$em->getRepository(User::class)->writeActivity($user);
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug, 'program' => $program])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no batch found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if ($customerHash = $request->get('customerId')) {
$customer = $em->getRepository(Customer::class)->findOneBy(['hash' => $customerHash]);
$teamId = $customer->getTeamId();
$team = $em->getRepository(Team::class)->findOneBy(['id' => $teamId]);
}
$settings = $em->getRepository(Application::class)->getSettingsProgram($program, $batch);
$productNumber = $batch->getBatchNumber();
$account = $this->getAccountBySlug($batchSlug);
$accountHash = $em->getRepository(Customer::class)->getAccountHashByAccount($account);
$promocode = $request->get('promocode') ? $request->get('promocode') : '';
if (isset($settings['isFrame']) and $settings['isFrame']) {
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/monsum.checkout.html.twig', [
'accountHash' => $accountHash,
'customerHash' => $customerHash,
'productNumber' => $productNumber,
'settings' => $settings,
'redirectUrl' => base64_encode(json_encode(['path' => 'rheinland-pitch_apply_home', 'parameters' => []])),
'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
]);
} else {
if ($promocode) {
return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&promocode={$promocode}&x_applicationId={$id}");
} else {
return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&x_applicationId={$id}");
}
/* Gerrit stash membership 11.4.23
if ($promocode) {
return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&promocode={$promocode}&x_applicationId={$id}&success_url={$successUrl}");
} else {
return $this->redirect("https://app.monsum.com/checkout/0/{$accountHash}/{$customerHash}/{$productNumber}&x_applicationId={$id}&success_url={$successUrl}");
}
*/
}
/*
Rückgabe von Monsum auf
https://www.startplatz.de/x/membership/receipt-monsum/17048?customerId=6a982bbfe539c9cb0ba1ca967210e0cc&subscriptionId=83add62a2825deabc141b278bd7f1fe3
*/
}
private function getAccountBySlug($slug)
{
$accountShortName = explode('-', $slug)[1];
$accounts = [
"cgn" => "SP-CGN",
"dus" => "SP-DUS",
"test" => "TESTPLATZ",
];
return $accounts[$accountShortName];
}
/**
* @Route("/access/startup-membership/{programSlug}/{batchSlug}/", name="access_startup-membership")
* @Security("is_granted('ROLE_USER')")
*/
public function hasStartupMembershipAction(Request $request, $programSlug, $batchSlug)
{
$em = $this->getDoctrine()->getManager();
/** @var User $user */
$user = $this->getUser();
$em->getRepository(User::class)->writeActivity($user);
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug, 'program' => $program])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no batch found');
return $this->redirect($this->generateUrl('apply_home', []));
}
$settings = [
'bgImage' => 'https://res.cloudinary.com/startplatz/image/upload/v1610197223/applications/backgrounds/friendly-coworking.png',
];
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/checkHasStartupMembership.html.twig', [
'program' => $program,
'batch' => $batch,
'settings' => $settings,
'product' => ['name' => 'test'],
'action' => 'default',
'application' => ['websiteUrl' => ''],
'redirectUrl' => base64_encode(json_encode(['path' => 'rheinland-pitch_apply_home', 'parameters' => []])),
'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
]);
}
/**
* @Route("/apply/rheinland-pitch/startup-academy-pitch-night-bewerbungen-00", name="redirect_applications")
*/
public function redirectApplicationAction()
{
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => 'event', 'batchSlug' => 'startup-academy-pitch-night-bewerbungen-01', 'id' => 'start']));
}
private function getExtraFieldsAttributes($settings)
{
if (!isset($settings['extraFields'])) {
return $settings;
}
$em = $this->getDoctrine()->getManager();
$extraFields = $settings['extraFields'];
$i = 0;
foreach ($extraFields as $extraField) {
if ($extraField['type'] == 'choice') {
$choices = [];
if (isset($extraField['arr'])) {
$choices = $em->getRepository(Attribute::class)->findCodesByAttributeName($extraField['arr']);
}
$settings['extraFields'][$i]['choices'] = $choices;
}
$i++;
}
return $settings;
}
private function getExtraFieldsData(Application $application, $settings, $form)
{
$extraFields = $settings['extraFields'];
$data = [];
$i = 0;
foreach ($extraFields as $extraField) {
$data[$extraField['field']] = $form->get($extraField['field'])->getData();
$i++;
}
if ($data) {
$application->setExtraFields(json_encode($data)) ;
}
return $application;
}
/**
* @Route("/schnuppermitgliedschaft-buchen/welcome/{id}", name="schnuppermitgliedschaft_buchen_welcome_de")
* @Route("/schnuppermitgliedschaft-buchen/{id}", name="schnuppermitgliedschaft_buchen_de")
* @Route("/schnuppermitgliedschaft-team-buchen/welcome/{id}", name="schnuppermitgliedschaft_team_buchen_welcome_de")
* @Route("/schnuppermitgliedschaft-team-buchen/{id}", name="schnuppermitgliedschaft_team_buchen_de")
* @Route("/startup-academy-test-mitgliedschaft-buchen/{id}", name="startup-academy-test-mitgliedschaft_buchen_de")
* @Route("/trial-membership-register/{id}", name="schnuppermitgliedschaft_buchen_en")
* @Route("/trial-membership-register/{id}", name="schnuppermitgliedschaft_buchen_en")
* @Route("/free-token/{id}", name="free-token")
* @Route("/apply/{programSlug}/{batchSlug}/{id}", name="apply_program_home")
* @Route("/{lang}/apply/{programSlug}/{batchSlug}/{id}", name="apply_program_home_lang")
*/
public function applyAction(Request $request, $programSlug = 'undef', $batchSlug = 'undef', $id = 'start', $lang = null)
{
##apply
$em = $this->getDoctrine()->getManager();
$now = new datetime();
$pathInfo = $request->getPathInfo();
$host = $request->getHost();
$test = $request->get('test');
$routeName = $request->get('_route');
$routeParameters = $request->get('_route_params');
$isMemberloggedIn = false;
$isEmailRegistered = false;
$product = null;
$landingPageContent = "";
$landingPageTwig = "";
$lang = strtoupper($lang ?? 'DE');
$priceAndDiscount = [];
$settings = []; // array contains specific definitions in relation to program, batch and template
// Retrieve the UTM parameters from the URL
$utmParameters = [
'utmSource' => $request->query->get('utm_source'),
'utmMedium' => $request->query->get('utm_medium'),
'utmCampaign' => $request->query->get('utm_campaign'),
'utmTerm' => $request->query->get('utm_term'),
'utmContent' => $request->query->get('utm_content'),
];
if ($routeName != 'apply_program_home' && $routeName != 'apply_program_home_lang') {
## evaluate special routes like 'schnuppermitgliedschaft_buchen_en' ########################
if (!$response = $this->evaluateAliasSlug($routeName)) {
$this->session->getFlashBag()->add('notice', 'ERROR url is invalid');
return $this->redirect($this->generateUrl('apply_home', []));
} else {
/** @var Program $program */
$program = $response['data']['program'];
/** @var Batch $batch */
$batch = $response['data']['batch'];
$batchSlug = $batch->getSlug();
$programSlug = $program->getSlug();
}
## end of route evaluation
} else {
## find program and batch by the default way ############
/** @var Program $program */
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug, 'program' => $program])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no batch found');
return $this->redirect($this->generateUrl('apply_home', []));
}
}
if ($program->getSlug() == 'membership') {
$productNumber = $batch->getBatchNumber();
$account = $this->getAccountBySlug($batchSlug);
// find product by productNumber, account and agent == monsum
$product = $em->getRepository(Product::class /*Product Member*/)->findOneBy(['account' => $account, 'productNumber' => $productNumber, 'agent' => 'monsum']);
}
##-- now we know program and batch (and product if membership) --##
// check if application is still open
if ($batch->getStatus() == 'inactive') {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, application is currently not active');
return $this->redirect($this->generateUrl('apply_home', []));
}
## is application open
##toBeTested
$response = $em->getRepository(Batch::class)->isApplicationOpen($batch);
if ($response['status'] == 'error') {
$this->session->getFlashBag()->add('notice', $response['message']);
return $this->redirect($this->generateUrl('apply_home', []));
}
// check if settings contains necessary setters
$batch = $em->getRepository(Batch::class)->checkLegacyData($batch);
// settings for program and batch will be merged
$settings = $em->getRepository(Application::class)->getSettingsProgram($program, $batch);
// check LoginStatus
/** @var User $user */
if ($user = $this->getUser()) {
## user is logged in. this will be the default case ############
$adminEmail = $user->getEmail();
$em->getRepository(User::class)->writeActivity($user);
/** @var Member $member */
$member = $em->getRepository(Member::class)->find($user->getMemberId());
$isMemberloggedIn = true;
} else {
## if user is not logged in - kick her out except it is allowed to access batch without being logged in
if ($batch->getAccess() != 'anonymous') {
// Pass the UTM parameters along with other necessary arguments to the createApplicationByApplyForm method
$application = $em->getRepository(Application::class)->createApplicationByApplyForm(
$program,
$batch,
$lang,
$priceAndDiscount,
$utmParameters // This is the array you created earlier
);
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig', [
'settings' => $settings,
'program' => $program,
'batch' => $batch,
'test' => $test,
'application' => $application,
'applicationId' => $id,
'phrases' => $em->getRepository(Option::class)->getApplicationPhrases($program, $batch, $product, $lang),
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang', 'parameters' => ['id' => $id, 'programSlug' => $programSlug, 'batchSlug' => $batchSlug], 'lang' => strtolower($lang)])),
'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI')),
]);
}
$member = $em->getRepository(Member::class)->setEmptyMemberAccount();
}
$settings['isMemberloggedIn'] = $isMemberloggedIn;
if ($isMemberloggedIn) {
// check access conditions
if ($batch->getAccess() == 'hasStartupMembership') {
$team = $em->getRepository(Team::class)->findOneBy(['id' => $user->getTeamId()]);
if (!$team->getHasStartupMembership()) {
return $this->redirect($this->generateUrl('access_startup-membership', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $id]));
}
}
// check is missing if Community Membership
}
## -- settings -- #############
// important distinction - is it necessary to bind this application to a team
// or is it okay to bind it with a person only
// event are normally person only, applications for accelerator need a team
// it can be defined via batch (isMultipleApplicationsPerTeam)
// but in every case an application need to be tied to a member and at least a virtual team
// we need to keep track is a member team relationship has been set
// because either member or team can be created during application process
$_isMemberTeamRelationSet = 0;
// for memberships we need the product type
$settings['productType'] = 'Applicant';
if ($product) {
$settings['productType'] = $product->getType();
}
// we set an virtual team as fallback if no new allmeda team is needed to process the request
$virtualTeam = array_key_exists('virtualTeam', $settings) ? $settings['virtualTeam'] : 'applicants';
// access the relevant virtual team or create that team if it does not exists
$applicantsTeam = $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
$adminEmail = $user ? $user->getEmail() : "";
$application = null;
// find application or create new one if id = start
if ($id == 'start') {
if ($teamId = $request->get('teamId') and $user and $teamId > 0) {
if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($user->getMemberId(), $teamId)) {
$this->session->getFlashBag()->add('notice', 'ERROR 01 no access to team');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['id' => $id, 'programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => strtolower($lang)]));
}
if ($application = $em->getRepository(Application::class)->findOneBy(['teamId' => $teamId, 'programSlug' => $programSlug, 'batchSlug' => $batchSlug])) {
$this->session->getFlashBag()->add('notice', 'SUCCESS application for your team found');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['id' => $application->getId(), 'programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => strtolower($lang)]));
}
}
if ($batch->isMultipleApplicationsPerTeam() and $user) {
// look up application of that member
$application = $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $user->getMemberId()]);
} elseif ($user) {
if (!$batch->isMultipleApplicationsPerMember()) {
// look up application of that team
if (!$application = $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'teamId' => $user->getTeamId()])) {
// if there is no application bound with the primary team of the member look for an application bound with that member directly
$application = $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $user->getMemberId()]);
}
}
}
if ($application) {
$member = $em->getRepository(Member::class)->find($application->getMemberId());
$teamId = $request->get('teamId') ? $request->get('teamId') : $application->getTeamId();
$team = $this->setTeam($member, $settings, $teamId, $applicantsTeam);
} else { // create new application
// Pass the UTM parameters along with other necessary arguments to the createApplicationByApplyForm method
$application = $em->getRepository(Application::class)->createApplicationByApplyForm(
$program,
$batch,
$lang,
$priceAndDiscount,
$utmParameters // This is the array you created earlier
);
if ($program->getSlug() == 'membership') {
if ($memberId = $request->get('w')) {
if ($werber = $em->getRepository(Member::class)->find($memberId)) {
$application->setRecommendedBy($werber->getEmail());
}
}
}
$member = $em->getRepository(Application::class)->setMember($program, $batch, $applicantsTeam, $user);
$application = $em->getRepository(Application::class)->updateApplicationByMember($application, $member);
if ($request->get('teamId')) {
$teamId = $request->get('teamId');
} elseif ($user) {
if ($settings['createAlwaysNewTeam']) {
$teamId = 0;
} else {
$teamId = $user->getTeamId();
}
} else {
$teamId = 0;
}
$team = $this->setTeam($member, $settings, $teamId, $applicantsTeam);
if ($settings['isTeamNeeded']) {
$application = $this->updateApplicationByTeam($application, $team);
} else {
$teamId = $applicantsTeam->getId();
$application->setTeamId($teamId);
}
}
} else {
if (!$application = $em->getRepository(Application::class)->find($id)) {
$this->session->getFlashBag()->add('notice', 'ERROR apply:01 - Application could not be found. You can create a new one');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => 'start', 'lang' => strtolower($lang)]));
}
if ($application->getProgramSlug() != $programSlug or $application->getBatchSlug() != $batchSlug) {
$this->session->getFlashBag()->add('notice', 'ERROR apply:011 - Application could not be found. You can create a new one');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => 'start', 'lang' => strtolower($lang)]));
}
$canPassWithoutLogin = [
"error:validateLogin",
"error:validateEmail",
];
if (!in_array($application->getEditStatus(), $canPassWithoutLogin)) {
if (!$user) {
$this->session->getFlashBag()->add('notice', 'ERROR apply:021 - Please Login first');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => 'start', 'lang' => strtolower($lang)]));
} else {
if ($application->getMemberId() != $user->getMemberId() and $user) {
$this->session->getFlashBag()->add('notice', 'ERROR apply:012 - Application could not be found. You can create a new one');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => 'start', 'lang' => strtolower($lang)]));
}
}
}
if ($user) {
if ($application->getMemberId() != $user->getMemberId()) {
if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($user->getMemberId(), $application->getTeamId())) {
$this->session->getFlashBag()->add('notice', 'ERROR apply:013 - No access to this application. You can create a new one');
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => 'start', 'lang' => strtolower($lang)]));
}
}
}
$teamId = $request->get('teamId') ? $request->get('teamId') : $application->getTeamId();
$team = $this->setTeam($member, $settings, $teamId, $applicantsTeam);
}
## now in every case there is an application
## we need to check the language
if ($lang) {
if ($lang != $application->getLang()) {
$application->setLang($lang);
}
} else {
$lang = $application->getLang() ? $application->getLang() : $batch->getLang();
}
## now in every case the variable $lang is set
// checkAccessRight for team if found by external teamId
if ($request->get('teamId') > 0 and !$teamMember = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team, 'member' => $member])) {
$this->session->getFlashBag()->add('notice', 'ERROR 02 no access to team');
return $this->redirect($this->generateUrl('apply_home'));
}
if ($adminEmail) {
$application->setLastChangeUser($adminEmail);
}
$action = $request->get('action');
// action can be only set to 'finish' internally
if ($action == "finish") {
$action = "";
}
if ($action == "changeName") {
$application->setStartupName("copy of " . $application->getStartupName());
$application->setEditStatus("open");
$action = "start";
}
if ($action == "shortenIdeaPitch") {
$application->setEditStatus("open");
$action = "start";
}
if (str_contains(strtolower($application->getEditStatus() ?? ''), "error") and $action and $user) {
// Zuordnung memberTeam checken bzw. erstellen - falls validate Login - falls keine Zuordnung und isTeamNeeded GF sonst MA
$response = $em->getRepository(Application::class)->validateApplication($application, $member, $team, $settings, $action, $request->get('code'));
/** @var Application $application */
$application = $response['data']['application'];
$action = $response['action'];
/* Gerrit stash membership 11.4.23
$application = $em->getRepository(Application::class)->setProcessGoToMonsum($application);
*/
/*
if ($response['status'] == "success") {
$application = $this->setApplicationStatusByTemplate($application);
$action = $this->setActionByProgramSlug($application);
}*/
/** @var Member $member */
$member = $response['data']['member'];
/** @var Team $team */
$team = $response['data']['team'];
$teamId = $team->getId();
if (!$user->getTeamId()) {
$em->getRepository(Member::class)->setPrimaryTeam($member, $team, $this->getUser()->getEmail());
}
/* Gerrit stash membership 11.4.23
} elseif ($program->getSlug() == 'membership' and $application->getEditStatus() == "success:applied" and $user) {
$action = "goToMonsum"; */
} elseif ($application->getEditStatus() == "success:applied" and $user) {
//todo find another status for people that have applied long before
$action = "finish";
} elseif ($application->getEditStatus() == "success:confirmationMailSent" and $user) {
$action = "done";
} elseif (($application->getEditStatus() == "success:validatedLogin" or $application->getEditStatus() == "success:validatedEmail" or $application->getEditStatus() == "validated") and $user) {
$action = $this->setActionByProgramSlug($application);
} elseif ($application->getApplicationStatus() == "started" and $user) {
$action = "continue";
} elseif ($application->getApplicationStatus() == "applied" and $user) {
if (in_array($application->getTemplate(), ['accelerator', 'rheinland-pitch'])) {
$action = "reopen";
} else {
$action = "finish";
}
}
$_isMemberTeamRelationSet = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team, 'member' => $member]) ? 1 : 0;
$form = $this->createForm(ApplicationType::class, $application, ['settings' => $settings, 'program' => $program, 'batch' => $batch]);
$form->handleRequest($request);
##############################################################
## form validation starts here ##
##############################################################
if ($form->isSubmitted() && $form->isValid()) {
// make email lower case
$application->setEmail(strtolower($application->getEmail()));
if (!$application->getPerson() and $application->getFirstName()) {
$application->setPerson("{$application->getFirstName()} {$application->getLastName()}");
}
if (!$adminEmail) {
$adminEmail = $application->getEmail();
}
if (isset($settings['extraFields'])) {
$application = $this->getExtraFieldsData($application, $settings, $form);
}
// now we can check if the email of the form already registered within startplatz
$isEmailRegistered = $em->getRepository(Member::class)->isEmailRegistered($application->getEmail());
if ($isMemberloggedIn or !$isEmailRegistered) {
// if settings[isTeamNeeded] is set a corporate team is created otherwise a person team
if ($teamId == 'create' or !$team->getId()) {
$team = $em->getRepository(Team::class)->createTeamByApplication($application, $settings, $member);
$application->setTeamId($team->getId());
$teamId = $team->getId();
}
}
##email validation - only relevant if access == anonymous or login
$response = $this->evaluateApplicationEmail($application, $member, $team, $settings, $user);
$application = $response['data']['application'];
$member = $response['data']['member'];
$hasExistingApplication = $response['hasExistingApplication'];
$_isMemberTeamRelationSet = $teamMember = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team, 'member' => $member]) ? 1 : 0;
// Do we allow multiple applications?
$allowMultiple = $settings['isTeamNeeded']
? $settings['isMultipleApplicationsPerTeam']
: $settings['isMultipleApplicationsPerMember'];
if (!$allowMultiple
&& $hasExistingApplication
&& $application->getApplicationStatus() == 'applied'
&& $program->getSlug() == 'membership'
) {
$targetUrl = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
$loginLink = $this->generateUrl('login', ['targetPath' => $targetUrl]);
$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>.");
$routeParameters['action'] = "";
return $this->redirect($targetUrl);
}
if (!$application->getApplicationStatus()) {
$application->setApplicationStatus('started');
}
$application = $em->getRepository(Application::class)->setApplication($application);
// at this point application is set and stored in database
// and member is set and team is set - now we can do last changes to team
if ($response['status'] == 'error') {
/*
$status = "error";
$todo = "validateLogin";
*/
$routeParameters = [
'programSlug' => $programSlug,
'batchSlug' => $batchSlug,
'id' => $application->getId(),
'lang' => $lang,
'action' => 'validate'
];
if ($test) {
$routeParameters['test'] = $test;
}
if ($response['todo'] == "validateLogin") {
$targetPath = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
$mailTemplate = $em->getRepository(MailTemplate::class)->getValidateLoginMailTemplateByBatch($batch, $application, $loginLink);
$feedback = Utility::sendAlertMailPerZapier($mailTemplate['recipientEmail'], $mailTemplate['mailText'], $mailTemplate['mailSubject'], $mailTemplate['replyToEmail'], $mailTemplate['fromName'], $mailTemplate['bodyType']);
$feedback = json_decode($feedback);
if ($feedback->status == "success") {
$routeParameters['action'] = "needsLoginValidation";
$targetUrl = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
return $this->redirect($targetUrl);
} else {
$this->session->getFlashBag()->add('notice', 'ERROR email is invalid please check your email address!');
$routeParameters['action'] = "";
$targetUrl = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
return $this->redirect($targetUrl);
}
}
if ($response['todo'] == "validateEmail") {
$targetPath = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
$mailTemplate = $em->getRepository(MailTemplate::class)->getValidateEmailMailTemplateByBatch($batch, $application, $loginLink);
$em->persist($application);
$em->flush();
$feedback = Utility::sendAlertMailPerZapier($mailTemplate['recipientEmail'], $mailTemplate['mailText'], $mailTemplate['mailSubject'], $mailTemplate['replyToEmail'], $mailTemplate['fromName'], $mailTemplate['bodyType']);
$feedback = json_decode($feedback);
if ($feedback->status == "success") {
$routeParameters['action'] = "needsEmailVerification";
$targetUrl = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
return $this->redirect($targetUrl);
} else {
$this->session->getFlashBag()->add('notice', 'ERROR email is invalid please check your email adress!');
$routeParameters['action'] = "";
$targetUrl = strtolower($this->generateUrl('apply_program_home_lang', $routeParameters));
return $this->redirect($targetUrl);
}
}
if ($test) {
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'test' => $test, 'lang' => strtolower($lang)]));
} else {
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'lang' => strtolower($lang)]));
}
}
$response = $this->checkPlausibility($application, $member, $team, $settings);
$application = $response['data']['application'];
$application = $em->getRepository(Application::class)->setApplication($application);
if (!$user) {
switch ($program->getSlug()) {
case "rheinland-pitch":
case "accelerator":
// make applicant a guest member and login
$guestTeam = $em->getRepository(Team::class)->getVirtualTeamByName("Guest Membership");
$memberTeam = $em->getRepository(Member::class)->setTeamAssignment($member, $guestTeam, "MA", $adminEmail);
break;
case "nft":
// make applicant a guest member and login
if (!$isEmailRegistered) {
$guestTeam = $em->getRepository(Team::class)->getVirtualTeamByName("Guest Membership");
$memberTeam = $em->getRepository(Member::class)->setTeamAssignment($member, $guestTeam, "MA", $adminEmail);
}
$user = $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
break;
default:
break;
}
}
if ($response['status'] == 'error') {
if (!$user) {
$targetPath = $this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), $action => 'validate']);
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
return $this->redirect($loginLink);
} else {
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), $action => 'validate']));
}
}
if ($settings['isPitchDeckRequired']) {
if ($form->get('uploadImage')->isClicked()) {
$uploadTag = "application/{$application->getId()}";
if ($application->getLinkPitchDeck()) {
$application->setLinkPitchDeck('');
$application->setPublicIdPitchDeck('');
$application = $em->getRepository(Application::class)->setApplication($application);
$result = $this->cloudinary->delete_resources_by_tag($uploadTag);
}
return $this->redirect($this->generateUrl('apply_program_uploadPitchDeck', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'teamId' => $application->getTeamId(), 'memberId' => $application->getMemberId()]));
}
}
if ($form->get('finish')->isClicked()) {
$action = "finish";
if ($application->getPhone() and !$member->getPhone()) {
$member = $em->getRepository(Member::class)->setPhone($member, $application->getPhone(), $adminEmail);
}
// relevant only for membership applicants - all applications for membership exit here
if ($program->getSlug() == 'membership') {
$settings['routeName'] = $routeName;
$settings['monsumArticleNumber'] = $product->getMonsumArticleNumber();
/* Gerrit stash membership 11.4.23 - exchange with next line
return $this->redirect($this->generateUrl('x_membership_monsum-checkout', ['productId' => $product->getProductNumber()]));
*/
return $this->goToMonsum($program, $batch, $settings, $application, $member, $team, $applicantsTeam, $user);
}
// make applicant member of additional virtual team specified in settings
$applicantsTeamMember = $em->getRepository(Member::class)->setTeamAssignment($member, $applicantsTeam, "MA", $adminEmail);
// final plausibility checks - brauchen wir die überhaupt noch? oder sind das finale Anpassungen der application
switch ($program->getSlug()) {
case "rheinland-pitch":
case "accelerator":
if (!$application->getLinkPitchDeck()) {
$this->session->getFlashBag()->add('notice', 'ERROR - Your application will not be processed unless you upload a pitch deck!');
} else {
$wordsCount = str_word_count($application->getIdeaPitch() ?? '');
if ($wordsCount > 1500) {
$this->session->getFlashBag()->add('notice', "ERROR - Your idea pitch contains {$wordsCount} words, please reduce the length of your idea pitch!");
} else {
$action = "finish";
$application->setApplicationStatus('applied');
if ($application->getVotesRegistered() == 0) {
$application->setVotesRegistered($settings['initialVotes']);
}
$em->persist($application);
$em->flush();
}
}
break;
default:
$application = $em->getRepository(Application::class)->setApplicationApplied($application);
break;
}
} // end of validation of submit button (finish)
if ($action != "finish") {
$this->session->getFlashBag()->add('notice', 'SUCCESS data saved');
if ($id != $application->getId()) {
if (!$user) {
$targetPath = $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'lang' => strtolower($lang)]);
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
return $this->redirect($loginLink);
} else {
return $this->redirect($this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'lang' => strtolower($lang)]));
}
} else {
$id = $application->getId();
}
}
} // end of form validation
else {
$errorString = $form->getErrors(true, false);
// @todo: $errorString ist ein Array -> StringCast in der nächsten Zeile anders behandeln
if (str_contains((string) $errorString, 'ERROR:')) {
$this->session->getFlashBag()->add('notice', 'ERROR - Data have not been saved, reason: ' . $errorString);
}
}
if ($action == "goToMonsum") {
$settings['routeName'] = $routeName;
$settings['monsumArticleNumber'] = $product->getMonsumArticleNumber();
return $this->goToMonsum($program, $batch, $settings, $application, $member, $team, $applicantsTeam, $user);
}
if ($action == "finish") {
$batch = $em->getRepository(Batch::class)->updateNumbers($batch);
##final actions and good bye messages
switch ($batch->getTemplate()) {
case "accelerator":
case "rheinland-pitch":
$this->session->getFlashBag()->add('notice', 'SUCCESS Thank you for your application. We have sent you a confirmation mail with additional information.');
break;
case "registration":
case "businessclub":
case "event":
if ($batch->getAccess() == "anonymous") {
if (!$user and $member->getId()) {
$targetPath = $this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $application->getId(), 'action' => 'finish']);
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
$user = $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
$this->sendConfirmationMailToApplicant($user, $settings, $application, $batch);
return $this->redirect($loginLink);
}
}
break;
case "speed-networking":
break;
case "sign-up":
// what follow up should be done after
if ($batch->getGoToPage() == 'editMentorsProfile') {
$targetPath = $this->generateUrl('x_connect_mentors_edit-profile', ['id' => $member->getId()]);
if (!$user and $member->getId()) {
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
return $this->redirect($loginLink);
} else {
return $this->redirect($targetPath);
}
}
break;
case "startup-tools":
$this->session->getFlashBag()->add('notice', 'SUCCESS Thank you for your application. We will come back to you soon');
break;
default:
$view = '@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig';
break;
}
//$this->session->getFlashBag()->add('notice', 'MESSAGE sendConfirmationMailToApplicant($user, $settings, $application, $batch)');
if (!$user){
$user = $em->getRepository(User::class)->findOneBy(['memberId' => $member->getId()]);
}
$this->sendConfirmationMailToApplicant($user, $settings, $application, $batch);
if ($programSlug == 'ai-hub'){
$application->setEditStatus("success:confirmationMailSent");
$application = $em->getRepository(Application::class)->setApplicationDoneWithoutWorkflow($application);
}
// additional actions for specific programs
switch ($batch->getTemplate()) {
case "accelerator":
//$this->session->getFlashBag()->add('notice', 'MESSAGE addApplicationToPodioByZapier($application, $batch)');
$response = $this->addApplicationToPodioByZapier($application, $batch);
break;
case "rheinland-pitch":
break;
}
if ($batch->getLandingPageTwig()) {
$loader = new ArrayLoader([
'landingPageTwig' => $batch->getLandingPageTwig(),
]);
$twig = new Environment($loader);
//$landingPageTwig = $twig->render('landingPageTwig', ['member' => $member]);
}
}
$editWidget = $this->setEditWidgetByTemplate($batch->getTemplate());
$phrases = $em->getRepository(Option::class)->getApplicationPhrases($program, $batch, $product, $lang);
$_isMemberTeamRelationSet = $teamMember = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team, 'member' => $member]) ? 1 : 0;
$showFooter = true; // Default to showing the footer
if ($request->query->get('iframe') === 'true') {
// If the 'iframe' parameter is 'true', always hide the footer
$showFooter = false;
} elseif (isset($settings['showFooter']) && $settings['showFooter'] == 0) {
// If the 'iframe' parameter is not 'true' and $setting['showFooter'] exists and is 0, hide the footer
$showFooter = false;
}
// Auswahl des Twig-Templates basierend auf programId
switch ($batch->getProgramId()) {
case 1:
case 3:
default:
// Fallback auf das zentrale Template, falls programId unbekannt ist
$view = '@StartPlatzRheinlandPitchBundle/Apply/apply.default.html.twig';
break;
}
$landingPageContent = $batch->getLandingPageContent();
##view-apply
// render specific application form or show landing page
return $this->render($view, [
'id' => $id,
'settings' => $settings,
'programSlug' => $programSlug,
'batchSlug' => $batchSlug,
'program' => $program,
'phrases' => $phrases,
'batch' => $batch,
'lang' => $lang,
'product' => $product,
'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
'test' => $test,
'host' => $host,
'pathInfo' => $pathInfo,
'view' => $view,
'editWidget' => $editWidget,
'showFooter' => $showFooter,
'member' => $member,
'team' => $team,
'teamId' => $teamId,
'application' => $application,
'applicationId' => $id,
'form' => $form->createView(),
'action' => $action,
'landingPageContent' => $landingPageContent,
'landingPageTwig' => $landingPageTwig,
'targetPathEN' => $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => 'en']),
'targetPathDE' => $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => 'de']),
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang', 'parameters' => ['id' => $id, 'programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => strtolower($lang)]])),
'menuLinksAndPhrases' => $this->menuTranslationService->getMenuLinksAndPhrases($request->server->get('REQUEST_URI'), $lang),
]);
}
private function goToMonsum($program, Batch $batch, $settings, Application $application, $member, $team, $applicantsTeam, $user)
{
$em = $this->getDoctrine()->getManager();
if ($program->getSlug() == 'membership') {
// assume that everything went right
// save member, assign member to team, save application
$data['email'] = $application->getEmail();
$data['name'] = $application->getPerson();
$adminEmail = $application->getEmail();
if (!$user) {
$member = $em->getRepository(Member::class)->createGuestMemberIfNotExists($data, $team, $adminEmail);
} else {
$applicantsTeamMember = $em->getRepository(Member::class)->setTeamAssignment($member, $applicantsTeam, "MA", $adminEmail);
}
$account = $this->getAccountBySlug($batch->getSlug());
if (!$customer = $em->getRepository(Customer::class)->findPrimaryMonsumAccount($member, $account)) {
$team = $em->getRepository(Team::class)->createTeamByMembershipApplicant($member);
$customer = $this->setMonsumAccountIfNotExists($member, $team, $application, $account);
}
$productNumber = $batch->getBatchNumber();
$customer = $em->getRepository(Customer::class)->setCheckoutData($customer, $account, $productNumber, $member->getId());
if ($batch->getTemplate() == 'membership-per-api') {
$login = $em->getRepository(Customer::class)->getLoginByAccount($customer->getAccount());
$payload = json_encode([
'SERVICE' => "subscription.create",
'DATA' => [
'CUSTOMER_ID' => "{$customer->getCustomerId()}",
'ARTICLE_NUMBER' => $settings['monsumArticleNumber'],
],
]);
$feedback = $this->callbackService->curl_get_monsum_all($payload, $login);
$feedback = json_decode($feedback);
if (isset($feedback->RESPONSE->STATUS) and $feedback->RESPONSE->STATUS == "success") {
$subscriptionId = $feedback->RESPONSE->SUBSCRIPTION_ID;
$application->setEditStatus("sucess:subscriptionId=={$subscriptionId}");
$application = $em->getRepository(Application::class)->setHistory($application, $application->getEditMessage());
$application->setApplicationStatus('applied');
$em->persist($application);
$em->flush();
## assign to team ##
$virtualTeam = array_key_exists('virtualTeam', $settings) ? $settings['virtualTeam'] : 'applicants';
$funnelTeam = $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
$memberTeam = $em->getRepository(Member::class)->setTeamAssignment($member, $funnelTeam, "MA", $adminEmail);
$action = "finish";
if ($settings['routeName'] != 'apply_program_home' && $settings['routeName'] != 'apply_program_home_lang') {
$route = $settings['routeName'];
if ($route == "schnuppermitgliedschaft_buchen_de") {
$route = "schnuppermitgliedschaft_buchen_welcome_de";
} elseif ($route == "schnuppermitgliedschaft_team_buchen_de") {
$route = "schnuppermitgliedschaft_team_buchen_welcome_de";
}
$targetPath = $this->generateUrl($route, ['id' => $application->getId()]);
} else {
$targetPath = $this->generateUrl('apply_program_home', ['programSlug' => $application->getProgramSlug(), 'batchSlug' => $application->getBatchSlug(), 'id' => $application->getId()]);
}
if (!$user) {
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
return $this->redirect($loginLink);
} else {
return $this->redirect($targetPath);
}
} else {
$application->setEditStatus("error:monsum-purchase-failed");
$em->persist($application);
$em->flush();
$action = "error";
}
} else {
$application = $em->getRepository(Application::class)->setProcessGoToMonsum($application);
$application = $em->getRepository(Application::class)->setHistory($application, $application->getEditMessage());
$application->setApplicationStatus('applied');
$em->persist($application);
$em->flush();
$promocode = $application->getRecommendedBy() ? 'welcome-startplatz' : '';
return $this->redirect($this->generateUrl('apply_program_monsum-checkout', [
'id' => $application->getId(),
'programSlug' => $program->getSlug(),
'batchSlug' => $batch->getSlug(),
'customerId' => $customer->getHash(),
'promocode' => $promocode,
]));
}
}
}
private function setEditWidgetByTemplate($template)
{
switch ($template) {
case "accelerator":
$editWidget = '@StartPlatzRheinlandPitchBundle/Apply/_edit.accelerator.widget.html.twig';
break;
case "membership":
$editWidget = '@StartPlatzRheinlandPitchBundle/Apply/_edit.membership.widget.html.twig';
break;
case "registration":
case "businessclub":
case "event":
case "speed-networking":
case "sign-up":
$editWidget = '@StartPlatzRheinlandPitchBundle/Apply/_edit.registration.widget.html.twig';
break;
case "nft":
$editWidget = '@StartPlatzRheinlandPitchBundle/Apply/_edit.nft.widget.html.twig';
break;
default:
$editWidget = '@StartPlatzRheinlandPitchBundle/Apply/_edit.default.widget.html.twig';
break;
}
/*
these templates are implemented as of 19.10.2021
accelerator 25
businessclub 8
effzeh 1
event 37
feedback-zu-deiner-startup-idee 46
membership 13
membership-per-api 2
registration 18
rheinland-pitch 122
sign-up 2
speed-networking 161
startup-tools 19
*/
return $editWidget;
}
private function getLandingPageDescription($type)
{
if ($type == 'default-de') {
$description = "
<section>
<ul>
<li>Du möchtest wissen, wie Du am STARTPLATZ Mitglied werden kannst?
<ul>
<li>=> <a href=\/tarife/\">Dann informiere Dich auf unserer Mitgliedschafts-Seite</a></li>
</ul>
</li>
<li>Du möchtest wissen, welche Konferenzräume Du am STARTPLATZ buchen kannst?
<ul>
<li>=> Dann informiere Dich zu den <a href=\"/koeln-tagungsraeume-und-konferenzraeume/\">Konferenzräumen in Köln</a> oder zu den <a href=\"/duesseldorf-tagungsraeume-und-konferenzraeume/\">Konferenzräumen in Düsseldorf</a></li>
</ul>
</li>
<li>Du möchtest wissen, welche Workshops oder Events am STARTPLATZ stattfinden?
<ul>
<li>=> <a href=\"/events/list\">Dann informiere Dich auf unseren Event-Seiten</a></li>
</ul>
</li>
</ul>
</section>
";
} else {
$description = "
<ul>
<li>Do you want to explore more options within STARTPLATZ?
<ul>
<li>=> <a href=\/tarife/\">go to our Membership Page</a></li>
</ul>
</li>
<li>Do you want to book additional conference rooms at STARTPLATZ?
<ul>
<li>=> Go to <a href=\"/koeln-tagungsraeume-und-konferenzraeume/\">Konferenzräumen in Köln</a> or go to <a href=\"/duesseldorf-tagungsraeume-und-konferenzraeume/\">Konferenzräumen in Düsseldorf</a></li>
</ul>
</li>
<li>Do you want to know more about current events at STARTPLATZ?
<ul>
<li>=> <a href=\"/events/list\">Go to our events page</a></li>
</ul>
</li>
</ul>
";
}
return $description;
}
private function setActionByProgramSlug(Application $application)
{
switch ($application->getTemplate()) {
case "rheinland-pitch":
case "rheinland-pitch-web3":
case "accelerator":
$action = "continue";
break;
case "membership":
$action = "goToMonsum";
break;
default:
$action = "finish";
break;
}
// only in case of membership the program slug counts more
if ($application->getProgramSlug() == 'membership') {
$action = "goToMonsum";
}
return $action;
}
private function setApplicationStatusByTemplate(Application $application)
{
$em = $this->getDoctrine()->getManager();
switch ($application->getTemplate()) {
case "rheinland-pitch":
case "rheinland-pitch-web3":
case "accelerator":
$application = $em->getRepository(Application::class)->setApplicationStarted($application);
break;
default:
$application = $em->getRepository(Application::class)->setApplicationApplied($application);
break;
}
return $application;
}
private function updateApplicationByTeam(Application $application, Team $team)
{
$em = $this->getDoctrine()->getManager();
$application->setTeamId($team->getId());
$application->setStartupName($team->getShortName());
$application->setCity($team->getAddressCity());
$application->setTeamSize($team->getNEmployees());
$application->setWebsiteUrl($team->getHomepage());
if ($team->getStartupId()) {
$startup = $em->getRepository(Startup::class)->find($team->getStartupId());
$application->setIdeaPitch($startup->getOneSentencePitch());
$application->setIndustry($startup->getIndustry());
$application->setStartupId($team->getStartupId());
}
return $application;
}
/**
* Snapshot member data at registration time for historical analysis.
* Captures tags, membership status, UTM source, and KI-Kompetenz at the moment of registration.
*/
private function setMemberSnapshotAtRegistration(Application $application, Member $member): void
{
// Capture member tags at registration
$application->setMemberTagsAtRegistration($member->getTags());
// Capture community membership status
$application->setWasCommunityMemberAtRegistration($member->getHasCommunityMembership() ?? false);
// Check if member was a physical/coworking member at registration time
$isPhysicalMember = $member->getPhysicalMembershipStarted() !== null
&& ($member->getPhysicalMembershipEnded() === null
|| $member->getPhysicalMembershipEnded() > new \DateTime());
$application->setWasPhysicalMemberAtRegistration($isPhysicalMember);
// Capture member's original UTM source (first touch attribution)
$application->setMemberUtmSourceAtRegistration($member->getUtmSource());
// Capture member's KI-Kompetenz level at registration
$application->setKiKompetenzAtRegistration($member->getKiKompetenz());
}
private function setTeam($member, $settings, $teamId, Team $applicantsTeam)
{
$em = $this->getDoctrine()->getManager();
if ($settings['isTeamNeeded']) {
if ($teamId == 'create' or $teamId == 0) {
$team = $em->getRepository(Team::class)->setNewTeamForApplication($member, $settings);
} else {
if ($settings['isSignUp']) {
// in this case virtual teams are okay
$team = $em->getRepository(Team::class)->find($teamId);
} else {
$virtualTeams = $em->getRepository(Team::class)->findKeysOfVirtualTeams();
if (in_array($member->getTeamId(), $virtualTeams)) {
$team = $em->getRepository(Team::class)->setNewTeamForApplication($member, $settings);
} else {
$team = $em->getRepository(Team::class)->find($teamId);
}
}
}
} else {
// in this case we need only the virtual team related with that batch
$team = $applicantsTeam;
}
return $team;
}
private function evaluateAliasSlug($routeName)
{
$em = $this->getDoctrine()->getManager();
$status = "";
$message = "";
$todo = "";
$data = ['program' => false, 'batch' => false];
$programSlug = 'membership';
switch ($routeName) {
case "startup-academy-test-mitgliedschaft_buchen_de":
$batchSlug = '16127-test-trial-startup-academy-community-membership';
break;
case "schnuppermitgliedschaft_buchen_de":
case "schnuppermitgliedschaft_buchen_welcome_de":
case "schnuppermitgliedschaft_buchen_en":
$batchSlug = '16017-cgn-trial-community-membership';
break;
case "schnuppermitgliedschaft_team_buchen_de":
case "schnuppermitgliedschaft_team_buchen_welcome_de":
$batchSlug = '17047-cgn-trial-startup-membership';
break;
case "free-token":
$batchSlug = 'free-to-own-token-meetup-24112022';
break;
default:
$batchSlug = '16017-cgn-trial-community-membership';
break;
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
return false;
} else {
$status = "success";
$data = ['batch' => $batch, 'program' => $batch->getProgram()];
$response = [
'status' => $status,
'todo' => $todo,
'message' => $message,
'data' => $data,
];
return $response;
}
}
private function evaluateApplicationEmail(Application $application, $member, Team $team, $settings, $user)
{
$em = $this->getDoctrine()->getManager();
$status = "";
$message = "";
$todo = "";
$data = ['application' => $application, 'member' => $member];
$isEmailRegistered = $em->getRepository(Member::class)->isEmailRegistered($application->getEmail());
$isMemberloggedIn = $user ? true : false;
$existingApplication = false;
if ($isEmailRegistered) {
$existingMember = $em->getRepository(Member::class)->findOneBy(['email' => $application->getEmail()]);
$existingApplication = $this->checkForMultipleApplications($team, $existingMember, $settings);
}
// ['Anonymous' => 'anonymous', 'Login' => 'login', 'Community Membership'=>'hasCommunityMembership', 'Startup Membership'=>'hasStartupMembership'],'required'=> false])
switch ($settings['access']) {
case "anonymous":
if ($isEmailRegistered == false and $isMemberloggedIn == false) {
if ($settings['isNeedsEmailValidation']) {
$status = "error";
$todo = "validateEmail";
$message = "Email is not yet registered. Email needs to be validated";
$application = $em->getRepository(Application::class)->setErrorValidateEmail($application);
} else {
$status = "process";
$todo = "notValidatedEmail";
$message = "Email will be registered without being validated";
$application = $em->getRepository(Application::class)->setEditStatus($application, $status, $todo, $message);
}
$data['email'] = $application->getEmail();
$data['firstName'] = $application->getFirstName();
$data['lastName'] = $application->getLastName();
$data['name'] = $application->getPerson();
$adminEmail = $application->getEmail();
if ($settings['isTeamNeeded']) {
$memberType = "GF";
} else {
$memberType = "MA";
}
$member = $em->getRepository(Member::class)->createGuestMemberIfNotExists($data, $team, $adminEmail, $memberType);
$application->setMemberId($member->getId());
$this->setMemberSnapshotAtRegistration($application, $member);
$application->setTeamId($team->getId());
$data = ['application' => $application, 'member' => $member];
}
if ($isEmailRegistered == false and $isMemberloggedIn == true) {
$status = "error";
$todo = "check2ndAccount";
$message = "You are registered at STARTPLATZ with another email address.";
$application->setSecondaryEmail($application->getEmail());
$application->setEmail($member->getEmail());
$data = ['application' => $application, 'member' => $member];
}
if ($isEmailRegistered == true and $isMemberloggedIn == false) {
// "error"; "validateLogin";
/** @var Member $existingMember */
$isAdmin = false;
if ($existingMember) {
// check if member is admin
$user = $em->getRepository(User::class)->findOneBy(['memberId' => $existingMember->getId()]);
if ($user->getIsAdmin()) {
$isAdmin = true;
}
}
if ($settings['isNeedsLoginValidation'] or $isAdmin) {
$status = "error";
$todo = "validateLogin";
$message = "This email address is already in use. Please login to make your application valid.";
} else {
$status = "process";
$todo = "notValidatedLogin";
$message = "This email address is already in use. Application will be processed without login being validated";
}
if (!$existingApplication) {
$message = "This email address is already in use. Please login to make your application valid.";
$application->setMemberId($existingMember->getId());
$this->setMemberSnapshotAtRegistration($application, $existingMember);
if (!$team->getId()) {
if ($settings['createAlwaysNewTeam']) {
$team = $em->getRepository(Team::class)->createTeamByApplication($application, $settings, $member);
$application->setTeamId($team->getId());
$em->getRepository(Member::class)->setTeamAssignment($existingMember, $team, 'GF', $application->getEmail());
} else {
$application->setTeamId($existingMember->getTeamId());
}
}
} else {
$message = "This email address is already in use and there is already an application of your team. Please login to edit your application.";
$application = $existingApplication;
}
$application = $em->getRepository(Application::class)->setEditStatus($application, $status, $todo, $message);
$data = ['application' => $application, 'member' => $existingMember];
}
if ($isEmailRegistered == true and $isMemberloggedIn == true) {
if ($user->getEmail() != $application->getEmail()) {
// "error"; "validateLogin";
$status = "error";
$todo = "validateLogin";
$application = $em->getRepository(Application::class)->setErrorValidateLogin($application);
} else {
if ($application->getProgramSlug() == "membership") {
$status = "process";
$todo = "goToMonsum";
$message = "You need to check out";
} else {
$status = "success";
$todo = "loggedIn";
$message = "We will register your application";
}
$data = ['application' => $application, 'member' => $member];
}
}
$application->setEditStatus("{$status}:{$todo}");
$application->setEditMessage($message);
break;
case "login":
case "hasCommunityMembership":
case "hasStartupMembership":
if ($existingApplication) {
$data['application'] = $existingApplication;
}
break;
default:
break;
}
$response = [
'status' => $status,
'todo' => $todo,
'message' => $message,
'data' => $data,
'hasExistingApplication' => !!$existingApplication,
];
return $response;
}
private function checkForMultipleApplications(Team $team, Member $member, $settings)
{
$em = $this->getDoctrine()->getManager();
$application = null;
if (!$settings['isMultipleApplicationsPerTeam'] and $team->getId()) {
$application = $em->getRepository(Application::class)->findOneBy(['teamId' => $team->getId(), 'batchId' => $settings['batchId']]);
} else {
if (!$settings['isMultipleApplicationsPerMember']) {
$application = $em->getRepository(Application::class)->findOneBy(['memberId' => $member->getId(), 'batchId' => $settings['batchId']]);
}
}
return $application;
}
private function checkPlausibility(Application $application, Member $member, Team $team, $settings)
{
$em = $this->getDoctrine()->getManager();
$status = "";
$message = "";
$todo = "";
$data = ['application' => $application];
switch ($settings['programSlug']) {
case "rheinland-pitch":
case "accelerator":
// plausibility checks
if ($em->getRepository(Application::class)->findByCriteriaButNotTeam(['programSlug' => $application->getProgramSlug(), 'batchSlug' => $application->getBatchSlug(), 'startupName' => $application->getStartupName()], $team)) {
$status = "error";
$todo = "changeName";
$message = "An Application with this name already exists. Please change name!";
}
if (!$application->getIdeaPitch()) {
$status = "error";
$todo = "fillOutIdeaPitch";
$message = "Please specify your idea pitch!";
}
$wordsCount = str_word_count($application->getIdeaPitch() ?? '');
if ($wordsCount > 150) {
$status = "error";
$todo = "shortenIdeaPitch";
$message = "Your idea pitch contains {$wordsCount} words, max words is 150, please reduce the length of your idea pitch!";
}
break;
default:
break;
}
if ($status > "") {
$application->setEditStatus("{$status}:{$todo}");
$application->setEditMessage($message);
$data = ['application' => $application];
}
$response = [
'status' => $status,
'todo' => $todo,
'message' => $message,
'data' => $data,
];
return $response;
}
private function addApplicationToPodioByZapier(Application $application, Batch $batch, $action = 'create')
{
$responseContent = [];
## check for validity of website url
## $application->getWebsiteUrl()
$websiteUrl = $application->getWebsiteUrl();
$urlConstraint = new Assert\Url();
// all constraint "options" can be set this way
$urlConstraint->message = 'Invalid url';
// use the validator to validate the value
$validator = Validation::createValidator();
$errors = $validator->validate(
$application->getWebsiteUrl(),
$urlConstraint
);
if ($errors->count()) {
$cleanedURL = Utility::generateSlug($application->getWebsiteUrl());
$cleanedURL = "https://{$cleanedURL}.de";
$websiteUrl = "https://error-with-url--{$cleanedURL}--please-check-application.de";
}
$dealRoomUrl = $application->getDealroomUrl();
$urlConstraint = new Assert\Url();
// all constraint "options" can be set this way
$urlConstraint->message = 'Invalid url';
// use the validator to validate the value
$validator = Validation::createValidator();
$errors = $validator->validate(
$application->getDealroomUrl(),
$urlConstraint
);
if ($errors->count()) {
$cleanedURL = Utility::generateSlug($application->getDealroomUrl());
$cleanedURL = "https://{$cleanedURL}.de";
$dealRoomUrl = "https://error-with-url--{$cleanedURL}--please-check-application.de";
}
$payload = json_encode([
'action' => $action == 'update' ? "update" : "add",
'applicationId' => $application->getId(),
'podioId' => $application->getPodioId(),
'podioItemId' => $application->getPodioItemId(),
'program' => "accelerator",
'batch' => $batch->getBatchNumber(),
'startupName' => $application->getStartupName(),
'location' => $application->getCity(),
'acceleratorStatus' => $application->getApplicationStatus(),
'teamId' => $application->getTeamId(),
'industry' => $application->getIndustry(),
'teamsize' => $application->getTeamSize(),
'website' => $websiteUrl,
'dealroomUrl' => $dealRoomUrl,
'fulltime' => $application->getFulltime(),
'mvpStatus' => $application->getMvpStatus(),
'pitchDeckLink' => $application->getLinkPitchDeck(),
'ideaPitch' => strip_tags($application->getIdeaPitch()),
'firstName' => $application->getFirstName(),
'lastName' => $application->getLastName(),
'email' => $application->getEmail(),
'phone' => $application->getPhone(),
'linkedIn' => $application->getLinkedin(),
'contactPerson' => $application->getPerson() ? $application->getPerson() : "{$application->getFirstName()} {$application->getLastName()}",
'applicationDate' => $application->getCreatedAt()->format('Y-m-d H:i'),
]);
if ($action == "update") {
$callbackUrl = "https://hooks.zapier.com/hooks/catch/1872803/bxz3547/";
} else {
$callbackUrl = "https://hooks.zapier.com/hooks/catch/1872803/o7r9f2c/";
}
$responseContent[] = $this->callbackService->curl_callback($callbackUrl, $payload);
return $responseContent;
}
private function addApplicationToPodioByZapierSwitch(Application $application, Batch $batch)
{
$responseContent = "";
$fields = Utility::getEntityFieldsArray($application, ['assessments']);
$storedData = Utility::fillDataByObject($application, $fields);
$payload = json_encode([
'action' => "add",
'batchNumber' => $batch->getBatchNumber(),
] + $storedData);
$callbackUrl = "https://hooks.zapier.com/hooks/catch/1872803/ovd3dks/";
$responseContent = $this->callbackService->curl_callback($callbackUrl, $payload);
//
return $responseContent;
}
private function setMonsumAccountIfNotExists(Member $member, Team $team, Application $application, $account)
{
$em = $this->getDoctrine()->getManager();
$adminEmail = $member->getEmail();
$responseContent = [];
$teamId = $team->getId();
$customer = null;
$monsumCustomer = null;
$settings = [
'adminEmail' => $adminEmail,
'location' => $em->getRepository(Customer::class)->getLocationByAccount($account),
'account' => $account,
'accountHash' => $em->getRepository(Customer::class)->getAccountHashByAccount($account),
];
$login = $em->getRepository(Customer::class)->getLoginByAccount($account);
$payload = json_encode([
'SERVICE' => "customer.get",
'FILTER' => [
'CUSTOMER_EXT_UID' => "{$team->getId()}",
],
]);
$feedback = $this->callbackService->curl_get_monsum_all($payload, $login);
$feedback = json_decode($feedback);
if (isset($feedback->RESPONSE->CUSTOMERS[0])) {
$responseContent[] = "Team {$teamId} has already account in Monsum";
$customer = $feedback->RESPONSE->CUSTOMERS[0];
} else {
$responseContent[] = "New account will be created for team {$teamId} in Monsum";
$customerSettings = $em->getRepository(Customer::class)->getCustomerSettingsByTeamAndMember($team, $member);
$payload = json_encode([
'SERVICE' => "customer.create",
'DATA' => $customerSettings,
]);
$feedback = $this->callbackService->curl_get_monsum_all($payload, $login);
$feedback = json_decode($feedback);
$monsumResponse = $feedback->RESPONSE;
if (isset($monsumResponse->ERRORS)) {
$responseContent[] = "ERROR ======== ERROR";
$responseContent[] = $monsumResponse->ERRORS;
$responseContent[] = $feedback;
} else {
$responseContent[] = $monsumResponse;
if ($monsumResponse->STATUS == "success") {
$customerId = $monsumResponse->CUSTOMER_ID;
$payload = $em->getRepository(Customer::class)->getPayloadSingleCustomerByCustomerId($customerId);
$feedback = $this->callbackService->curl_get_monsum_all($payload, $login);
if ($feedback = json_decode($feedback)) {
$customer = $feedback->RESPONSE->CUSTOMERS[0];
} else {
$responseContent[] = "ERROR: could not decode feedback from monsum";
$responseContent[] = $feedback;
}
}
}
}
if ($customer) {
$monsumCustomer = $em->getRepository(Customer::class)->createOrUpdateMonsumCustomerByTeam($customer, $settings, $team);
}
return $monsumCustomer;
}
/**
* @Route("/apply-add-application/{memberId}/{batchId}/", name="apply_add-application")
*/
public function addApplicationAction(Request $request, $batchId, $memberId)
{
$em = $this->getDoctrine()->getManager();
$redirect = Utility::getRedirectTarget($request);
$now = new datetime();
$batch = $em->getRepository(Batch::class)->findOneBy(['id' => $batchId]);
$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['id' => $batch->getProgramId()]);
$member = $em->getRepository(Member::class)->findOneBy(['id' => $memberId]);
// check if settings contains necessary setters
$batch = $em->getRepository(Batch::class)->checkLegacyData($batch);
$settings = $em->getRepository(Application::class)->getSettingsProgram($program, $batch);
/** @var User $user */
$user = $this->getUser();
$adminEmail = $user->getEmail();
$em->getRepository(User::class)->writeActivity($user);
// falls member Mitglied in mehreren teams ist, auswählen lassen, ob für bestehendes team einreichen oder für neues team
$virtualTeam = array_key_exists('virtualTeam', $settings) ? $settings['virtualTeam'] : 'applicants';
$applicantsTeam = $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
// check if $member is part of specified - virtual team
if (!$applicantsTeamMember = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $applicantsTeam, 'member' => $member])) {
$em->getRepository(Member::class)->setTeamAssignmentByUser($user, $member->getId(), $applicantsTeam->getId());
}
$id = $member->getTeamId();
$team = $em->getRepository(Team::class)->findOneBy(['id' => $id]);
$teamMember = $em->getRepository(MemberTeam::class)->findOneBy(['team' => $team, 'member' => $member]);
$teamId = $team->getId();
if ($batch->getIsMultipleApplicationsPerTeam()) {
if (!$application = $em->getRepository(Application::class)->findOneBy(['programSlug' => $program->getSlug(), 'batchSlug' => $batch->getSlug(), 'memberId' => $member->getId()])) {
$application = $em->getRepository(Application::class)->createApplicationIfNotExists($program, $batch, $team, $member, $adminEmail);
}
} else {
if (!$application = $em->getRepository(Application::class)->findOneBy(['programSlug' => $program->getSlug(), 'batchSlug' => $batch->getSlug(), 'teamId' => $teamId])) {
$application = $em->getRepository(Application::class)->createApplicationIfNotExists($program, $batch, $team, $member, $adminEmail);
}
}
$application->setBatchStatus('applicant');
$application->setApplicationStatus('applied');
$em->persist($application);
$em->flush();
$batch = $em->getRepository(Batch::class)->updateNumbers($batch);
$this->session->getFlashBag()->add('notice', 'SUCCESS ' . "Application created for member {$member->getName()} and batch {$batch->getName()}");
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/action/get-access", name="apply_program_get_access")
*/
public function getAccessAction(Request $request, $programSlug, $batchSlug)
{
$em = $this->getDoctrine()->getManager();
$data = $request->request->all();
if (!($data['email'] and $data['firstName'] and $data['lastName'])) {
$this->session->getFlashBag()->add('notice', 'ERROR Please fill in your data');
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
// https://symfony.com/doc/4.4/validation/raw_values.html
$validator = Validation::createValidator();
$constraint = new Assert\Collection([
// the keys correspond to the keys in the input array
'firstName' => new Assert\Length(['min' => 3]),
'lastName' => new Assert\Length(['min' => 3]),
'email' => new Assert\Email(),
]);
if ($violations = $validator->validate($data, $constraint)) {
$error = false;
foreach ($violations as $violation) {
$this->session->getFlashBag()->add('notice', 'ERROR ' . $violation->getMessage());
$error = true;
}
if ($error) {
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
}
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no batch found');
return $this->redirect($this->generateUrl('apply_home', []));
}
$settingsProgram = $em->getRepository(Application::class)->getSettingsProgram($program, $batch);
//$adminEmail = $data['email'];
$userEmail = $data['email'];
$adminEmail = "support@startplatz.de";
// check if there is the defined virtual team
$virtualTeam = array_key_exists('virtualTeam', $settingsProgram) ? $settingsProgram['virtualTeam'] : 'applicants';
$team = $em->getRepository(Team::class)->getVirtualTeamByName($virtualTeam);
$member = $em->getRepository(Member::class)->createGuestMemberIfNotExists($data, $team, $userEmail);
$loginLink = $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
$mailSubject = "{$settingsProgram['programName']} - Access Code - Application Area";
$mailText = $this->renderView(
'@StartPlatzRheinlandPitchBundle/Apply/_mail.get.access.txt.twig',
[
'member' => $member,
'loginLink' => $loginLink,
'settings' => $settingsProgram,
]
);
$this->callbackService->sendAlertMailPerZapier("{$member->getEmail()}", $mailText, $mailSubject, $adminEmail);
$mailText = "
Es gibt eine Anmeldung von {$data['firstName']} {$data['lastName']}
Bewerber im Program {$settingsProgram['programName']} mit der E-Mail-Adresse {$data['email']}
und der Bitte um Zugang zum internen Bereich
";
$this->callbackService->sendAlertMailPerZapier($adminEmail, $mailText, "{$settingsProgram['programName']} - Registration internal Area", $userEmail);
$this->callbackService->setSlackMonitoring($mailText);
$this->session->getFlashBag()->add('notice', 'SUCCESS Thank you for your message; we have sent you an access code');
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/action/feedback", name="apply_program_feedback")
*/
public function receiveFeedbackAction(Request $request, $programSlug, $batchSlug)
{
$em = $this->getDoctrine()->getManager();
$data = $request->request->all();
if (!array_key_exists('context', $data)) {
$data['context'] = "Application Platform";
}
if (!$data['email']) {
$this->session->getFlashBag()->add('notice', 'ERROR Please specify your email address');
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
$mailText = "
Es gibt eine Nachricht von {$data['name']}
mit der E-Mail-Adresse {$data['email']}
und dem Betreff: {$data['subject']}
und dem Inhalt:
{$data['message']}
";
$this->callbackService->sendAlertMailPerZapier("lorenz.graef@startplatz.de", $mailText, $data['context'] . ": " . $data['subject'], "support@startplatz.de");
$this->callbackService->setSlackMonitoring($mailText);
$this->session->getFlashBag()->add('notice', 'SUCCESS Thank you for your message');
return $this->redirect($this->generateUrl('apply_program_home', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/{id}/account", name="apply_program_account")
* @Security("is_granted('ROLE_USER')")
*/
public function accountAction(Request $request, $programSlug, $batchSlug, $id)
{
$em = $this->getDoctrine()->getManager();
if (!$user = $this->getUser()) {
return $this->redirect($this->generateUrl('apply_home', []));
}
$em->getRepository(User::class)->writeActivity($user);
$form = $this->createForm(SetPasswordFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var User $user */
$user = $this->getUser();
$data = $form->getData();
$password = $data['new_password'];
$encodedPassword = $this->encoder->encodePassword($user, $password);
$user->setPassword($encodedPassword);
$em->getRepository(User::class)->add($user);
$message = new Email();
$message->to($user->getEmail());
$message->from('info@startplatz.de');
$message->subject('Your password for startplatz.de has been changed');
$message->text(
$this->renderView(
'@StartPlatzUserBundle/Mails/passwordChangeAlert.txt.twig',
[
'email' => $user->getEmail(),
'password' => $password,
]
)
);
$this->mailer->send($message);
$this->session->getFlashBag()->add('notice', 'SUCCESS ' . "Passwort has been set");
return $this->redirect($this->generateUrl('apply_program_home', ['id' => $id, 'programSlug' => $programSlug, 'batchSlug' => $batchSlug]));
}
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/account.html.twig', [
'form' => $form->createView(),
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home', 'parameters' => ['programSlug' => $programSlug, 'batchSlug' => $batchSlug]])),
]);
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/{id}/uploadPitchDeck", name="apply_program_uploadPitchDeck")
*/
public function uploadPitchDeckAction(Request $request, $programSlug, $batchSlug, $id)
{
$em = $this->getDoctrine()->getManager();
$now = new datetime();
if (!$program = $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => $programSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no program found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['slug' => $batchSlug])) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no batch found');
return $this->redirect($this->generateUrl('apply_home', []));
}
$settings = $em->getRepository(Application::class)->getSettingsProgram($program, $batch);
/** @var User $user */
if ($user = $this->getUser()) {
$em->getRepository(User::class)->writeActivity($user);
}
$isAdminUpload = $request->get('isAdminUpload');
if (!$application = $em->getRepository(Application::class)->findOneBy(['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'id' => $id])) {
$this->session->getFlashBag()->add('notice', 'ERROR no application found ');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$teamId = $application->getTeamId()) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no team found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$memberId = $application->getMemberId()) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, no member found');
return $this->redirect($this->generateUrl('apply_home', []));
}
if (!$isAdminUpload) {
if (!$em->getRepository(MemberTeam::class)->isMemberOfTeam($memberId, $teamId)) {
$this->session->getFlashBag()->add('notice', 'ERROR Sorry, we found a problem with the team access rights');
return $this->redirect($this->generateUrl('apply_home', []));
}
}
$publicId = $request->get('PublicId');
$uploadTag = "application/{$application->getId()}";
if (!$isAdminUpload) {
$redirectTargetUrl = $this->generateUrl('apply_program_home_lang', ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => strtolower($application->getLang())]);
} else {
$redirectTargetUrl = $this->generateUrl('allmeda_application_edit', ['id' => $application->getId()]);
}
return $this->render('@StartPlatzRheinlandPitchBundle/Apply/uploadPitchDeck.html.twig', [
'application' => $application,
'settings' => $settings,
'programSlug' => $programSlug,
'batchSlug' => $batchSlug,
'program' => $program,
'batch' => $batch,
'uploadTag' => $uploadTag,
'publicId' => $publicId,
'isAdminUpload' => $isAdminUpload,
'teamId' => $teamId,
'memberId' => $memberId,
'redirect' => $redirectTargetUrl,
'redirectUrl' => base64_encode(json_encode(['path' => 'apply_program_home_lang', 'parameters' => ['programSlug' => $programSlug, 'batchSlug' => $batchSlug, 'lang' => strtolower($application->getLang())]])),
]);
}
/**
* @Route("/apply/{programSlug}/{batchSlug}/{id}/add-images-by-tag/", name="apply_program_add_images_by_tag")
*/
public function addImagesByTagAction(Request $request, $programSlug, $batchSlug, $id)
{
$time_start = microtime(true);
$tag = $request->request->get('tag');
$redirect = Utility::getRedirectTarget($request);
$em = $this->getDoctrine()->getManager();
$now = new DateTime();
if (!$application = $em->getRepository(Application::class)->findOneBy(['id' => $id])) {
$response = new Response();
$response->setContent(json_encode('ERROR no application found'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$result = $this->cloudinary->resources_by_tag($tag);
$resources = $result['resources'];
foreach ($resources as $resource) {
$publicId = $resource['public_id'];
$secureUrl = $resource['secure_url'];
$application->setLinkPitchDeck($secureUrl);
$application->setPublicIdPitchDeck($publicId);
$application->setEditStatus("feedback:pitchdeckUploaded");
$application->setEditMessage("Thank you for uploading your pitch deck.");
$em->persist($application);
$em->flush();
}
$response = new Response();
$response->setContent(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
private function getSettingsProgramDefault()
{
return [
"programName" => "Example",
"programSlug" => "example",
"batchName" => "Batch11",
"batchSlug" => "batch11",
"applicationStart" => "2019-11-11",
"programStart" => "2019-12-11",
"programEnd" => "2019-12-11",
"applicationStages" => "applied,approved",
"programStages" => "applicant,participant,alumni,drop-out,rejected",
"programTag" => "example-batch11-participant",
"eventId" => "4982",
"bgImage" => "https://res.cloudinary.com/startplatz/image/upload/v1573496116/rheinland-pitch/impressions/final-koeln-2017_audience_manor-lux.jpg",
"virtualTeam" => "example-team",
"status" => "test",
];
}
/**
* @Route("/apply/administration/batch/test-confirmation-mail/{batchId}", name="apply_test_confirmation-mail")
* @Security("is_granted('ROLE_ADMIN')")
*/
public function sendConfirmationTestMail(Request $request, $batchId)
{
$redirect = Utility::getRedirectTarget($request);
$em = $this->getDoctrine()->getManager();
$reminder = null;
$sendReminderMail = $request->get('sendReminderMail');
/** @var User $user */
$user = $this->getUser();
$em->getRepository(User::class)->writeActivity($user);
if ($sendReminderMail){
$reminder = $em->getRepository(Reminder::class)->find($batchId);
$batchId = $reminder->getBatchId();
}
/** @var Batch $batch */
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['id' => $batchId])) {
$this->session->getFlashBag()->add('notice', 'ERROR batch not found');
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
$member = $em->getRepository(Member::class)->find($user->getMemberId());
if (!$application = $em->getRepository(Application::class)->findOneBy(['memberId'=>$member->getId(), 'batchId'=>$batch->getId()])){
$application = $em->getRepository(Application::class)->getTemporaryApplicationByBatchAndMember($batch, $member);
$application = $em->getRepository(Application::class)->setApplicationDone($application);
}
$application->setApplicationStatus('applied');
// Start timing
$this->stopwatch->start('confirmation_mail');
$response = $this->sendConfirmationMailToApplicant($user, [], $application, $batch, $reminder);
// Stop timing
$stopwatchEvent = $this->stopwatch->stop('confirmation_mail');
// Get duration and memory usage
$duration = $stopwatchEvent->getDuration();
$memory = round($stopwatchEvent->getMemory() / (1024 * 1024), 2); // Convert to MB and round to 2 decimal places
$this->addFlash('notice', "SUCCESS via service: A test confirmation mail has been sent to {$user->getEmail()}. Time: {$duration}ms, Memory: {$memory} MB");
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
/**
* @Route("/apply/administration/batch/test-confirmation-mail-service/{batchId}", name="apply_test_confirmation-mail_service")
* @Security("is_granted('ROLE_ADMIN')")
*/
public function sendConfirmationTestMailViaService(Request $request, $batchId)
{
$redirect = Utility::getRedirectTarget($request);
$em = $this->getDoctrine()->getManager();
$reminder = null;
$sendReminderMail = $request->get('sendReminderMail');
/** @var User $user */
$user = $this->getUser();
$em->getRepository(User::class)->writeActivity($user);
if ($sendReminderMail){
$reminder = $em->getRepository(Reminder::class)->find($batchId);
$batchId = $reminder->getBatchId();
}
/** @var Batch $batch */
if (!$batch = $em->getRepository(Batch::class)->findOneBy(['id' => $batchId])) {
$this->session->getFlashBag()->add('notice', 'ERROR batch not found');
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
$member = $em->getRepository(Member::class)->find($user->getMemberId());
if (!$application = $em->getRepository(Application::class)->findOneBy(['memberId'=>$member->getId(), 'batchId'=>$batch->getId()])){
$application = $em->getRepository(Application::class)->getTemporaryApplicationByBatchAndMember($batch, $member);
$application = $em->getRepository(Application::class)->setApplicationDone($application);
}
$application->setApplicationStatus('applied');
// Start timing
$this->stopwatch->start('confirmation_mail');
$result = $this->confirmationMailService->sendConfirmationMailToApplicant($user, $member, [], $application, $batch, $reminder);
// Stop timing
$stopwatchEvent = $this->stopwatch->stop('confirmation_mail');
// Get duration and memory usage
$duration = $stopwatchEvent->getDuration();
$memory = round($stopwatchEvent->getMemory() / (1024 * 1024), 2); // Convert to MB and round to 2 decimal places
// Verarbeiten der Nachrichten aus dem Service
foreach ($result['messages'] as $message) {
$this->addFlash('notice', $message);
}
// Zusätzliche Flash-Nachricht für Leistungsinformationen
$this->addFlash('notice', "Service execution: Time: {$duration}ms, Memory: {$memory} MB");
// Status-basierte Nachricht
if ($result['status'] === 'success') {
$this->addFlash('notice', 'SUCCESS: Mail sent successfully via service');
} else {
$this->addFlash('notice', 'ERROR: Failed to send mail via service');
}
return $this->redirect($this->generateUrl($redirect->path, (array)$redirect->parameters));
}
private function sendConfirmationMailToApplicant(User $user, $settings, Application $application, Batch $batch, Reminder $reminder = null)
{
$em = $this->getDoctrine()->getManager();
if (!$settings) {
$application->setStartupName("Test Startup");
$application->setEmail($user->getEmail());
}
$program = $batch->getProgram();
$routeParameters = [
'programSlug' => $program->getSlug(),
'batchSlug' => $batch->getSlug(),
];
if (isset($reminder) && $reminder->getType() == 'feedbackMail' && $batch->getSurveyId() > ''){
$loginPath = ['path'=>'survey_proceed','parameters'=>['id'=>$batch->getSurveyId(), 'slug'=>"{$program->getSlug()}-{$batch->getSlug()}"]];
//$mailTemplate->setLoginPath(json_encode($loginPath));
$targetPath = $this->generateUrl($loginPath['path'], $loginPath['parameters']);
} else {
$targetPath = $this->generateUrl('apply_program_home', $routeParameters);
}
$loginLink = $this->loginService->getLoginLinkByTargetPath($application->getEmail(), $targetPath);
$metaName = $batch->getMailDesignTemplate();
$designTemplate = $em->getRepository(Option::class)->getOptionMetaValuePlain($metaName);
if ($reminder){
$content = $reminder->getReminderMailContent();
$subject = $reminder->getReminderMailSubject();
} else {
$content = $batch->getConfirmationMailContent();
$subject = $batch->getConfirmationMailSubject();
}
$loader = new ArrayLoader([
'mailBase' => $designTemplate,
'content' => $content,
'subject' => $subject,
]);
// create new twig object with all twig templates
$twig = new Environment($loader);
$viewBase = 'mailBase';
$viewContent = 'content';
$viewSubject = 'subject';
$renderedSubject = $twig->render(
$viewSubject,
[
'userId' => $user->getId(),
'loginLink' => $loginLink,
'batch' => $batch,
'program' => $program,
'application' => $application,
'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
'dateDE' => $batch->getPitchDate()->format('d.m.y'),
'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
'timeDE' => $batch->getPitchTime()->format('H:i'), // German 24-hour format
'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
]
);
$renderedContent = $twig->render(
$viewContent,
[
'userId' => $user->getId(),
'name' => $application->getPerson(),
'firstName' => $application->getFirstName(),
'loginLink' => $loginLink,
'batch' => $batch,
'program' => $program,
'application' => $application,
'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
'dateDE' => $batch->getPitchDate()->format('d.m.y'),
'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
'timeDE' => $batch->getPitchTime()->format('H:i'), // German 24-hour format
'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
]
);
$html = $twig->render(
$viewBase,
[
'userId' => $user->getId(),
'name' => $application->getPerson(),
'firstName' => $application->getFirstName(),
'loginLink' => $loginLink,
'batch' => $batch,
'program' => $program,
'application' => $application,
'dateEN' => $batch->getPitchDate()->format('Y-m-d'),
'dateDE' => $batch->getPitchDate()->format('d.m.y'),
'timeEN' => $batch->getPitchTime()->format('g:i A'), // English 12-hour format
'timeDE' => $batch->getPitchTime()->format('H:i'), // German 24-hour format
'zoomLink' => Utility::getZoomLink($batch->getZoomLink(), $application->getId()),
'googleCalendarLink' => $em->getRepository(Event::class)->getGoogleCalendardEventByEventId($batch->getEventId(), Utility::getZoomLink($batch->getZoomLink(), $application->getId())),
'icsDownloadLink' => $this->generateUrl('event_download',['eventId'=>(int)$batch->getEventId()],UrlGeneratorInterface::ABSOLUTE_URL),
'content' => $renderedContent,
]
);
$feedback = Utility::sendAlertMailPerZapier($application->getEmail(), $html, $renderedSubject, $batch->getSenderMail(), $batch->getFromName(), 'html');
$this->session->getFlashBag()->add('notice', "SUCCESS Confirmation Mail has been sent via Zapier to {$application->getEmail()} with feedback=" . print_r($feedback, true));
$mailSubject = "{$batch->getProgram()->getName()} - Application submitted by {$application->getStartupName()}";
$mailText = $this->renderView(
'@StartPlatzRheinlandPitchBundle/Apply/_mail.altert.admin.application.txt.twig',
[
'user' => $user,
'batch' => $batch,
'application' => $application,
]
);
$feedback = $this->callbackService->sendAlertMailPerZapier($batch->getRecipientMonitoringMail(), $mailText, $mailSubject, $application->getEmail());
$this->session->getFlashBag()->add('notice', "SUCCESS Confirmation Mail has been sent via Zapier to {$application->getEmail()} with feedback=" . print_r($feedback, true));
if ($batch->getSkoolWebhook() > ''){
$feedback = $this->callbackService->sendPostRequest($batch->getSkoolWebhook(), $application->getEmail());
$this->session->getFlashBag()->add('notice', "SUCCESS Skool Webhook has been posted with email= {$application->getEmail()} and feedback=" . print_r($feedback, true));
}
if ($batch->getZapierWebhook() > ''){
$payload = json_encode($em->getRepository(Event::class)->setPayloadSingleApplicationAndBatch($application, $batch));
$callbackUrl = $batch->getZapierWebhook();
$feedback = $this->callbackService->curl_callback($callbackUrl, $payload);
$this->session->getFlashBag()->add('notice', "SUCCESS Zapier webhook {$batch->getZapierWebhook()} called with feedback=" . print_r($feedback,true));
}
if ($reminder && $reminder->getSkoolWebhook() > ''){
$feedback = $this->callbackService->sendPostRequest($reminder->getSkoolWebhook(), $application->getEmail());
$this->session->getFlashBag()->add('notice', "SUCCESS Skool Webhook has been posted with email= {$application->getEmail()} and feedback=" . print_r($feedback, true));
}
if ($reminder && $reminder->getZapierWebhook() > ''){
$payload = json_encode($em->getRepository(Event::class)->setPayloadSingleApplicationAndBatch($application, $batch));
$callbackUrl = $reminder->getZapierWebhook();
$feedback = $this->callbackService->curl_callback($callbackUrl, $payload);
$this->session->getFlashBag()->add('notice', "SUCCESS Zapier webhook {$reminder->getZapierWebhook()} called with feedback=" . print_r($feedback,true));
}
return true;
}
}