<?php
namespace App\AtechNet\CoreBundle\Helper\Furbify;
use App\AtechNet\CoreBundle\Entity\Attribute;
use App\AtechNet\CoreBundle\Entity\Basket;
use App\AtechNet\CoreBundle\Entity\BasketItem;
use App\AtechNet\CoreBundle\Entity\Coupon;
use App\AtechNet\CoreBundle\Entity\Customer;
use App\AtechNet\CoreBundle\Entity\CustomerAddress;
use App\AtechNet\CoreBundle\Entity\CustomerBillingoData;
use App\AtechNet\CoreBundle\Entity\Document;
use App\AtechNet\CoreBundle\Entity\DocumentGroup;
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\OrderItem;
use App\AtechNet\CoreBundle\Entity\PickupPoint;
use App\AtechNet\CoreBundle\Entity\Product;
use App\AtechNet\CoreBundle\Entity\ProductType;
use App\AtechNet\CoreBundle\Entity\UnasTranslator;
use App\AtechNet\CoreBundle\Entity\User;
use App\AtechNet\CoreBundle\Enum\PaymentType;
use App\AtechNet\CoreBundle\Helper\Billingo;
use App\AtechNet\CoreBundle\Helper\Instacash;
use App\AtechNet\CoreBundle\Helper\Milpay;
use App\AtechNet\CoreBundle\Repository\OrderRepository;
use GoPay\Definition\Response\PaymentStatus;
use GuzzleHttp\Exception\GuzzleException;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
class OrderHelper
{
private $request;
private $entityManager;
private $translator;
private $dbTranslator;
private $container;
private $environment;
public static string $apiToken = '423235h54gf42154132g541tf45rer4832r24364yrd231rf4tgtf432r3246h324rf36y4fde3r432';
/**
* OrderHelper constructor.
*
* @param $request
* @param $entityManager
* @param $translator
* @param $dbTranslator
* @param $router
* @param $mailer
* @param $mailerReplyTo
* @param $cloudFlareConfig
*/
public function __construct($request, $entityManager, $translator, $dbTranslator, $router, $mailer, $mailerReplyTo, $cloudFlareConfig, $environment)
{
$this->request = $request;
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->dbTranslator = $dbTranslator;
$this->router = $router;
$this->mailer = $mailer;
$this->mailerReplyTo = $mailerReplyTo;
$this->cloudFlareConfig = $cloudFlareConfig;
$this->environment = $environment;
}
/**
* @param Order $order
* @param ProductHelper $productHelper
* @param $contactInfos
* @param array $whitelistCouponCodes
* @param bool $bccSalesManager
* @param bool $confirmOrder
*
* @return array
*/
public function sendOrderEmail(Order $order, ProductHelper $productHelper, $contactInfos, array $whitelistCouponCodes = [], bool $bccSalesManager = false, $confirmOrder = false): array
{
if ($unasDomainSetting = $order->getUnasOrderDomainSetting()) {
$this->translator->setLocale($unasDomainSetting->getValue());
$unasData['isUnas'] = true;
$unasData['unasDomain'] = "https://www.furbify.{$unasDomainSetting->getValue()}/";
$unasData['externalOrderId'] = $order->getExternalOrderCode();
}
else {
$unasData['isUnas'] = false;
}
$orderData = $this->getDataFromEmail($order, $productHelper, $contactInfos, $whitelistCouponCodes);
$emailData = array_merge($orderData['emailData'], $unasData);
$response = $orderData['response'];
// Order Confirmed Email
$emailData['confirmOrder'] = $confirmOrder;
$domain = $order->getDomain();
$emailData['domainId'] = $order->getDomain()->getId();
$emailData['createdDate'] = $order->getCreated();
if ($confirmOrder) {
$subject = 'Furbify - ' . $this->translator->trans('Order confirmed') . ' ' . $order->getId();
}
else {
$subject = 'Furbify - ' . $this->translator->trans('Order') . ' ' . $order->getId();
}
$emailTo = !is_null($order->getCustomer()->getSalesManager())
&& $order->getCustomer()->getSalesManager()->getId() == User::USER_ID_IMRICH_ZUBER
&& !is_null($order->getCustomer()->getFinanceEmail())
&& $order->getCustomer()->getFinanceEmail() != ''
? $order->getCustomer()->getFinanceEmail()
: $order->getBillingEmail();
switch ($order->getDomain()->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$emailData['furbifyManualLink'] = 'https://www.furbify.sk/furbify-manual';
break;
case Domain::DOMAIN_ID_RT_HU:
$emailData['furbifyManualLink'] = 'https://www.furbify.hu/furbify-kisokos';
break;
case Domain::DOMAIN_ID_RT_CZ:
$emailData['furbifyManualLink'] = 'https://www.furbify.cz/furbify-manual';
break;
}
$email = (new TemplatedEmail())
->subject($subject)
->to($emailTo)
->replyTo($this->mailerReplyTo)
->bcc('webshop@furbify.eu')
->htmlTemplate('AtechNetCoreBundle/Email/order.html.twig')
->context($emailData);
//for testing the email
//you need to enable this part in CheckoutController return $this->render('AtechNetCoreBundle/Email/order.html.twig', $emailSendingResult);
/*return $emailData;*/
if (
$bccSalesManager
&& in_array($domain->getId(), [
Domain::DOMAIN_ID_RT_SK,
Domain::DOMAIN_ID_RT_HU,
Domain::DOMAIN_ID_RT_CZ,
Domain::DOMAIN_ID_RT_EU,
Domain::DOMAIN_ID_WS_SK,
Domain::DOMAIN_ID_WS_HU,
Domain::DOMAIN_ID_WS_CZ,
Domain::DOMAIN_ID_WS_EU,
]) && !is_null($order->getCustomer()->getSalesManager())) {
if (!in_array($domain->getId(), [Domain::DOMAIN_ID_RT_EU, Domain::DOMAIN_ID_WS_EU])) {
if (
$order->getCustomer()->getSalesManager()->getId() != User::USER_ID_BEATA_SEDLAROVA
&& ((
$order->getCustomer()->isB2B()
&& in_array($order->getDomain()->getId(), [Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_RT_CZ])
)
|| $order->getDomain()->getId() == Domain::DOMAIN_ID_WS_CZ
)
) {
$email->addBcc('bea.sedlarova@furbify.eu');
}
else {
$email->addBcc($order->getCustomer()->getSalesManager()->getEmail());
}
}
else {
if ($domain->getId() == Domain::DOMAIN_ID_RT_EU) {
$email->addBcc('webshop@furbify.eu');
}
else {
$email->addBcc('export@furbify.eu');
}
}
}
if ($domain->getId() == Domain::DOMAIN_ID_RT_SK) {
$email->attachFromPath('https://www.furbify.sk/storage/files/furbify-vop-2026-sk.pdf');
$email->attachFromPath('https://www.furbify.sk/storage/files/furbify-reklamacny-poriadok-2026-sk.pdf');
}
if ($domain->getId() == Domain::DOMAIN_ID_RT_CZ) {
$email->attachFromPath('https://www.furbify.cz/storage/files/furbify-vop-2026-cz.pdf');
$email->attachFromPath('https://www.furbify.cz/storage/files/furbify-reklamacny-poriadok-2026-cz.pdf');
}
if ($domain->getId() == Domain::DOMAIN_ID_RT_HU) {
$email->attachFromPath('https://www.furbify.hu/storage/files/furbify-vop-2026-hu.pdf');
$email->attachFromPath('https://www.furbify.hu/storage/files/garancialis_es_jotallasi_feltetelek_furbify.pdf');
}
$this->mailer->send($email);
$response['total'] = $emailData['total'];
$response['currency'] = $emailData['currency'];
return $response;
}
/**
* @param string $status
* @param order $order
* @param ProductHelper $productHelper
* @param $contactInfos
* @param array $whitelistCouponCodes
*/
public function sendPaymentStatusEmail(string $status, Order $order, ProductHelper $productHelper, $contactInfos, array $whitelistCouponCodes = [])
{
$orderData = $this->getDataFromEmail($order, $productHelper, $contactInfos, $whitelistCouponCodes);
$emailData = $orderData['emailData'];
$response = $orderData['response'];
if ($status == 'success') {
$emailData['successfulPayment'] = true;
$subject = $this->translator->trans('Successful card payment');
}
else {
$emailData['successfulPayment'] = false;
$subject = $this->translator->trans('Unsuccessful card payment');
}
$emailData['domainId'] = $order->getDomain()->getId();
$orderRepository = $this->entityManager->getRepository(Order::class);
$emailData['publicOrderLink'] = $order->getDomain()->getUrl() .
$this->router->generate(
'customer_order_show',
[
'orderId' => $order->getId(),
'token' => $orderRepository->generatePublicLinkToken([
'orderId' => $order->getId(),
]),
]
);
$email = (new TemplatedEmail())
->subject($subject)
->to($order->getBillingEmail())
->replyTo($this->mailerReplyTo)
->htmlTemplate('AtechNetCoreBundle/Email/payment.html.twig')
->context($emailData);
$this->mailer->send($email);
$response['total'] = $emailData['total'];
$response['currency'] = $emailData['currency'];
return $response;
}
/**
* @param Order $order
* @param ProductHelper $productHelper
* @param $contactInfos
* @param array $whitelistCouponCodes
*
* @return array
*/
public function sendOrderShippingConfirmationEmail(Order $order, ProductHelper $productHelper, $contactInfos, array $whitelistCouponCodes = [], ?Billingo $billingoHelper = null)
{
$orderData = $this->getDataFromEmail($order, $productHelper, $contactInfos, $whitelistCouponCodes, true);
$emailData = $orderData['emailData'];
$response = $orderData['response'];
$emailAddress = !is_null($order->getCustomer()->getFinanceEmail()) && $order->getCustomer()->getFinanceEmail() != '' ? $order->getCustomer()->getFinanceEmail() : $order->getBillingEmail();
$subject = 'Furbify - ' . $this->translator->trans('Order') . ' ' . $order->getId() . ' - ' . $this->translator->trans('Package sent') . ' & ' . $this->translator->trans('Invoice in the attachment mail header');
$email = (new TemplatedEmail())
->subject($subject)
->to($emailAddress)
->replyTo($this->mailerReplyTo)
->htmlTemplate('AtechNetCoreBundle/Email/orderShippingConfirmation.html.twig')
->attachFromPath($this->getOutinvoiceForAttachment($order, $billingoHelper))
->context($emailData);
$trustindexEmail = $this->getTrustindexEmail($order);
if ($trustindexEmail) {
$email->addBcc($trustindexEmail);
}
$this->mailer->send($email);
$response['total'] = $emailData['total'];
$response['currency'] = $emailData['currency'];
return $response;
}
/**
* @param Order $order
* @param ProductHelper $productHelper
* @param $contactInfos
* @param array $whitelistCouponCodes
*
* @return array
*/
public function sendOrderPickupConfirmationEmail(Order $order, ProductHelper $productHelper, $contactInfos, array $whitelistCouponCodes = [], ?Billingo $billingoHelper = null)
{
$orderData = $this->getDataFromEmail($order, $productHelper, $contactInfos, $whitelistCouponCodes, true);
$emailData = $orderData['emailData'];
$response = $orderData['response'];
$emailAddress = !is_null($order->getCustomer()->getFinanceEmail()) && $order->getCustomer()->getFinanceEmail() != '' ? $order->getCustomer()->getFinanceEmail() : $order->getBillingEmail();
$email = (new TemplatedEmail())
->subject('Furbify - ' . $this->translator->trans('Order') . ' ' . $order->getId() . ' ' . $this->translator->trans('prepared'))
->to($emailAddress)
->replyTo($this->mailerReplyTo)
->htmlTemplate('AtechNetCoreBundle/Email/orderPickupConfirmation.html.twig')
->attachFromPath($this->getOutinvoiceForAttachment($order, $billingoHelper))
->context($emailData);
$trustindexEmail = $this->getTrustindexEmail($order);
if ($trustindexEmail) {
$email->addBcc($trustindexEmail);
}
$this->mailer->send($email);
$response['total'] = $emailData['total'];
$response['currency'] = $emailData['currency'];
return $response;
}
/**
* @param Order $order
*
* @return string|null
*/
private function getTrustindexEmail(Order $order): string|null
{
return match ($order->getDomain()->getId()) {
Domain::DOMAIN_ID_RT_SK => 'invite-d0d9ea14612g351d@trustindex.io',
Domain::DOMAIN_ID_RT_HU => 'invite-b304b414586g16b5@trustindex.io',
Domain::DOMAIN_ID_RT_EU => 'invite-014e1316997g1716@trustindex.io',
default => null,
};
}
/**
* @param Order $order
* @param Billingo|null $billingoHelper
*
* @throws GuzzleException
*/
private function getOutinvoiceForAttachment(Order $order, ?Billingo $billingoHelper)
{
if ($order->getDomain()->getLanguage()->getCode() == 'hu' && $order->getBillingoDocuments()->count() > 0) {
/**
* @var CustomerBillingoData $billingoInvoice
*/
$billingoInvoice = $order->getBillingoDocuments()->filter(function (CustomerBillingoData $cbd) {
return $cbd->getType() == Billingo::TYPE_INVOICE;
})->last();
$pdfString = $billingoHelper->downloadDocument($billingoInvoice->getInvoiceV3Id());
$documentCode = $billingoInvoice->getInvoiceCode();
$pdfString = "data:application/pdf;base64,$pdfString";
$pdfPath = sprintf(
'%s/%s_%d.pdf',
sys_get_temp_dir(),
strtolower(
str_replace(
' ',
'_',
iconv(
'utf-8',
'us-ascii//TRANSLIT',
'faktúra'
)
)
),
$documentCode
);
$f = fopen($pdfPath, 'wb');
fwrite($f, $pdfString, strlen($pdfString));
fclose($f);
return $pdfPath;
}
else {
$invoice = false;
foreach ([DocumentGroup::TYPE_INVOICE_OUT, DocumentGroup::TYPE_INVOICE_PRE, DocumentGroup::TYPE_BILL_OF_DELIVERY] as $documentGroupId) {
foreach ($order->getDocuments() as $document) {
if ($document->getGroup()->getType() == $documentGroupId) {
$invoice = $document;
break 2;
}
}
}
$documentCode = $invoice->getCode();
$invoice->setSentDate(new \DateTime());
$invoice->setEmailSent($order->getBillingEmail());
$this->entityManager->flush();
$pdf = $this->entityManager->getRepository(Document::class)->createPdf($invoice, 0);
$pdfPath = sprintf(
'%s/%s_%d.pdf',
sys_get_temp_dir(),
strtolower(
str_replace(
' ',
'_',
iconv(
'utf-8',
'us-ascii//TRANSLIT',
'faktúra'
)
)
),
$documentCode
);
$pdf->output($pdfPath, 'F');
return $pdfPath;
}
}
/**
* @param Order $order
* @param ProductHelper $productHelper
* @param $contactInfos
* @param $whitelistCouponCodes
*
* @return array[]
*/
public function getDataFromEmail(Order $order, ProductHelper $productHelper, $contactInfos, $whitelistCouponCodes, $hideInvoicePublicLink = false): array
{
$needTranslation = !is_null($order->getUnasOrderDomainSetting());
$translationLocal = $order->getUnasOrderDomainSetting()?->getValue();
$unasTranslatorEntity = $this->entityManager->getRepository(UnasTranslator::class);
$emailData = [];
$emailData['containsNB'] = false;
$response['marketingProducts'] = $response['marketingProductsGA4'] = '';
$domain = $order->getDomain();
$emailData['currency'] = $domain->getCurrency();
$emailData['precision'] = $domain->getPricePrecision();
if (mb_strtolower(trim($domain->getCurrency())) == 'ft') {
$emailData['currencyCode'] = 'HUF';
}
else if (mb_strtolower(trim($domain->getCurrency())) == 'kč') {
$emailData['currencyCode'] = 'CZK';
}
else {
$emailData['currencyCode'] = 'EUR';
}
$emailData['orderId'] = $order->getId();
$emailData['bankTransfer'] = $order->getPaymentType() == 3;
$emailData['dateAdded'] = $order->getCreated()->format($this->translator->trans('datetime.format'));
$emailData['customerEmail'] = $order->getBillingEmail();
$emailData['telephone'] = $order->getBillingPhone();
$emailData['greetingName'] = !is_null($order->getBillingBusinessName()) && $order->getBillingBusinessName() != '' && !is_null($order->getBillingBusinessId()) && $order->getBillingBusinessId() != '' ? $order->getBillingBusinessName() : $order->getBillingFirstName();
$format = '{businessname}' . "\n" . ($order->getBillingBusinessId() != null ? '{businessId}' . "\n" : '') . ($order->getBillingTaxId() != null ? '{taxId}' . "\n" : '') . '{firstname} {lastname}' . "\n" . '{street}' . "\n" . '{postalcode} {city}' . "\n" . '{country}';
$find = [
'{businessname}',
'{businessId}',
'{taxId}',
'{firstname}',
'{lastname}',
'{street}',
'{city}',
'{postalcode}',
'{country}',
];
$replace = [
'businessname' => (!is_null($order->getBillingBusinessName()) && $order->getBillingBusinessName() != '') ? $order->getBillingBusinessName() : '',
'businessId' => "<b>{$this->translator->trans('Business ID')}:</b> {$order->getBillingBusinessId()}",
'taxId' => "<b>{$this->translator->trans('Tax ID')}:</b> {$order->getBillingTaxId()}",
'firstname' => $order->getBillingFirstName(),
'lastname' => $order->getBillingLastName(),
'street' => $order->getBillingStreet(),
'city' => $order->getBillingCity(),
'postalcode' => $order->getBillingZip(),
'country' => isset(CustomerAddress::getCountries()[$order->getBillingCountry()]) ? CustomerAddress::getCountries()[$order->getBillingCountry()] : $order->getBillingCountry(),
];
$emailData['billingAddress'] = str_replace(
["\r\n", "\r", "\n"],
'<br />',
preg_replace(
["/\s\s+/", "/\r\r+/", "/\n\n+/"],
'<br />',
trim(str_replace($find, $replace, $format))
)
);
$emailData['billingFirstName'] = $order->getBillingFirstName();
$emailData['billingLastName'] = $order->getBillingLastName();
$emailData['billingStreet'] = $order->getBillingStreet();
$emailData['billingCity'] = $order->getBillingCity();
$emailData['billingCountry'] = $order->getBillingCountry();
if ($order->useBillingAddressAsShippingAddress()) {
$emailData['shippingAddress'] = $emailData['billingAddress'];
$emailData['shippingFirstName'] = $order->getBillingFirstName();
$emailData['shippingLastName'] = $order->getBillingLastName();
$emailData['shippingStreet'] = $order->getBillingStreet();
$emailData['shippingCity'] = $order->getBillingCity();
$emailData['shippingPostalCode'] = $order->getBillingZip();
$emailData['shippingCountry'] = $order->getBillingCountry();
}
else {
$replace = [
'businessname' => (!is_null($order->getShippingBusinessName()) && $order->getShippingBusinessName() != '') ? $order->getShippingBusinessName() : '',
'firstname' => $order->getShippingFirstName(),
'lastname' => $order->getShippingLastName(),
'street' => $order->getShippingStreet(),
'city' => $order->getShippingCity(),
'postalcode' => $order->getShippingZip(),
'country' => isset(CustomerAddress::getCountries()[$order->getShippingCountry()]) ? CustomerAddress::getCountries()[$order->getShippingCountry()] : $order->getShippingCountry(),
];
$emailData['shippingAddress'] = str_replace(
["\r\n", "\r", "\n"],
'<br />',
preg_replace(
["/\s\s+/", "/\r\r+/", "/\n\n+/"],
'<br />',
trim(str_replace($find, $replace, $format))
)
);
$emailData['shippingFirstName'] = $order->getShippingFirstName();
$emailData['shippingLastName'] = $order->getShippingLastName();
$emailData['shippingStreet'] = $order->getShippingStreet();
$emailData['shippingCity'] = $order->getShippingCity();
$emailData['shippingPostalCode'] = $order->getShippingZip();
$emailData['shippingCountry'] = $order->getShippingCountry();
}
$emailData['isShippedToPickupPoint'] = $order->getPickupPointSetting() || (!is_null($order->getPacketaBranchIdSetting()) && is_numeric($order->getPacketaBranchIdSetting()->getValue()));
$emailData['pickupPointAddress'] = '';
$pickupPoint = false;
if ($emailData['isShippedToPickupPoint']) {
if ($order->getPickupPointSetting()) {
$pickupPointId = $order->getPickupPointSetting()->getValue();
$pickupPoint = $this->entityManager->getRepository(PickupPoint::class)->findOneById($pickupPointId);
$emailData['pickupPointAddress'] = $pickupPoint->getStreet() . ', ' . $pickupPoint->getCity() . ', ' . $pickupPoint->getZip() . ', ' . CustomerAddress::getCountries()[$pickupPoint->getCountry()];
}
if (!is_null($order->getPacketaBranchIdSetting()) && is_numeric($order->getPacketaBranchIdSetting()->getValue())) {
$emailData['pickupPointAddress'] = $order->getPacketaBranchNameSetting()->getValue();
}
/**
* @var PickupPoint $pickupPoint
*/
if ($emailData['pickupPointAddress'] != '') {
$emailData['shippingFirstName'] = '';
$emailData['shippingLastName'] = '';
$emailData['shippingStreet'] = '';
$emailData['shippingCity'] = '';
$emailData['shippingPostalCode'] = '';
$emailData['shippingCountry'] = '';
}
if ($pickupPoint) {
$emailData['shippingStreet'] = $pickupPoint->getStreet();
$emailData['shippingCity'] = $pickupPoint->getCity();
$emailData['shippingPostalCode'] = $pickupPoint->getZip();
$emailData['shippingCountry'] = $pickupPoint->getCountry();
}
}
$emailData['total'] = 0;
$emailData['subTotal'] = 0;
$emailData['items'] = [];
$emailData['countItems'] = 0;
$placeholder = $this->getImage('placeholder.png', '')->resize(Image::PRODUCT_CART_THUMB_WIDTH, Image::PRODUCT_CART_THUMB_HEIGHT);
$couponRepo = $this->entityManager->getRepository(Coupon::class);
if ($order->getCouponCode()) {
$coupon = $couponRepo->findOneByCode($order->getCouponCode());
if ($coupon) {
$emailData['discount'] = $coupon->getDiscount();
}
}
/**
* @var int $index
* @var OrderItem $item
*/
foreach ($order->getOrderItems() as $index => $item) {
if ($item->getProduct()->getType()->getId() === ProductType::PRODUCT_TYPE_ID_NOTEBOOK) {
$emailData['containsNB'] = true;
}
if ($item->getItemFullPrice() == 0.00 && in_array($item->getProduct()->getType()->getId(), ProductType::getConfigurableProductTypes())) {
continue;
}
if ($item->getParent() == null) {
$itemProduct = $item->getProduct();
$product = $productHelper->getStructuredDataForProduct($itemProduct, 'cart');
if ($product) {
$options = [];
foreach ($item->getItemAttributes() as $attribute) {
$option = $attribute->getAttributeOption();
$optionMeta = $option->getDomainMeta($domain);
if ($optionMeta) {
$optionValue = $option->getLongTitle($this->dbTranslator);
if (!$optionValue) {
$optionValue = $option->getTitle($this->dbTranslator);
}
$optionTitle = $option->getAttribute()->getTitle();
if ($needTranslation) {
$optionTitle = $unasTranslatorEntity->findOneBy(['translationKey' => $optionTitle])
?->getTranslationByCountryCode($translationLocal) ?? $optionTitle;
if ($option->getAttribute()->getId() != Attribute::ATTRIBUTE_ID_NOTEBOOK_SKIN) {
$optionValue = $unasTranslatorEntity->findOneBy(['translationKey' => $optionValue])
?->getTranslationByCountryCode($translationLocal) ?? $optionValue;
}
}
$options[] = [
'id' => $attribute->getId(),
'title' => $optionTitle,
'value' => $optionValue,
];
}
}
$configText = !is_null($item->getCustomConfiguration()) && $item->getCustomConfiguration() != '' ? $item->getCustomConfiguration() : $product['shortDescription'];
if ($needTranslation) {
$translated = '';
foreach (explode("|", $configText) as $line) {
$translation = $unasTranslatorEntity->findOneBy(['translationKey' => trim($line)]);
if ($translation && !preg_match('/bronze|silver|gold|new/', strtolower($line))) {
$translated .= $translation->getTranslationByCountryCode($translationLocal) . ' | ';
}
else {
$translated .= trim($line) . ' | ';
}
}
if ($translated != '') {
$configText = trim($translated, ' | ');
}
}
$image = $markupImage = $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);
$markupImage = $this->getImage($product['images'], 'product/' . $product['code'])->resize(Image::PRODUCT_VIEW_POPUP_WIDTH, Image::PRODUCT_VIEW_POPUP_HEIGHT);
}
$emailData['items'][] = [
'id' => $item->getId(),
'productId' => $product['id'],
'model' => $product['code'],
'name' => ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'],
'description' => $configText,
'quantity' => $item->getQuantity(),
'price' => $item->getItemFullPrice(),
'originalPrice' => array_key_exists('discount', $emailData) && $emailData['discount'] ? $item->getItemFullPrice() / (1-( $emailData['discount']/100)) : null,
'image' => $image,
'markupImage' => $markupImage,
'options' => $options,
'url' => $this->url()->link('product', [
'product_id' => $item->getId(),
'isBazaar' => $product['isBazaar'] ?? 0
]),
'outOfStockStatus' => $item->getProduct()->getOutOfStockStatus(),
];
$response['marketingProducts'] = ($response['marketingProducts'] !== '' ? ',' : '') . '{"id": "' . $product['code'] . '","name": "' . ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'] . '","brand": "' . $product['vendor'] . '","category": "' . $product['productType'] . '","quantity": ' . $item->getQuantity() . ',"price": \'' . $item->getItemFullPrice() . '\'}';
$response['marketingProductsGA4'] .= ($response['marketingProductsGA4'] !== '' ? ',' : '') . '{ item_id: \'' . $product['code'] . '\', item_name: \'' . ($product['vendor'] !== '' ? $product['vendor'] . ' ' : '') . $product['title'] . '\', item_brand: \'' . $product['vendor'] . '\', item_category: \'' . $product['productType'] . '\', quantity: ' . $item->getQuantity() . ', price: \'' . $item->getItemFullPrice() . '\', index: ' . $index . '}';
}
}
}
$emailData['paymentTitle'] = $emailData['shippingTitle'] = $emailData['paymentTitle'] = $emailData['coupon'] = '';
$emailData['paymentCost'] = $emailData['shippingCost'] = $emailData['discount'] = 0;
$emailData['paymentType'] = $order->getPaymentType();
$emailData['isShippedByCarrier'] = in_array($order->getShippingType(), [DomainShippingType::ShippingType_Carrier_Id, DomainShippingType::ShippingType_Post_Id, DomainShippingType::ShippingType_PICKUP_POINT_Id]);
$translationKey = 'shipping.method.type.' . $order->getShippingType() . ($order->getDomain()->getId() == 4 ? '.achu' : '');
if (($emailData['shippingTitle'] = $this->translator->trans($translationKey)) == $translationKey) {
$translationKey = str_replace('.achu', '', $translationKey);
$emailData['shippingTitle'] = $this->translator->trans($translationKey);
}
$emailData['shippingCost'] = $order->getShippingPrice();
if ($order->getDomain()->getId() == Domain::DOMAIN_ID_WS_HU && $order->getPaymentType() == PaymentType::BankTransfer->value) {
$translationKey = 'payment.method.type.' . $order->getPaymentType() . '.wshu';
}
else {
$translationKey = 'payment.method.type.' . $order->getPaymentType();
}
$emailData['paymentTitle'] = $this->translator->trans($translationKey);
$emailData['paymentCost'] = $order->getPaymentPrice();
if (!empty($order->getCouponCode()) && !in_array($order->getCouponCode(), $whitelistCouponCodes)) {
$emailData['coupon'] = $order->getCouponCode();
$couponSetting = $order->getCouponCodeSetting();
if ($couponSetting) {
$coupon = $this->entityManager->getRepository(Coupon::class)->findOneById($couponSetting->getValue());
if ($coupon) {
$emailData['discount'] = $coupon->getDiscount();
$emailData['discountType'] = $coupon->getDiscountType();
$emailData['freeShippingCoupon'] = $coupon->hasFreeShipping();
}
}
}
$emailData['isPaidByCard'] = in_array($order->getPaymentType(), [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value]);
$emailData['subTotal'] = $order->getSubTotal();
$emailData['total'] = $order->getFullPrice();
$domain = $order->getDomain();
$domainLanguageCode = $domain->getLanguage()->getCode();
if ($domainLanguageCode == 'en') {
$emailData['domainLanguageCode'] = 'eu';
}
else {
$emailData['domainLanguageCode'] = $domainLanguageCode;
}
$emailData['logo_country_suffix'] = '';
if (in_array($domainLanguageCode, ['sk', 'hu'])) {
$emailData['logo_country_suffix'] = '-' . $domainLanguageCode;
}
$emailData['deliveryData'] = [
'packageNumber' => '',
'trackingUrl' => '',
];
if ($emailData['isShippedByCarrier']) {
$post = json_decode($this->request->getContent(), true);
if (!is_null($post)) {
$post = array_column($post, null, 'id');
$tracking = $post[$order->getId()]['tracking'][0] ?? null;
if ($tracking) {
$emailData['deliveryData']['packageNumber'] = $tracking['number'];
$emailData['deliveryData']['trackingUrl'] = $tracking['url'];
}
}
}
$expectedDeliveryBaseDate = !is_null($order->getShipDate()) ? clone $order->getShipDate() : clone $order->getCreated();
$emailData['expectedArrivalUntil'] = str_replace('+', '-', $expectedDeliveryBaseDate->add(new \DateInterval('P1D'))->format('c'));
// Public Order Link
$orderRepository = $this->entityManager->getRepository(Order::class);
$emailData['publicOrderLink'] = !$hideInvoicePublicLink ? $order->getDomain()->getUrl() .
$this->router->generate('customer_order_show', [
'orderId' => $order->getId(),
'token' => $orderRepository->generatePublicLinkToken([
'orderId' => $order->getId(),
]),
]) : '';
$emailData['customerTypeId'] = $this->request->getSession()->get('customerTypeId');
$emailData['company_name'] = $contactInfos['company.' . $domainLanguageCode . '.name'];
$emailData['bank_account'] = $contactInfos['company.' . $domainLanguageCode . '.bankAccount'];
$emailData['phone_number'] = $contactInfos['phone.webshop.' . $domainLanguageCode . '.' . $order->getDomain()->getType()];
$emailData['iban'] = $contactInfos['company.' . $domainLanguageCode . '.iban'];
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
case Domain::DOMAIN_ID_WS_SK:
case Domain::DOMAIN_ID_RT_CZ:
case Domain::DOMAIN_ID_WS_CZ:
case Domain::DOMAIN_ID_RT_EU:
case Domain::DOMAIN_ID_WS_EU:
$emailData['facebook_link'] = 'https://www.facebook.com/furbify.atechnet/';
$emailData['instagram_link'] = 'https://www.instagram.com/furbify.sk';
break;
case Domain::DOMAIN_ID_RT_HU:
case Domain::DOMAIN_ID_WS_HU:
$emailData['facebook_link'] = 'https://www.facebook.com/furbify.hu/';
$emailData['instagram_link'] = 'https://www.instagram.com/furbify.hu';
break;
default:
$emailData['facebook_link'] = '';
$emailData['instagram_link'] = '';
}
return [
'emailData' => $emailData,
'response' => $response,
];
}
/**
* @return string[]
*/
protected function getBaseGlsTrackingUrls(): array
{
return [
'sk' => 'https://gls-group.eu/SK/sk/parcel-tracking.html?match=',
'hu' => 'https://gls-group.eu/HU/hu/csomagkovetes.html?match=',
'cz' => 'https://gls-group.eu/CZ/cs/sledovani-zasilek?match=',
'en' => 'https://gls-group.eu/EU/en/parcel-tracking.html?match=',
];
}
/**
* @param string $postalCode
* @param string $country
* @param Request $request
*
* @return string
*/
public static function findDistrict(string $postalCode, string $country, Request $request): string
{
if (!empty($postalCode) && !empty($country) && in_array(strtolower($country), ['sk', 'hu', 'cz'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.atechcomp.eu/centralis/web/api/customer/find/district');
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, false);
curl_setopt($ch, CURLOPT_USERAGENT, $request->server->get('HTTP_USER_AGENT'));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'tkn' => self::$apiToken,
'pstlCd' => $postalCode,
'cntr' => $country,
]));
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
if (!empty($response['result'])) {
if ($response['result'] !== false) {
return $response['result'];
}
}
return '';
}
return '';
}
/**
* @return SeoUrlHelper
*/
public function url(): SeoUrlHelper
{
return new SeoUrlHelper($this->entityManager, $this->request, $this->environment);
}
/**
* @param object|string $photo
* @param string $directory
*
* @return Image
*/
protected function getImage($photo, string $directory = 'product'): Image
{
return new Image($this->cloudFlareConfig, $photo, $directory);
}
/**
* @param int $domainId
* @param null|Customer $customer
* @param null|Basket $cart
* @param null|Instacash $instacash
* @param Milpay|null $milpay
* @param bool $isCompany
* @param OrderRepository|null $orderRepository
*
* @return array
*/
public function getPaymentMethodData(int $domainId, ?Customer $customer = null, ?Basket $cart = null, ?Instacash $instacash = null, ?Milpay $milpay = null, bool $isCompany = false, ?OrderRepository $orderRepository = null): array
{
$paymentMethodList = [];
// Get all integrated payment methods
$paymentMethods = $this->entityManager->createQueryBuilder()
->select('dpt')
->from('AtechNetCoreBundle:DomainPaymentType', 'dpt')
->andWhere('dpt.domain = :domainId')
->setParameter(':domainId', $domainId)
->andWhere('dpt.integrated = :integrated')
->setParameter(':integrated', 1)
->orderBy('dpt.sortOrder', 'ASC')
->getQuery()->getResult();
// Custom customer payment methods
$customCustomerPaymentMethods = null;
if ($customer) {
$customCustomerPaymentMethods = $customer->getPaymentTypes();
}
$translator = $this->translator;
$payOnDelivery = true;
$noDeliveryPaymentDescription = '';
if ($cart) {
$priceLimits = DomainPaymentType::CASH_ON_DELIVERY_LIMITS;
$price = 0;
/**
* @var $cartItem BasketItem
*/
foreach ($cart->getBasketItems() as $cartItem) {
$productMeta = array_filter($cartItem->getProduct()->getMetas(), function ($meta) use ($domainId) {
return $meta->getDomain()->getId() === $domainId;
});
$price += $productMeta[array_key_first($productMeta)]->isDiscounted()
? $productMeta[array_key_first($productMeta)]->getDomainVatDiscount() * $cartItem->getQuantity()
: $productMeta[array_key_first($productMeta)]->getDomainVatPrice() * $cartItem->getQuantity();
$domainCurrency = $productMeta[array_key_first($productMeta)]->getDomain()->getCurrency();
if ($price > $priceLimits[$domainCurrency]) {
$payOnDelivery = false;
$noDeliveryPaymentDescription = $translator->trans('noOnDeliveryPayment.description') . ' ' . $priceLimits[$domainCurrency] . $domainCurrency;
break;
}
}
}
$showCetelemCalculator = false;
$cetelemDescLink = '';
$cetelemDesc = '';
$pastPayAvailable = false;
/**
* @var DomainPaymentType $paymentMethod
*/
foreach ($paymentMethods as $paymentMethod) {
$bnplWarning = null;
if ($this->entityManager->getRepository(Product::class)->isBasketIncludesOnlyGiftCart($cart)) {
if (
in_array($paymentMethod->getType(), [
PaymentType::Cetelem->value,
PaymentType::PastPay->value,
PaymentType::Quatro->value,
PaymentType::Klarna->value,
PaymentType::Instacash->value,
PaymentType::PayPal->value,
PaymentType::Milpay->value,
])) {
continue;
}
}
if (($customer?->isB2B() || $isCompany) && in_array($paymentMethod->getType(), [PaymentType::Klarna->value, PaymentType::Instacash->value, PaymentType::Milpay->value])) {
continue;
}
if (!is_null($customCustomerPaymentMethods) && $customCustomerPaymentMethods->count() > 0) {
foreach ($customCustomerPaymentMethods as $customCustomerPaymentMethod) {
if ($paymentMethod->getType() == $customCustomerPaymentMethod->getPaymentType()->getType() && !$customCustomerPaymentMethod->isActive()) {
continue 2;
}
}
}
else if (!$paymentMethod->isActiveOnWeb()) {
continue;
}
if ($domainId == Domain::DOMAIN_ID_WS_HU && $paymentMethod->getType() == PaymentType::BankTransfer->value) {
$translationKey = 'payment.method.type.' . $paymentMethod->getType() . '.wshu';
}
else {
$translationKey = 'payment.method.type.' . $paymentMethod->getType();
}
$defaultCountry = $this->request->getSession()->get('defaultCountry');
$cartTotalPrice = $cart ? $cart->getTotalPrice() : false;
if ($paymentMethod->getType() == PaymentType::Cetelem->value) {
if ($cartTotalPrice && constant(MultiStore::class . '::MINIMAL_LOAN_CETELEM_' . $defaultCountry) > $cartTotalPrice) {
continue;
}
if ($defaultCountry != 'SK') {
if ($defaultCountry == 'HU') {
$showCetelemCalculator = true;
$cetelemDescLink = $this->url($this->request)->link('page', [
'static_id' => 19,
]);
$cetelemDesc = $translator->trans('CetelemDesc');
}
else {
continue;
}
}
}
if ($cart && $paymentMethod->getType() == PaymentType::Quatro->value && MultiStore::MINIMAL_LOAN_QUATRO > $cart->getTotalPrice()) {
continue;
}
if ($cartTotalPrice && $paymentMethod->getType() == PaymentType::Instacash->value) {
$availableOffer = $instacash->getAvailableOffers();
if ($cartTotalPrice && $cartTotalPrice < $availableOffer['minAmount'] || $cartTotalPrice > $availableOffer['maxAmount']) {
continue;
}
}
if ($paymentMethod->getType() == PaymentType::Klarna->value) {
if ($cart && $orderRepository->haveNotFinishedBnpOrdersFromThisCustomer($cart, PaymentType::Klarna)) {
$bnplWarning = $translator->trans('bnplWarning.notFinishedOrders.klarna');
}
}
if (!is_null($milpay) && $cartTotalPrice && $paymentMethod->getType() == PaymentType::Milpay->value) {
$availableOffer = $milpay->getAvailableOffers();
if ($cartTotalPrice < $availableOffer['minAmount'] || $cartTotalPrice > $availableOffer['maxAmount']) {
continue;
}
if ($cart && $orderRepository->haveNotFinishedBnpOrdersFromThisCustomer($cart, PaymentType::Milpay)) {
$bnplWarning = $translator->trans('bnplWarning.notFinishedOrders.miplay');
}
}
else if (is_null($milpay) && $paymentMethod->getType() == PaymentType::Milpay->value) {
continue;
}
if (($title = $translator->trans($translationKey)) == $translationKey) {
$title = false;
}
if (($plusInfo = $translator->trans($translationKey . '.plusInfo')) == $translationKey . '.plusInfo') {
$plusInfo = false;
}
if (($description = $translator->trans($translationKey . '.description')) == $translationKey . '.description') {
$description = false;
}
if (($icon = $translator->trans($translationKey . '.icon')) == $translationKey . '.icon') {
$icon = false;
}
$inactive = false;
if (!$payOnDelivery && in_array($paymentMethod->getType(), [PaymentType::CashOnDelivery->value, PaymentType::CashOnDelivery3Percent->value]) && !in_array($domainId, [Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_WS_SK, Domain::DOMAIN_ID_WS_CZ, Domain::DOMAIN_ID_WS_EU])) {
$description = $noDeliveryPaymentDescription;
$inactive = true;
}
if ($title) {
$paymentMethodList[$paymentMethod->getId()] = [
'id' => $paymentMethod->getId(),
'type' => $paymentMethod->getType(),
'title' => $title,
'plusInfo' => $plusInfo,
'description' => $description,
'price' => $paymentMethod->getPrice(),
'icon' => $icon,
'logo' => (PaymentType::tryFrom($paymentMethod->getType()))?->getLogoFileName(),
];
if ($bnplWarning) {
$paymentMethodList[$paymentMethod->getId()]['bnplWarning'] = $bnplWarning;
$paymentMethodList[$paymentMethod->getId()]['inactive'] = true;
}
if ($paymentMethod->getType() == PaymentType::PastPay->value) {
$pastPayAvailable = true;
}
if ($inactive) {
$paymentMethodList[$paymentMethod->getId()]['inactive'] = true;
}
}
}
return [
'paymentList' => $paymentMethodList,
'showCetelemCalculator' => $showCetelemCalculator,
'cetelemDescLink' => $cetelemDescLink,
'cetelemDesc' => $cetelemDesc,
'pastPayAvailable' => $pastPayAvailable,
];
}
}