<?php
namespace App\AtechNet\CoreBundle\Controller;
use App\AtechNet\CoreBundle\Entity\Attribute;
use App\AtechNet\CoreBundle\Entity\AttributeOption;
use App\AtechNet\CoreBundle\Entity\Basket;
use App\AtechNet\CoreBundle\Entity\BasketItem;
use App\AtechNet\CoreBundle\Entity\BasketItemAttributeOption;
use App\AtechNet\CoreBundle\Entity\BillingoPayment;
use App\AtechNet\CoreBundle\Entity\Coupon;
use App\AtechNet\CoreBundle\Entity\Customer;
use App\AtechNet\CoreBundle\Entity\CustomerAddress;
use App\AtechNet\CoreBundle\Entity\CustomerEmail;
use App\AtechNet\CoreBundle\Entity\DocumentPayment;
use App\AtechNet\CoreBundle\Entity\Domain;
use App\AtechNet\CoreBundle\Entity\DomainPaymentType;
use App\AtechNet\CoreBundle\Entity\DomainShippingType;
use App\AtechNet\CoreBundle\Entity\Order;
use App\AtechNet\CoreBundle\Entity\Statistics\OrderChangelog;
use App\AtechNet\CoreBundle\Entity\OrderComment;
use App\AtechNet\CoreBundle\Entity\OrderItem;
use App\AtechNet\CoreBundle\Entity\OrderItemAttributeOption;
use App\AtechNet\CoreBundle\Entity\OrderSetting;
use App\AtechNet\CoreBundle\Entity\PickupPoint;
use App\AtechNet\CoreBundle\Entity\Product;
use App\AtechNet\CoreBundle\Entity\ProductType;
use App\AtechNet\CoreBundle\Entity\StockItem;
use App\AtechNet\CoreBundle\Entity\StockMovement;
use App\AtechNet\CoreBundle\Entity\StockMovementItem;
use App\AtechNet\CoreBundle\Entity\Survey;
use App\AtechNet\CoreBundle\Entity\SurveyQuestion;
use App\AtechNet\CoreBundle\Entity\SurveyQuestionOption;
use App\AtechNet\CoreBundle\Entity\User;
use App\AtechNet\CoreBundle\Enum\PaymentType;
use App\AtechNet\CoreBundle\Form\CheckoutType;
use App\AtechNet\CoreBundle\Helper\DeliveryUtil;
use App\AtechNet\CoreBundle\Helper\Furbify\CartHelper;
use App\AtechNet\CoreBundle\Helper\Furbify\Heureka;
use App\AtechNet\CoreBundle\Helper\Furbify\Image;
use App\AtechNet\CoreBundle\Helper\Furbify\MultiStore;
use App\AtechNet\CoreBundle\Helper\Furbify\OrderHelper;
use App\AtechNet\CoreBundle\Helper\Furbify\PayPal;
use App\AtechNet\CoreBundle\Helper\Furbify\Registration;
use App\AtechNet\CoreBundle\Helper\Instacash;
use App\AtechNet\CoreBundle\Helper\Klarna;
use App\AtechNet\CoreBundle\Helper\KlaviyoConnect;
use App\AtechNet\CoreBundle\Helper\Milpay;
use App\AtechNet\CoreBundle\Helper\OrderStatistics;
use App\AtechNet\CoreBundle\Helper\Packeta;
use App\AtechNet\CoreBundle\Helper\Security as SecurityHelper;
use App\AtechNet\CoreBundle\Repository\StockMovementRepository;
use Doctrine\ORM\Exception\NotSupported;
use Doctrine\ORM\Exception\ORMException;
use Doctrine\ORM\OptimisticLockException;
use Exception;
use Firebase\JWT\JWT;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Mime\Email;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class CheckoutController extends AbstractController
{
public const TIMEOUT = 2; // hours
public const SHIPPING_TYPES_WITH_IMMEDIATE_SHIPPING = [
DomainShippingType::SHIPPING_TYPE_CARRIER_EXPRESS_ID,
DomainShippingType::ShippingType_PICKUP_POINT_Id,
];
private $unWantedAttributes = [
237, 239, 247, 241, 387, 388, 405, 409, 415, 419, 529, 854, 940,
];
private $extenalCheckPaymentTypes = [
PaymentType::DebitCard->value,
PaymentType::Quatro->value,
PaymentType::Cetelem->value,
PaymentType::DebitCard3Percent->value,
PaymentType::Instacash->value,
PaymentType::PastPay->value,
PaymentType::Klarna->value,
PaymentType::PayPal->value,
PaymentType::Milpay->value,
];
/**
* Pick-up Point Select
*/
private $enablePickupPointSelector = [
DomainShippingType::ShippingType_PICKUP_POINT_Id,
];
/**
* Hide Payment Methods by Selected Shipping Method if necessary
*/
private $paymentMethodRestriction = [
DomainShippingType::ShippingType_PICKUP_POINT_Id => [PaymentType::CashOnDelivery->value],
];
private function isYear2025(): bool
{
$currentDate = (int) (new \DateTime('NOW'))->format('Y');
return $currentDate == 2025;
}
/**
* @Route("/checkout/customer", name="checkout_customer", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/customer", name="checkout_customer_locale", defaults={"_locale":""})
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Exception
*/
public function customerAction(Request $request)
{
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
// Multi-Store
$multiStore = $this->getMultiStoreHelper($request);
// Checkout DATA
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
if ($customer || $request->getSession()->get('abandonedCart') != null) {
$abandonedCartData = $request->getSession()->get('abandonedCart');
$checkout['updated'] = new \DateTime();
$checkout['email'] = $abandonedCartData ? $abandonedCartData->email : $customer->getEmail();
$data['name'] = $abandonedCartData ? '' : $customer->getFullName();
$request->getSession()->set('checkout', $checkout);
return $this->redirectToRoute('checkout_address');
}
$data = [];
$data['hideChat'] = true;
/**
* @var Basket $cart
*/
$cart = $this->getCart($request->getSession()->get('cartId'));
if (!$cart) {
return $this->redirectToRoute('cart_show');
}
$entityManager = $this->getEntityManager();
// Basket expires
$cartUpdated = clone $cart->getUpdated();
// if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
// $entityManager->remove($cart);
// $entityManager->flush();
// return $this->redirectToRoute('cart_show');
// }
$orderSummary = $this->orderSummary($cart, $request);
// Validate cart has products and has stock.
if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
return $this->redirectToRoute('cart_show');
}
// Logged in Customer
if ($customer) {
$data['loggedIn'] = true;
$data['name'] = $customer->getFullName();
if (empty($checkout['email'])) {
$checkout['email'] = $customer->getEmail();
}
} else {
$data['loggedIn'] = false;
}
$checkout['step'] = 2;
$form = $this->createForm(CheckoutType::class, $checkout, [
'locale' => $request->getLocale(),
'defaultLocale' => $multiStore->getDefaultLocale(),
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$cart->setUpdated((new \DateTime('NOW')));
$entityManager->flush();
}
if ($form->isSubmitted() && $form->isValid()) {
$checkout['updated'] = new \DateTime();
$checkout['email'] = $form->get('email')->getData();
$request->getSession()->set('checkout', $checkout);
$customer = $entityManager->getRepository(Customer::class)->findOneBy([
'email' => $checkout['email'],
'domain' => $this->getMultiStoreHelper($request)->getDomain(),
]);
if ($customer) {
$cart->setCustomer($customer);
}
$cart->setAbandonedEmail($checkout['email']);
$entityManager->flush();
return $this->redirectToRoute('checkout_address');
}
$data['form'] = $form->createView();
// Order Summary
$data['orderSummary'] = $orderSummary;
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['stepsOptions'] = $this->checkoutSteps(2);
return $this->render('AtechNetCoreBundle/Checkout/customer.html.twig', $data);
}
/**
* @Route("/checkout/shipping-and-payment", name="checkout_shipping_and_payment", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/shipping-and-payment", name="checkout_shipping_and_payment_locale", defaults={"_locale":""})
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Exception
*/
public function shippingPaymentAction(Request $request)
{
$multiStore = $this->getMultiStoreHelper($request);
$domain = $multiStore->getDomain();
$domainId = $domain->getId();
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$data = [];
$data['hideChat'] = true;
$data['shippingCountry'] = $domain->getLanguage()->getCode();
$data['packetaApiKey'] = $this->getParameter('packeta')['api_key'];
// Checkout DATA
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
// Get Cart Items
$cart = $this->getCart($request->getSession()->get('cartId'));
if ($cart) {
$entityManager = $this->getEntityManager();
$translator = $this->getTranslator();
$data['isBasketIncludesGamerProduct'] = $this->getEntityManager()->getRepository(Product::class)->isBasketIncludesGamerProduct($cart);
// Basket expires
$cartUpdated = clone $cart->getUpdated();
// if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
// $entityManager->remove($cart);
// $entityManager->flush();
// return $this->redirectToRoute('cart_show');
// }
$orderSummary = $this->orderSummary($cart, $request);
// Validate cart has products and has stock.
if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
return $this->redirectToRoute('cart_show');
}
// Coupon Free Shipping
$isCouponApplicableForFreeShipping = false;
if (isset($checkout['coupon']['code']) && $checkout['coupon']['code'] != '') {
$coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
'code' => $checkout['coupon']['code'],
'domain' => $domain,
]);
if ($coupon) {
// Set Email
if (!empty($checkout['email'])) {
$cart->setEmail($checkout['email']);
} else {
$cart->setEmail(null);
}
$isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
}
}
// Shipping Methods
$data['shippingMethods'] = [];
$shippingMethods = $entityManager->getRepository(DomainShippingType::class)->findBy([
'domain' => $domainId,
'activeOnWeb' => true,
], [
'sortIndex' => 'ASC',
]);
$getPickupPoints = false;
$hasMainProductTypes = CartHelper::hasMainProductType($cart);
/**
* @var DomainShippingType $shippingMethod
*/
foreach ($shippingMethods as $shippingMethod) {
$methodIsDisabled = false;
if ($shippingMethod->getType() == DomainShippingType::ShippingType_Carrier_Id && $domainId == Domain::DOMAIN_ID_WS_HU) {
$translationKey = 'shipping.method.type.' . $shippingMethod->getType() . '.achu';
} else {
$translationKey = 'shipping.method.type.' . $shippingMethod->getType();
}
if (($title = $translator->trans($translationKey)) == $translationKey) {
$title = false;
}
if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
$description = false;
}
if (($icon = $translator->trans($translationKey . '.icon')) == $translationKey . '.icon') {
$icon = false;
}
// Validate Pickup Point availability
if (in_array(
$shippingMethod->getType(),
[
DomainShippingType::ShippingType_PICKUP_POINT_Id,
DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID,
]
)) {
if (!$cart->isPickupPointAvailable()) {
$methodIsDisabled = true;
}
}
if ($shippingMethod->getType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
&& $orderSummary['subTotal'] >= Packeta::getCodLimitByDomainMarketCode(strtoupper($domain->getLanguage()->getCode()))) {
$methodIsDisabled = true;
}
// Shipping Cost
$shippingPrice = in_array($shippingMethod->getType(), $orderSummary['enableFreeShipping']) ? 0 : $shippingMethod->getPrice();
// Free Shipping
if ((float)$shippingMethod->getFreeShipLimit() > 0 && (float)$shippingMethod->getFreeShipLimit() < $orderSummary['subTotal']) {
$shippingPrice = 0;
}
// Coupon Free Shipping
if ($isCouponApplicableForFreeShipping) {
$shippingPrice = 0;
}
// Round Shipping Cost
if (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
$shippingPrice = number_format($shippingPrice, 0, '.', '');
}
if ($title) {
$shiftBy = ((int)explode('-', $shippingMethod->getShippingDays())[0]) - 1;
$data['shippingMethods'][$shippingMethod->getId()] = [
'id' => $shippingMethod->getId(),
'type' => $shippingMethod->getType(),
'title' => $title,
'description' => $description,
'price' => $shippingPrice,
'icon' => $icon,
'collapse' => in_array($shippingMethod->getType(), $this->enablePickupPointSelector) ? 1 : 0,
'estimatedDeliveryDate' => (new DeliveryUtil())->getEstimatedDeliveryDate($shippingMethod->getDomain()->getId(), $data['isBasketIncludesGamerProduct'], false, $shiftBy),
'restriction' => isset($this->paymentMethodRestriction[$shippingMethod->getType()]) ? $this->paymentMethodRestriction[$shippingMethod->getType()] : [],
'disabled' => $methodIsDisabled,
];
}
if (in_array($shippingMethod->getType(), $this->enablePickupPointSelector)) {
$getPickupPoints = true;
}
}
if (isset($checkout['packetaPickupPointId']) && (is_numeric($checkout['packetaPickupPointId']) || ($checkout['packetaPickupPointCarrierId'] == Packeta::FOXPOST_CARRIER_ID)) ) {
$data['packetaPickupPointId'] = $checkout['packetaPickupPointId'];
}
if (isset($checkout['packetaPickupPointTitle']) && $checkout['packetaPickupPointTitle'] != '') {
$data['packetaPickupPointTitle'] = (string)$checkout['packetaPickupPointTitle'];
}
if (isset($checkout['packetaPickupPointCarrierId']) && is_numeric($checkout['packetaPickupPointCarrierId'])) {
$data['packetaPickupPointCarrierId'] = (int)$checkout['packetaPickupPointCarrierId'];
}
if (!isset($checkout['shippingMethodId'])) {
$checkout['shippingMethodId'] = $cart->getShippingMethod();
}
// Pick-up Points
$data['pickupPoints'] = [];
if ($getPickupPoints) {
$pickupPoints = $entityManager->getRepository(PickupPoint::class)->findBy([
'active' => true,
'country' => $multiStore->getDefaultCountry(),
], [
'city' => 'ASC',
]);
foreach ($pickupPoints as $pickupPoint) {
$data['pickupPoints'][$pickupPoint->getId()] = [
'id' => $pickupPoint->getId(),
'title' => $pickupPoint->getTitle(),
'address' => $pickupPoint->getCity() . ', ' . $pickupPoint->getStreet(),
'street' => $pickupPoint->getStreet(),
'city' => $pickupPoint->getCity(),
'zip' => $pickupPoint->getZip(),
'sortOrder' => $pickupPoint->getCity(),
];
}
}
// Payment Methods
$instacash = null;
if (in_array($domain->getLanguage()->getCode(), ['sk', 'hu'])) {
$instacash = $this->getInstacash($domain->getLanguage()->getCode());
}
$milpay = null;
if (in_array($domain->getId(), [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ])) {
$milpay = $this->getMilpay($domain->getLanguage()->getCode());
}
$isCompany = $checkout['isCompany'] && (!is_null($checkout['billingTaxId']) || !is_null($checkout['billingVatNumber']));
$paymentData = $this->getOrderHelper($request)->getPaymentMethodData($domainId, $customer, $cart, $instacash, $milpay, $isCompany, $entityManager->getRepository(Order::class));
$data['paymentMethods'] = $paymentData['paymentList'];
$data['showCetelemCalculator'] = $paymentData['showCetelemCalculator'];
$data['cetelemDescLink'] = $paymentData['cetelemDescLink'];
$data['cetelemDesc'] = $paymentData['cetelemDesc'];
$data['pastPay'] = [
'available' => $paymentData['pastPayAvailable'] && $checkout['isCompany'] && $checkout['billingTaxId'] != null,
'debtorTaxNumber' => $checkout['billingTaxId'],
];
if (!isset($checkout['paymentMethodId'])) {
$checkout['paymentMethodId'] = $cart->getPaymentMethod();
}
$priceLimits = DomainPaymentType::CASH_ON_DELIVERY_LIMITS;
//REMOVE SELECTED CASH ON DELIVERY WHEN IT IS DISABLED
if ($priceLimits[$orderSummary['currency']]
&& $orderSummary['total'] > $priceLimits[$orderSummary['currency']]
&& isset($checkout['paymentMethodTypeId'])
&& $checkout['paymentMethodTypeId'] == PaymentType::CashOnDelivery->value) {
$checkout['paymentMethodId'] = null;
}
//
if ( isset($checkout['shippingMethodTypeId']) && $checkout['shippingMethodTypeId'] == DomainShippingType::ShippingType_Personally_Id) {
$checkout['shippingMethodId'] = null;
$checkout['paymentMethodId'] = null;
}
// Abandoned cart
if (!$request->getSession()->has('abandonedCart')) {
$customer = $entityManager->getRepository(Customer::class)->findOneBy([
'email' => $checkout['email'],
'domain' => $this->getMultiStoreHelper($request)->getDomain(),
]);
if ($customer) {
$cart->setCustomer($customer);
}
$cart->setUpdated((new \DateTime('NOW')));
$cart->setAbandonedEmail($checkout['email']);
$entityManager->flush();
}
$checkout['step'] = 4;
$form = $this->createForm(CheckoutType::class, $checkout, [
'locale' => $request->getLocale(),
'defaultLocale' => $multiStore->getDefaultLocale(),
'action' => $this->generateUrl('checkout_shipping_and_payment'),
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$cart->setUpdated((new \DateTime('NOW')));
$entityManager->flush();
}
if ($form->isSubmitted() && $form->isValid()) {
$checkout['updated'] = new \DateTime();
$checkout['shippingMethodId'] = (int)$form->get('shippingMethodId')->getData();
$checkout['paymentMethodId'] = (int)$form->get('paymentMethodId')->getData();
if ($request->request->get('packeta-pickup-point-id') != "") {
$checkout['packetaPickupPointId'] = $request->request->get('packeta-pickup-point-id');
}
$checkout['packetaPickupPointTitle'] = (string)$request->request->get('packeta-pickup-point-title');
$checkout['packetaPickupPointCarrierId'] = (string)$request->request->get('packeta-pickup-point-carrier-id');
$checkout['shippingMethodPickupPointId'] = (int)$form->get('shippingMethodPickupPointId')->getData();
$checkout['shippingMethodTypeId'] = (int)$form->get('shippingMethodTypeId')->getData();
$checkout['paymentMethodTypeId'] = (int)$form->get('paymentMethodTypeId')->getData();
$checkout['estimatedDeliveryDate'] = $form->get('estimatedDeliveryDate')->getData();
$checkout['3_percent_discount'] = in_array($checkout['paymentMethodTypeId'], [6, 7, 8, 15]); // 3 Percent payments
$request->getSession()->set('checkout', $checkout);
return $this->redirectToRoute('checkout_review');
} elseif ($form->isSubmitted()) {
$checkout['shippingMethodId'] = (int)$form->get('shippingMethodId')->getData();
$checkout['paymentMethodId'] = (int)$form->get('paymentMethodId')->getData();
$checkout['shippingMethodPickupPointId'] = (int)$form->get('shippingMethodPickupPointId')->getData();
$checkout['shippingMethodTypeId'] = (int)$form->get('shippingMethodTypeId')->getData();
$checkout['paymentMethodTypeId'] = (int)$form->get('paymentMethodTypeId')->getData();
$checkout['estimatedDeliveryDate'] = $form->get('estimatedDeliveryDate')->getData();
$data['error'] = true;
}
$data['form'] = $form->createView();
// Order Summary
$data['orderSummary'] = $orderSummary;
// Defaults
if (isset($checkout['shippingMethodId'])) {
$data['shippingMethodId'] = (int)$checkout['shippingMethodId'];
} else {
$data['shippingMethodId'] = 0;
}
if (isset($checkout['paymentMethodId'])) {
$data['paymentMethodId'] = (int)$checkout['paymentMethodId'];
} else {
$data['paymentMethodId'] = 0;
}
if (isset($checkout['paymentMethodTypeId'])) {
$data['paymentMethodTypeId'] = (int)$checkout['paymentMethodTypeId'];
} else {
$data['paymentMethodTypeId'] = 0;
}
if (isset($checkout['shippingMethodPickupPointId'])) {
$data['shippingMethodPickupPointId'] = (int)$checkout['shippingMethodPickupPointId'];
} else {
$data['shippingMethodPickupPointId'] = 0;
}
if (isset($data['shippingMethods'][$data['shippingMethodId']])) {
$data['shippingMethod'] = $data['shippingMethods'][$data['shippingMethodId']];
} else {
$data['shippingMethod'] = [];
}
if (isset($data['paymentMethods'][$data['paymentMethodId']])) {
$data['paymentMethod'] = $data['paymentMethods'][$data['paymentMethodId']];
} else {
$data['paymentMethod'] = [];
}
if (isset($data['pickupPoints'][$data['shippingMethodPickupPointId']])) {
$data['pickupPoint'] = $data['pickupPoints'][$data['shippingMethodPickupPointId']];
} else {
$data['pickupPoint'] = [];
}
//klarna
$shippingCountry = $checkout['shippingCountry'] ?? $domain->getLanguage()->getCode();
$klarna = $this->getKlarna($domainId, $request, $shippingCountry, $checkout['coupon'] ?? []);
if (!is_null($klarna)) {
$klarnaSession = $klarna->createKlarnaSession($orderSummary, $checkout, $cart->getBasketItems());
if ($klarna->isValidKlarnaSession($klarnaSession, $shippingCountry)) {
$data['klarna_client_token'] = $klarnaSession['client_token'];
$request->getSession()->set(
'klarnaClientToken',
$klarnaSession['client_token']
);
$request->getSession()->set(
'klarnaSessionId',
$klarnaSession['session_id']
);
}
}
$data['quatro_calculator'] = $this->getParameter('quatro_calculator_url');
$domain = $multiStore->getDomain();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['stepsOptions'] = $this->checkoutSteps(4);
$data['domain'] = $domain;
$data['cashOnDeliveryLimits'] = DomainShippingType::getCashOnDeliveryPriceLimits($domain->getId());
$data['basketItemListIncludesMobileProduct'] = $this->getEntityManager()->getRepository(Order::class)->isBasketItemListIncludesMobileProduct($cart);
$data['paymentType'] = PaymentType::toArray();
$data['currentCustomer'] = $this->getLoginHelper($request)->getLoggedInCustomer();
return $this->render('AtechNetCoreBundle/Checkout/shippingPayment.html.twig', $data);
}
return $this->redirectToRoute('cart_show');
}
/**
* @Route("/checkout/address", name="checkout_address", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/address", name="checkout_address_locale", defaults={"_locale":""})
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Exception
*/
public function addressAction(Request $request)
{
$data = [];
$data['hideChat'] = true;
// Multi-Store
$multiStore = $this->getMultiStoreHelper($request);
// Checkout DATA
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
$customerTypeId = $request->getSession()->get('customerTypeId');
$checkout['customerTypeId'] = $customerTypeId;
// Get Cart Items
$cart = $this->getCart($request->getSession()->get('cartId'));
if ($cart) {
$data['abandonedCartLink'] = $this->getKlaviyoConnect($request)->createPublicUrlForAbandonedCart($cart);
$entityManager = $this->getEntityManager();
$translator = $this->getTranslator();
// Basket expires
$cartUpdated = clone $cart->getUpdated();
// if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
// $entityManager->remove($cart);
// $entityManager->flush();
// return $this->redirectToRoute('cart_show');
// }
$orderSummary = $this->orderSummary($cart, $request);
// Validate cart has products and has stock.
if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
return $this->redirectToRoute('cart_show');
}
$checkout['step'] = 3;
if (!isset($checkout['isCompany'])) {
$checkout['isCompany'] = false;
}
if (!isset($checkout['billingAddressIsShippingAddress'])) {
$checkout['billingAddressIsShippingAddress'] = true;
}
if ($customerTypeId == MultiStore::CUSTOMER_TYPE_WHOLESALE) {
$checkout['isCompany'] = true;
$checkout['billingAddressIsShippingAddress'] = false;
}
if (!isset($checkout['register'])) {
$checkout['register'] = false;
}
$data['domainLanguageCode'] = $multiStore->getDefaultLanguage()->getCode();
$data['loggedIn'] = false;
$loggedInCustomer = $this->getLoginHelper($request)->getLoggedInCustomer();
if ($loggedInCustomer) {
$checkout['billingFirstName'] = $loggedInCustomer->getFirstName();
$checkout['billingLastName'] = $loggedInCustomer->getLastName();
$checkout['billingBusinessName'] = $loggedInCustomer->getBusinessName();
$checkout['billingCity'] = '';
$checkout['billingPostalCode'] = '';
$checkout['billingAddress'] = '';
$checkout['isCompany'] = $loggedInCustomer->isCompany();
$billingAddress = null;
$shippingAddresses = [];
foreach ($loggedInCustomer->getAddresses() as $address) {
if ($address->getType() == CustomerAddress::AddressType_Billing_Id) {
$billingAddress = $address;
} else {
$shippingAddresses[] = $address;
}
}
if ($billingAddress) {
$checkout['billingFirstName'] = $billingAddress->getFirstName();
$checkout['billingLastName'] = $billingAddress->getLastName();
$checkout['billingBusinessName'] = $billingAddress->getBusinessName() ?? $loggedInCustomer->getBusinessName();
$checkout['billingCity'] = $billingAddress->getCity();
$checkout['billingPostalCode'] = $billingAddress->getZip();
$checkout['billingAddress'] = $billingAddress->getStreet();
}
if (empty($shippingAddresses)) {
$checkout['shippingFirstName'] = $checkout['billingFirstName'];
$checkout['shippingLastName'] = $checkout['billingLastName'];
$checkout['shippingBusinessName'] = $checkout['billingBusinessName'];
$checkout['shippingCity'] = $checkout['billingCity'];
$checkout['shippingPostalCode'] = $checkout['billingPostalCode'];
$checkout['shippingAddress'] = $checkout['billingAddress'];
} else {
$shippingAddress = end($shippingAddresses);
$checkout['shippingFirstName'] = $shippingAddress->getFirstName();
$checkout['shippingLastName'] = $shippingAddress->getLastName();
$checkout['shippingBusinessName'] = $shippingAddress->getBusinessName();
$checkout['shippingCity'] = $shippingAddress->getCity();
$checkout['shippingPostalCode'] = $shippingAddress->getZip();
$checkout['shippingAddress'] = $shippingAddress->getStreet();
}
// Phone Number
$phoneNumber = $loggedInCustomer->getPhone();
// Remove non-numeric characters
$_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
// Add plus sign if was removed
if (substr($phoneNumber, 0, 1) == '+') {
$_phoneNumber = '+' . $_phoneNumber;
}
// Remove calling codes to prevent duplication
if ($data['domainLanguageCode'] == 'cz') {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($data['domainLanguageCode'] == 'hu') {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
$checkout['billingBusinessId'] = $loggedInCustomer->getBusinessId();
$checkout['billingTaxId'] = $loggedInCustomer->getTaxId();
$checkout['billingVatNumber'] = $loggedInCustomer->getVatId();
if (($checkout['billingFirstName'] . $checkout['billingLastName'] . $checkout['billingCity'] . $checkout['billingPostalCode'] . $checkout['billingAddress']) !== ($checkout['shippingFirstName'] . $checkout['shippingLastName'] . $checkout['shippingCity'] . $checkout['shippingPostalCode'] . $checkout['shippingAddress'])) {
$checkout['billingAddressIsShippingAddress'] = false;
}
$data['loggedIn'] = true;
} elseif (!empty($checkout['shippingPhoneNumber'])) {
// Phone Number
$phoneNumber = $checkout['shippingPhoneNumber'];
// Remove non-numeric characters
$_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
// Add plus sign if was removed
if (substr($phoneNumber, 0, 1) == '+') {
$_phoneNumber = '+' . $_phoneNumber;
}
// Remove calling codes to prevent duplication
if ($data['domainLanguageCode'] == 'cz') {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($data['domainLanguageCode'] == 'hu') {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$checkout['shippingPhoneNumber'] = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
}
$form = $this->createForm(CheckoutType::class, $checkout, [
'locale' => $request->getLocale(),
'defaultLocale' => $multiStore->getDefaultLocale(),
'action' => $this->generateUrl('checkout_address'),
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$checkout['updated'] = new \DateTime();
$checkout['register'] = $form->get('register')->getData();
$checkout['shippingFirstName'] = $form->get('shippingFirstName')->getData();
$checkout['shippingLastName'] = $form->get('shippingLastName')->getData();
$checkout['shippingBusinessName'] = $form->get('shippingBusinessName')->getData();
if ($multiStore->getDomain()->getId() == Domain::DOMAIN_ID_RT_EU) {
$checkout['shippingCountry'] = $form->get('shippingCountry')->getData();
}
$checkout['shippingCity'] = $form->get('shippingCity')->getData();
$checkout['shippingPostalCode'] = preg_replace('/\D/', ' ', $form->get('shippingPostalCode')->getData());
$checkout['shippingAddress'] = $form->get('shippingAddress')->getData();
// Phone Number
$phoneNumber = $form->get('shippingPhoneNumber')->getData();
// Remove non-numeric characters
$_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
// Add plus sign if was removed
if (substr($phoneNumber, 0, 1) == '+') {
$_phoneNumber = '+' . $_phoneNumber;
}
// Remove calling codes to prevent duplication
if ($data['domainLanguageCode'] == 'cz') {
$checkout['shippingPhoneNumber'] = '+420' . preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($data['domainLanguageCode'] == 'hu') {
$checkout['shippingPhoneNumber'] = '+36' . preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} elseif ($data['domainLanguageCode'] == 'sk') {
$checkout['shippingPhoneNumber'] = '+421' . preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
} else {
$checkout['shippingPhoneNumber'] = $_phoneNumber;
}
$checkout['isCompany'] = $form->get('isCompany')->getData();
$checkout['billingBusinessName'] = $form->get('billingBusinessName')->getData();
$checkout['billingBusinessId'] = $form->get('billingBusinessId')->getData();
$checkout['billingTaxId'] = $form->get('billingTaxId')->getData();
$checkout['billingVatNumber'] = $form->get('billingVatNumber')->getData();
if ((is_null($checkout['billingVatNumber']) || $checkout['billingVatNumber'] == '') && $multiStore->getDefaultLocale() == 'cz') {
$checkout['billingVatNumber'] = $checkout['billingTaxId'];
}
$checkout['billingAddressIsShippingAddress'] = $form->get('billingAddressIsShippingAddress')->getData();
$checkout['billingFirstName'] = $form->get('billingFirstName')->getData();
$checkout['billingLastName'] = $form->get('billingLastName')->getData();
if ($multiStore->getDomain()->getId() == Domain::DOMAIN_ID_RT_EU) {
$checkout['billingCountry'] = $checkout['billingAddressIsShippingAddress'] ? $form->get('shippingCountry')->getData() : $form->get('billingCountry')->getData();
}
$checkout['billingCity'] = $form->get('billingCity')->getData();
$checkout['billingPostalCode'] = preg_replace('/\D/', ' ', $form->get('billingPostalCode')->getData());
$checkout['billingAddress'] = $form->get('billingAddress')->getData();
if ($loggedInCustomer && !in_array($loggedInCustomer->getId(), $this->getGuestAccountIds())) {
$billingAddress = false;
$shippingAddress = false;
foreach ($loggedInCustomer->getAddresses() as $address) {
if ($address->getType() == CustomerAddress::AddressType_Billing_Id) {
$billingAddress = $address;
} else {
$shippingAddress = $address;
}
}
if (isset($checkout['billingBusinessName']) && $checkout['billingBusinessName'] != '') {
$loggedInCustomer->setBusinessName($checkout['billingBusinessName']);
}
if (isset($checkout['billingBusinessId']) && $checkout['billingBusinessId'] != '') {
$loggedInCustomer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
}
if (isset($checkout['billingTaxId']) && $checkout['billingTaxId'] != '') {
$loggedInCustomer->setTaxId($checkout['billingTaxId']);
}
if (isset($checkout['billingVatNumber']) && $checkout['billingVatNumber'] != '') {
$loggedInCustomer->setVatId($checkout['billingVatNumber']);
}
$persistShippingAddress = false;
if (!$shippingAddress) {
$shippingAddress = new CustomerAddress();
$shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
$shippingAddress->setCustomer($loggedInCustomer);
$shippingAddress->setTitle('.');
$persistShippingAddress = true;
}
switch ($loggedInCustomer->getDomain()->getId()) {
case Domain::DOMAIN_ID_RT_SK:
case Domain::DOMAIN_ID_WS_SK:
$country = 'SK';
break;
case Domain::DOMAIN_ID_RT_HU:
case Domain::DOMAIN_ID_WS_HU:
$country = 'HU';
break;
case Domain::DOMAIN_ID_RT_CZ:
case Domain::DOMAIN_ID_WS_CZ:
$country = 'CZ';
break;
default:
$country = 'EN';
}
if ($country == 'EN' && !is_null($loggedInCustomer->getCountry())) {
$country = $loggedInCustomer->getCountry();
$checkout['billingCountry'] = $country;
$checkout['shippingCountry'] = $country;
}
$street = !is_null($checkout['shippingAddress']) ? $checkout['shippingAddress'] : '';
$shippingAddress->setFirstName($checkout['shippingFirstName']);
$shippingAddress->setLastName($checkout['shippingLastName']);
$shippingAddress->setBusinessName($checkout['shippingBusinessName']);
$shippingAddress->setStreet($street);
$shippingAddress->setCity($checkout['shippingCity']);
$shippingAddress->setZip($checkout['shippingPostalCode']);
$shippingAddress->setPhone($checkout['shippingPhoneNumber']);
$shippingAddress->setEmail($loggedInCustomer->getEmail());
$shippingAddress->setCountry($country);
$loggedInCustomer->setPhone($checkout['shippingPhoneNumber']);
if ($persistShippingAddress) {
$entityManager->persist($shippingAddress);
}
if (!$checkout['billingAddressIsShippingAddress']) {
$persistBillingAddress = false;
if (!$billingAddress) {
$billingAddress = new CustomerAddress();
$billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
$billingAddress->setCustomer($loggedInCustomer);
$billingAddress->setTitle('.');
$persistBillingAddress = true;
}
$street = !is_null($checkout['billingAddress']) ? $checkout['billingAddress'] : '';
$billingAddress->setFirstName($checkout['billingFirstName']);
$billingAddress->setLastName($checkout['billingLastName']);
$billingAddress->setBusinessName($checkout['billingBusinessName']);
$billingAddress->setStreet($street);
$billingAddress->setCity($checkout['billingCity']);
$billingAddress->setZip($checkout['billingPostalCode']);
$billingAddress->setPhone($checkout['shippingPhoneNumber']);
$billingAddress->setEmail($loggedInCustomer->getEmail());
$billingAddress->setCountry($country);
if ($persistBillingAddress) {
$entityManager->persist($billingAddress);
}
} else {
$persistBillingAddress = false;
if (!$billingAddress) {
$billingAddress = new CustomerAddress();
$billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
$billingAddress->setCustomer($loggedInCustomer);
$billingAddress->setTitle('.');
$persistBillingAddress = true;
}
$street = !is_null($checkout['shippingAddress']) ? $checkout['shippingAddress'] : '';
$billingAddress->setFirstName($checkout['shippingFirstName']);
$billingAddress->setLastName($checkout['shippingLastName']);
$billingAddress->setBusinessName($checkout['shippingBusinessName']);
$billingAddress->setStreet($street);
$billingAddress->setCity($checkout['shippingCity']);
$billingAddress->setZip($checkout['shippingPostalCode']);
$billingAddress->setPhone($checkout['shippingPhoneNumber']);
$billingAddress->setEmail($loggedInCustomer->getEmail());
$billingAddress->setCountry($country);
if ($persistBillingAddress) {
$entityManager->persist($billingAddress);
}
}
}
$cart->setUpdated((new \DateTime('NOW')));
$entityManager->flush();
$request->getSession()->set('checkout', $checkout);
if ($form->get('register')->getData() === true) {
$domain = $entityManager->getRepository(Domain::class)->findOneById(MultiStore::defineDomainId($request->getSession()->get('customerTypeId'), $request->getHttpHost()));
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$domainsToCheck = '1,2';
break;
case Domain::DOMAIN_ID_RT_HU:
$domainsToCheck = '3,4';
break;
case Domain::DOMAIN_ID_RT_CZ:
$domainsToCheck = '9,5';
break;
case Domain::DOMAIN_ID_RT_EU:
$domainsToCheck = '7,11';
break;
default:
$domainsToCheck = '';
}
$duplicateCustomerCheck = $entityManager
->createQuery("SELECT c FROM AtechNetCoreBundle:Customer c WHERE c.email = :email AND c.domain IN (" . $domainsToCheck . ")")
->setParameter('email', $checkout['email'])
->getResult();
if (count($duplicateCustomerCheck) > 0) {
$this->addFlash(
'errorRegister',
$translator->trans('E-Mail Address is already registered')
);
return $this->redirectToRoute('checkout_address');
}
}
}
if ($form->isSubmitted()) {
if (!empty($form->get('password')->getData()) && SecurityHelper::insecure($form->get('password')->getData())) {
$form->get('password')->addError(new FormError($translator->trans('Unfortunately, the password provided is not secure, therefore it cannot be used in our webshop')));
}
}
if ($form->isSubmitted() && $form->isValid()) {
$checkout['password'] = $form->get('password')->getData();
if ($checkout['isCompany'] && isset($checkout['coupon']) && $checkout['coupon']['code'] == 'DIV+furbify') {
unset($checkout['coupon']);
$cart->setCouponCode(null);
$entityManager->flush();
$this->addFlash(type: 'shippingError', message: 'A "DIV+furbify" kuponkód el lett távolítva a kosaradból.');
}
$request->getSession()->set('checkout', $checkout);
return $this->redirectToRoute('checkout_shipping_and_payment');
}
$data['form'] = $form->createView();
// Checkout DATA
$data['checkout'] = [
'register' => $checkout['register'],
];
// Order Summary
$data['orderSummary'] = $orderSummary;
$data['isCompany'] = (bool)$checkout['isCompany'];
$data['billingAddressIsShippingAddress'] = (bool)$checkout['billingAddressIsShippingAddress'];
$data['legal_links'] = $this->getLegalLinks($request, $cart->getDomain()->getId());
if ($data['domainLanguageCode'] == 'cz') {
$data['callingCountryCode'] = '+420';
} elseif ($data['domainLanguageCode'] == 'hu') {
$data['callingCountryCode'] = '+36';
} else {
$data['callingCountryCode'] = '+421';
}
$domain = $this->getMultiStoreHelper($request)->getDomain();
if ($domain->getId() != Domain::DOMAIN_ID_WS_EU) {
$data['countryValue'] = $translator->trans(strtoupper($data['domainLanguageCode']));
if ($loggedInCustomer) {
$country = $loggedInCustomer->getCountry() ?? $domain->getLanguage()->getCode();
$data['countryName'] = Countries::getNames()[strtoupper($country)];
}
} else {
$data['countryValue'] = $cart->getCustomer()->getCountry();
}
$data['insecurePasswords'] = SecurityHelper::getMostCommonPasswords();
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['stepsOptions'] = $this->checkoutSteps(3);
$data['domainType'] = $cart->getDomain()->getType();
$data['diversumCodeIsActive'] = isset($checkout['coupon']) && $checkout['coupon']['code'] == 'DIV+furbify';
return $this->render('AtechNetCoreBundle/Checkout/address.html.twig', $data);
}
return $this->redirectToRoute('cart_show');
}
/**
* @Route("/checkout/review", name="checkout_review", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/review", name="checkout_review_locale", defaults={"_locale":""})
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function reviewAction(Request $request, UserPasswordHasherInterface $passwordHasher)
{
$data = [];
$statisticsEntityManager = $this->getEntityManager('statistics');
$data['hideChat'] = true;
// Checkout DATA
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
/**
* @var Basket $cart
*/
$cart = $this->getCart($request->getSession()->get('cartId'));
if ($cart) {
$entityManager = $this->getEntityManager();
$translator = $this->getTranslator();
// Multi-Store
$multiStore = $this->getMultiStoreHelper($request);
// Basket expires
$cartUpdated = clone $cart->getUpdated();
// if ($cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H")) <= (new \DateTime('NOW'))) {
// $entityManager->remove($cart);
// $entityManager->flush();
// return $this->redirectToRoute('cart_show');
// }
$orderSummary = $this->orderSummary($cart, $request);
// Validate Pickup Point availability
if (!$orderSummary['validShipping']) {
return $this->redirectToRoute('checkout_shipping_and_payment');
}
// Logged in Customer
if ($this->getLoginHelper($request)->getLoggedInCustomerId()) {
$data['loggedIn'] = true;
} else {
$data['loggedIn'] = false;
}
// Validate cart has products and has stock
if (!$orderSummary['valid'] && $orderSummary['countItems'] > 0) {
return $this->redirectToRoute('cart_show');
}
// Validate payment method
$selectedInvalidBnpPayment = $entityManager->getRepository(Order::class)->haveNotFinishedBnpOrdersFromThisCustomer($cart, PaymentType::from($checkout['paymentMethodTypeId']));
if (empty($checkout['paymentMethodTypeId']) || $selectedInvalidBnpPayment) {
return $this->redirectToRoute('checkout_shipping_and_payment');
}
// Validate shipping method
if (empty($checkout['shippingMethodTypeId'])) {
return $this->redirectToRoute('checkout_shipping_and_payment');
}
// Validate Pickup Point availability
if (!$orderSummary['validShipping']) {
return $this->redirectToRoute('checkout_shipping_and_payment');
}
// Payment method
if ($cart->getDomain()->getId() == Domain::DOMAIN_ID_WS_HU && $checkout['paymentMethodTypeId'] == PaymentType::BankTransfer->value) {
$translationKey = 'payment.method.type.' . $checkout['paymentMethodTypeId'] . '.wshu';
} else {
$translationKey = 'payment.method.type.' . $checkout['paymentMethodTypeId'];
}
if (($title = $translator->trans($translationKey)) == $translationKey) {
$title = false;
}
if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
$description = false;
}
$data['paymentMethod'] = [
'title' => $title,
'description' => $description,
'cetelem_calculator' => false,
];
$domain = $cart->getDomain();
// Cetelem
if ($checkout['paymentMethodTypeId'] == PaymentType::Cetelem->value) {
$data['paymentMethod']['cetelem_calculator'] = true;
$data['paymentMethod']['cetelem_calculator_country'] = $domain->getLanguage()->getCode();
}
// Shipping method
$translationKey = 'shipping.method.type.' . $checkout['shippingMethodTypeId'];
if (($title = $translator->trans($translationKey)) == $translationKey) {
$title = false;
}
if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
$description = false;
}
$data['shippingMethod'] = [
'title' => $title,
'description' => $description,
];
if ((int)$checkout['shippingMethodPickupPointId'] > 0) {
$pickupPoint = $entityManager->getRepository(PickupPoint::class)->findOneById($checkout['shippingMethodPickupPointId']);
if ($pickupPoint) {
$data['pickupPoint'] = [
'title' => $pickupPoint->getTitle(),
'address' => $pickupPoint->getCity() . ', ' . $pickupPoint->getStreet(),
'street' => $pickupPoint->getStreet(),
'city' => $pickupPoint->getCity(),
'zip' => $pickupPoint->getZip(),
];
}
}
$checkout['step'] = 5;
$form = $this->createForm(CheckoutType::class, $checkout, [
'locale' => $request->getLocale(),
'defaultLocale' => $multiStore->getDefaultLocale(),
'action' => $this->generateUrl('checkout_review'),
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$checkout['messageToSeller'] = $form->get('messageToSeller')->getData();
$checkout['newsletter'] = $form->get('newsletter')->getData();
$cart->setUpdated((new \DateTime('NOW')));
$entityManager->flush();
$request->getSession()->set('checkout', $checkout);
}
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getEntityManager();
$multiStore = $this->getMultiStoreHelper($request);
$domain = $multiStore->getDomain();
// New Order
$order = new Order();
$order->setStatus(Order::STATUS_TRIAGE);
$order->setDomain($domain);
$order->setPriority(true);
$country = $multiStore->getDefaultCountry();
if (isset($checkout['billingCountry']) && $checkout['billingCountry'] != '') {
$country = $checkout['billingCountry'];
}
if ($this->getLoginHelper($request)->getLoggedInCustomerId()) { //Logged in Customer
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$order->setCustomer($customer);
} elseif (isset($checkout['register']) && $checkout['register']) { // New Customer
$customer = new Customer();
$customer->setEmail($checkout['email']);
$customer->setPhone($checkout['shippingPhoneNumber']);
$customer->setPassword($checkout['password']);
$customer->setGuest(false);
if (!empty($checkout['billingFirstName'])) {
$customer->setFirstName($checkout['billingFirstName']);
} else {
$customer->setFirstName($checkout['shippingFirstName']);
}
if (!empty($checkout['billingLastName'])) {
$customer->setLastName($checkout['billingLastName']);
} else {
$customer->setLastName($checkout['shippingLastName']);
}
if (!empty($checkout['billingBusinessName'])) {
$customer->setBusinessName($checkout['billingBusinessName']);
}
if (!empty($checkout['billingBusinessId'])) {
$customer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
}
if (!empty($checkout['billingTaxId'])) {
$customer->setTaxId($checkout['billingTaxId']);
}
if (!empty($checkout['billingVatNumber'])) {
$customer->setVatId($checkout['billingVatNumber']);
}
$registration = new Registration($this->getEntityManager(), $request, $passwordHasher);
$registration->save($customer, $domain);
$entityManager->flush();
// Billing Address
$billingAddress = new CustomerAddress();
$billingAddress->setCustomer($customer);
$billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
$billingAddress->setTitle($translator->trans('Billing address'));
if ($checkout['billingAddressIsShippingAddress']) {
$billingAddress->setFirstName($checkout['shippingFirstName']);
$billingAddress->setLastName($checkout['shippingLastName']);
$billingAddress->setStreet($checkout['shippingAddress']);
$billingAddress->setZip($checkout['shippingPostalCode']);
$billingAddress->setCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$billingAddress->setCountry($checkout['shippingCountry']);
} else {
$billingAddress->setCountry($country);
}
} else {
$billingAddress->setFirstName($checkout['billingFirstName']);
$billingAddress->setLastName($checkout['billingLastName']);
$billingAddress->setStreet($checkout['billingAddress']);
$billingAddress->setZip($checkout['billingPostalCode']);
$billingAddress->setCity($checkout['billingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$billingAddress->setCountry($checkout['billingCountry']);
} else {
$billingAddress->setCountry($country);
}
}
// District
$billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
$entityManager->persist($billingAddress);
$entityManager->flush();
// Shipping Address
if (!$checkout['billingAddressIsShippingAddress']) {
$shippingAddress = new CustomerAddress();
$shippingAddress->setCustomer($customer);
$shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
$shippingAddress->setTitle($translator->trans('Shipping address'));
$shippingAddress->setFirstName($checkout['shippingFirstName']);
$shippingAddress->setLastName($checkout['shippingLastName']);
$shippingAddress->setStreet($checkout['shippingAddress']);
$shippingAddress->setZip($checkout['shippingPostalCode']);
$shippingAddress->setCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$shippingAddress->setCountry($checkout['shippingCountry']);
} else {
$shippingAddress->setCountry($country);
}
$entityManager->persist($shippingAddress);
$entityManager->flush();
}
$entityManager->refresh($customer);
$order->setCustomer($customer);
} else { // Guest Customer
// Try to set customer from existing accounts
$guestCustomer = $entityManager->getRepository(Customer::class)->findOneBy([
'domain' => $domain,
'email' => $checkout['email'],
]);
/**
* @var Customer $guestCustomer
*/
if (!$guestCustomer) {
$guestCustomer = new Customer();
$guestCustomer->setDomain($domain);
$guestCustomer->setActive(true);
$guestCustomer->setEmail($checkout['email']);
$guestCustomer->setPhone($checkout['shippingPhoneNumber']);
$guestCustomer->setType(Customer::TYPE_NORMAL);
if ($checkout['billingAddressIsShippingAddress']) {
$guestCustomer->setFirstName($checkout['shippingFirstName']);
$guestCustomer->setLastName($checkout['shippingLastName']);
} else {
$guestCustomer->setFirstName($checkout['billingFirstName']);
$guestCustomer->setLastName($checkout['billingLastName']);
}
$guestCustomer->setBusinessName($checkout['billingBusinessName']);
$guestCustomer->setBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
$guestCustomer->setTaxId($checkout['billingTaxId']);
$guestCustomer->setVatId($checkout['billingVatNumber']);
$guestCustomer->setGuest(true);
$salesManager = $domain->getDefaultSalesManager();
if (!is_null($guestCustomer->getBusinessName()) && trim($guestCustomer->getBusinessName()) != ''
&& !is_null($guestCustomer->getTaxId()) && trim($guestCustomer->getTaxId()) != '') {
$userRepository = $entityManager->getRepository(User::class);
switch ($guestCustomer->getDomain()->getId()) {
case Domain::DOMAIN_ID_RT_SK:
case Domain::DOMAIN_ID_RT_CZ:
$salesManager = $userRepository->findOneById(User::USER_ID_BEATA_SEDLAROVA);
break;
case Domain::DOMAIN_ID_RT_HU:
$salesManager = $userRepository->findOneById(68);
break;
default:
$salesManager = $userRepository->findOneById(68);
}
}
$guestCustomer->setSalesManager($salesManager);
if ($checkout['newsletter']) {
$guestCustomer->setWantsNewsletter(true);
} else {
$guestCustomer->setWantsNewsletter(false);
}
$guestCustomer->setSource(Customer::SOURCE_SIGN_UP);
$entityManager->persist($guestCustomer);
$entityManager->flush();
$entityManager->refresh($guestCustomer);
// Billing Address
$billingAddress = new CustomerAddress();
$billingAddress->setCustomer($guestCustomer);
$billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
$billingAddress->setTitle($translator->trans('Billing address'));
if ($checkout['billingAddressIsShippingAddress']) {
$billingAddress->setFirstName($checkout['shippingFirstName']);
$billingAddress->setLastName($checkout['shippingLastName']);
$billingAddress->setStreet($checkout['shippingAddress']);
$billingAddress->setZip($checkout['shippingPostalCode']);
$billingAddress->setCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$billingAddress->setCountry($checkout['shippingCountry']);
} else {
$billingAddress->setCountry($country);
}
} else {
$billingAddress->setFirstName($checkout['billingFirstName']);
$billingAddress->setLastName($checkout['billingLastName']);
$billingAddress->setStreet($checkout['billingAddress']);
$billingAddress->setZip($checkout['billingPostalCode']);
$billingAddress->setCity($checkout['billingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$billingAddress->setCountry($checkout['billingCountry']);
} else {
$billingAddress->setCountry($country);
}
}
// District
$billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
$entityManager->persist($billingAddress);
$entityManager->flush();
// Shipping Address
if (!$checkout['billingAddressIsShippingAddress']) {
$shippingAddress = new CustomerAddress();
$shippingAddress->setCustomer($guestCustomer);
$shippingAddress->setType(CustomerAddress::AddressType_Shipping_Id);
$shippingAddress->setTitle($translator->trans('Shipping address'));
$shippingAddress->setFirstName($checkout['shippingFirstName']);
$shippingAddress->setLastName($checkout['shippingLastName']);
$shippingAddress->setStreet($checkout['shippingAddress']);
$shippingAddress->setZip($checkout['shippingPostalCode']);
$shippingAddress->setCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$shippingAddress->setCountry($checkout['shippingCountry']);
} else {
$shippingAddress->setCountry($country);
}
$entityManager->persist($shippingAddress);
$entityManager->flush();
}
$entityManager->refresh($guestCustomer);
}
$order->setCustomer($guestCustomer);
// Newsletter Subscription
if ($checkout['newsletter']) {
$emailExists = $entityManager->getRepository(CustomerEmail::class)->findOneBy([
'customer' => $guestCustomer,
'email' => $checkout['email'],
]);
if (empty($emailExists)) {
$customerEmail = new CustomerEmail();
$customerEmail->setCustomer($guestCustomer);
$customerEmail->setEmail($checkout['email']);
$entityManager->persist($customerEmail);
$entityManager->flush();
}
$connect = $this->getKlaviyoConnect($request);
$klaviyoProfileData = $connect->getProfileWithFilter(['email' => $checkout['email']]);
$klaviyoProfileData = $klaviyoProfileData[array_key_first($klaviyoProfileData)] ?? [];
if (!empty($klaviyoProfileData))
{
$connect->updateProfile($guestCustomer, $klaviyoProfileData);
}
}
$customer = $guestCustomer;
}
$order->setPaymentType($checkout['paymentMethodTypeId']);
$order->setPaymentStatus(Order::PaymentStatus_Pending);
$order->setPaymentPrice(0);
if ($checkout['paymentMethodTypeId'] == PaymentType::Cetelem->value && !is_null($request->request->get('cetelem'))) {
$checkout['cetelem'] = $request->request->get('cetelem');
} elseif ($checkout['paymentMethodTypeId'] == PaymentType::Klarna->value && $request->getSession()->has('klarnaSessionId')) {
$klarnaSessionIdOrderSetting = new OrderSetting();
$klarnaSessionIdOrderSetting->setType(OrderSetting::TYPE_KLARNA_PAYMENT_SESSION_ID);
$klarnaSessionIdOrderSetting->setOrder($order);
$klarnaSessionIdOrderSetting->setValue($request->getSession()->get('klarnaSessionId'));
$entityManager->persist($klarnaSessionIdOrderSetting);
//KLARNA SET SHIPPING
/** @var DomainShippingType $shippingMethod */
$shippingMethod = $entityManager->getRepository(DomainShippingType::class)->findOneById($checkout['shippingMethodId']);
if ($shippingMethod->getType() == DomainShippingType::ShippingType_Carrier_Id && $domain->getId() == Domain::DOMAIN_ID_WS_HU) {
$translationKey = 'shipping.method.type.' . $shippingMethod->getType() . '.achu';
}
else {
$translationKey = 'shipping.method.type.' . $shippingMethod->getType();
}
$icon = '';
if ($translator->trans($translationKey . '.icon') != $translationKey . '.icon') {
$icon = $domain->getUrl() . '/theme/images/' . $translator->trans($translationKey . '.icon');
}
$shippingCountry = $checkout['shippingCountry'] ?? null;
$freeShipping = false;
if (in_array($shippingMethod->getId(), $this->getActiveFreeShippingTypeIds($domain)))
{
$freeShipping = $cart->getBasketItems()->filter(function (BasketItem $basketItem) use ($shippingMethod) {
if (empty($shippingMethod->getFreeShippingProductTypes())){
return true;
}
if (in_array($basketItem->getProduct()->getType()->getId(), $shippingMethod->getFreeShippingProductTypes())) {
return true;
}
return false;
});
$freeShipping = $freeShipping->count() > 0;
}
$this->getKlarna($domain->getId(), $request, $shippingCountry)
->addShipping(
$request->getSession()->get('klarnaSessionId'),
$icon,
$shippingMethod,
$domain,
$checkout,
$freeShipping
);
}
$order->setShippingType($checkout['shippingMethodTypeId']);
if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
&& isset($checkout['packetaPickupPointId'])
&& (is_numeric($checkout['packetaPickupPointId']) || ($checkout['packetaPickupPointCarrierId'] == Packeta::FOXPOST_CARRIER_ID))) {
$packetaIdOrderSetting = new OrderSetting();
$packetaIdOrderSetting->setType(OrderSetting::TYPE_PACKETA_BRANCH_ID);
$packetaIdOrderSetting->setOrder($order);
$packetaIdOrderSetting->setValue($checkout['packetaPickupPointId']);
$entityManager->persist($packetaIdOrderSetting);
}
if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
&& isset($checkout['packetaPickupPointTitle'])
&& $checkout['packetaPickupPointTitle'] != '') {
$packetaTitleOrderSetting = new OrderSetting();
$packetaTitleOrderSetting->setType(OrderSetting::TYPE_PACKETA_BRANCH_NAME);
$packetaTitleOrderSetting->setOrder($order);
$packetaTitleOrderSetting->setValue($checkout['packetaPickupPointTitle']);
$entityManager->persist($packetaTitleOrderSetting);
}
if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_PACKETA_PICKUP_POINT_ID
&& isset($checkout['packetaPickupPointCarrierId'])
&& $checkout['packetaPickupPointCarrierId'] != '') {
$packetaTitleOrderSetting = new OrderSetting();
$packetaTitleOrderSetting->setType(OrderSetting::TYPE_PACKETA_CARRIER_ID);
$packetaTitleOrderSetting->setOrder($order);
$packetaTitleOrderSetting->setValue($checkout['packetaPickupPointCarrierId']);
$entityManager->persist($packetaTitleOrderSetting);
}
// Shipping Address
$order->setShippingBusinessName($checkout['shippingBusinessName']);
$order->setShippingFirstName($checkout['shippingFirstName']);
$order->setShippingLastName($checkout['shippingLastName']);
$order->setShippingStreet($checkout['shippingAddress']);
$order->setShippingZip($checkout['shippingPostalCode']);
$order->setShippingCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$order->setShippingCountry($checkout['shippingCountry']);
} else {
$order->setShippingCountry($country);
}
$order->setShippingPhone($checkout['shippingPhoneNumber']);
$order->setShippingEmail($checkout['email']);
// Billing Address
if ($checkout['billingAddressIsShippingAddress']) {
$order->setBillingFirstName($checkout['shippingFirstName']);
$order->setBillingLastName($checkout['shippingLastName']);
$order->setBillingStreet($checkout['shippingAddress']);
$order->setBillingZip($checkout['shippingPostalCode']);
$order->setBillingCity($checkout['shippingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$order->setBillingCountry($checkout['billingCountry']);
} else {
$order->setBillingCountry($country);
}
$order->setUseBillingAddressAsShippingAddress(true);
} else {
$order->setBillingFirstName($checkout['billingFirstName']);
$order->setBillingLastName($checkout['billingLastName']);
$order->setBillingStreet($checkout['billingAddress']);
$order->setBillingZip($checkout['billingPostalCode']);
$order->setBillingCity($checkout['billingCity']);
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$order->setBillingCountry($checkout['billingCountry']);
} else {
$order->setBillingCountry($country);
}
$order->setUseBillingAddressAsShippingAddress(false);
}
$order->setBillingPhone($checkout['shippingPhoneNumber']);
$order->setBillingEmail($checkout['email']);
// Company
$order->setBillingBusinessName($checkout['billingBusinessName']);
$order->setBillingBusinessId(str_replace([' ', '-'], '', $checkout['billingBusinessId']));
$order->setBillingTaxId($checkout['billingTaxId']);
$order->setBillingVatId($checkout['billingVatNumber']);
if (isset($checkout['3_percent_discount']) && $checkout['3_percent_discount']) {
$order->setDiscount(3);
}
// Message to Seller
$message = $this->remove_emoji($checkout['messageToSeller']);
$order->setMessage($message);
// Save Order
$entityManager->persist($order);
$entityManager->flush();
if (is_null($customer->getCountry())) {
$countryCode = Customer::getCountryCodeByDomainId($domain->getId());
if (is_null($countryCode)) {
$countryCode = $order->getBillingCountry();
}
$customer->setCountry($countryCode);
}
// Add Products
$cart = $this->getCart($request->getSession()->get('cartId'));
if ($cart) {
$position = 1;
// Validate Coupon
if (!empty($checkout['coupon']['code'])) {
$coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
'code' => $checkout['coupon']['code'],
'domain' => $domain,
]);
if ($coupon) {
// Set Email
if (!empty($checkout['email'])) {
$cart->setEmail($checkout['email']);
} else {
$cart->setEmail(null);
}
// Coupon Free Shipping
$isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
// Coupon Discount
$isCouponValidForBasket = CartHelper::isCouponValidForBasket($coupon, $cart, $entityManager);
if ($isCouponValidForBasket !== false || $isCouponApplicableForFreeShipping) {
$checkout['coupon'] = [
'code' => $coupon->getCode(),
'type' => $coupon->getDiscountType(),
'discount' => (float)$isCouponValidForBasket,
'freeShipping' => $isCouponApplicableForFreeShipping,
];
} // Drop Invalid Coupon Code
else {
unset($checkout['coupon']);
}
} // Drop Invalid Coupon Code
else {
unset($checkout['coupon']);
}
}
// Coupon Code
if (!empty($checkout['coupon']['code']) && ((isset($checkout['coupon']['discount']) && (int)$checkout['coupon']['discount'] >= 0) || in_array($checkout['coupon']['code'], $this->getWhiteListCouponCodes()))) {
$order->setCouponCode($checkout['coupon']['code']);
}
if (isset($checkout['coupon']['discount']) && (float)$checkout['coupon']['discount'] >= 0 && $checkout['coupon']['type'] == Coupon::DISCOUNT_TYPE_PERCENT) {
$coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
'domain' => $domain,
'code' => $checkout['coupon']['code'],
'discountType' => Coupon::DISCOUNT_TYPE_PERCENT,
]);
if ($coupon) {
$orderSetting = new OrderSetting();
$orderSetting->setOrder($order);
$orderSetting->setType(OrderSetting::TYPE_COUPON_CODE);
$orderSetting->setValue($coupon->getId());
$entityManager->persist($orderSetting);
}
}
// Sub-total for avoid Minus Total
$validateCouponDiscountPrice = 0;
if (isset($checkout['coupon']['discount']) && (float)$checkout['coupon']['discount'] >= 0 && $checkout['coupon']['type'] == Coupon::DISCOUNT_TYPE_PRICE) {
$coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
'domain' => $domain,
'code' => $checkout['coupon']['code'],
'discountType' => Coupon::DISCOUNT_TYPE_PRICE,
]);
if ($coupon) {
$orderSetting = new OrderSetting();
$orderSetting->setOrder($order);
$orderSetting->setType(OrderSetting::TYPE_COUPON_CODE);
$orderSetting->setValue($coupon->getId());
$entityManager->persist($orderSetting);
}
}
$useZeroVat = $this->useZeroVat($customer, $request);
if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_HU) {
$adattorloProduct = $entityManager->getRepository(Product::class)->findOneById(Product::ADATTORLO_PRODUCT_ID);
$adattorloQuantity = 0;
/**
* @var BasketItem $basketItem
*/
foreach ($cart->getBasketItems() as $basketItem) {
if (in_array($basketItem->getProduct()->getType()->getId(), [ProductType::PRODUCT_TYPE_ID_PC, ProductType::PRODUCT_TYPE_ID_NOTEBOOK, ProductType::PRODUCT_TYPE_ID_TABLET, ProductType::PRODUCT_TYPE_ID_SMARTPHONE])) {
$adattorloQuantity += $basketItem->getQuantity();
}
}
if ($adattorloQuantity > 0) {
$adattorloBasketItem = new BasketItem();
$adattorloBasketItem->setBasket($cart);
$adattorloBasketItem->setProduct($adattorloProduct);
$adattorloBasketItem->setQuantity($adattorloQuantity);
$cart->addBasketItem($adattorloBasketItem);
$cart->setUpdated(new \DateTime());
$entityManager->persist($cart);
$entityManager->flush();
}
}
$freeEsetProductItemCount = 0;
/**
* @var BasketItem $item
*/
foreach ($cart->getBasketItems() as $item) {
$product = $item->getProduct();
if ($product) {
$orderItem = new OrderItem();
$orderItem->setProduct($product);
if (
in_array($order->getDomain()->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_RT_HU]) &&
$request->request->has('eset-90-day-free') &&
$entityManager->getRepository(Product::class)->isFreeEsetCompatible($product)
) {
$freeEsetProductItemCount += $item->getQuantity();
}
$productMeta = $product->getDomainMeta($domain);
if ($useZeroVat) {
$domainPrice = $productMeta->isDiscounted()
? $productMeta->getDomainDiscount()
: $productMeta->getDomainPrice();
} else {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$domainPrice = $productMeta->isDiscounted()
? $domain->createVatPrice($productMeta->getDomainDiscount(), 1.27)
: $domain->createVatPrice($productMeta->getDomainPrice(), 1.27);
} else {
$domainPrice = $productMeta->isDiscounted()
? $productMeta->getDomainVatDiscount()
: $productMeta->getDomainVatPrice();
}
}
$isTimedSale = $productMeta->isTimedSaleActive(true);
$orderItem->setFromTimedSale($isTimedSale);
if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
$domainPrice = $this->calculateDiscountedPrice($domainPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
}
$orderItem->setPrice($domainPrice);
$productPrice = $domainPrice;
$orderItem->setQuantity($item->getQuantity());
$orderItem->setPosition($position);
$orderItem->setOrder($order);
// Save Order Product
$entityManager->persist($orderItem);
$entityManager->flush();
if ($product->isContainer()) {
foreach ($product->getProductContainers() as $container) {
$position++;
$containerMeta = $container->getDomainMeta($domain);
if ($useZeroVat) {
$containerOrderItemPrice = $productMeta->isDiscounted() ? $containerMeta->getDomainDiscount() : $containerMeta->getDomainPrice();
} else {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$containerOrderItemPrice = $productMeta->isDiscounted()
? $domain->createVatPrice($containerMeta->getDomainDiscount(), 1.27)
: $domain->createVatPrice($containerMeta->getDomainPrice(), 1.27);
} else {
$containerOrderItemPrice = $productMeta->isDiscounted()
? $containerMeta->getDomainVatDiscount()
: $containerMeta->getDomainVatPrice();
}
}
if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
$containerOrderItemPrice = $this->calculateDiscountedPrice($containerOrderItemPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
}
$containerOrderItem = new OrderItem();
$childProduct = null;
if (!is_null($container->getChild())) {
$childProduct = $container->getChild();
} elseif (!is_null($container->getProductTag())) {
$childProduct = $entityManager->getRepository(Product::class)->getAvailableProductByProductTag($container->getProductTag());
}
if (!$childProduct) {
continue;
}
$containerOrderItem->setOrder($order);
$containerOrderItem->setProductContainer($container);
$containerOrderItem->setProduct($childProduct);
$containerOrderItem->setParent($orderItem);
$containerOrderItem->setQuantity($container->getMultiplier());
$containerOrderItem->setPosition($position);
$containerOrderItem->setPrice($containerOrderItemPrice);
$entityManager->persist($containerOrderItem);
}
$entityManager->flush();
}
// Cross-sell Attribute Options
$crossSellAttributeOptions = CartHelper::getCrossSellAttributeOptionsByProductTypeId($product->getType()->getId(), $domain->getId());
$optionPrice = 0;
// Add Product Attributes
if ($item->getItemAttributes() != null) {
/**
* @var $attribute BasketItemAttributeOption
*/
foreach ($item->getItemAttributes() as $attribute) {
$option = $attribute->getAttributeOption();
if ($option && !in_array($option->getId(), $this->unWantedAttributes)) {
$optionMeta = $option->getDomainMeta($domain);
if ($optionMeta) {
$orderItemAttribute = new OrderItemAttributeOption();
if ($useZeroVat) {
$optionDomainPrice = $optionMeta->isDiscounted() ? $optionMeta->getDomainDiscount() : $optionMeta->getDomainPrice();
} else {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$optionDomainPrice = $optionMeta->isDiscounted()
? $domain->createVatPrice($optionMeta->getDomainDiscount(), 1.27)
: $domain->createVatPrice($optionMeta->getDomainPrice(), 1.27);
} else {
$optionDomainPrice = $optionMeta->isDiscounted()
? $optionMeta->getDomainVatDiscount()
: $optionMeta->getDomainVatPrice();
}
}
// Cross-sell Attribute Options Calculated Price
if (isset($crossSellAttributeOptions[$option->getId()])) {
if (isset($crossSellAttributeOptions[$option->getId()]['percentPrice'])) {
$optionDomainPrice = $domain->createVatPrice((($item->getPriceWithAttributesForDomainWithException($domain, $option) * $crossSellAttributeOptions[$option->getId()]['percentPrice']) / 100), 1.);
}
}
if (!is_null($order->getDiscount()) && $order->getDiscount() > 0) {
$optionDomainPrice = $this->calculateDiscountedPrice($optionDomainPrice, $order->getDiscount(), $domain->getLanguage()->getCode());
}
$orderItemAttribute->setPrice($optionDomainPrice);
$optionPrice += $optionDomainPrice;
$orderItemAttribute->setAttributeOption($option);
$orderItemAttribute->setOrderItem($orderItem);
$entityManager->persist($orderItemAttribute);
if ($option->getAttribute()->getId() == Attribute::ATTRIBUTE_ID_NEW_BATTERY) {
$orderComment = new OrderComment();
$orderComment->setOrder($order);
$orderComment->setText("aksi belemegy\na notiba 100%\nfoto");
$orderComment->setType(OrderComment::TYPE_FOR_INSTALLATION);
$entityManager->persist($orderComment);
$newBatAtt = $entityManager->getRepository(AttributeOption::class)->find(AttributeOption::ATTRIBUTE_OPTION_ID_NEW_BATTERY);
$notAddedYet = true;
$connectedProducts = $product->getProductModel()->getConnectedProducts();
/** @var Product $connectedProduct */
foreach ($connectedProducts as $connectedProduct) {
if ($connectedProduct->getType()->getId() == ProductType::PRODUCT_TYPE_ID_NOTEBOOK_BATTERY) {
if (!$connectedProduct->isAvailable()) {
continue;
}
if (str_contains(strtolower($connectedProduct->getName()), 'used')) {
continue;
}
$batteryAtrOpt = $entityManager->getRepository(AttributeOption::class)->findOneBy(['product' => $connectedProduct->getId()]);
if (!$batteryAtrOpt) {
$batteryAtrOpt = new AttributeOption();
$batteryAtrOpt->setProduct($connectedProduct);
$batteryAtrOpt->setParent($newBatAtt);
$batteryAtrOpt->setAttribute($entityManager->getRepository(Attribute::class)->find(Attribute::ATTRIBUTE_ID_BATTERY));
$batteryAtrOpt->setSortIndex(999);
$batteryAtrOpt->setTitle($connectedProduct->getName());
$batteryAtrOpt->setLongTitle($connectedProduct->getLongName());
$batteryAtrOpt->setPrivate(false);
$batteryAtrOpt->setCreatedBy($this->getEntityManager()->getRepository(User::class)->find(User::CENTRALIS_USER_ID));
$entityManager->persist($batteryAtrOpt);
}
$batteryAttribute = new OrderItemAttributeOption();
$batteryAttribute->setOrderItem($orderItem);
$batteryAttribute->setPrice(0);
$batteryAttribute->setAttributeOption($batteryAtrOpt);
$orderItem->addItemAttribute($batteryAttribute);
$entityManager->persist($batteryAttribute);
$notAddedYet = false;
break;
}
}
if ($notAddedYet) {
foreach ($connectedProducts as $connectedProduct) {
if ($connectedProduct->getType()->getId() == ProductType::PRODUCT_TYPE_ID_NOTEBOOK_BATTERY) {
if (str_contains(strtolower($connectedProduct->getName()), 'used')) {
continue;
}
$batteryAtrOpt = $entityManager->getRepository(AttributeOption::class)->findOneBy(['product' => $connectedProduct->getId()]);
if (!$batteryAtrOpt) {
$batteryAtrOpt = new AttributeOption();
$batteryAtrOpt->setProduct($connectedProduct);
$batteryAtrOpt->setParent($newBatAtt);
$batteryAtrOpt->setAttribute($entityManager->getRepository(Attribute::class)->find(Attribute::ATTRIBUTE_ID_BATTERY));
$batteryAtrOpt->setSortIndex(999);
$batteryAtrOpt->setTitle($connectedProduct->getName());
$batteryAtrOpt->setLongTitle($connectedProduct->getLongName());
$batteryAtrOpt->setPrivate(false);
$batteryAtrOpt->setCreatedBy($this->getEntityManager()->getRepository(User::class)->find(User::CENTRALIS_USER_ID));
$entityManager->persist($batteryAtrOpt);
}
$batteryAttribute = new OrderItemAttributeOption();
$batteryAttribute->setOrderItem($orderItem);
$batteryAttribute->setPrice(0);
$batteryAttribute->setAttributeOption($batteryAtrOpt);
$orderItem->addItemAttribute($batteryAttribute);
$entityManager->persist($batteryAttribute);
break;
}
}
}
}
}
}
}
}
$adapterAdded = false;
foreach ($product->getProductAttributes() as $productAttribute) {
if ($productAttribute->isAlways()) {
$attributeOption = $productAttribute->getOption();
if ($domain->getId() == Domain::DOMAIN_ID_WS_EU && $attributeOption->getId() == 1194) { // No cables for WS EU
continue;
}
if ($attributeOption->getAttribute()->getId() == 150 && ($adapterAdded || ($attributeOption->getProduct() && $attributeOption->getProduct()->getAvailable() < 1))) {
continue;
} else {
$adapterAdded = true;
}
$orderItemAttribute = new OrderItemAttributeOption();
$orderItemAttribute->setOrderItem($orderItem);
$orderItemAttribute->setAttributeOption($attributeOption);
$orderItemAttribute->setPrice(0);
$entityManager->persist($orderItemAttribute);
}
}
$entityManager->flush();
$entityManager->refresh($orderItem);
$validateCouponDiscountPrice += ($productPrice + $optionPrice) * $item->getQuantity();
$position++;
}
}
if ($freeEsetProductItemCount > 0) {
$antiVirusProductId = $domain->getId() == Domain::DOMAIN_ID_RT_SK ? Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID : Product::GDATA_90_DAY_TRIAL_PRODUCT_ID;
$product = $this->getEntityManager()->getRepository(Product::class)->findOneById($antiVirusProductId);
$orderItem = new OrderItem();
$orderItem->setProduct($product);
$orderItem->setPrice(0);
$orderItem->setQuantity($freeEsetProductItemCount);
$orderItem->setPosition($position);
$orderItem->setOrder($order);
// Save Order Product
$entityManager->persist($orderItem);
$entityManager->flush();
$position++;
}
if (!empty($orderSummary['cashOnDeliveryProductItem']) && isset($orderSummary['cashOnDeliveryProductItem']['price']) && $orderSummary['cashOnDeliveryProductItem']['price'] != 0) {
$product = $entityManager->getRepository(Product::class)->findOneById(Product::CASH_ON_DELIVERY_PRODUCT_ID);
$orderItem = new OrderItem();
$orderItem->setProduct($product);
$orderItem->setPrice($orderSummary['cashOnDeliveryProductItem']['price']);
$orderItem->setQuantity(1);
$orderItem->setPosition($position);
$orderItem->setOrder($order);
// Save Order Product
$entityManager->persist($orderItem);
$entityManager->flush();
$position++;
}
if ($order->getShippingType() == DomainShippingType::SHIPPING_TYPE_MPL_ID) {
$product = $entityManager->getRepository(Product::class)->findOneById(Product::MPL_PACKAGE_FEE_PRODUCT_ID);
$orderItem = new OrderItem();
$orderItem->setProduct($product);
$orderItem->setPrice($orderSummary['packageFee']['price']);
$orderItem->setQuantity(1);
$orderItem->setPosition($position);
$orderItem->setOrder($order);
// Save Order Product
$entityManager->persist($orderItem);
$entityManager->flush();
$position++;
}
if (isset($checkout['coupon']['discount'])) {
// Avoid Minus Total
$couponDiscountPrice = $checkout['coupon']['discount'];
$couponOrderItem = new OrderItem();
$couponProduct = $entityManager->getRepository(Product::class)->findOneById(Coupon::COUPON_PRODUCT_ID);
$discountPrice = '-' . $couponDiscountPrice;
$couponOrderItem->setOrder($order);
$couponOrderItem->setQuantity(1);
$couponOrderItem->setProduct($couponProduct);
$couponOrderItem->setPrice($discountPrice);
$couponOrderItem->setFromTimedSale(false);
$couponOrderItem->setPosition($position);
$entityManager->persist($couponOrderItem);
}
}
// Order Setting - Pickup Point
if ((int)$checkout['shippingMethodPickupPointId'] > 0) {
$orderSetting = new OrderSetting();
$orderSetting->setOrder($order);
$orderSetting->setType(OrderSetting::TYPE_PICKUP_POINT_ID);
$orderSetting->setValue($checkout['shippingMethodPickupPointId']);
$entityManager->persist($orderSetting);
}
$selectedStockItems = $request->getSession()->get('stockItemCodes') ?? false;
if ($selectedStockItems) {
$orderCommentStockItems = new OrderComment();
$orderCommentStockItems->setOrder($order);
$orderCommentStockItems->setCreatedBy($this->getCentralisUser());
$orderCommentStockItems->setType(OrderComment::TYPE_FOR_PREPARATION);
$stockItemCodes = StockItem::PREFIX_FOR_SELECTED_ITEMS;
foreach ($selectedStockItems as $product) {
foreach ($product as $key => $stockItemId) {
$stockItemCodes .= $stockItemId . ';';
}
}
$orderCommentStockItems->setText($stockItemCodes);
$entityManager->persist($orderCommentStockItems);
}
$entityManager->flush();
// Refresh Order
$entityManager->refresh($order);
/**
* @var DomainShippingType $domainShippingType
*/
$domainShippingType = $entityManager->getRepository(DomainShippingType::class)->findOneBy([
'domain' => $domain,
'type' => $order->getShippingType(),
]);
if ($domainShippingType) {
$domainShippingPrice = CartHelper::hasMainProductType($cart) ? 0 : $domainShippingType->getPrice();
// Shipping Cost
$order->setShippingPrice($domainShippingPrice);
// Free Shipping
if (($domainShippingType->getFreeShipLimit() > 0 && $order->getSubTotal() > $domainShippingType->getFreeShipLimit())) {
$order->setShippingPrice(0);
$order->setForceFreeShipping(true);
}
} else {
$order->setShippingPrice(0);
}
// Coupon Free Shipping
if (isset($checkout['coupon']['freeShipping']) && $checkout['coupon']['freeShipping'] === true) {
$order->setShippingPrice(0);
$order->setForceFreeShipping(true);
}
if (in_array($order->getShippingType(), $orderSummary['enableFreeShipping'])) {
$order->setShippingPrice(0);
}
// Update Full Price
$order->setFullPrice();
// Update customer all order price and quantity
$order->getCustomer()->updateAllOrderPriceAndQuantity();
// Add WAITING changelog
$orderChangelog = new OrderChangelog();
$orderChangelog->setOrderId($order->getId());
$orderChangelog->setStatus(Order::STATUS_TRIAGE);
$orderChangelog->setCreatedBy($this->getCentralisUser()->getId());
$statisticsEntityManager->persist($orderChangelog);
// Remove basket after successful order creation
$entityManager->remove($cart);
$entityManager->flush();
$statisticsEntityManager->flush();
// Full Price will be set on success page
$checkout['orderId'] = $order->getId();
if (!is_null($request->request->get('heureka-checkbox')) && $request->request->get('heureka-checkbox') == '1') {
$checkout['heureka-form'] = 1;
}
$request->getSession()->set('checkout', $checkout);
$this->getKlaviyoConnect($request)->createFinishedOrderEvent($order);
if (in_array($checkout['paymentMethodTypeId'], PaymentType::getBnplPaymentTypeIds())) {
$this->getKlaviyoConnect($request)->createBnplSelectedEvent($order, PaymentType::from($checkout['paymentMethodTypeId']));
}
return $this->redirectToRoute('checkout_success');
}
$data['form'] = $form->createView();
// Checkout data
$data['checkout'] = $checkout;
// Order Summary
$data['orderSummary'] = $orderSummary;
$data['legal_links'] = $this->getLegalLinks($request, $cart->getDomain()->getId());
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['stepsOptions'] = $this->checkoutSteps(5);
$data['cetelem_hu_shop_id'] = $this->getParameter('cetelem_hu_shop_id');
$data['cetelem_hu_url'] = $this->getParameter('cetelem_hu_url');
$data['cetelem_hu_barem_code'] = $this->getParameter('cetelem_hu_barem_code');
$data['cetelem_hu_price_minimum'] = $this->getParameter('cetelem_hu_price_minimum');
return $this->render('AtechNetCoreBundle/Checkout/review.html.twig', $data);
}
return $this->redirectToRoute('cart_show');
}
/**
* @Route("/checkout/success", name="checkout_success", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/success", name="checkout_success_locale", defaults={"_locale":""})
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Exception
*/
public function successAction(Request $request)
{
$data = [];
$data['hideChat'] = true;
// Checkout DATA
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
if (isset($checkout['orderId']) && (int)$checkout['orderId'] > 0) {
$entityManager = $this->getEntityManager();
$multiStore = $this->getMultiStoreHelper($request);
$productHelper = $this->getProductHelper($request);
$translator = $this->getDatabaseTranslator($request);
$domainId = $multiStore->getDomainId();
$order = $entityManager->getRepository(Order::class)->findOneById($checkout['orderId']);
if ($order) {
$domain = $order->getDomain();
$orderHelper = $this->getOrderHelper($request);
if ($this->getEnvironment() == 'prod') {
$emailSendingResult = $orderHelper->sendOrderEmail(
$order,
$productHelper,
$this->getContactInfos(),
$this->getWhiteListCouponCodes(),
true
);
//for testing the email
//you need to enable this part in OrderHelper return $emailData;
/*return $this->render('AtechNetCoreBundle/Email/order.html.twig', $emailSendingResult);*/
// Marketing
$data['marketingProducts'] = $emailSendingResult ? $emailSendingResult['marketingProducts'] : '';
$data['marketingProductsGA4'] = $emailSendingResult ? $emailSendingResult['marketingProductsGA4'] : '';
}
if (
$this->getEnvironment() == 'prod' &&
in_array($domain->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ]) &&
isset($checkout['heureka-form']) && $checkout['heureka-form'] == 1
) {
$heureka = new Heureka($this->getTwig());
$heureka->sendOrderInfo($order);
}
$data['orderId'] = $order->getId();
$data['email'] = $order->getBillingEmail();
$data['domainName'] = $domain->getName();
$data['orderTotal'] = $order->getFullPrice();
$data['orderTax'] = round($order->getTaxOutOfFullPrice(), 2);
switch ($domain->getCurrency()) {
case 'Ft':
$data['currencyCode'] = 'HUF';
break;
case 'Kč':
$data['currencyCode'] = 'CZK';
break;
case '€':
$data['currencyCode'] = 'EUR';
break;
default:
$data['currencyCode'] = 'EUR';
}
$data['orderShipping'] = $order->getShippingPrice();
$data['payAtDelivery'] = false;
$data['gopay_data'] = null;
$data['simplepay_data'] = null;
$data['klarna_data'] = null;
$notebookCount = 0;
$upgradableNotebookCount = 0;
$upgradablePcCount = 0;
$pcCount = 0;
$monitorCount = 0;
$checkForAddedRamAccessories = false;
$oldPrice = 0;
$newPrice = 0;
$trustPilotData = [
'skuList' => [],
'products' => [],
];
/**
* @var OrderItem $oi
* @var OrderItemAttributeOption $oia
* @var Product $product
*/
foreach ($order->getOrderItems() as $oi) {
$product = $oi->getProduct();
if (
in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU]) &&
in_array($order->getBillingEmail(), ['roland.toth@furbify.eu', 'sandor.lakatos@furbify.eu']) // for testing
) {
$productPhotoList = $product->getAlbum()->getPhotos();
$productPhoto = $productPhotoList->count() > 0 ? $productPhotoList->first() : false;
$productImage = $productPhoto ? $this->getImage($productPhoto, 'product/' . $product->getCode())->resize(Image::PRODUCT_LIST_THUMB_WIDTH, Image::PRODUCT_LIST_THUMB_HEIGHT) : '';
$trustPilotData['products'][] = [
'sku' => $oi->getProduct()->getCode(),
'productUrl' => $this->url($request)->link('product', [
'product_id' => $oi->getProduct()->getId(),
'isBazaar' => $oi->getProduct()->isBazaar()
]),
'imageUrl' => $productImage,
'name' => $product->getFullTitle(),
];
$trustPilotData['skuList'][] = $product->getCode();
}
switch ($product->getType()->getId()) {
case 52: // Notebook
$checkForAddedRamAccessories = false;
foreach ($oi->getItemAttributes() as $oia) {
if (in_array($oia->getAttributeOption()->getAttribute()->getId(), [29, 31, 153])) {
$checkForAddedRamAccessories = true;
}
}
$isChromeBook = in_array('Chromebook', $product->getBadges());
foreach ($product->getSpecificationAttributeOptions() as $ao) {
$attribute = $ao->getAttribute();
if ($attribute->getId() == 4 && in_array($ao->getId(), [100, 937])
&& strpos($product->getName(), 'EliteBook Folio 1040') === false
&& strpos($product->getName(), 'S1 Yoga') === false) {
$upgradableNotebookCount = $upgradableNotebookCount + $oi->getQuantity();
switch ($ao->getId()) {
case 100: // DDR3
$accesoryId = 421;
break;
case 937: // DDR4
$accesoryId = 1706;
break;
}
$ramAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById($accesoryId);
$ramAccessoryMeta = $ramAccessory->getDomainMeta($domain);
$oldPrice = $ramAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
$newPrice = $domain->createVatPrice($ramAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
}
}
$notebookCount = $notebookCount + $oi->getQuantity();
break;
case 60: // PC
$checkForAddedRamAccessories = false;
foreach ($oi->getItemAttributes() as $oia) {
if (in_array($oia->getAttributeOption()->getAttribute()->getId(), [28, 30, 147])) {
$checkForAddedRamAccessories = true;
}
}
foreach ($product->getSpecificationAttributeOptions() as $ao) {
$attribute = $ao->getAttribute();
if ($attribute->getId() == 3 && in_array($ao->getId(), [81, 1276])) {
$upgradablePcCount = $upgradablePcCount + $oi->getQuantity();
switch ($ao->getId()) {
case 81: // DDR3
$accesoryId = 417;
break;
case 1276: // DDR4
$accesoryId = 1521;
break;
}
$ramAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById($accesoryId);
$ramAccessoryMeta = $ramAccessory->getDomainMeta($domain);
$oldPrice = $ramAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
$newPrice = $domain->createVatPrice($ramAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
}
}
$pcCount = $pcCount + $oi->getQuantity();
break;
case 44: // Monitor
$monitorCount++;
$cleanerAccessory = $entityManager->getRepository(AttributeOption::class)->findOneById(1766);
$cleanerAccessoryMeta = $cleanerAccessory->getDomainMeta($domain);
$oldPrice = $cleanerAccessoryMeta->getDomainVatPrice() . ' ' . $domain->getCurrency();
$newPrice = $domain->createVatPrice($cleanerAccessoryMeta->getDomainPrice() * 0.9) . ' ' . $domain->getCurrency();
break;
}
}
$data['show_upsell'] = false;
$data['upsell_type'] = 0;
$data['upsell_old_price'] = 0;
$data['upsell_new_price'] = 0;
$data['surveyQuestions'] = [];
// NB RAM UPSELL
if (in_array($domain->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_HU])) {
if ($upgradableNotebookCount == 1
&& $notebookCount == 1
&& !$isChromeBook
&& $pcCount == 0
&& $monitorCount == 0
&& !$checkForAddedRamAccessories
&& $order->getPaymentType() == PaymentType::CashOnDelivery->value) {
$data['upsell_type'] = 1;
$data['show_upsell'] = true;
$data['upsell_old_price'] = $oldPrice;
$data['upsell_new_price'] = $newPrice;
$upsellOrderSetting = new OrderSetting();
$upsellOrderSetting->setOrder($order);
$upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
$upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
$entityManager->persist($upsellOrderSetting);
$entityManager->flush();
}
// PC RAM UPSELL
if ($upgradablePcCount == 1
&& $notebookCount == 0
&& $pcCount == 1
&& $monitorCount == 0
&& !$checkForAddedRamAccessories
&& $order->getPaymentType() == PaymentType::CashOnDelivery->value) {
$data['upsell_type'] = 2;
$data['show_upsell'] = true;
$data['upsell_old_price'] = $oldPrice;
$data['upsell_new_price'] = $newPrice;
$upsellOrderSetting = new OrderSetting();
$upsellOrderSetting->setOrder($order);
$upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
$upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
$entityManager->persist($upsellOrderSetting);
$entityManager->flush();
}
// MONITOR UPSELL
if ($notebookCount == 0
&& $pcCount == 0
&& $monitorCount == 1
&& $order->getPaymentType() == PaymentType::CashOnDelivery->value
&& $domain->getId() == 3) {
$data['upsell_type'] = 3;
$data['show_upsell'] = true;
$data['upsell_old_price'] = $oldPrice;
$data['upsell_new_price'] = $newPrice;
$upsellOrderSetting = new OrderSetting();
$upsellOrderSetting->setOrder($order);
$upsellOrderSetting->setType(OrderSetting::TYPE_UPSELL_STATS);
$upsellOrderSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_VIEW);
$entityManager->persist($upsellOrderSetting);
$entityManager->flush();
}
}
$data['externalPayment'] = in_array($order->getPaymentType(), $this->extenalCheckPaymentTypes);
/**
* @var Order $order
*/
if (in_array($order->getPaymentType(), $this->extenalCheckPaymentTypes)) {
if ($order->getPaymentType() == PaymentType::Quatro->value) {
$callbackUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Quatro->value,
'orderId' => $order->getId(),
], UrlGeneratorInterface::ABSOLUTE_URL);
$quatroPaymentURL = $this->getParameter('quatro_order_url');
$quatroKey = $this->getParameter('quatro_key');
$quatroSubject = '';
foreach ($order->getOrderItems() as $oi) {
if ($quatroSubject != '') {
$quatroSubject .= ', ';
}
$product = $oi->getProduct();
$quatroSubject .= $product->getType()->getTitle($translator) . ' - ' . $product->getVendor()->getName() . ' - ' . $product->getName();
}
$payload = [
'application' => [
'orderNumber' => $order->getId(),
'applicant' => [
'firstName' => $order->getBillingFirstName(),
'lastName' => $order->getBillingLastName(),
'email' => $order->getBillingEmail(),
'mobile' => $order->getBillingPhone(),
'permanentAddress' => [
'addressLine' => $order->getBillingStreet(),
'city' => $order->getBillingCity(),
'zipCode' => $order->getBillingZip(),
'country' => 'SVK',
],
],
'subject' => $quatroSubject,
'totalAmount' => number_format($order->getFullPrice(), 2, '.', ''),
'callback' => $callbackUrl,
],
'iat' => time(),
];
$signatureToken = JWT::encode($payload, base64_decode($quatroKey));
$quatroUrl = $quatroPaymentURL . $signatureToken;
$entityManager->flush();
$data['quatro_url'] = $quatroUrl;
}
if ($order->getPaymentType() == PaymentType::Cetelem->value) {
$domainId = $order->getDomain()->getId();
if ($domainId == 1) { // CETELEM SK - LPC
$cetelemSkId = $this->getParameter('cetelem_sk_id');
$cetelem = $this->getCetelemHelperSK();
$cetelemData = $cetelem->getCalculatorData([
'kodBaremu' => $checkout['cetelem']['kodBaremu'],
'kodPoistenia' => $checkout['cetelem']['kodPoistenia'],
'kodMaterialu' => $checkout['cetelem']['kodMaterialu'],
'cenaTovaru' => $order->getFullPrice(),
'priamaPlatba' => $checkout['cetelem']['priamaPlatba'],
'pocetSplatok' => $checkout['cetelem']['pocetSplatok'],
'odklad' => $checkout['cetelem']['odklad'],
]);
$orderedItemTitles = '';
foreach ($order->getOrderItems() as $orderItem) {
$orderedItemTitles .= $orderedItemTitles == '' ? $orderItem->getProduct()->getName() : ',' . $orderItem->getProduct()->getName();
}
$orderedItemTitles = mb_substr($orderedItemTitles, 0, 30);
$cetelemReturnURL = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Cetelem->value,
'orderId' => $order->getId(),
], UrlGeneratorInterface::ABSOLUTE_URL);
$data['cetelem_form'] = $this->renderView('AtechNetCoreBundle/Module/cetelemSubmitFormSK.html.twig', [
'postUrl' => $cetelem->getPostUrl(),
'cetelem_sk_id' => $cetelemSkId,
'cetelem' => $cetelemData,
'customerId' => $order->getCustomer()->getId(),
'orderId' => $order->getId(),
'orderedItemTitles' => $orderedItemTitles,
'cetelemReturnURL' => $cetelemReturnURL,
]);
} elseif ($domainId == Domain::DOMAIN_ID_RT_HU) { // CETELEM HU - FPC
$cetelemHuReturnURLs['cbZold'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Cetelem->value,
'orderId' => $order->getId(),
'gateResponse' => md5($order->getId() . '1'),
], UrlGeneratorInterface::ABSOLUTE_URL);
$cetelemHuReturnURLs['cbNarancs'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Cetelem->value,
'orderId' => $order->getId(),
'gateResponse' => md5($order->getId() . '2'),
], UrlGeneratorInterface::ABSOLUTE_URL);
$cetelemHuReturnURLs['cbPiros'] = $cetelemBaseReturnUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Cetelem->value,
'orderId' => $order->getId(),
'gateResponse' => md5($order->getId() . '3'),
], UrlGeneratorInterface::ABSOLUTE_URL);
$data['cetelem_form'] = $this->renderView('AtechNetCoreBundle/Module/cetelemSubmitFormHU.html.twig', [
'postUrl' => $this->getParameter('cetelem_hu_url'),
'shopCode' => $this->getParameter('cetelem_hu_shop_id'),
'purchaseAmount' => number_format($order->getFullPrice(), 0, '.', ''),
'orderId' => $order->getId(),
'cbZold' => $cetelemHuReturnURLs['cbZold'],
'cbNarancs' => $cetelemHuReturnURLs['cbNarancs'],
'cbPiros' => $cetelemHuReturnURLs['cbPiros'],
]);
}
}
if (in_array($order->getPaymentType(), [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value])) {
$gopayHelper = $this->getGopayHelper($request);
$data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
}
if ($order->getPaymentType() == PaymentType::Instacash->value) {
$instacash = $this->getInstacash($domain->getLanguage()->getCode());
$redirectUrl = $this->generateUrl(
'checkout_payment_check',
[
'orderId' => $order->getId(),
'paymentTypeId' => PaymentType::Instacash->value,
]
);
$response = $instacash->createApplication($order, $redirectUrl);
$instacashRedirectUrl = $instacash->getRedirectToMerchantUrl($response['publicId']);
$data['instacashRedirectUrl'] = $instacashRedirectUrl;
}
if ($order->getPaymentType() == PaymentType::Milpay->value) {
$milpay = $this->getMilpay($domain->getLanguage()->getCode());
$redirectUrl = $this->generateUrl(
'checkout_payment_check',
[
'orderId' => $order->getId(),
'paymentTypeId' => PaymentType::Milpay->value,
],
UrlGeneratorInterface::ABSOLUTE_URL
);
$response = $milpay->createApplication($order, $redirectUrl);
$app = $milpay->getApplicationStatus($response['applicationId']);
$milpayRedirectUrl = $milpay->getRedirectToMerchantUrl($domain->getLanguage()->getCode(), $response['publicId'], $app['financier']);
$data['milpayRedirectUrl'] = $milpayRedirectUrl;
}
if ($order->getPaymentType() == PaymentType::PastPay->value) {
$pastPay = $this->getPastPay($order->getDomain()->getId());
$redirectUrl = $this->generateUrl('checkout_payment_check', [
'orderId' => $order->getId(),
'paymentTypeId' => PaymentType::PastPay->value,
]);
$pastPay->setOrder($order);
$pastPay->setDebtorTaxNumber($checkout['billingTaxId']);
$redirectUrl = $pastPay->createOrderAndGetRedirectUrl($redirectUrl);
if (!is_array($redirectUrl)) {
$data['pastPayRedirectUrl'] = $redirectUrl;
}
}
if ($order->getPaymentType() == PaymentType::Klarna->value) {
$klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
$redirectUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Klarna->value,
'orderId' => $order->getId(),
]);
$redirectUrl = $klarna->createKlarnaUrl($redirectUrl, $request->getSession()->get('klarnaSessionId'));
$data['klarna_data'] = $redirectUrl['redirect_url'];
}
if ($order->getPaymentType() == PaymentType::PayPal->value) {
$orderItems = [];
/** @var OrderItem $oi */
foreach ($order->getOrderItems() as $oi) {
$orderItems[] = [
'id' => $oi->getProduct()->getCode(),
'quantity' => $oi->getQuantity(),
];
}
$data['paypal_data'] = [
'items' => $orderItems,
'totalPrice' => $order->getFullPrice(),
'scriptSrc' => $this->getPaypal()->getScriptSrc($order),
'currency' => $order->getDomain()->getCurrencyTextCode(),
];
if ($order->getPaymentStatus() == Order::PAYMENT_STATUS_PAID) {
$request->getSession()->remove('checkout');
//This will be moved to stock movement creation
#$request->getSession()->remove('stockItemCodes');
$data['paypal_data']['success'] = true;
}
}
} else {
$request->getSession()->remove('checkout');
//This will be moved to stock movement creation
#$request->getSession()->remove('stockItemCodes');
/**
* Success survey
* @var Survey $survey
* @var SurveyQuestion $question
* @var SurveyQuestionOption $questionOption
*/
if ($domain->getType() == 'retail') {
switch ($domainId) {
case 1:
$surveyId = 2;
break;
case 3:
$surveyId = 1;
break;
default:
$surveyId = 0;
}
$survey = $entityManager->getRepository(Survey::class)->findOneById($surveyId);
if ($survey) {
foreach ($survey->getQuestions() as $question) {
$options = [];
if (in_array($question->getType(), [SurveyQuestion::TYPE_OPTIONS, SurveyQuestion::TYPE_CHECKBOXES])) {
foreach ($question->getOptions() as $questionOption) {
$options[] = [
'id' => $questionOption->getId(),
'text' => $questionOption->getOptionText(),
];
}
}
$data['surveyQuestions'][] = [
'id' => $question->getId(),
'type' => $question->getType(),
'text' => $question->getQuestion(),
'options' => $options,
];
}
}
}
}
//-> Google enhanced conversion
$data['customerEmail'] = $order->getBillingEmail();
$data['customerPhone'] = $order->getBillingPhone();
$data['customerFirstName'] = $order->getBillingFirstName();
$data['customerLastName'] = $order->getBillingLastName();
$data['customerStreet'] = $order->getBillingStreet();
$data['customerCity'] = $order->getBillingCity();
$data['customerPostalCode'] = $order->getBillingZip();
$data['customerCountry'] = $order->getBillingCountry();
//<- Google enhanced conversion
$data['trustPilot'] = count($trustPilotData['products']) > 0 ? $trustPilotData : false;
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
}
} else if ($request->getSession()->get('canceledOrderId')) {
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['show_upsell'] = false;
$data['payAtDelivery'] = false;
$data['surveyQuestions'] = [];
$data['externalPayment'] = null;
$data['canceledOrderId'] = $request->getSession()->get('canceledOrderId');
$request->getSession()->remove('canceledOrderId');
return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
}
return $this->redirectToRoute('cart_show');
}
/**
* @Route("/checkout/payment-check/{orderId}/{paymentTypeId}/{gateResponse}", name="checkout_payment_check", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/payment-check/{orderId}/{paymentTypeId}/{gateResponse}", name="checkout_payment_check_locale", defaults={"_locale":""})
* @param Request $request
* @param int $paymentTypeId
* @param int $orderId
* @param int|string $gateResponse
* @return Response
* @throws InvalidArgumentException
*/
public function paymentCheckAction(Request $request, int $paymentTypeId, int $orderId, $gateResponse = 0): Response
{
$data = [];
$data['hideChat'] = true;
$entityManager = $this->getEntityManager();
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
} else {
$checkout = [];
}
if ($request->getSession()->has('paymentOrderId')) {
$paymentOrderId = $request->getSession()->get('paymentOrderId');
} else {
$paymentOrderId = 0;
}
if ($request->getSession()->has('updateOrderId')) {
$updateOrderId = $request->getSession()->get('updateOrderId');
} else {
$updateOrderId = 0;
}
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['payment_verification_valid'] = false;
$data['payment_check_result'] = false;
$data['cetelem_hu_check'] = false;
$data['cetelem_sk_check'] = false;
$data['gopay_check'] = false;
$data['simplepay_check'] = false;
$data['simplepay_canceled'] = false;
$data['simplepay_timeout'] = false;
$data['simplepay_transaction_id'] = false;
$data['gopay_payment_result_link'] = false;
$data['publicOrderLink'] = false;
$data['instacash_check'] = false;
$data['milpay_check'] = false;
$data['pastpay_check'] = false;
$data['klarna_check'] = false;
$data['klarna_check_result'] = false;
$data['orderId'] = 0;
if ((isset($checkout['orderId']) && (int)$checkout['orderId'] > 0 && $checkout['orderId'] == $orderId) || ($paymentOrderId == $orderId) || ($updateOrderId == $orderId)) {
$data['payment_verification_valid'] = true;
/**
* @var Order $order
*/
if (in_array($paymentTypeId, $this->extenalCheckPaymentTypes)) {
$orderRepository = $this->getEntityManager()->getRepository(Order::class);
$order = $orderRepository->findOneById($orderId);
if ($order) {
$domainId = $order->getDomain()->getId();
if ($paymentTypeId == PaymentType::Quatro->value) {
if (!is_null($request->query->get('state'))) {
$state = $request->query->get('state');
switch ($state) {
case 'approved':
$data['payment_check_result'] = false;
$order->setPaymentStatus(0);
break;
case 'signed':
$data['payment_check_result'] = true;
$order->setPaymentStatus(1);
break;
case 'canceled':
$data['payment_check_result'] = false;
$order->setPaymentStatus(2);
break;
default:
$order->setPaymentStatus(2);
$data['payment_check_result'] = false;
}
} else {
$order->setPaymentStatus(2);
$data['payment_check_result'] = false;
}
$entityManager->flush();
}
if ($paymentTypeId == PaymentType::Cetelem->value) {
if ($domainId == 1) { // CETELEM SK - LPC SK
$data['cetelem_sk_check'] = true;
if (!is_null($request->query->get('result')) && is_numeric($request->query->get('result'))) {
$result = $request->query->get('result');
switch ($result) {
case 1:
$order->setPaymentStatus(1);
$data['payment_check_result'] = true;
break;
case 2:
$order->setStatus(Order::STATUS_WAITING);
$order->setPaymentStatus(0);
break;
case 3:
case 5:
$order->setStatus(Order::STATUS_WAITING);
$order->setPaymentStatus(2);
break;
default:
$order->setStatus(Order::STATUS_WAITING);
$order->setPaymentStatus(2);
}
$entityManager->flush();
}
} elseif ($domainId == 3) { // CETELEM HU - FPC HU
if ($gateResponse != 0) {
switch ($gateResponse) {
case md5($order->getId() . '1'): // OK
$order->setPaymentStatus(0);
$data['cetelem_hu_check'] = 1;
break;
case md5($order->getId() . '2'): // Pending
$order->setPaymentStatus(0);
$data['cetelem_hu_check'] = 2;
break;
case md5($order->getId() . '3'): // Rejected
$order->setPaymentStatus(2);
$data['cetelem_hu_check'] = 3;
break;
default:
$order->setPaymentStatus(2);
$data['cetelem_hu_check'] = 3;
}
$entityManager->flush();
}
}
}
if (in_array($paymentTypeId, [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value])) {
$domainIdsForGoPay = [
Domain::DOMAIN_ID_RT_SK,
Domain::DOMAIN_ID_WS_SK,
Domain::DOMAIN_ID_RT_CZ,
Domain::DOMAIN_ID_WS_CZ,
Domain::DOMAIN_ID_RT_EU,
Domain::DOMAIN_ID_WS_EU,
Domain::DOMAIN_ID_WS_HU,
Domain::DOMAIN_ID_RT_HU,
];
// GoPay
if (in_array($domainId, $domainIdsForGoPay)) {
$data['gopay_check'] = true;
$paymentid = $request->query->get('id');
$goPayHelper = $this->getGopayHelper($request);
// Order Helper
$orderHelper = $this->getOrderHelper($request);
$productHelper = $this->getProductHelper($request);
if ($goPayHelper->checkPaymentStatus($paymentid)) {
$data['payment_check_result'] = true;
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
$orderSetting = new OrderSetting();
$orderSetting->setOrder($order);
$orderSetting->setType(OrderSetting::TYPE_PAID_PRICE_BY_CARD);
$orderSetting->setValue($order->getFullPrice());
$entityManager->persist($orderSetting);
if ($order->getPaymentType() != $paymentTypeId) {
$order->setPaymentType($paymentTypeId);
$entityManager->persist($order);
}
// Send Email
$orderHelper->sendPaymentStatusEmail(
'success',
$order,
$productHelper,
$this->getContactInfos(),
$this->getWhiteListCouponCodes()
);
} else {
// Check if paid status is not set already to paid, if yes, do not change it back to failed
if ($order->getPaymentStatus() != Order::PAYMENT_STATUS_PAID) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_FAILED);
// Send Email
/*$orderHelper->sendPaymentStatusEmail(
'fail',
$order,
$productHelper,
$this->getContactInfos(),
$this->getWhiteListCouponCodes()
);*/
$this->getKlaviyoConnect($request)->createNewOrderIsNotPayedDebitCartEvent($order);
// Payment Helper
$gopayHelper = $this->getGopayHelper($request);
// Payment Data
$data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
// Save Order ID
$request->getSession()->set('updateOrderId', $order->getId());
}
}
$entityManager->flush();
}
$data['publicOrderLink'] = $order->getDomain()->getUrl() . $this->generateUrl(
'customer_order_show',
[
'orderId' => $order->getId(),
'token' => $orderRepository->generatePublicLinkToken(
[
'orderId' => $order->getId(),
]
),
]
);
}
if ($order->getPaymentType() == PaymentType::Instacash->value) {
$data['payment_verification_valid'] = true;
$data['instacash_check'] = true;
}
if ($order->getPaymentType() == PaymentType::Milpay->value) {
$data['payment_verification_valid'] = true;
$data['milpay_check'] = true;
}
if ($order->getPaymentType() == PaymentType::PastPay->value) {
$data['pastpay_check'] = true;
switch ($gateResponse) {
case 'success':
$data['payment_verification_valid'] = true;
$data['pastpay_check_result'] = true;
$orderSettingApplicationStatus = OrderSetting::createSetting(
$order,
OrderSetting::TYPE_PAST_PAY_RESERVE,
'CREATED'
);
$entityManager->persist($orderSettingApplicationStatus);
$entityManager->flush();
break;
case 'failure':
$data['pastpay_check_result'] = false;
$domainIdsForGoPay = [
Domain::DOMAIN_ID_RT_SK,
Domain::DOMAIN_ID_WS_SK,
Domain::DOMAIN_ID_RT_CZ,
Domain::DOMAIN_ID_WS_CZ,
Domain::DOMAIN_ID_RT_EU,
Domain::DOMAIN_ID_WS_EU,
];
if ($this->isYear2025() || ($this->getLoginHelper($request)->getLoggedInCustomer() && $this->getLoginHelper($request)->getLoggedInCustomer()->getId() == 11463)) {
$domainIdsForGoPay = array_merge([], $domainIdsForGoPay, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU]);
}
if (in_array($domainId, $domainIdsForGoPay)) {
$gopayHelper = $this->getGopayHelper($request);
$data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
} elseif (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
$simplePayHelper = $this->getSimplePayHelper($request);
$data['simplepay_data'] = $simplePayHelper->createPaymentUrlForOrder($order, $request);
}
$request->getSession()->set('updateOrderId', $order->getId());
break;
}
}
if ($order->getPaymentType() == PaymentType::Klarna->value) {
$data['klarna_check'] = true;
$klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
if ($request->query->has('session_id') && $request->query->has('authorization_token')) {
$klarnaSession = $klarna->getKlarnaHppSession($request->query->get('session_id'));
if (gettype($klarnaSession) == "array" && $klarnaSession['status'] == Klarna::ACCPETED_HPP_STATUS) {
$data['klarna_check_result'] = $this->klarnaAuthorizationCallback($domainId, $order, $request);
if ($data['klarna_check_result'] != false && $data['klarna_check_result']['status'] == 'complete') {
switch ($order->getDomain()->getCurrency()) {
case 'Ft':
$data['currencyCode'] = 'HUF';
break;
case 'Kč':
$data['currencyCode'] = 'CZK';
break;
case '€':
$data['currencyCode'] = 'EUR';
break;
default:
$data['currencyCode'] = 'EUR';
}
$orderData = $this->getOrderHelper($request)->getDataFromEmail(
$order,
$this->getProductHelper($request),
$this->getContactInfos(),
$this->getWhiteListCouponCodes()
);
$data['ecommerce_klarna'] = [
'orderId' => $order->getId(),
'domainName' => $order->getDomain()->getName(),
'currencyCode' => match ($order->getDomain()->getCurrency()) {
'Ft' => $data['currencyCode'] = 'HUF',
'Kč' => $data['currencyCode'] = 'CZK',
default => $data['currencyCode'] = 'EUR',
},
'orderTotal' => $order->getFullPrice(),
'orderTax' => round($order->getTaxOutOfFullPrice(), 2),
'orderShipping' => $order->getShippingPrice(),
'marketingProductsGA4' => $orderData['response']['marketingProductsGA4'],
'customerEmail' => $order->getShippingEmail(),
'customerPhone' => $order->getShippingPhone(),
'customerFirstName' => $order->getShippingFirstName(),
'customerLastName' => $order->getSHippingLastName(),
'customerStreet' => $order->getShippingStreet(),
'customerCity' => $order->getShippingCity(),
'customerPostalCode' => $order->getShippingZip(),
'customerCountry' => $order->getShippingCountry(),
];
}
}
} else {
$klarnaSession = $klarna->getKlarnaSession($request->getSession()->get('klarnaSessionId'));
if ($klarnaSession['status'] == Klarna::INCOMPLETE_STATUS) {
$redirectUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Klarna->value,
'orderId' => $order->getId(),
]);
$redirectUrl = $klarna->createKlarnaUrl($redirectUrl, $request->getSession()->get('klarnaSessionId'));
$gopayHelper = $this->getGopayHelper($request);
$data['klarna_data'] = [
'redirectUrl' => $redirectUrl['redirect_url'],
'gopay_data' => $gopayHelper->getInlineGatewayDataForOrder($order),
];
$data['payment_verification_valid'] = true;
$request->getSession()->set('updateOrderId', $order->getId());
}
}
}
$data['orderId'] = $order->getId();
$data['shippingTypeId'] = $order->getShippingType();
}
}
if ($request->getSession()->has('checkout')) {
$request->getSession()->remove('checkout');
}
if ($request->getSession()->has('paymentOrderId')) {
$request->getSession()->remove('paymentOrderId');
}
if (!in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ])) {
$data['overLimit'] = $order->getFullPrice() > 300;
} elseif (in_array($domainId, [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU])) {
$data['overLimit'] = $order->getFullPrice() > 120_000;
} else {
$data['overLimit'] = $order->getFullPrice() > 7_500;
}
}
return $this->render('AtechNetCoreBundle/Checkout/paymentResult.html.twig', $data);
}
/**
* @Route("/checkout/payment-notification/{orderId}/{paymentTypeId}", name="checkout_payment_notification", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/payment-notification/{orderId}/{paymentTypeId}", name="checkout_payment_notification_locale", defaults={"_locale":""})
* @param Request $request
* @param int $paymentTypeId
* @param int $orderId
* @param int|string $gateResponse
* @return Response
* @throws InvalidArgumentException
*/
public function paymentNotificationAction(Request $request, $paymentTypeId, $orderId)
{
$data = [];
$entityManager = $this->getEntityManager();
$paymentId = $request->query->get('id');
if (is_numeric($paymentId)) {
$order = $entityManager->getRepository(Order::class)->find($orderId);
if ($order) {
$goPayHelper = $this->getGopayHelper($request);
if ($goPayHelper->checkPaymentStatus($paymentId)) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
} else {
if ($order->getPaymentStatus() != Order::PAYMENT_STATUS_PAID) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_FAILED);
}
}
$entityManager->flush();
$data['result'] = true;
}
}
if (!isset($data['result'])) {
$data['result'] = false;
}
return new JsonResponse($data);
}
/**
* @Route("/checkout/payment-ipn-check", name="checkout_payment_ipn_check", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/payment-ipn-check", name="checkout_payment_ipn_check_locale", defaults={"_locale":""})
* @param Request $request
* @throws \Exception
*/
public function paymentIpnCheckAction(Request $request)
{
$simplePayHelper = $this->getSimplePayHelper($request);
$json = file_get_contents('php://input');
$result = $simplePayHelper->getIpnValidationData($request, $json);
if (is_array($result)) {
$response = new Response(
$result['confirmContent'],
Response::HTTP_OK,
[
'Accept-language' => 'EN',
'Content-type' => 'application/json',
'Signature' => $result['signature'],
]
);
} else {
$response = new Response('Invalid data');
}
return $response;
}
/**
* @param Basket $cart
* @param Request $request
* @return array
* @throws \Exception
*/
private function orderSummary(Basket $cart, Request $request)
{
$data = [];
$data['hideChat'] = true;
$entityManager = $this->getEntityManager();
$multiStore = $this->getMultiStoreHelper($request);
$productHelper = $this->getProductHelper($request);
$translator = $this->getDatabaseTranslator($request);
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$useZeroVat = $this->useZeroVat($customer, $request);
$domain = $multiStore->getDomain();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
$placeholder = $this->getImage('placeholder.jpg', '')->resize(Image::PRODUCT_CART_THUMB_WIDTH, Image::PRODUCT_CART_THUMB_HEIGHT);
$data['total'] = 0;
$data['subTotal'] = 0;
$data['items'] = [];
$data['marketingProductsGA4'] = '';
$data['countItems'] = 0;
$data['valid'] = true;
$data['validShipping'] = true;
$data['enableFreeShipping'] = [];
$data['cartId'] = $cart->getId();
$checkout = $request->getSession()->get('checkout');
$checkoutCustomerIsCompany = $this->checkoutCustomerIsCompany($request);
/**
* CHECK IF EXIST A SHIPPING METHOD WITH FREE SHIPPING
*/
$shippingTypesWithFreeShipping = $this->getActiveFreeShippingTypes($domain);
foreach ($cart->getBasketItems() as $index => $item) {
$stock = true;
$product = $productHelper->getStructuredDataForProduct($item->getProduct(), 'cart');
if ($product) {
$image = $placeholder;
if (is_object($product['images'])) {
$image = $this->getImage($product['images'], 'product/' . $product['code'])->resize(Image::PRODUCT_CART_THUMB_WIDTH, Image::PRODUCT_CART_THUMB_HEIGHT);
}
// Cross-sell Attribute Options
$crossSellAttributeOptions = CartHelper::getCrossSellAttributeOptionsByProductTypeId($product['productTypeId'], $domain->getId());
$optionPrice = $optionPriceValue = $optionSpecialValue = 0;
$accessories = '';
/**
* @var AttributeOption $option
*/
foreach ($item->getItemAttributes() as $attribute) {
$option = $attribute->getAttributeOption();
if ($option && !in_array($option->getId(), $this->unWantedAttributes)) {
$optionMeta = $option->getDomainMeta($domain);
if ($optionMeta) {
// Option Price excluding VAT
if ($useZeroVat) {
if ($optionMeta->isDiscounted()) {
$price = $optionMeta->getDomainDiscount();
$optionSpecialValue += $optionMeta->getDomainDiscount();
} else {
$price = $optionMeta->getDomainPrice();
}
$optionPriceValue += $optionMeta->getDomainPrice();
}
// Option Price including VAT
else {
if ($optionMeta->isDiscounted()) {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$price = $domain->createVatPrice($optionMeta->getDiscount(), 1.27);
$optionSpecialValue += $domain->createVatPrice($optionMeta->getDiscount(), 1.27);
} else {
$price = $optionMeta->getDomainVatDiscount();
$optionSpecialValue += $optionMeta->getDomainVatDiscount();
}
} else {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$price = $domain->createVatPrice($optionMeta->getPrice(), 1.27);
} else {
$price = $optionMeta->getDomainVatPrice();
}
}
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$optionPriceValue += $domain->createVatPrice($optionMeta->getPrice(), 1.27);
} else {
$optionPriceValue += $optionMeta->getDomainVatPrice();
}
}
// Cross-sell Attribute Options Calculated Price
if (isset($crossSellAttributeOptions[$option->getId()])) {
if (isset($crossSellAttributeOptions[$option->getId()]['percentPrice'])) {
$price = $domain->createVatPrice((($item->getPriceWithAttributesForDomainWithException($domain, $option) * $crossSellAttributeOptions[$option->getId()]['percentPrice']) / 100), 1.);
}
}
$accessories .= $option->getAttribute()->getTitle($translator) . ': ' . $option->getTitle($translator) . '<br>';
$optionPrice += $price;
}
}
}
// Price
$priceValue = $specialValue = 0;
if ($useZeroVat) {
if ($product['isDiscounted']) {
$price = $specialValue = $product['rawDiscountPrice'];
} else {
$price = $product['price'];
}
$priceValue = $product['price'];
} else {
if ($product['isDiscounted']) {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$price = $specialValue = $domain->createVatPrice($product['discountPrice'], 1.27);
} else {
$price = $specialValue = $product['discountVatPrice'];
}
} else {
if (isset($customer) && $customer->getId() == Customer::MAXMEDIA_KFT_ID) {
$price = $domain->createVatPrice($product['rawPrice'], 1.27);
} else {
$price = $product['vatPrice'];
}
}
$priceValue = $product['vatPrice'];
}
if ($product['availableQty'] < $item->getQuantity() && !$product['isReservable'] && $product['outOfStockStatus'] !== Product::OutOfStockStatus_VisibleShadow) {
$stock = $data['valid'] = false;
}
if (
$domain->getId() == Domain::DOMAIN_ID_RT_EU &&
is_array($checkout) &&
array_key_exists('billingCountry', $checkout) &&
$checkoutCustomerIsCompany
) {
$country = $checkout['billingCountry'];
$price = $domain->createWithoutVatPriceFromVatPrice($price, $country);
$optionPrice = $domain->createWithoutVatPriceFromVatPrice($optionPrice, $country);
}
$data['items'][] = [
'id' => $item->getId(),
'productId' => $product['id'],
'stock' => $stock,
'model' => $product['code'],
'name' => ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'],
'image' => $image,
'price' => ($price + $optionPrice) * $item->getQuantity(),
'href' => $this->url($request)->link('product', [
'product_id' => $product['id'],
'isBazaar' => $product['isBazaar'] ?? 0
]),
'accessories' => $accessories,
'quantity' => $item->getQuantity(),
];
$data['subTotal'] += ($price + $optionPrice) * $item->getQuantity();
$data['countItems'] += (int)$item->getQuantity();
$data['marketingProductsGA4'] .= ($data['marketingProductsGA4'] !== '' ? ',' : '') . '{ item_id: \'' . $product['code'] . '\', item_name: \'' . ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'] . '\', item_brand: \'' . $product['vendor'] . '\', item_category: \'' . $product['productType'] . '\', quantity: ' . $item->getQuantity() . ', discount: \'' . (round(($specialValue + $optionSpecialValue), $data['precision']) > 0 ? (round(($priceValue + $optionPriceValue), $data['precision']) - round(($specialValue + $optionSpecialValue), $data['precision'])) : 0) . '\', price: \'' . round(($priceValue + $optionPriceValue), $data['precision']) . '\', index: ' . $index . '}';
}
$filteredShippingTypes = array_filter($shippingTypesWithFreeShipping, function ($shippingType) use ($product) {
/** @var DomainShippingType $shippingType */
if (empty($shippingType->getFreeShippingProductTypes())) {
return true;
}
return in_array($product['productTypeId'], $shippingType->getFreeShippingProductTypes(), true);
});
if (count($filteredShippingTypes) > 0) {
/** @var DomainShippingType $shippingType */
foreach ($filteredShippingTypes as $shippingType) {
$data['enableFreeShipping'][] = $shippingType->getType();
}
}
}
$data['estimation'] = true;
$data['coupon'] = '';
$data['discount'] = 0;
$data['shippingCost'] = $data['paymentCost'] = $data['packageFee'] = null;
if ($domain->getId() == Domain::DOMAIN_ID_RT_HU) {
$packageFeeProduct = $entityManager->getRepository(Product::class)->findOneById(Product::MPL_PACKAGE_FEE_PRODUCT_ID);
$data['packageFee'] = [
'title' => 'Package fee',
'price' => $packageFeeProduct->getDomainMeta($domain)->getCurrentVatPrice(),
];
}
$mplIsSelected = false;
if ($request->getSession()->has('checkout')) {
$checkout = $request->getSession()->get('checkout');
// Selected Shipping Method
if (isset($checkout['shippingMethodId']) && (int)$checkout['shippingMethodId'] > 0) {
$shippingMethod = $entityManager->getRepository(DomainShippingType::class)->findOneBy([
'id' => $checkout['shippingMethodId'],
'domain' => $multiStore->getDomainId(),
]);
if ($shippingMethod) {
// Shipping Cost
$data['shippingCost'] = in_array($shippingMethod->getType(), $data['enableFreeShipping']) ? 0 : $shippingMethod->getPrice();
// Shipping Type
$data['shippingType'] = $shippingMethod->getType();
// Free Shipping
if (((float)$shippingMethod->getFreeShipLimit() > 0 && (float)$shippingMethod->getFreeShipLimit() < $data['subTotal'])) {
$data['shippingCost'] = 0;
}
$data['estimation'] = false;
// Validate Pickup Point availability
if ($shippingMethod->getType() == DomainShippingType::ShippingType_PICKUP_POINT_Id) {
if (!$cart->isPickupPointAvailable()) {
$data['validShipping'] = false;
}
}
if ($shippingMethod->getType() == DomainShippingType::SHIPPING_TYPE_MPL_ID) {
$mplIsSelected = true;
}
}
} // Default Shipping Method
else {
// Shipping Cost
$data['shippingCost'] = null;
$data['estimation'] = false;
}
if (isset($checkout['paymentMethodId']) && (int)$checkout['paymentMethodId'] > 0) {
$paymentMethod = $entityManager->getRepository(DomainPaymentType::class)->findOneBy([
'id' => $checkout['paymentMethodId'],
'domain' => $multiStore->getDomainId(),
]);
if ($paymentMethod) {
$data['paymentCost'] = $paymentMethod->getPrice();
}
}
$cashonDeliveryPaymentTypes = [
PaymentType::CashOnDelivery->value,
PaymentType::CashOnDelivery3Percent->value,
];
if (isset($checkout['paymentMethodTypeId']) && in_array((int)$checkout['paymentMethodTypeId'], $cashonDeliveryPaymentTypes)) {
$domainPaymentType = $entityManager->getRepository(DomainPaymentType::class)->findOneBy(
[
'domain' => $multiStore->getDomainId(),
'type' => $checkout['paymentMethodTypeId'],
]
);
if ($domainPaymentType) {
$data['cashOnDeliveryProductItem'] = [
'title' => $translator->trans('Cash on delivery'),
'price' => $domainPaymentType->getPrice(),
];
}
}
} else {
$data['shippingCost'] = null;
$data['estimation'] = false;
}
// Coupon
if (isset($checkout['coupon']['code']) && $checkout['coupon']['code'] != '') {
$data['coupon'] = $checkout['coupon']['code'];
$coupon = $entityManager->getRepository(Coupon::class)->findOneBy([
'code' => $checkout['coupon']['code'],
'domain' => $domain,
]);
if ($coupon && $cart) {
// Set Email
if (!empty($checkout['email'])) {
$cart->setEmail($checkout['email']);
} else {
$cart->setEmail(null);
}
// Coupon Free Shipping
$isCouponApplicableForFreeShipping = CartHelper::isCouponApplicableForFreeShipping($coupon, $cart, $entityManager);
// Coupon Discount
$isCouponValidForBasket = CartHelper::isCouponValidForBasket($coupon, $cart, $entityManager);
if ($isCouponValidForBasket !== false || $isCouponApplicableForFreeShipping) {
$data['discount'] = (float)$isCouponValidForBasket;
} else {
$data['coupon'] = '';
}
// Free Shipping
if ($isCouponApplicableForFreeShipping) {
$data['shippingCost'] = 0;
}
} else {
$data['coupon'] = '';
}
} else {
$data['coupon'] = '';
}
if (isset($checkout['3_percent_discount']) && $checkout['3_percent_discount'] && $data['discount'] == 0) {
if ($cart) {
$data['discount'] = CartHelper::getPercentDiscountForBasket($cart, 3);
$data['three_percent_partner_discount'] = true;
}
}
$data['total'] = $data['subTotal'] + $data['shippingCost'] + $data['paymentCost'] - $data['discount'];
if ($mplIsSelected) {
$data['total'] += $data['packageFee']['price'];
}
$data['currency_ISO'] = $this->getCurrencyISOForm($domain->getCurrency());
// Basket expires in...
$cartUpdated = clone $cart->getUpdated();
$data['expire'] = $cartUpdated->add(new \DateInterval("PT" . self::TIMEOUT . "H"))->format('Y-m-d H:i:s');
return $data;
}
/**
* @Route("/checkout/success-upsell", name="checkout_add_upsell", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/success-upsell", name="checkout_add_upsell_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
*/
public function successUpsellAction(Request $request)
{
$response = [
'result' => 'fail',
];
$entityManager = $this->getEntityManager();
$req = $request->request;
$orderId = $req->get('orderId');
$upsellType = $req->get('upsellType');
$price = $req->get('price');
$want = $req->get('want');
if (is_numeric($orderId)) {
$order = $entityManager->getRepository(Order::class)->findOneById($orderId);
if ($order) {
$centralisUser = $this->getCentralisUser();
$orderUpsellSetting = $order->getUpsellStatSetting();
if ($want == 1) {
if (in_array($upsellType, [1, 2])) {
$text = 'YES, +4GB RAM UPSELL ' . $price;
}
if ($upsellType == 3) {
$text = 'YES, CLEANER KIT ' . $price;
}
if ($orderUpsellSetting) {
$orderUpsellSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_WANT);
}
} else {
$text = 'NO UPSELL';
if ($orderUpsellSetting) {
$orderUpsellSetting->setValue(OrderSetting::SUB_TYPE_UPSELL_STATS_WANT);
}
}
$orderComment = new OrderComment();
$orderComment->setOrder($order);
$orderComment->setText($text);
$orderComment->isDeletableByUser($centralisUser);
$orderComment->setCreatedBy($centralisUser);
$orderComment->setType(OrderComment::TYPE_FOR_PREPARATION);
$entityManager->persist($orderComment);
$entityManager->flush();
$response = [
'result' => 'success',
];
}
}
return new JsonResponse($response);
}
/**
* @param float $originalPrice
* @param int $discountPercentage
* @param string $domainLanguageCode
* @return float|int
*/
private function calculateDiscountedPrice($originalPrice, $discountPercentage, $domainLanguageCode)
{
$discountedPrice = $originalPrice * (1 - ($discountPercentage / 100));
if ($domainLanguageCode == 'hu') {
$discountedPrice = ceil($discountedPrice / 10) * 10;
}
if ($domainLanguageCode == 'cz') {
$discountedPrice = round($discountedPrice);
}
return $discountedPrice;
}
/**
* @Route("/checkout/order/{orderId}/create-stock-reservation", name="checkout_add_stock_movement", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/order/{orderId}/create-stock-reservation", name="checkout_add_stock_movement_locale", defaults={"_locale":""})
* @param Request $request
* @param int $orderId
*
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function createStockMovementAction(Request $request, $orderId): JsonResponse
{
$json = [];
$entityManager = $this->getEntityManager();
/** @var Order $order */
$order = $entityManager->getRepository(Order::class)->findOneById($orderId);
//> Order Statistics
// Manager's Pick
$managersPick = $this->getHiglightedFlashSaleData($request, $order->getDomain());
// Record
OrderStatistics::record($order, $entityManager, $managersPick);
//< Order Statistics
// AntiVirus comment
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_RT_HU ]) ) {
$antiVirusProductId = $order->getDomain()->getId() == Domain::DOMAIN_ID_RT_SK
? Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID
: Product::GDATA_90_DAY_TRIAL_PRODUCT_ID;
/**
* @var OrderItem $antiVirusOrderItem
*/
$antiVirusOrderItem = $order->getOrderItems()
->filter(
function (OrderItem $orderItem) use ($antiVirusProductId) {
return $orderItem->getProduct()->getId() == $antiVirusProductId;
}
)
->last();
if ( $antiVirusOrderItem ) {
// ESET
if ( $antiVirusProductId == Product::ESET_NOD32_90_DAY_TRIAL_PRODUCT_ID ) {
$prefix = 'ESET-trial#';
}
// G DATA
else {
$prefix = 'GDATA-trial#';
}
$orderCommentEsetSerialTexts = $entityManager
->createQuery("SELECT oc.text
FROM AtechNetCoreBundle:OrderComment oc
WHERE oc.type = :typeInstallation AND oc.text LIKE '" . $prefix . "%'")
->setParameter('typeInstallation', OrderComment::TYPE_FOR_INSTALLATION)
->getResult()
;
$usedEsetSerialList = [];
foreach ( $orderCommentEsetSerialTexts as $serials ) {
$serialKey = explode(',', str_replace($prefix, '', $serials['text']));
foreach ( $serialKey as $key => $keyValue ) {
if ( str_contains($keyValue, 'email') ) {
$serialKey[$key] = substr($keyValue, 0, strpos($keyValue, "; email"));
}
}
$usedEsetSerialList = array_merge([], $serialKey, $usedEsetSerialList);
}
$productRepo = $entityManager->getRepository(Product::class);
$availableEsetStockItemList = $productRepo->getStockItems(
$antiVirusOrderItem->getProduct(),
[
'inStock' => true,
'available' => true,
'filterEsetCommentSerials' => $usedEsetSerialList,
]
);
if ( count($availableEsetStockItemList) < $antiVirusOrderItem->getQuantity() ) {
$orderCommentForEsetProductText = "Serial Number WARNING: not enough serial numbers available for this order!";
} else {
$orderCommentForEsetProductText = $prefix;
$esetStockItemSerials = [];
for ( $i = 0; $i < $antiVirusOrderItem->getQuantity(); $i++ ) {
$esetStockItemSerials[] = $availableEsetStockItemList[$i]->getSerialNumber();
}
$orderCommentForEsetProductText .= implode(',', $esetStockItemSerials) . '; email#' . $order->getCustomer()->getEmail();
}
$orderComment = new OrderComment();
$orderComment->setOrder($order);
$orderComment->setCreatedBy($this->getCentralisUser());
$orderComment->setType(OrderComment::TYPE_FOR_INSTALLATION);
$orderComment->setText($orderCommentForEsetProductText);
$entityManager->persist($orderComment);
$entityManager->flush();
}
}
// Replace Windows Attributes
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK, Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
$refresh = false;
foreach ( $order->getOrderItems() as $orderItem ) {
foreach ( $orderItem->getItemAttributes() as $orderItemAttribute ) {
if ( $orderItemAttribute->getAttributeOption()->getAttribute()->getId() == Attribute::ATTRIBUTE_ID_ACCESSORY_OS ) {
$windowsAttributeOption = null;
// Windows 10 Pro
if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_10_PRO ) {
// HU
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_HU);
}
// SK
elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_SK);
}
// CZ
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_PRO_CZ);
}
}
// Windows 11 Pro
if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_11_PRO ) {
// HU
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_HU);
}
// SK
elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_SK);
}
// CZ
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_PRO_CZ);
}
}
// Windows 10 Home
if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_10_HOME ) {
// HU
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_HU);
}
// SK
elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_SK);
}
// CZ
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN10_HOME_CZ);
}
}
// Windows 11 Home
if ( $orderItemAttribute->getAttributeOption()->getId() == AttributeOption::ATTRIBUTE_OPTION_ID_WINDOWS_11_HOME ) {
// HU
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_HU);
}
// SK
elseif ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_SK);
}
// CZ
if ( in_array($order->getDomain()->getId(), [ Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ ]) ) {
$windowsAttributeOption = $entityManager->getRepository(AttributeOption::class)->findOneById(AttributeOption::ATTRIBUTE_OPTION_ID_WIN11_HOME_CZ);
}
}
// Update
if ( $windowsAttributeOption ) {
$orderItemAttribute->setAttributeOption($windowsAttributeOption);
$entityManager->flush();
$refresh = true;
}
}
}
}
if ( $refresh ) {
$entityManager->refresh($order);
}
}
if (
/*$this->getEnvironment() == 'prod' &&*/
$order &&
is_null($order->getLastStockMovement())
) {
$stockItems = $request->getSession()->get('stockItemCodes');
$entityManager->getRepository(StockMovement::class)->createOrderStockMovement($order, $this->getCentralisUser(), $stockItems);
$request->getSession()->remove('stockItemCodes');
}
return new JsonResponse($json);
}
/**
* @Route("/checkout/order/{orderId}/active-campaign-sync", name="checkout_sync_active_campaign")
* @param Request $request
* @param int $orderId
*
* @return JsonResponse
*/
public function syncActiveCampaignAction(Request $request, $orderId): JsonResponse
{
$json = [];
$entityManager = $this->getEntityManager();
$order = $entityManager->getRepository(Order::class)->findOneById($orderId);
if (
$this->getEnvironment() == 'prod' &&
$order &&
in_array($order->getDomain()->getId(), Domain::DOMAIN_IDS_FOR_ACTIVE_CAMPAIGN)
) {
$activeCampaign = $this->getActiveCampaignConnect();
if (!$this->getLoginHelper($request)->getLoggedInCustomerId()) {
$activeCampaign->createContactFromCentralisCustomer($order->getCustomer());
} else {
$activeCampaign->updateContactFromCentralisCustomer($order->getCustomer());
}
// Finish abandoned cart
if ($request->getSession()->get('abandonedCart')) {
$activeCampaign->finishAbandonedCart($order, $request->getSession()->get('abandonedCart'));
} else {
$activeCampaign->createEcomOrderFromCentralisOrder($order);
}
$request->getSession()->remove('abandonedCart');
}
return new JsonResponse($json);
}
/**
* @Route("/checkout/order-summary-ajax", name="checkout_order_summary_ajax", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/order-summary-ajax", name="checkout_order_summary_ajax_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
*/
public function orderSummaryAjaxAction(Request $request): JsonResponse
{
$cart = $this->getCart($request->getSession()->get('cartId'));
$orderSummary = $this->orderSummary($cart, $request);
return new JsonResponse($orderSummary);
}
/**
* @Route("/checkout/pay-at-delivery", name="checkout_pay_at_delivery", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/pay-at-delivery", name="checkout_pay_at_delivery_locale", defaults={"_locale":""})
*
* @param Request $request
* @return RedirectResponse
* @throws NotSupported
* @throws ORMException
* @throws \Doctrine\ORM\ORMException
* @throws OptimisticLockException
*/
public function payAtDeliveryAction(Request $request): RedirectResponse
{
$entityManager = $this->getEntityManager();
// Order ID - Session
if ($request->getSession()->has('updateOrderId')) {
$orderId = (int)$request->getSession()->get('updateOrderId');
} else {
$orderId = 0;
}
$_orderId = (int)$request->query->get('orderId');
if ($orderId != $_orderId) {
return $this->redirectToRoute('not_found');
}
$orderRepository = $entityManager->getRepository(Order::class);
$multiStore = $this->getMultiStoreHelper($request);
/**
* @var Order $order
*/
$order = $orderRepository->findOneById($orderId);
if (empty($order)) {
return $this->redirectToRoute('not_found');
}
if ($order->getPaymentType() == PaymentType::CashOnDelivery->value) {
return $this->redirectToRoute('checkout_success_update');
}
$order->setPaymentType(PaymentType::CashOnDelivery->value);
$order->setPaymentStatus(Order::PaymentStatus_Pending);
$domainPaymentType = $entityManager->getRepository(DomainPaymentType::class)->findOneBy([
'domain' => $multiStore->getDomainId(),
'type' => PaymentType::CashOnDelivery->value,
]);
$order->setPaymentPrice($domainPaymentType->getPrice());
if ((float)$order->getPaymentPrice() > 0) {
$product = $entityManager->getRepository(Product::class)->findOneById(Product::CASH_ON_DELIVERY_PRODUCT_ID);
$orderItem = new OrderItem();
$orderItem->setProduct($product);
$orderItem->setPrice((float)$order->getPaymentPrice());
$orderItem->setQuantity(1);
$orderItem->setPosition($order->getOrderItems()->count());
$orderItem->setOrder($order);
// Save Order Product
$entityManager->persist($orderItem);
$entityManager->flush();
// Add cash on delivery to stock movement
$stockMovement = $order->getStockMovements()->first();
if ($stockMovement) {
$stockMovementItem = new StockMovementItem();
$stockMovementItem->setMovement($stockMovement);
$stockMovementItem->setProduct($product);
$stockMovementItem->setPrice((float)$order->getPaymentPrice() / (1 + $order->getDomain()->getVat() / 100));
$stockMovementItem->setOrderItem($orderItem);
$stockMovementItem->setQuantity(1);
$entityManager->persist($stockMovementItem);
$entityManager->flush();
$entityManager->refresh($stockMovement);
$totalPrice = 0;
foreach ($stockMovement->getMovementItems() as $movementItem) {
$totalPrice += $movementItem->getTotalPricePerItem();
}
$stockMovement->setTotalPrice($totalPrice);
$entityManager->flush();
}
}
$order->setFullPrice();
$entityManager->flush();
return $this->redirectToRoute('checkout_success_update');
}
/**
* @Route("/checkout/pay-bank-transfer", name="checkout_pay_bank_transfer", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/pay-bank-transfer", name="checkout_pay_bank_transfer_locale", defaults={"_locale":""})
*
* @param Request $request
* @return RedirectResponse|void
* @throws NotSupported
*/
public function payVieBankTransferAction(Request $request)
{
$entityManager = $this->getEntityManager();
// Order ID - Session
if ($request->getSession()->has('updateOrderId')) {
$orderId = (int)$request->getSession()->get('updateOrderId');
} else {
$orderId = 0;
}
$_orderId = (int)$request->query->get('orderId');
if ($orderId != $_orderId) {
return $this->redirectToRoute('not_found');
}
$orderRepository = $entityManager->getRepository(Order::class);
/**
* @var Order $order
*/
$order = $orderRepository->findOneById($orderId);
if (empty($order)) {
return $this->redirectToRoute('not_found');
}
if (in_array($order->getPaymentType(), [PaymentType::BankTransfer->value, PaymentType::BankTransfer3Percent->value])) {
return $this->redirectToRoute('checkout_success_update');
}
$order->setPaymentType(PaymentType::BankTransfer->value);
$order->setPaymentStatus(Order::PaymentStatus_Pending);
$entityManager->flush();
return $this->redirectToRoute('checkout_success_update');
}
/**
* @Route("/checkout/success/update", name="checkout_success_update", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/success/update", name="checkout_success_update_locale", defaults={"_locale":""})
*
* @param Request $request
* @return RedirectResponse|Response
* @throws \Exception
*/
public function successUpdateAction(Request $request)
{
$data = [];
$data['hideChat'] = true;
// Order ID - Session
if ($request->getSession()->has('updateOrderId')) {
$orderId = (int)$request->getSession()->get('updateOrderId');
} else {
$orderId = 0;
}
if ($orderId > 0) {
$entityManager = $this->getEntityManager();
$productHelper = $this->getProductHelper($request);
$order = $entityManager->getRepository(Order::class)->findOneById($orderId);
if ($order) {
$domain = $order->getDomain();
$orderHelper = $this->getOrderHelper($request);
$emailSendingResult = $orderHelper->sendOrderEmail(
$order,
$productHelper,
$this->getContactInfos(),
$this->getWhiteListCouponCodes(),
true
);
$data['orderId'] = $order->getId();
$data['email'] = $order->getBillingEmail();
$data['domainName'] = $domain->getName();
$data['orderTotal'] = $emailSendingResult['total'];
$data['orderTax'] = round($data['orderTotal'] - $order->getTaxOutOfFullPrice(), 2);
switch ($domain->getCurrency()) {
case 'Ft':
$data['currencyCode'] = 'HUF';
break;
case 'Kč':
$data['currencyCode'] = 'CZK';
break;
case '€':
$data['currencyCode'] = 'EUR';
break;
default:
$data['currencyCode'] = 'EUR';
}
$data['surveyQuestions'] = [];
$data['show_upsell'] = false;
$data['externalPayment'] = null;
$data['gopay_data'] = null;
$data['simplepay_data'] = null;
$data['payAtDelivery'] = true;
if ($request->getSession()->has('checkout')) {
$request->getSession()->remove('checkout');
}
if ($request->getSession()->has('paymentOrderId')) {
$request->getSession()->remove('paymentOrderId');
}
if ($request->getSession()->has('updateOrderId')) {
$request->getSession()->remove('updateOrderId');
}
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Checkout/success.html.twig', $data);
}
}
if ($request->getSession()->has('checkout')) {
$request->getSession()->remove('checkout');
}
if ($request->getSession()->has('paymentOrderId')) {
$request->getSession()->remove('paymentOrderId');
}
if ($request->getSession()->has('updateOrderId')) {
$request->getSession()->remove('updateOrderId');
}
return $this->redirectToRoute('cart_show');
}
/**
* @Route("/checkout/instacash-webhook/{token}", name="checkout_instacash_webhook", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/instacash-webhook/{token}", name="checkout_instacash_webhook_locale", defaults={"_locale":""})
*
* @param Request $request
* @param string $token
* @return JsonResponse
* @throws NotSupported
* @throws ORMException
* @throws OptimisticLockException
*/
public function intacashWebhookAction(Request $request, string $token): JsonResponse
{
$instacashToken = '328943154gjfvr-emvdscf894j31gt3df9e-wqruf4938tfds13t';
if ($token != $instacashToken) {
throw new AccessDeniedException('Access denied');
}
$response = 'error on sync';
$requestContent = $request->getContent();
$requestBody = json_decode($requestContent, true);
if (isset($requestBody['application']['status']) && in_array($requestBody['application']['status'], Instacash::getApplicationStatusChoices())) {
$status = $requestBody['application']['status'];
$applicationId = $requestBody['application']['id'];
$transactions = [];
if (isset($requestBody['deal']) && isset($requestBody['deal']['transactions'])) {
$transactions = $requestBody['deal']['transactions'];
}
$orderApplicationIdStatus = $this->getEntityManager()->getRepository(OrderSetting::class)->findOneBy([
'type' => OrderSetting::TYPE_INSTACASH_APPLICATION_ID,
'value' => $applicationId,
]);
if ($orderApplicationIdStatus) {
$order = $orderApplicationIdStatus->getOrder();
$entityManager = $this->getEntityManager();
$orderApplicationStatusSetting = $order->getInstacashApplicationStatusSetting();
if ((!$orderApplicationStatusSetting && $status == 'COMPLETED') ||
($orderApplicationStatusSetting && $orderApplicationStatusSetting->getValue() != 'COMPLETED' && $status == 'COMPLETED')) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PARTIAL);
}
if ($status == 'COMPLETED' && count($transactions) > 0) {
$paid = 0.0;
$alreadyAddedPayments = $order->getInstacashPaymentSettings();
foreach ($transactions as $transaction) {
if ($transaction['status'] != 'PAID') {
continue;
}
$transactionSum = (float)$transaction['sum'];
$paid = $paid + $transactionSum;
$createPaymentSetting = true;
$paymentAlreadyAdded = false;
foreach ($alreadyAddedPayments as $key => $alreadyAddedPayment) {
if ($alreadyAddedPayment->getValue() == $transactionSum && !$paymentAlreadyAdded) {
$createPaymentSetting = false;
unset($alreadyAddedPayments[$key]);
$paymentAlreadyAdded = true;
}
}
if ($createPaymentSetting) {
$instacashPaymentSetting = OrderSetting::createSetting(
$order,
OrderSetting::TYPE_INSTACASH_PAYMENT,
$transactionSum
);
$entityManager->persist($instacashPaymentSetting);
if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_SK) {
if (count($transactions) > 1 && $order->getDocuments()->count() > 0) {
$document = $order->getDocuments()->first();
$documentPayment = new DocumentPayment();
$sequence = '';
if (isset($transaction['seq'])) {
$sequence = $transaction['seq'];
}
$centralisUser = $entityManager->getRepository(User::class)->findOneById(User::CENTRALIS_USER_ID);
$documentPayment->setPaymentSource(DocumentPayment::INSTACASH);
$documentPayment->setPaymentDate(new \DateTime());
$documentPayment->setNote('Instacash payment ' . $sequence);
$documentPayment->setAmount($transactionSum);
$documentPayment->setCreatedBy($centralisUser);
$documentPayment->setDocument($document);
$entityManager->persist($documentPayment);
}
}
if ($order->getDomain()->getId() == Domain::DOMAIN_ID_RT_HU) {
if (count($transactions) > 1 && $order->getBillingoDocuments()->count() > 0) {
$customerBillingoData = $order->getBillingoDocuments()->first();
$billingoPayment = new BillingoPayment();
$sequence = '';
if (isset($transaction['seq'])) {
$sequence = $transaction['seq'];
}
$billingoPayment->setPaymentSource(DocumentPayment::INSTACASH);
$billingoPayment->setPaymentDate(new \DateTime());
$billingoPayment->setNote('Instacash payment ' . $sequence);
$billingoPayment->setAmount($transactionSum);
$centralisUser = $entityManager->getRepository(User::class)->findOneById(User::CENTRALIS_USER_ID);
$entityManager->getRepository(BillingoPayment::class)->createBillingoPayment($this->getBillingo(), $customerBillingoData, $billingoPayment, $centralisUser);
}
}
}
}
if ($paid == $order->getFullPrice()) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
} elseif ($paid > 0) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PARTIAL);
} else {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PENDING);
}
}
if ($orderApplicationStatusSetting) {
$orderApplicationStatusSetting->setValue($status);
} else {
$orderSettingApplicationStatus = OrderSetting::createSetting(
$order,
OrderSetting::TYPE_INSTACASH_APPLICATION_STATUS,
$status
);
$entityManager->persist($orderSettingApplicationStatus);
}
$entityManager->flush();
$response = 'synced';
}
}
return new JsonResponse($response);
}
/**
* @Route("/checkout/milpay-webhook/{token}", name="checkout_milpay_webhook", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/checkout/milpay-webhook/{token}", name="checkout_milpay_webhook_locale", defaults={"_locale":""})
*
* @param Request $request
* @param string $token
* @return JsonResponse
* @throws NotSupported
* @throws ORMException
* @throws OptimisticLockException
*/
public function milpayWebhookAction(Request $request, string $token): JsonResponse
{
if ($token != Milpay::MILPAY_WEBHOOK_TOKE) {
throw new AccessDeniedException('Access denied');
}
$response = 'error on sync';
$requestContent = $request->getContent();
$requestBody = json_decode($requestContent, true);
if (isset($requestBody['application']['status']) && in_array($requestBody['application']['status'], Milpay::getApplicationStatusChoices())) {
$status = $requestBody['application']['status'];
$applicationId = $requestBody['application']['id'];
$transactions = [];
if (isset($requestBody['deal']) && isset($requestBody['deal']['transactions'])) {
$transactions = $requestBody['deal']['transactions'];
}
$orderApplicationIdStatus = $this->getEntityManager()->getRepository(OrderSetting::class)->findOneBy([
'type' => OrderSetting::TYPE_MILPAY_APPLICATION_ID,
'value' => $applicationId,
]);
if ($orderApplicationIdStatus) {
$order = $orderApplicationIdStatus->getOrder();
$entityManager = $this->getEntityManager();
$orderApplicationStatusSetting = $order->getMilpayApplicationStatusSetting();
/*if ((!$orderApplicationStatusSetting && $status == 'COMPLETED') ||
($orderApplicationStatusSetting && $orderApplicationStatusSetting->getValue() != 'COMPLETED' && $status == 'COMPLETED')) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
}*/
if ($status == 'COMPLETED' && count($transactions) > 0) {
$alreadyAddedPayments = $order->getMilpayPaymentSettings();
if (empty($alreadyAddedPayments)) {
foreach ($transactions as $transaction) {
if ($transaction['status'] != 'PAID') {
continue;
}
$milpayPaymentSetting = OrderSetting::createSetting(
$order,
OrderSetting::TYPE_MILPAY_PAYMENT,
$order->getFullPrice()
);
$entityManager->persist($milpayPaymentSetting);
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
break;
}
}
}
if ($orderApplicationStatusSetting) {
$orderApplicationStatusSetting->setValue($status);
} else {
$orderSettingApplicationStatus = OrderSetting::createSetting(
$order,
OrderSetting::TYPE_MILPAY_APPLICATION_STATUS,
$status
);
$entityManager->persist($orderSettingApplicationStatus);
}
$entityManager->flush();
$response = 'synced';
}
}
return new JsonResponse($response);
}
private function remove_emoji($string)
{
$symbols = "\x{1F100}-\x{1F1FF}" // Enclosed Alphanumeric Supplement
. "\x{1F300}-\x{1F5FF}" // Miscellaneous Symbols and Pictographs
. "\x{1F600}-\x{1F64F}" //Emoticons
. "\x{1F680}-\x{1F6FF}" // Transport And Map Symbols
. "\x{1F900}-\x{1F9FF}" // Supplemental Symbols and Pictographs
. "\x{2600}-\x{26FF}" // Miscellaneous Symbols
. "\x{2700}-\x{27BF}"; // Dingbats
return preg_replace('/[' . $symbols . ']+/u', '', $string);
}
public function klarnaAuthorizationCallback(int $domainId, Order $order, Request $request)
{
$orderSetting = $order->getKlarnaPaymentSessionIdSetting(false);
$klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
$klarnaOrder = $klarna->createKlarnaOrder($klarna->getKlarnaSession($orderSetting->getValue()));
$klarna->updateKlarnaMerchantReference($order->getId(), $klarnaOrder['order_id']);
$getKlarnaOrderDetails = $klarna->getKlarnaOrder($klarnaOrder['order_id']);
$sessionData = $klarna->getKlarnaSession($orderSetting->getValue());
if ($sessionData['status'] == Klarna::ACCEPTED_STATUS) {
$order->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
$this->getEntityManager()->persist($order);
$klarnaOrderSettingOrderId = new OrderSetting();
$klarnaOrderSettingOrderId->setOrder($order);
$klarnaOrderSettingOrderId->setType(OrderSetting::TYPE_KLARNA_ORDER_ID);
$klarnaOrderSettingOrderId->setValue($getKlarnaOrderDetails['klarna_reference']);
$this->getEntityManager()->persist($klarnaOrderSettingOrderId);
foreach ($order->getAllKlarnaPaymentSessionIdSettings() as $setting) {
$klarna->deleteKlarnaSession($setting->getValue());
$this->getEntityManager()->remove($setting);
}
$this->getEntityManager()->flush();
}
return [
'status' => $sessionData['status'],
'orderID' => $getKlarnaOrderDetails['klarna_reference'],
];
}
/**
* @param Domain $domain
* @return float|int|mixed|string
*/
public function getActiveFreeShippingTypes(Domain $domain): mixed
{
return $this->getEntityManager()->createQueryBuilder()
->select('dst')
->from('AtechNetCoreBundle:DomainShippingType', 'dst')
->where('dst.domain = :domain')
->andWhere('dst.freeShippingStartDate IS NOT NULL AND dst.freeShippingEndDate IS NOT NULL')
->andWhere('dst.freeShippingStartDate <= :now AND dst.freeShippingEndDate >= :now')
->setParameters([
'domain' => $domain->getId(),
'now' => (new \DateTime())->format('Y-m-d'),
])
->getQuery()
->getResult();
}
/**
* @param Domain $domain
* @return float|int|mixed|string
*/
public function getActiveFreeShippingTypeIds(Domain $domain): mixed
{
return $this->getEntityManager()->createQueryBuilder()
->select('dst.id')
->from('AtechNetCoreBundle:DomainShippingType', 'dst')
->where('dst.domain = :domain')
->andWhere('dst.freeShippingStartDate IS NOT NULL AND dst.freeShippingEndDate IS NOT NULL')
->andWhere('dst.freeShippingStartDate <= :now AND dst.freeShippingEndDate >= :now')
->setParameters([
'domain' => $domain->getId(),
'now' => (new \DateTime())->format('Y-m-d'),
])
->getQuery()
->getSingleColumnResult();
}
//PAYPAL
/**
* @Route("/checkout/paypal/create/order", name="checkout_paypal_create_order")
*/
public function paypalCreteOrderAction(Request $request): JsonResponse
{
$content = $request->getContent();
$data = json_decode($content, true);
$entityManager = $this->getEntityManager();
if (isset($data['cart']) && isset($data['amount']) && isset($data['currency']) && isset($data['centralisOrderId'])) {
header('Content-Type: application/json');
try {
$orderResponse = $this->getPaypal()->createOrder($data['amount'], $data['currency']);
$order = $entityManager->find(Order::class, $data['centralisOrderId']);
$orderSetting = new OrderSetting();
$orderSetting->setOrder($order);
$orderSetting->setType(OrderSetting::TYPE_PAYPAL_ORDER_ID);
$orderSetting->setValue($orderResponse['jsonResponse']->getId());
$entityManager->persist($orderSetting);
$entityManager->flush();
return new JsonResponse($orderResponse['jsonResponse']);
} catch (Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], 500);
}
}
// If 'cart' does not exist in the payload
return new JsonResponse([
'success' => false,
'message' => 'No cart data received',
], 400);
}
/**
* @Route("/checkout/paypal/capture/order/{orderId}", name="checkout_paypal_capture_order")
*/
public function paypalCaptureOrderAction(Request $request, string $orderId): JsonResponse
{
$entityManager = $this->getEntityManager();
try {
$captureResponse = $this->getPaypal()->captureOrder($orderId);
$centralisOrder = $entityManager->getRepository(OrderSetting::class)->findOneBy([
'value' => $orderId,
])?->getOrder();
if (isset($captureResponse['jsonResponse']) && !is_array($captureResponse['jsonResponse'])){
if ($centralisOrder) {
$status = $captureResponse['jsonResponse']->getStatus();
$transactionId = $captureResponse['jsonResponse']
?->getPurchaseUnits()[0]
?->getPayments()
?->getCaptures()[0]
?->getId() ?? null;
if ($status == Paypal::SUCCESS_STATUS) {
$centralisOrder->setPaymentStatus(Order::PAYMENT_STATUS_PAID);
if ($transactionId) {
$entityManager->persist(OrderSetting::createSetting(
$centralisOrder,
OrderSetting::TYPE_PAYPAL_TRANSACTION_ID,
$transactionId
));
}
$entityManager->flush();
}
else {
$this->getKlaviyoConnect($request)->createNewOrderIsNotPayedPaypalEvent($centralisOrder);
}
}
}
return new JsonResponse($captureResponse['jsonResponse']);
} catch (Exception $e) {
return new JsonResponse(['error' => $e->getMessage()], 500);
}
}
/**
* @Route("/checkout/klarna/cancel/order/{orderId}", name="checkout_klarna_cancel_order")
* @param Request $request
* @param int $orderId
* @return RedirectResponse
*/
public function calcelOrder(Request $request, int $orderId): RedirectResponse
{
$entityManager = $this->getEntityManager();
$order = $entityManager->find(Order::class, $orderId);
$order->setStatus(Order::STATUS_CANCELED);
$stockMovementRepo = $entityManager->getRepository(StockMovement::class);
foreach ($order->getStockMovements() as $stockMovement) {
$stockMovementRepo->deleteStockMovement($stockMovement);
}
$entityManager->flush();
$request->getSession()->set('canceledOrderId', $orderId);
return $this->redirectToRoute('checkout_success');
}
}