<?php
namespace App\Controller\Front;
use App\Entity\AppFee;
use App\Entity\Command;
use App\Entity\CommandPack;
use App\Entity\CommandProduct;
use App\Entity\Product;
use App\Entity\ProductOption;
use App\Entity\Transfert;
use App\Form\BrowserInfoType;
use App\Form\ConfirmAdresseUserType;
use App\Form\ValidPromoCodeType;
use App\Repository\AdminPromoRepository;
use App\Repository\CommandProductRepository;
use App\Repository\CommandRepository;
use App\Repository\CompanyRepository;
use App\Repository\PackRepository;
use App\Repository\ProductOptionRepository;
use App\Repository\ProductRepository;
use App\Repository\TransporteurWeightPriceRepository;
use App\Services\Filter;
use App\Services\Mail;
use App\Services\MangoPayService;
use App\Services\StripeClient;
use App\Services\StripeConnectService;
use DateTime;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Dompdf\Options;
use MangoPay\BrowserInfo;
use MangoPay\Libraries\ResponseException;
use MangoPay\PayInRecurringRegistration;
use MangoPay\TransactionStatus;
use Stripe\Charge;
use Stripe\Stripe;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class CommandController extends AbstractController
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var HttpClientInterface
*/
private $client;
public function __construct(EntityManagerInterface $em, HttpClientInterface $client)
{
$this->em = $em;
$this->client = $client;
}
/**
* @Route("/mon-panier", name="front_my_basket")
*/
public function basket(Request $request, SessionInterface $session, ProductRepository $productRepository, PackRepository $packRepository)
{
$products = $session->get('products');
$form = $this->createForm(ValidPromoCodeType::class)->handleRequest($request);
$allProducts = [];
if (!empty($products)) {
foreach ($products as $productId) {
if (!empty($productId['options_fairepar']) && $productId['options_fairepar'] != null) {
$product = $productRepository->find($productId['productId']);
$quantity = $productId['quantity'];
$optionsf = $productId['options_fairepar'];
$allProducts[] = [
'productId' => $product->getId(),
'product' => $product,
'quantity' => $quantity,
'options_farep' => $optionsf,
'promo' => null,
];
} else {
$product = $productRepository->find($productId['productId']);
$quantity = $productId['quantity'];
// $quantityOpt = $productId['qtyOption'];
$size = $productId['size'];
$color = $productId['color'];
// $optionsArray = [];
// if (!empty($productId['options'])) {
// foreach ($productId['options'] as $optionId => $price) {
// $optionsArray[] = $optionId;
// }
// }
// $optionsQtyArray = [];
// if (!empty($productId['qtyOption'])) {
// foreach ($productId['qtyOption'] as $optionIdQty => $qtyO) {
// $optionsQtyArray[] = $optionIdQty;
// }
// }
//dd($products,$productId['options'],$productId['qtyOption']);
$allProducts[] = [
'productId' => $product->getId(),
'product' => $product,
'quantity' => $quantity,
'size' => $size,
'color' => $color,
'options' => $productId['options'],
'promo' => null,
// 'qtyOption' => $quantityOpt
];
}
}
}
// dd($products,$allProducts);
if ($session->get('packs')) {
$pack = $packRepository->findOneBy(['id' => $session->get('packs')]);
} else {
$pack = null;
}
$isMessagePromo = false;
if ($form->isSubmitted() && $form->isValid()) {
$codePromo = $form->get('codePromo')->getData();
foreach ($allProducts as $key => $arrayProduct) {
/** @var Product $product */
// dd($key, $arrayProduct);
$product = $arrayProduct['product'];
if ($arrayProduct['options_farep'] != null) {
$productOpt = $arrayProduct['options'];
//dd($productOpt);
$newArrayProduct = $arrayProduct;
if ($codePromo === $product->getCodePromo()) {
//dd($newArrayProduct);
$newArrayProduct['promo'] = $product->getCodePromoEuro();
$newArrayProduct['options'] = $productOpt;
unset($allProducts[$key]);
$allProducts[] = $newArrayProduct;
$isMessagePromo = true;
}
} else {
$productOpt = $arrayProduct['options'];
//dd($productOpt);
$newArrayProduct = $arrayProduct;
if ($codePromo === $product->getCodePromo()) {
//dd($newArrayProduct);
$newArrayProduct['promo'] = $product->getCodePromoEuro();
$newArrayProduct['options'] = $productOpt;
unset($allProducts[$key]);
$allProducts[] = $newArrayProduct;
$isMessagePromo = true;
}
}
}
$session->set('products', $allProducts);
}
return $this->render('front/command/basket.html.twig', [
'products' => $allProducts,
'pack' => $pack,
'form' => $form->createView(),
'isMessagePromo' => $isMessagePromo
]);
}
/**
* @Route("/get-option/{id}", name="get_option")
*/
public function getOption(SessionInterface $session, ProductOptionRepository $productOptionRepository, Product $product, Filter $filtre, $id): Response
{
$modifOption = $filtre->getProductOptionByProduit($product);
$qtoption = $session->get('products');
$qte = [];
foreach ($qtoption as $qt) {
if ($qt['productId'] == $id) {
$qte["qty"] = $qt['qtyOption'];
}
}
$data[] = $modifOption;
$data[] = $qte;
$data[] = $id;
return $this->json($data, 200, [], ['groups' => 'post:read']);
}
/**
* @Route("/mon-panier/suppression-article/{id}", name="front_my_basket_remove_product")
*/
public function removeProductToBasket(Product $product, SessionInterface $session)
{
$allProducts = $session->get('products');
foreach ($session->get('products') as $key => $productSession) {
if (array_search($product->getId(), $productSession)) {
unset($allProducts[$key]);
$session->set('products', $allProducts);
}
}
return $this->redirectToRoute('front_my_basket');
}
/**
* @Route("/commande/livraison", name="front_command_livraison")
*/
public function livraison(SessionInterface $session, PackRepository $packRepository, ProductRepository $productRepository)
{
if (!$this->getUser()) {
$session->set('commandInCurse', true);
return $this->redirectToRoute('app_login');
}
$products = $session->get('products');
$packs = $session->get('packs');
if ($session->get('packs')) {
$pack = $packRepository->findOneBy(['id' => $session->get('packs')]);
} else {
$pack = null;
}
$allProducts = [];
if (!empty($products)) {
foreach ($products as $productId) {
$optionsArray = [];
if (!empty($productId['options'])) {
foreach ($productId['options'] as $optionId => $price) {
$optionsArray[] = $optionId;
}
}
$optionFeraparArray = [];
if (!empty($productId['options_fairepar'])) {
for ($i = 0; $i < sizeof($productId['options_fairepar']); $i++) {
$optionFeraparArray[] = $productId['options_fairepar']['option_' . $i];
}
}
$product = $productRepository->find($productId['productId']);
$isService = false;
foreach ($product->getSubCategories() as $subcategory) {
if ($subcategory->getIsService()) {
$isService = true;
}
}
$quantity = $productId['quantity'];
$size = $productId['size'];
$color = $productId['color'];
$promo = $productId['promo'] ?? null;
$allProducts[] = [
'id' => $product->getId(),
'product' => $product,
'quantity' => $quantity,
'size' => $size,
'color' => $color,
'isService' => $isService,
'pack' => null,
'options' => $productId['options'],
'options_fairepar' => $optionFeraparArray,
'promo' => $promo,
'transporteurs' => $product->getTransporteurs()
];
}
}
if (!empty($packs)) {
$pack = $packRepository->find($packs);
foreach ($pack->getProductPercents() as $productPercent) {
$allProducts[] = [
'product' => $productPercent->getProduct(),
'quantity' => null ?? 1,
'size' => null,
'color' => null,
'pack' => $pack->getName()
];
}
}
return $this->render('front/command/livraison.html.twig', [
'products' => $allProducts,
'pack' => $pack
]);
}
/**
* @Route("/commande/validation", name="front_command_validation")
*/
public function validateCommand(
SessionInterface $session,
Request $request,
ProductOptionRepository $productOptionRepository,
ProductRepository $productRepository,
PackRepository $packRepository,
TransporteurWeightPriceRepository $transporteurWeightPriceRepository,
AdminPromoRepository $adminPromoRepository
) {
$products = $session->get('products');
if ($request->get('livraison')) {
$session->set('livraison', $request->get('livraison'));
}
if ($request->get('address') && $request->get('address') != "") {
$session->set('address', $request->get('address'));
/** @var User $user */
$user = $this->getUser();
$address = explode(',', $request->get('address'));
$user->setLivraisonAdress($address[0]);
$user->setLivraisonZipCode($address[1]);
$user->setLivraisonCity($address[2]);
}
$isLivraison = false;
$isService = false;
$isFairepart = false;
if (!empty($products)) {
foreach ($products as $productId) {
$product = $productRepository->find($productId['productId']);
foreach ($product->getSubCategories() as $subCategory) {
if ($subCategory->getIsService()) {
$isService = true;
}
if ($subCategory->getIsSuivi()) {
$isLivraison = true;
}
if ($subCategory->getIsFairepart()) {
$isFairepart = true;
}
}
}
}
$form = $this->createForm(ConfirmAdresseUserType::class, $this->getUser(), ['isLivraison' => $isLivraison, 'isService' => $isService])->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$newCommand = new Command();
$newCommand->setClient($this->getUser());
$newCommand->setRelaypoint($session->get('address'));
$totalAmount = 0;
$totalFraisLivraison = 0;
if (!empty($products)) {
foreach ($products as $productId) {
$product = $productRepository->find($productId['productId']);
$quantity = $productId['quantity'];
$newCommandProduct = new CommandProduct();
$newCommandProduct->setProduct($product);
$newCommandProduct->setCommand($newCommand);
$newCommandProduct->setQuantity($quantity);
if ($productId['size']) {
$newCommandProduct->setSize($productId['size']);
}
if ($productId['color']) {
$newCommandProduct->setColor($productId['color']);
}
if (array_key_exists('promo', $productId)) {
$newCommandProduct->setPromo($productId['promo']);
}
$arrayLivraisons = $session->get('livraison');
if ($arrayLivraisons && array_key_exists($product->getId(), $arrayLivraisons)) {
$transporteur = $transporteurWeightPriceRepository->find($arrayLivraisons[$product->getId()]['transporteur']);
$weightInInt = str_replace('g', '', $transporteur->getWeight());
$weightInInt = (int) str_replace('kg', '', $weightInInt);
$totalWeightProducts = $weightInInt * $quantity;
$arrayLivraisonMode = [
'idTransporteur' => $transporteur->getTransporteur()->getId(),
'idTransporteurWeight' => $transporteur->getId(),
'totalWeight' => $totalWeightProducts,
];
$newCommandProduct->setLivraisonMode($arrayLivraisonMode);
$totalFraisLivraison = $totalFraisLivraison + $transporteur->getPrice();
$newCommandProduct->setLivraisonPrice($transporteur->getPrice());
}
$priceOptions = 0;
if ($isFairepart) {
if (!empty($productId['options_fairepar'])) {
$arrayOptions = [];
for ($j = 0; $j < sizeof($productId['options_fairepar']); $j++) {
$arrayOptions[] = $productId['options_fairepar']['option_' . $j];
$operation = $productId['options_fairepar']['option_' . $j]['quantite'] * $productId['options_fairepar']['option_' . $j]['price'];
$priceOptions = $priceOptions + $operation;
}
$newCommandProduct->setOptionfarepart($arrayOptions);
}
}
if (!empty($productId['options'])) {
$arrayOptions = [];
foreach ($productId['options'] as $key => $optiond) {
$optionProduct = $productOptionRepository->find($key);
$priceOptions = 0;
$group = [];
foreach ($optiond as $vale) {
$priceOptions = $priceOptions + $optionProduct->getPrice();
$operation = $vale["prix"] * ($vale["qte"] ? $vale["qte"] : 1);
$priceOptions = $priceOptions + $operation;
$group[$vale["valeur"]] = [
'price' => $vale["prix"],
'qty' => $vale["qte"] ? $vale["qte"] : 1
];
}
$arrayOptions[] = [
'id' => $optionProduct->getId(),
'name' => $optionProduct->getName(),
'group' => $group
];
}
$newCommandProduct->setOptions($arrayOptions);
}
$newCommand->addCommandProduct($newCommandProduct);
$totalAmount = $totalAmount + (($product->getPrice() - $newCommandProduct->getPromo()) * $quantity) + $priceOptions;
$this->em->persist($newCommandProduct);
}
}
if ($session->get('packs')) {
$pack = $packRepository->find($session->get('packs'));
$commandPack = new CommandPack();
$commandPack->setPack($pack);
$commandPack->setCommand($newCommand);
$newCommand->addCommandPack($commandPack);
$this->em->persist($commandPack);
$totalAmount = $totalAmount + $pack->getPrice();
}
$today = new DateTimeImmutable();
$appFees = 0;
$adminPromo = $adminPromoRepository->findOneByPeriod($today);
if ($adminPromo != null) {
$appFees = ($totalAmount * floatval($adminPromo->getValue())) / 100;
} else {
$appFees = ($totalAmount * 10) / 100;
}
$newCommand->setTotalAmount($totalAmount + $totalFraisLivraison + $appFees);
$newCommand->setTotalFraisLivraison($totalFraisLivraison);
$appFee = new AppFee();
$appFee->setValue($appFees);
$appFee->setCommand($newCommand);
$appFee->setPaid(false);
$this->em->persist($appFee);
$this->em->persist($newCommand);
$this->em->flush();
return $this->redirectToRoute('front_command_paiement_type');
}
return $this->render('front/command/validate_commande.html.twig', [
'form' => $form->createView(),
'isLivraison' => $isLivraison,
'isService' => $isService,
'isFairepart' => $isFairepart
]);
}
/**
* @Route("/commande/paiement/type", name="front_command_paiement_type")
*/
public function paymentType(Request $request, SessionInterface $session, CommandRepository $commandRepository, CommandProductRepository $commandProduct)
{
//$prodSession = $session->get('products');
if (!$this->getUser()) {
$session->set('commandInCurse', true);
return $this->redirectToRoute('app_login');
}
if ($request->isMethod('POST')) {
$data = json_decode($request->getContent(), true);
$session->set('paymentType', $data);
$urlGenerator = $this->generateUrl('front_command_stripe_payment');
return $this->json([
'status' => 'ok',
'data' => $urlGenerator
]);
}
/** @var Command|null $lastCommandUser */
$lastCommandUser = $commandRepository->getLastPackUser($this->getUser());
$commandProductUser = $commandProduct->getCommandProductsByCommandUser($lastCommandUser);
return $this->render('front/command/paymentType.html.twig', [
'commandProduit' => $commandProductUser,
'command' => $lastCommandUser,
'commandSize' => $lastCommandUser->getCommandPacks()->count() + $lastCommandUser->getCommandProducts()->count()
]);
}
/**
* @Route("/commande/paiement", name="front_command_paiement")
*/
public function payment(Request $request, SessionInterface $session, CommandRepository $commandRepository, MangoPayService $mangoPayService, CommandProductRepository $commandProduct)
{
if (!$this->getUser()) {
$session->set('commandInCurse', true);
return $this->redirectToRoute('app_login');
}
/** @var Command|null $lastCommandUser */
$lastCommandUser = $commandRepository->getLastPackUser($this->getUser());
$cardRegistration = $mangoPayService->createCardRegistration($this->getUser());
//dd($cardRegistration);
$session->set('cardRegistrationId', $cardRegistration->Id);
$session->set('commandId', $lastCommandUser->getId());
if ($request->isMethod('POST')) {
foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
$quantityCommanded = $commandProduct->getQuantity();
$productQuantity = $commandProduct->getProduct()->getQuantity();
$commandProduct->getProduct()->setQuantity($productQuantity - $quantityCommanded);
}
$this->em->flush();
$session->set('confirmPayment', $this->getUser()->getId());
return $this->redirectToRoute('front_payment_process');
}
//Payment process link
$paymentProcessUrl = $_ENV['COMMAND_PAYMENT_URL'];
$mongopayContro = $_ENV['MONGOPAY_CONTROLER'];
$clientId = $_ENV['CLIENT_ID'];
$commandProductUser = $commandProduct->getCommandProductsByCommandUser($lastCommandUser);
return $this->render('front/command/payment.html.twig', [
'commandProduit' => $commandProductUser,
'command' => $lastCommandUser,
'cardRegistration' => $cardRegistration,
'paymentProcessUrl' => $paymentProcessUrl,
'mongopayContrUrl' => $mongopayContro,
'clientId' => $clientId
]);
}
/**
* @Route("/payment/process", name="front_payment_process", methods={"POST"})
*/
public function paymentProcess(SessionInterface $session, MangoPayService $mangoPayService, CommandRepository $commandRepository)
{
$request = Request::createFromGlobals();
$browserInfo = new BrowserInfo();
$form = $this->createForm(BrowserInfoType::class, $browserInfo)->submit(json_decode($request->getContent(), true));
if (!$form->isValid()) {
$this->json([
"status" => "failed",
"msg" => "invalid data"
]);
}
$browserInfo->AcceptHeader = $request->headers->get('Accept');
$session->set("browserInfo", $browserInfo);
$session->set("ipAddress", $request->getClientIp());
$lastCommandUser = $commandRepository->getLastPackUser($this->getUser());
$updatedCard = $mangoPayService->getCardRegistration($session->get('cardRegistrationId'));
$paymentType = $session->get("paymentType");
$payIn = $paymentType["type"] == "RECURRING_PAYMENT"
? $mangoPayService->createRecurringPay($updatedCard, $lastCommandUser)
: $mangoPayService->createPayIn($updatedCard, $lastCommandUser);
return $this->json([
"status" => "success",
"data" => $payIn->Status == "FAILED"
? $this->generateUrl('front_payment_redirect_process')
: (($payIn->Status == TransactionStatus::Created && $payIn->ExecutionDetails->SecureModeNeeded)
? $payIn->ExecutionDetails->SecureModeRedirectURL
: $payIn->ExecutionDetails->SecureModeReturnURL
)
]);
}
/**
* @Route("/redirect-payment/process", name="front_payment_redirect_process")
*/
public function redirectPaymentProcess(SessionInterface $session, Mail $mail, CommandRepository $commandRepository, MangoPayService $mangoPayService)
{
if (!$session->get('commandId') || !$session->get('payInId')) {
$this->addFlash('danger', 'Echec du paiement, veuillez retenter ultérieurement.');
return $this->redirectToRoute('front_command_paiement');
}
$payIn = $mangoPayService->getPayIn($session->get('payInId'));
if ($payIn && $payIn->Status !== 'SUCCEEDED') {
$session->remove("walletClientId");
$this->addFlash('danger', 'Echec du paiement, Le paiement n’a pas été validé.');
return $this->redirectToRoute('front_command_paiement');
}
$command = $commandRepository->find($session->get('commandId'));
if ($command->getPaymentType() == "RECURRING_PAYMENT") {
$payIn = $mangoPayService->getPayInRecurringRegistration($command->getCommandNumber());
} else {
$tranferedFundBuyerToSeller = $mangoPayService->transfertFundWalledBuyerToSeller($command, $payIn);
if ($tranferedFundBuyerToSeller instanceof ResponseException) {
$message = $tranferedFundBuyerToSeller->GetErrorDetails()->Message;
$this->addFlash('danger', 'Echec du paiement: ' . $message);
return $this->redirectToRoute('front_command_paiement');
}
}
$command->setLastPayAt(new \DateTime());
$command->setStatus($payIn->Status);
$this->em->flush();
$session->set('confirmPayment', $this->getUser()->getId());
$mail->ConfirmationPaiementClient($this->getUser(), $command, $this->createInvoicePdf($command));
$arrayCompanies = [];
foreach ($command->getCommandProducts() as $commandProduct) {
array_push($arrayCompanies, $commandProduct->getProduct()->getCompany());
}
$mail->confirmationCommandCompany($arrayCompanies);
//mise à jour de la quantité totale de produits
$lastCommandUser = $commandRepository->getLastPackUser($this->getUser());
foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
$quantityCommanded = $commandProduct->getQuantity();
$productQuantity = $commandProduct->getProduct()->getQuantity();
$commandProduct->getProduct()->setQuantity($productQuantity - $quantityCommanded);
$this->em->persist($commandProduct->getProduct());
}
$this->em->flush();
return $this->redirectToRoute('front_command_paiement_confirm');
}
/**
* @Route("/commande/paiement/confirmation", name="front_command_paiement_confirm")
*/
public function confirmPaymentProduct(SessionInterface $session)
{
if (!$session->get('confirmPayment') || $session->get('confirmPayment') !== $this->getUser()->getId()) {
return $this->redirectToRoute('front_my_basket');
}
$session->remove('confirmPayment');
$session->remove('products');
$session->remove('packs');
$session->remove('cardRegistrationId');
$session->remove('payInId');
$session->remove('paymentType');
$session->remove('weddingdate');
$session->remove('address');
return $this->render('front/command/confirm_command.html.twig');
}
/**
* @Route("/commande/stripe/paiement", name="front_command_stripe_payment")
*/
public function stripePayment(StripeConnectService $stripeConnectService, SessionInterface $session, CommandRepository $commandRepository): Response
{
if (!$this->getUser()) {
$session->set('commandInCurse', true);
return $this->redirectToRoute('app_login');
}
/** @var Command|null $lastCommandUser */
$lastCommandUser = $commandRepository->getLastPackUser($this->getUser());
$line_items = [];
$transfer_group = 'ORDER' . $lastCommandUser->getId();
$success_url = $this->generateUrl('front_command_stripe_success', [], 0);
$cancel_url = $this->generateUrl('front_command_stripe_cancel', [], 0);
$session->set('commandId', $lastCommandUser->getId());
$session->set('transfer_group', $transfer_group);
$commandProductTotalPrice = 0;
foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
// A mettre après le checkout
$quantityCommanded = $commandProduct->getQuantity();
$productQuantity = $commandProduct->getProduct()->getQuantity();
$commandProduct->getProduct()->setQuantity($productQuantity - $quantityCommanded);
$this->em->persist($commandProduct->getProduct());
$this->em->flush();
$commandProductTotalPrice += $commandProduct->getProduct()->getPrice() * $quantityCommanded;
array_push($line_items, [
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => $commandProduct->getProduct()->getName(),
],
'unit_amount' => $commandProduct->getProduct()->getPrice() * 100, // amount in cents
],
'quantity' => $quantityCommanded,
]);
}
$appFeeTotalPrice = 0;
foreach ($lastCommandUser->getAppFees() as $appFee) {
array_push($line_items, [
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => 'Commission Hobiin commande n° ' . $lastCommandUser->getId(),
],
'unit_amount' => $appFee->getValue() * 100 // amount in cents
],
'quantity' => 1,
]);
$appFeeTotalPrice += $appFee->getValue();
}
if ($lastCommandUser->getTotalFraisLivraison() > 0) {
array_push($line_items, [
'price_data' => [
'currency' => 'eur',
'product_data' => [
'name' => 'Frais de livraison commande n° ' . $lastCommandUser->getId(),
],
'unit_amount' => $lastCommandUser->getTotalFraisLivraison() * 100 // amount in cents
],
'quantity' => 1,
]);
}
$session = $stripeConnectService->createCheckoutSessionForProductCommands($lastCommandUser, $line_items, $transfer_group, $success_url, $cancel_url);
return $this->redirect($session->url);
}
/**
* @Route("/command/stripe/success", name="front_command_stripe_success")
*/
public function stripeSuccess(Request $request, SessionInterface $session, CommandRepository $commandRepository, Mail $mail, StripeConnectService $stripeConnectService): Response
{
$command = $commandRepository->find(intval($session->get('commandId')));
$checkoutSessionId = $request->get('session_id'); // Recuperates checkout session ID
$checkoutSession = $stripeConnectService->retrieveCheckoutSession($checkoutSessionId); // Recuperates checkout
if (!$checkoutSession) {
return new Response('error : Checkout session not found', 404);
}
$paymentIntentId = $checkoutSession->payment_intent; // Recuperates payment intent ID
$paymentIntent = $stripeConnectService->retrievePaymentIntent($paymentIntentId); // Recuperates payment intent
if (!$paymentIntent) {
return new Response('error : Payment intent not found', 404);
}
$paymentIntentChargeId = $paymentIntent->latest_charge; // Recuperates latest charge ID
if (!$paymentIntentChargeId) {
return new Response('error : Payment intent charge not found', 404);
}
$latestCharge = $stripeConnectService->retrieveLatestCharge($paymentIntentChargeId); // Recuperates latest charge
foreach ($command->getCommandProducts() as $commandProduct) {
$transfer = null;
$quantityCommanded = $commandProduct->getQuantity();
$singleproductPrice = $commandProduct->getProduct()->getPrice() * 100; // Amount in cents
try {
$transfer = $stripeConnectService->createTransfer(
$singleproductPrice * $quantityCommanded, // Amount in cents
$commandProduct->getProduct()->getCompany()->getStripeAccountId(), // Connected account ID
$latestCharge->id, // Charge ID
'eur', // Currency
'Paiement de la commande ' . $command->getId() // Description
);
} catch (\Throwable $th) {
$this->addFlash('danger', 'Echec du paiement: ' . $th->getMessage());
}
if ($transfer != null) {
$hobiin_transfer = (new Transfert)
->setStripeTransferId($transfer->id)
->setCommand($commandProduct->getCommand());
$commandProduct->setPayinId($checkoutSession->latest_charge);
$command->setChargeId($checkoutSession->id);
$command->setCommandNumber($checkoutSession->id);
$command->setStatus('succeeded');
$this->em->persist($hobiin_transfer);
$this->em->persist($commandProduct);
}
}
foreach ($command->getAppFees() as $appFee) {
if ($checkoutSession->status === 'complete') {
$appFee->setPaid(true);
} else {
$appFee->setPaid(false);
}
$this->em->persist($appFee);
}
$this->em->flush();
$session->remove('products');
$session->remove('transfer_group');
$session->remove('packs');
$session->remove('commandId');
$session->remove('session_id');
$this->addFlash('success', 'Paiement réussi!');
return $this->redirectToRoute('front_client_space_command_list');
}
/**
* @Route("/command/stripe/cancel", name="front_command_stripe_cancel")
*/
public function stripeCancel(SessionInterface $session, CommandRepository $commandRepository): Response
{
$session->remove('products');
$session->remove('transfer_group');
$session->remove('packs');
$session->remove('commandId');
$session->remove('session_id');
$this->addFlash('warning', 'Paiement annulé!');
return $this->redirectToRoute('front_client_space_command_list');
}
public function createInvoicePdf(Command $command)
{
// Configure Dompdf according to your needs
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->isRemoteEnabled(true);
$pdfOptions->isHtml5ParserEnabled(true);
// Instantiate Dompdf with our options
$dompdf = new Dompdf($pdfOptions);
// Retrieve the HTML generated in our twig file
$html = $this->renderView('front/email/confirmation_paiement_test.html.twig', compact('command'));
// Load HTML to Dompdf
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Store PDF Binary Data
$output = $dompdf->output();
// In this case, we want to write the file in the public directory
$publicDirectory = $this->getParameter('kernel.project_dir') . '/public';
// e.g /var/www/project/public/mypdf.pdf
$pdfFilepath = $publicDirectory . '/mypdf.pdf';
// Write file to the desired path
file_put_contents($pdfFilepath, $output);
return $pdfFilepath;
}
/**
* @Route("/panierpdf", name="pdf_generate")
*/
public function createBasketPdf(SessionInterface $session, ProductRepository $productRepository, PackRepository $packRepository, Filter $filter)
{
$product = $session->get('products', []);
// dd($product);
$prduit = [];
foreach ($product as $key => $prod) {
// for ($i=0; $i < sizeof($product); $i++) {
if (isset($prod['options_fairepar'])) {
$options = [];
foreach ($prod['options_fairepar'] as $key => $value) {
$options[] = [
"id" => $value["idoption"],
"nom" => $value["nomoption"],
"qte" => $value["quantite"],
"price" => $value["price"]
];
}
$prduit[] = [
"productId" => $prod["productId"],
"quantity" => $prod["quantity"],
"options" => $options ? $options : null
];
} else {
// $options=[];
if (isset($prod['options'])) {
$options = [];
foreach ($prod['options'] as $key => $value) {
$produitoption = $filter->getProductOption($key);
$produitoption->setQuantite([$value]);
$options[] = [
"id" => $produitoption->getId(),
"nom" => $produitoption->getName(),
"qte" => $produitoption->getQuantite()[0],
"price" => $produitoption->getPrice()
];
}
$prduit[] = [
"productId" => $prod["productId"],
"quantity" => $prod["quantity"],
"options" => $options ? $options : null
];
} else {
$options = null;
$prduit[] = [
"productId" => $prod["productId"],
"quantity" => $prod["quantity"],
"options" => $options
];
}
}
}
// dd($prduit);
if ($session->get('packs')) {
$pack = $packRepository->findOneBy(['id' => $session->get('packs')]);
} else {
$pack = null;
}
// dd($prduit);
// $session->set('products', $allProducts);
// Configure Dompdf according to your needs
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
// Instantiate Dompdf with our options
$dompdf = new Dompdf($pdfOptions);
// Retrieve the HTML generated in our twig file
$html = $this->renderView('front/command/basketPdf.html.twig', [
'products' => $prduit,
'pack' => $pack,
// 'form' => $form->createView(),
//'isMessagePromo' => $isMessagePromo
]);
// Load HTML to Dompdf
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser (force download)
$dompdf->stream("panierpdf.pdf", [
"Attachment" => true
]);
return new Response();
}
}