<?php
// src/Controller/EntrepriseController.php
namespace App\Controller;
use App\Entity\AppUser;
use App\Entity\Boutique;
use App\Entity\Plan;
use App\Form\BoutiqueType;
use App\Entity\CodePromo;
use App\Entity\TVA;
use App\Entity\ValiditeService;
use App\Entity\Service;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Spipu\Html2Pdf\Html2Pdf;
/**
* @Route("/{_locale}/affiliation")
*/
class AffiliationController extends AbstractController
{
private $kernel;
private $session;
public function __construct(KernelInterface $kernel, SessionInterface $session)
{
$this->kernel = $kernel;
$this->session = $session;
}
/**
* @Route("/acceuil", name="affiliation_accueil")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function accueilAction(Request $request)
{
$em = $this->getDoctrine()
->getManager();
$user = $this->getUser();
$codePromo = $em->getRepository(CodePromo::class)
->findOneBy(
array(
'user' => $user
)
);
$intervalleDeDate = $this->intervalleSemaine(date('Y-m-d'));
$dateDebut = new \DateTime($intervalleDeDate['debut']);
$dateDebut->setTime(0, 0);
$dateFin = new \DateTime($intervalleDeDate['fin']);
$dateFin->setTime(23, 59);
$intervalleMois = $this->intervalleMois(date('Y-m-d'));
$startMonth = $intervalleMois['debut'];
$endMonth = $intervalleMois['fin'];
$startYear = date('Y-01-01');
$endYear = date('Y-12-31');
return $this->render('affiliation/accueil.html.twig', [
'codePromo' => $codePromo,
'dateDebut' => $dateDebut,
'dateFin' => $dateFin,
'startMonth' => $startMonth,
'endMonth' => $endMonth,
'startYear' => $startYear,
'endYear' => $endYear,
]);
}
/**
* @Route("/clients", name="affiliation_clients")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function clientsAction(Request $request)
{
$em = $this->getDoctrine()
->getManager();
$user = $this->getUser();
$codePromo = $em->getRepository(CodePromo::class)
->findOneBy(
array(
'user' => $user
)
);
$intervalleDeDate = $this->intervalleSemaine(date('Y-m-d'));
$dateDebut = new \DateTime($intervalleDeDate['debut']);
$dateDebut->setTime(0, 0);
$dateFin = new \DateTime($intervalleDeDate['fin']);
$dateFin->setTime(23, 59);
$intervalleMois = $this->intervalleMois(date('Y-m-d'));
$startMonth = $intervalleMois['debut'];
$endMonth = $intervalleMois['fin'];
$startYear = date('Y-01-01');
$endYear = date('Y-12-31');
return $this->render('affiliation/clients.html.twig', [
'codePromo' => $codePromo,
'dateDebut' => $dateDebut,
'dateFin' => $dateFin,
'startMonth' => $startMonth,
'endMonth' => $endMonth,
'startYear' => $startYear,
'endYear' => $endYear,
]);
}
/**
* @Route("/new-shop/{plan}", name="affiliation_new_shop")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function nouvelleBoutiqueAction(Request $request, $plan)
{
if(!$this->isGranted('IS_AUTHENTICATED_FULLY')){
return $this->redirectToRoute('security_login');
}
$em = $this->getDoctrine()
->getManager();
$plan = $em->getRepository(Plan::class)
->findOneBySlug($plan);
$user = $this->getUser();
if(null == $plan){
return $this->createNotFoundException();
}
$codePromo = $em->getRepository(CodePromo::class)
->findOneBy(
array(
'user' => $user
)
);
$boutique = new Boutique;
$form = $this->createForm(BoutiqueType::class, $boutique);
$ok_soumission = '';
$error = '';
$totalAchat = 10;
$prix = $plan->getTarif() * 10;
$remise = 0;
$coupon = '';
$taxes = array();
$tvaa = array(
'libelle' =>'TVA normal de 18%',
'valeur' => 18,
'libelleInterne' => 'TVA'
);
$tvab = array(
'libelle' =>'TVA réduit de 9%',
'valeur' => 9,
'libelleInterne' => 'TVAB'
);
$tvac = array(
'libelle' =>'TVA exec conv de 0%',
'valeur' => 0,
'libelleInterne' => 'TVAC'
);
$tvad = array(
'libelle' =>'TVA exec leg de 0%',
'valeur' => 0,
'libelleInterne' => 'TVAD'
);
array_push($taxes, $tvaa);
array_push($taxes, $tvab);
array_push($taxes, $tvac);
array_push($taxes, $tvad);
$totalAchat *= (float)$plan->getTarif();
$reduction = 0;
if($codePromo != null){
$remise = $codePromo->getRemise() + $codePromo->getRemisePourLePartenaire();
$reduction = $totalAchat * $remise/100;
}
$totalAchat = $totalAchat - $reduction;
if($request->getMethod() == 'POST'){
$form->handleRequest($request);
if($form->isValid()){
$boutique->getSettings()->setEnteDocument($boutique->getNom());
$coupon = $_POST['coupon'];
$remise = $_POST['remise'];
$mt = $_POST['mt'];
$taxe = $_POST['taxe'];
if($plan->getNom() == 'Free' /*|| $plan->getNom() == 'Standard'*/){
$em->persist($boutique);
$service = new Service;
$service->setUser($user);
$service->setBoutique($boutique);
$service->setPlan($plan);
$em->persist($service);
$em->flush();
$this->enregistrerDonneesComptabilite($boutique);
$this->creerRubriquesSalaires($boutique);
$em->persist($validiteService);
$validiteService->setService($service);
$validiteService->setValableJusquAu($today);
$userBoutique = new UserBoutique;
$userBoutique->setUser($user);
$userBoutique->setBoutique($boutique);
$userBoutique->setRole(RoleBoutique::ADMIN);
$userBoutique->setDroits(DroitUtilisateur::getDroits());
$em->persist($userBoutique);
$em->flush();
return $this->redirectToRoute('admin.show_shop', array('slug' => $boutique->getSlug()));
$boutique = new Boutique;
$user = $this->getUser();
$form = $this->createForm(BoutiqueType::class, $boutique);
$ok_soumission =" Votre message a été pris en compte";
$boutique = new Boutique;
$form = $this->createForm(BoutiqueType::class, $boutique);
} else{
//If user need to pay, store data in session and redirect to payment page
$validiteService = new ValiditeService;
$today = new \DateTime();
$today->modify('+1 year');
$validiteService->setTypeValidite(ValiditeService::TYPE_PAYE);
$validiteService->setPayePar(ValiditeService::PAYE_PAR_PARTENAIRE);
$validiteService->setValableJusquAu($today);
$em->persist($validiteService);
$em->flush();
$boutique = $form->getData();
$this->session->set('boutique', $boutique);
$this->session->set('taxes', $taxes);
$this->session->set('taxe', $taxe);
$this->session->set('plan', $plan);
$this->session->set('coupon', $coupon);
$this->session->set('mt', $mt);
$this->session->set('montant', $totalAchat);
$this->session->set('remise', $remise);
$this->session->set('commande', $validiteService->getId());
return $this->redirectToRoute('affiliation_creer_compte_utilisateur');
}
} else {
$error =" Veillez corrigez vos erreurs";
}
}
return $this->render('affiliation/new_shop.html.twig', [
'form' => $form->createView(),
'totalAchat' => $totalAchat,
'prix' => $prix,
'taxes' => $taxes,
'codePromo' => $codePromo,
'plan' => $plan,
'remise' => $remise
]);
}
/**
* @Route("/creer-compte-utilisateur", name="affiliation_creer_compte_utilisateur")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function creerCompteUtilisateurAction(Request $request)
{
$em = $this->getDoctrine()
->getManager();
$user = $this->getUser();
$nom = '';
$email = '';
$error = '';
$motDePasse1 = '';
$motDePasse2 = '';
$creationCompte = 'ancienCompte';
if($request->getMethod() == 'POST'){
$creationCompte = $request->request->get('creation_compte');
$nom = $request->request->get('nom');
$email = $request->request->get('email');
$motDePasse1 = $request->request->get('motDePasse1');
$motDePasse2 = $request->request->get('motDePasse2');
$paymentMethod = $request->request->get('paymentMethod');
$this->session->set('creationCompte', $creationCompte);
$this->session->set('paymentMethod', $paymentMethod);
if($creationCompte == 'nouveauCompte'){
if($nom == ''){
$error = 'Veuillez indiquer le nom du client';
}
if($email == ''){
$error = 'Veuillez indiquer l\'adresse mail';
}
if($motDePasse1 == '' || $motDePasse1 != $motDePasse2){
$error = 'Les deux mot de passe ne correspondent pas';
}
if($error == ''){
$this->session->set('nom', $nom);
$this->session->set('email', $email);
$this->session->set('motDePasse1', $motDePasse1);
}
}
if($error == ''){
return $this->redirectToRoute('affiliation_payment');
}
}
return $this->render('affiliation/creer_compte_utilisateur.html.twig', [
'nom' => $nom,
'email' => $email,
'error' => $error,
'motDePasse1' => $motDePasse1,
'motDePasse2' => $motDePasse2,
'creationCompte' => $creationCompte
]);
}
/**
* @Route("/payment", name="affiliation_payment")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function paymentAction(Request $request)
{
if(!$this->isGranted('IS_AUTHENTICATED_FULLY')){
return $this->redirectToRoute('security_login');
}
$em = $this->getDoctrine()
->getManager();
$boutique = $this->session->get('boutique');
$plan = $this->session->get('plan');
$commande = $this->session->get('commande');
//$montant = $this->session->get('montant');
$montant = 100 ;
$montant = ceil($montant + $montant * 0.015);
$montant = $montant * 100;
$coupon = $this->session->get('coupon');
$coupon = $em->getRepository(CodePromo::class)
->findOneByNom($coupon);
$remise = $this->session->get('remise');
$mt = $this->session->get('mt');
$total = $plan->getTarif() * 12;
$laRemise = 0;
//Authentification
/*
$ch = curl_init($this->getJekoBaseUrl().'/stores');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-KEY:'. $this->getJekoAPI(),
'X-API-KEY-ID:'.$this->getJekoAPIID(),
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
$paymentRequest = json_decode($response, true);
*/
//Paiement
$commande = 'reference '.$commande;
$paymentMethod = $this->session->get('paymentMethod');
$successUrl = $this->generateUrl('affiliation_jeko_success', array('commande' => $commande), UrlGeneratorInterface::ABSOLUTE_URL);
$errorUrl = $this->generateUrl('affiliation_jeko_error', array('commande' => $commande), UrlGeneratorInterface::ABSOLUTE_URL);
$ch = curl_init($this->getJekoBaseUrl().'/payment_requests');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-API-KEY:'. $this->getJekoAPI(),
'X-API-KEY-ID:'.$this->getJekoAPIID(),
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'storeId' => $this->getJekoStoreId(),
'amountCents' => $montant,
'currency' => 'XOF',
'reference' =>$commande,
'paymentDetails' => [
'type' => 'redirect',
'data' => [
'paymentMethod' => $paymentMethod,
'successUrl' => $successUrl,
'errorUrl' => $errorUrl
]
]
]));
$response = curl_exec($ch);
curl_close($ch);
$paymentRequest = json_decode($response, true);
return $this->redirect($paymentRequest['redirectUrl']);
$redirectUrl = $this->generateUrl('save_payment');
return $this->render('affiliation/payment.html.twig', [
'montant' => $montant,
'redirectUrl' => $redirectUrl
]);
}
/**
* @Route("/jeko-success/{commande}", name="affiliation_jeko_success")
* @return \Symfony\Component\HttpFoundation\Response
*
* Faire très attention à cette fonction, car elle doit influencer aussi tous les achats venant
* de AppSumo et autre
*/
public function jekoSuccessAction(Request $request, $commande)
{
if(!$this->isGranted('IS_AUTHENTICATED_FULLY')){
return $this->redirectToRoute('security_login');
}
$em = $this->getDoctrine()
->getManager();
$user = $this->getUser();
$commande = explode(' ', $commande);
$commande = $commande[1];
$boutique = $this->session->get('boutique');
$plan = $this->session->get('plan');
$validiteService = $em->getRepository(ValiditeService::class)
->findOneById($commande);
$plan = $em->getRepository(Plan::class)
->findOneBySlug($plan);
if(null != $validiteService){
// Le paiement a bien marché
$em->persist($boutique);
$em->flush();
$service = new Service;
$service->setUser($user);
$service->setBoutique($boutique);
//$service->setPlan($plan);
$em->persist($service);
$em->flush();
$validiteService->setEtatTransaction(true);
$em->flush();
}
return $this->render('affiliation/jeko_success.html.twig', [
]);
}
/**
* @Route("/jeko-error/{commande}", name="affiliation_jeko_error")
* @return \Symfony\Component\HttpFoundation\Response
*
* Faire très attention à cette fonction, car elle doit influencer aussi tous les achats venant
* de AppSumo et autre
*/
public function jekoErrorAction(Request $request, $commande)
{
return $this->render('affiliation/jeko_error.html.twig', [
]);
}
public function getJekoBaseUrl()
{
return 'https://api.jeko.africa/partner_api' ;
}
public function getJekoAPI()
{
return 'jeko_6e150bc6f5a47803a33191db886520fceb70e14f7223469a12d7122703fbc4b7';
}
public function getJekoAPIID()
{
return '01e5b9bc-e49b-43d5-a7b5-fa31fbc1a3ce';
}
public function getJekoStoreId()
{
return '6a0d33da-43bc-4b54-af2c-e68b01c2caa0';
//return 'a9dd63b6-42ae-4d03-82f1-1e8d2112efd1';
}
function intervalleMois($datestr)
{
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"debut" => date ('Y-m-d', strtotime ('first day of this month', $dt)),
"fin" => date ('Y-m-d', strtotime ('last day of this month', $dt))
);
}
function intervalleSemaine($datestr) {
date_default_timezone_set (date_default_timezone_get());
$dt = strtotime ($datestr);
return array (
"debut" => date ('N', $dt) == 1 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('last monday', $dt)),
"fin" => date('N', $dt) == 7 ? date ('Y-m-d', $dt) : date ('Y-m-d', strtotime ('next sunday', $dt))
);
}
}