<?php
namespace Nen\Bundle\KennisbankPlatformBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\DBAL\Driver\Connection;
use Nen\Bundle\KennisbankPlatformBundle\Entity\BoltPage;
use Nen\Bundle\KennisbankPlatformBundle\Repository\BoltSubscriptionRepository;
use Nen\Bundle\KennisbankPlatformBundle\Repository\UserRepository;
use Nen\Bundle\KennisbankPlatformBundle\Repository\CompanyRepository;
use Nen\Bundle\KennisbankPlatformBundle\Entity\BoltSubscription;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Nen\Bundle\KennisbankPlatformBundle\Form\RegistrationType;
use Nen\Bundle\KennisbankPlatformBundle\Form\UpgradeLicenseType;
use Nen\Bundle\KennisbankPlatformBundle\Form\UserPasswordType;
use App\Entity\User;
use Nen\Bundle\KennisbankPlatformBundle\Model\RegistrationModel;
use Nen\Bundle\KennisbankPlatformBundle\Model\UpgradeLicenseModel;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Nen\Bundle\KennisbankPlatformBundle\Support\CodeGeneratorInterface;
use Nen\Bundle\KennisbankPlatformBundle\Exceptions\InvalidTokenException;
use App\Entity\Company;
use Nen\Bundle\KennisbankPlatformBundle\Handler\SubscriptionHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\UserActivationHandler;
use Symfony\Component\HttpFoundation\Session\Session;
use Illuminate\Support\Collection;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use function Symfony\Component\Translation\t;
class SubscriptionController extends AbstractController
{
private $params;
private $codeGenerator;
public function __construct(ParameterBagInterface $params, CodeGeneratorInterface $codeGenerator)
{
$this->params = $params;
$this->codeGenerator = $codeGenerator;
}
/**
* @Route("/abonnementen", name="subscription_index")
*
* @Entity("page", expr="repository.findOneByGeneralSectionAndSlug('abonnementen')")
*
* @param BoltPage $page
* @param BoltSubscriptionRepository $subscriptionRepository
* @return Response
*/
public function index(BoltPage $page, BoltSubscriptionRepository $subscriptionRepository)
{
if ($this->getUser()) {
return $this->redirectToRoute('gebruikers_omzetten');
}
$licensesConfig = $this->params->get('licenses');
$licenses = $subscriptionRepository->findBy([], ['sorting' => 'ASC']);
return $this->render('@KennisbankPlatform/pages/abonnementen.html.twig', [
'page' => $page,
'licenses' => $licenses
]);
}
/**
* @Route("/abonnementen/{slug}", name="abonnementen_detail")
*
*/
public function abonnementenDetail(
Request $request,
BoltSubscription $subscription,
SubscriptionHandler $subscriptionHandler,
UserRepository $userRepository,
EventDispatcherInterface $eventDispatcher
) {
$isUpgrade = (bool) $request->query->get('upgrade', false);
if ($isUpgrade) {
if (! $user = $this->getUser()) {
$session = $request->getSession();
if ($id = $session->get('expired')) {
$user = $userRepository->find($id);
}
if (! $user) {
$this->addFlash('error', t('Log in om uw abonnement om te zetten.'));
return $this->redirectToRoute('home');
}
}
$company = $user->getCompany();
$model = new UpgradeLicenseModel();
$type = UpgradeLicenseType::class;
} else {
$user = new User();
$company = new Company();
$model = new RegistrationModel();
$type = RegistrationType::class;
}
$company->setLicenseAmount($request->query->get('userAmount', 1));
$user->setCompany($company);
$options = [
'license' => $subscription
];
$model->setUser($user);
if ($request->query->has('jwt')) {
$model->setJwt($request->query->get('jwt'));
}
if ($isUpgrade) {
$options['method'] = 'PATCH';
}
$form = $this->createForm($type, $model, $options);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($form->has('hash')) {
$hash = $form->get('hash')->getData();
} else {
$hash = null;
}
$subscriptionHandler->handle($user, $subscription, $hash, $isUpgrade, $model->getJwt());
if ($isUpgrade) {
$this->addFlash('success', t('Uw abonnement is succesvol omgezet.'));
// $token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles());
// // For older versions of Symfony, use security.context here
// $this->get("security.token_storage")->setToken($token);
// // Fire the login event
// // Logging the user in above the way we do it doesn't do this automatically
// $event = new InteractiveLoginEvent($request, $token);
// $eventDispatcher->dispatch("security.interactive_login", $event);
return $this->redirectToRoute('mijnomgeving_account_index');
}
$this->addFlash('success', t('U ontvangt een e-mail om uw gebruiker te activeren via %username%.', ['%username%' => $user->getUsername()]));
return $this->redirectToRoute('home');
}
return $this->render('@KennisbankPlatform/pages/abonnement.html.twig', [
// 'page' => $page,
'license' => $subscription,
'form' => $form->createView(),
'is_upgrade' => $isUpgrade
]);
}
/**
* @Route("/activeren", name="activate")
*/
public function activate(Request $request, UserRepository $userRepository, UserPasswordHasherInterface $passwordHasher, UserActivationHandler $userActivationHandler)
{
$token = $request->query->get('token');
try {
$user = $userRepository->validateToken($this->codeGenerator, $token);
} catch (InvalidTokenException $e) {
return $this->render('@KennisbankPlatform/subscriptions/activate.html.twig', [
'error' => true,
'message' => 'Ongeldige token.'
]);
}
if (!empty($user->getPasswordAt()) && empty($user->getActivationAt())) {
$userActivationHandler->handle($user);
$this->addFlash('success', t('Uw abonnement is nu actief. Log rechtsboven in om gebruik te maken van uw abonnement.'));
return $this->redirectToRoute('home');
}
if (!empty($user->getActivationAt())) {
$this->addFlash('error', t('Uw account is al geactiveerd. Bent u uw wachtwoord vergeten? Vraag dan opnieuw uw wachtwoord aan.'));
return $this->redirectToRoute('home');
}
$form = $this->createForm(UserPasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$userActivationHandler->handle($user, $form);
// encode the plain password
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$form->get('hash')->getData()
)
);
$user->setActivationAt(new \DateTime("now"));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', t('Uw abonnement is nu actief. Log rechtsboven in om gebruik te maken van uw abonnement.'));
return $this->redirectToRoute('home');
}
return $this->render('@KennisbankPlatform/subscriptions/activate.html.twig', [
'error' => false,
'passwordForm' => $form->createView()
]);
}
/**
* @Route("/omzetten", name="gebruikers_omzetten")
*/
public function omzetten(Request $request, UserRepository $userRepository, BoltSubscriptionRepository $subscriptionRepository)
{
if ($request->getSession()->has('expired')) {
/** @var User $user */
$user = $userRepository->find((int)$request->getSession()->get('expired'));
} else {
/** @var User $user */
$user = $this->getUser();
}
$subscription = $subscriptionRepository->findOneBy(['slug' => $user->getCompany()->getLicenseType()]);
// When a subscription was not found, fallback on the previous method
// of deciding is a subscription can be upgraded.
if (empty($subscription)) {
if ($user && !$user->getCompany()->canUpgradeLicense()) {
$this->addFlash('error', t('U kunt dit abonnement niet omzetten.'));
return $this->redirectToRoute('home');
}
}
$convertSubscription = $subscription->getConvertSubscription();
if (empty($convertSubscription)) {
$this->addFlash('error', t('U kunt dit abonnement niet omzetten.'));
return $this->redirectToRoute('home');
}
$licenses = $subscriptionRepository->findBy([
'slug' => $convertSubscription
], ['sorting' => 'ASC']);
$licenses = Collection::make($licenses)->keyBy(function ($o) {
return $o->getSlug();
})->toArray();
unset($licenses['trial']);
return $this->render('@KennisbankPlatform/subscriptions/omzetten.twig', [
'record' => $user,
'licenses' => $licenses
]);
}
}