<?php
namespace App\AtechNet\CoreBundle\Controller;
use App\AtechNet\CoreBundle\Entity\Claim;
use App\AtechNet\CoreBundle\Entity\ClaimMedia;
use App\AtechNet\CoreBundle\Entity\ClaimStatus;
use App\AtechNet\CoreBundle\Entity\ClaimTest;
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\DocumentItem;
use App\AtechNet\CoreBundle\Entity\Domain;
use App\AtechNet\CoreBundle\Entity\DomainPaymentType;
use App\AtechNet\CoreBundle\Entity\DomainShippingType;
use App\AtechNet\CoreBundle\Entity\Notification;
use App\AtechNet\CoreBundle\Entity\NotificationConfig;
use App\AtechNet\CoreBundle\Entity\Order;
use App\AtechNet\CoreBundle\Entity\OrderItem;
use App\AtechNet\CoreBundle\Entity\OrderSetting;
use App\AtechNet\CoreBundle\Entity\PickupPoint;
use App\AtechNet\CoreBundle\Entity\ProductCommission;
use App\AtechNet\CoreBundle\Entity\ProductType;
use App\AtechNet\CoreBundle\Entity\StockMovement;
use App\AtechNet\CoreBundle\Entity\StockItem;
use App\AtechNet\CoreBundle\Entity\StockMovementItem;
use App\AtechNet\CoreBundle\Entity\UnasTranslator;
use App\AtechNet\CoreBundle\Entity\User;
use App\AtechNet\CoreBundle\Enum\PaymentType;
use App\AtechNet\CoreBundle\Form\CustomerAddressType;
use App\AtechNet\CoreBundle\Form\CustomerClaimType;
use App\AtechNet\CoreBundle\Form\CustomerEditType;
use App\AtechNet\CoreBundle\Form\CustomerForgotPasswordType;
use App\AtechNet\CoreBundle\Form\CustomerLoginType;
use App\AtechNet\CoreBundle\Form\CustomerType;
use App\AtechNet\CoreBundle\Form\CustomerWithdrawalType;
use App\AtechNet\CoreBundle\Form\NewsletterType;
use App\AtechNet\CoreBundle\Helper\BillingoOperation;
use App\AtechNet\CoreBundle\Helper\Furbify\MultiStore;
use App\AtechNet\CoreBundle\Helper\Furbify\OrderHelper;
use App\AtechNet\CoreBundle\Helper\Furbify\Registration;
use App\AtechNet\CoreBundle\Helper\KlaviyoConnect;
use App\AtechNet\CoreBundle\Helper\Security as SecurityHelper;
use Doctrine\ORM\Exception\NotSupported;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Mpdf\Mpdf;
use Mpdf\MpdfException;
use Psr\SimpleCache\InvalidArgumentException;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcher;
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\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use App\AtechNet\CoreBundle\Service\FinstatService;
class CustomerController extends AbstractController
{
public const INVOICE_TYPE_CENTRALIS = 1;
public const INVOICE_TYPE_BILLINGO = 2;
/**
* @Route("/registration", name="customer_registration", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/registration", name="customer_registration_locale", defaults={"_locale":""})
* @param Request $request
* @param UserPasswordHasherInterface $passwordHasher
* @return RedirectResponse|Response
* @throws InvalidArgumentException
* @throws OptimisticLockException
*/
public function registrationAction(Request $request, UserPasswordHasherInterface $passwordHasher)
{
$data = $this->registrationBaseData($request, $passwordHasher);
return is_array($data) ? $this->render('AtechNetCoreBundle/Customer/registration.html.twig', $data) : $data;
}
/**
* @param Request $request
* @param UserPasswordHasherInterface $passwordHasher
* @return array|RedirectResponse
* @throws InvalidArgumentException
* @throws OptimisticLockException
* @throws ORMException
*/
private function registrationBaseData(Request $request, UserPasswordHasherInterface $passwordHasher)
{
if ($this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('homepage');
}
$data = [];
$data['hideChat'] = true;
$data['heading_title'] = $this->getTranslator()->trans('Create account');
$multiStoreHelper = $this->getMultiStoreHelper($request);
$domain = $multiStoreHelper->getDomain();
$translator = $this->getTranslator();
$languageCode = $multiStoreHelper->getLanguage()->getCode();
$domainLanguageCode = $defaultLanguageCode = $multiStoreHelper->getDefaultLanguage()->getCode();
if ($domainLanguageCode == 'en') {
$domainLanguageCode = 'eu';
}
$customer = new Customer();
$customer->setCountry(strtoupper($domainLanguageCode));
$customer->setType((int)$request->get('type') ?: 0);
$form = $this->createForm(CustomerType::class, $customer, [
'action' => $this->generateUrl('customer_registration'),
'locale' => $languageCode,
'defaultLocale' => $defaultLanguageCode,
]);
$form->handleRequest($request);
$data['errorMessage'] = '';
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()) {
$entityManager = $this->getEntityManager();
if ($form->get('type')->getData() == 0) {
$customerType = MultiStore::CUSTOMER_TYPE_RETAIL;
} else {
$customerType = $form->get('type')->getData();
}
$setCountry = false;
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';
$setCountry = true;
break;
default:
$domainsToCheck = '';
}
if ($setCountry) {
$customer->setCountry(strtoupper($form->get('country')->getData()));
}
$domain = $entityManager->getRepository(Domain::class)->findOneById(MultiStore::defineDomainId($customerType, $request->getHttpHost()));
$duplicateCustomerCheck = $this->getEntityManager()
->createQuery("SELECT c
FROM AtechNetCoreBundle:Customer c
WHERE c.email = :email AND c.domain IN (" . $domainsToCheck . ")")
->setParameter('email', $form->get('email')->getData())
->getResult();
$captchaResponse = $request->request->get('g-recaptcha-response');
$captchaResult = $this->verifyGoogleCaptcha($captchaResponse);
if ($captchaResult) {
if (count($duplicateCustomerCheck) < 2) {
$itWasAGuestCustomer = false;
if (count($duplicateCustomerCheck) == 1) {
$newPassword = $customer->getPassword();
/**
* @var Customer $customer
*/
$customer = $duplicateCustomerCheck[0];
$itWasAGuestCustomer = true;
$registration = new Registration($this->getEntityManager(), $request, $passwordHasher);
$registration->saveGuestAsNewCustomer($customer, $newPassword);
} else {
$registration = new Registration($this->getEntityManager(), $request, $passwordHasher);
$registration->save($customer, $domain);
}
if ($this->getEnvironment() == 'prod') {
$contactInfos = $this->getContactInfos();
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:
$facebookLink = 'https://www.facebook.com/furbify.atechnet/';
$instagramLink = 'https://www.instagram.com/furbify.sk';
break;
case Domain::DOMAIN_ID_RT_HU:
case Domain::DOMAIN_ID_WS_HU:
$facebookLink = 'https://www.facebook.com/furbify.hu/';
$instagramLink = 'https://www.instagram.com/furbify.hu';
break;
default:
$facebookLink = '';
$instagramLink = '';
}
// Mailer
$mailer = $this->getMailer();
// Email
$email = (new TemplatedEmail())
->subject($this->getTranslator()->trans('Thank you for registering'))
->to($customer->getEmail())
->replyTo($this->getParameter('mailer_reply_to'))
->htmlTemplate('AtechNetCoreBundle/Email/registration.html.twig')
->context([
'retail' => $customerType == MultiStore::CUSTOMER_TYPE_RETAIL,
'domainLanguageCode' => $domainLanguageCode,
'greetingName' => $customer->getFirstname(),
'companyName' => $contactInfos['company.' . $defaultLanguageCode . '.name'],
'companySteet' => $contactInfos['company.' . $defaultLanguageCode . '.street'],
'companyCity' => $contactInfos['company.' . $defaultLanguageCode . '.city'],
'companyCountry' => $contactInfos['company.' . $defaultLanguageCode . '.country'],
'companyBusinessId' => $contactInfos['company.' . $defaultLanguageCode . '.id'],
'companyVatId' => $contactInfos['company.' . $defaultLanguageCode . '.vatId'],
'phoneNumber' => $contactInfos['phone.webshop.' . $defaultLanguageCode . '.' . $domain->getType()],
'shopEmail' => $contactInfos['mail.webshop.' . $defaultLanguageCode . '.' . $domain->getType()],
'facebookLink' => $facebookLink,
'instagramLink' => $instagramLink,
])
;
// Send Notification
$mailer->send($email);
if ($customerType == MultiStore::CUSTOMER_TYPE_WHOLESALE) {
$emailTo = $domain->getId() != Domain::DOMAIN_ID_WS_EU ? $customer->getSalesManager()->getEmail() : 'export@furbify.eu';
$email = (new TemplatedEmail())
->subject('New registration to activate ' . $customer->getDomain()->getShortTitle() . ' - ' . $customer->getBusinessName())
->to($emailTo)
->html('New registration on ' . $customer->getDomain()->getShortTitle() . ' - ' . $customer->getBusinessName());
$mailer->send($email);
$email = (new TemplatedEmail())
->subject($this->getTranslator()->trans('wholesaleEmail.subject'))
->to($customer->getEmail())
->replyTo($this->getParameter('mailer_reply_to'))
->htmlTemplate('AtechNetCoreBundle/Email/wholesaleRegistration.html.twig')
->context([])
;
$mailer->send($email);
}
}
$customer->setWantsNewsletter(true);
$entityManager->flush();
$this->getKlaviyoConnect($request)->createProfile($customer);
if ($customerType != MultiStore::CUSTOMER_TYPE_WHOLESALE && !$itWasAGuestCustomer) {
// "main" is the name of the firewall at security.yml
$token = new UsernamePasswordToken($customer, $customer->getPassword(), 'main', $customer->getRoles());
$this->container->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$dispatcher = new EventDispatcher();
$dispatcher->dispatch($event, "security.interactive_login");
$login = $this->getLoginHelper($request);
$login->login($customer->getEmail());
}
return $this->redirectToRoute('customer_registration_successful', [
'customerType' => $customerType,
]);
} else {
$data['errorMessage'] = $this->getTranslator()->trans('E-Mail Address is already registered');
if ($this->getEnvironment() == 'prod' && $domain->getId() == Domain::DOMAIN_ID_WS_EU) {
$mailer = $this->getMailer();
$customerEmail = $form->get('email')->getData();
$email = (new TemplatedEmail())
->subject('New registration attempt on WS EU - ' . $customerEmail)
->to('timea.osziova@furbify.eu')
->replyTo($this->getParameter('mailer_reply_to'))
->html('New registration attempt on WS EU - ' . $customerEmail);
$mailer->send($email);
}
}
} else {
$data['errorMessage'] = $this->getTranslator()->trans('Captcha check failed, please try again!');
}
}
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Create account'),
'href' => $this->generateUrl('customer_registration'),
];
$legalLinks = $this->getLegalLinks($request, $domain->getId());
$data['privacy_policy_link'] = $legalLinks['terms_conditions'];
$data['form'] = $form->createView();
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
if ($defaultLanguageCode == 'cz') {
$data['callingCountryCode'] = '+420';
} elseif ($defaultLanguageCode == 'hu') {
$data['callingCountryCode'] = '+36';
} else {
$data['callingCountryCode'] = '+421';
}
$data['insecurePasswords'] = SecurityHelper::getMostCommonPasswords();
return $data;
}
#[Route('/check-existing-email', name: 'check_existing_email')]
public function checkExistingEmailAction(Request $request): JsonResponse
{
$data = $request->request->get('customer');
if (!is_array($data)) {
return new JsonResponse(false);
}
$email = $data['email'];
$domainId = $request->getSession()->get('domainId');
$customer = $this->getEntityManager()->getRepository(Customer::class)->findOneBy([
'email' => $email,
'domain' => [$domainId, Domain::getRetailWholesaleDomainPairs()[$domainId]],
]);
return new JsonResponse(!((bool) $customer));
}
/**
* @Route("/registration-successful/{customerType}", name="customer_registration_successful", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/registration-successful/{customerType}", name="customer_registration_successful_locale", defaults={"_locale":""})
* @param Request $request
* @param int $customerType
* @return Response
* @throws InvalidArgumentException
*/
public function registrationSuccessfulAction(Request $request, int $customerType): Response
{
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Successful registration');
$data['breadcrumbs'] = [];
$data['customerType'] = $customerType;
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Successful registration'),
'href' => $this->generateUrl('customer_registration_successful', [
'customerType' => $customerType,
]),
];
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/registrationSuccessful.html.twig', $data);
}
/**
* @Route("/login", name="customer_login", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/login", name="customer_login_locale", defaults={"_locale":""})
* @param AuthenticationUtils $authenticationUtils
* @param Request $request
* @return Response
* @throws InvalidArgumentException
* @throws OptimisticLockException
*/
public function loginAction(AuthenticationUtils $authenticationUtils, Request $request)
{
$error = $authenticationUtils->getLastAuthenticationError(false);
if ($error) {
$this->addFlash(
'danger',
$this->getTranslator()->trans(
$this->getLoginHelper($request)->handleRequestError($error)
)
);
$request->getSession()->remove(Security::AUTHENTICATION_ERROR);
$referer = $request->headers->get('referer');
if (str_contains($referer, 'partner-login')) {
return $this->redirectToRoute('partner_login');
}
}
$loginData = $this->loginBaseData($request);
if (is_array($loginData)) {
return $this->render('AtechNetCoreBundle/Customer/login.html.twig', $loginData);
} else {
return $loginData;
}
}
/**
* @Route("/partner-login", name="partner_login", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/partner-login", name="partner_login_locale", defaults={"_locale":""})
* @param AuthenticationUtils $authenticationUtils
* @param Request $request
* @return array|Response
* @throws InvalidArgumentException
* @throws OptimisticLockException
*/
public function partnerLoginAction(Request $request)
{
$data = $this->loginBaseData($request);
if (is_array($data)) {
$multiStore = $this->getMultiStoreHelper($request);
$domain = $multiStore->getDomain();
$domainLanguage = $domain->getLanguage();
$entityManager = $this->getEntityManager();
// get the wholesale type of current language domain
$domain = $entityManager->getRepository(Domain::class)->findOneBy([
'language' => $domainLanguage,
'type' => Domain::TYPE_WHOLESALE,
]);
$data['warrantyYear'] = $this->getWarrantyForNonProductText($domain->getId());
// default salesManager
$data['salesManager'] = $domain->getDefaultSalesManager();
if ($domainLanguage->getCode() == 'sk') {
$data['salesManager1'] = $entityManager->getRepository(User::class)->findOneById(231);
$data['salesManager2'] = $entityManager->getRepository(User::class)->findOneById(224);
}
$data['languageCode'] = $domainLanguage->getCode();
return $this->render('AtechNetCoreBundle/Customer/partnerLogin.html.twig', $data);
} else {
return $data;
}
}
/**
* @param Request $request
* @return array|RedirectResponse
* @throws InvalidArgumentException
* @throws OptimisticLockException
*/
private function loginBaseData(Request $request)
{
if ($this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_account');
}
$translator = $this->getTranslator();
$data = [];
$data['hideChat'] = true;
$data['heading_title'] = $translator->trans('Login');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Login'),
'href' => $this->generateUrl('customer_login'),
];
$targetPath = !is_null($request->get('_target_path')) ? $request->get('_target_path') : '';
$data['targetPath'] = $targetPath;
$customer = new Customer();
$form = $this->createForm(CustomerLoginType::class, $customer, [
'action' => $this->generateUrl('customer_login'),
]);
$form->handleRequest($request);
$data['form'] = $form->createView();
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $data;
}
/**
* @Route("/account", name="customer_account", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account", name="customer_account_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function accountAction(Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$multiStore = $this->getMultiStoreHelper($request);
$translator = $this->getTranslator();
$customerTypeId = $request->getSession()->get('customerTypeId');
$data = [];
$data['heading_title'] = $this->getTranslator()->trans('My Account');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$data['name'] = $customerTypeId == MultiStore::CUSTOMER_TYPE_RETAIL ? $customer->getFullName() : $customer->getBusinessName();
$domain = $multiStore->getDomain();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
// Orders under processing
$data['orders'] = [];
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder
->select('o')
->from('AtechNetCoreBundle:Order', 'o')
->andWhere('o.customer = :customerId')
->setParameter(':customerId', $customer->getId())
->andWhere(
$queryBuilder->expr()->notIn('o.status', [Order::STATUS_CANCELED, Order::STATUS_FINISHED])
)
->andWhere('o.domain = :domainId')
->setParameter(':domainId', $domain->getId())
->orderBy('o.created', 'DESC')
->setFirstResult(0);
$query = $queryBuilder->getQuery();
$results = $query->getResult();
foreach ($results as $result) {
$data['orders'][] = [
'orderId' => $result->getId(),
'dateAdded' => $result->getCreated()->format($this->getTranslator()->trans('datetime.format')),
'status' => $result->getStatus() > 0 ? $result->getStatusTitle($this->getDatabaseTranslator($request)) : '',
'statusId' => $result->getStatus(),
'total' => $result->getFullPrice(),
'view' => $this->generateUrl('customer_order_show', [
'orderId' => $result->getId(),
]),
];
}
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/account.html.twig', $data);
}
/**
* @Route("/account/edit", name="customer_account_edit", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/edit", name="customer_account_edit_locale", defaults={"_locale":""})
* @param Request $request
* @param UserPasswordHasherInterface $passwordHasher
* @return Response
* @throws InvalidArgumentException
*/
public function accountEditAction(Request $request, UserPasswordHasherInterface $passwordHasher): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$multiStore = $this->getMultiStoreHelper($request);
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Account Details');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account Details'),
'href' => $this->generateUrl('customer_account_edit'),
];
// Logged in Customer
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
// Billing Address
$billingAddress = null;
foreach ($customer->getAddresses() as $address) {
if ($address->getType() == CustomerAddress::AddressType_Billing_Id) {
$billingAddress = $address;
break;
}
}
// Doman Language Code
$domainLanguageCode = $multiStore->getDomain()->getLanguage()->getCode();
// Phone Number
$phoneNumber = $customer->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 ($domainLanguageCode == 'cz') {
$phoneNumber = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$phoneNumber = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
// Build Form
$defaultData = [
'email' => $customer->getEmail(),
'phoneNumber' => $phoneNumber,
'firstName' => $customer->getFirstName(),
'lastName' => $customer->getLastName(),
'address' => !is_null($billingAddress) ? $billingAddress->getStreet() : '',
'postalCode' => !is_null($billingAddress) ? $billingAddress->getZip() : '',
'city' => !is_null($billingAddress) ? $billingAddress->getCity() : '',
'country' => !is_null($billingAddress) ? $billingAddress->getCountry() : $multiStore->getDefaultCountry(),
'businessName' => $customer->getBusinessName(),
'businessId' => $customer->getBusinessId(),
'taxId' => $customer->getTaxId(),
'vatNumber' => $customer->getVatId(),
];
$form = $this->createForm(CustomerEditType::class, $defaultData, [
'locale' => $request->getLocale(),
'customer' => $customer,
'passwordHasher' => $passwordHasher,
]);
$originalEmail = $customer->getEmail();
$form->handleRequest($request);
if ($form->isSubmitted()) {
if (!empty($form->get('password')->get('first')->getData()) && SecurityHelper::insecure($form->get('password')->get('first')->getData())) {
$form->get('password')->get('first')->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()) {
$entityManager = $this->getEntityManager();
// Billing Address
if (is_null($billingAddress)) { // Insert New
$billingAddress = new CustomerAddress();
$billingAddress->setCustomer($customer);
$billingAddress->setType(CustomerAddress::AddressType_Billing_Id);
$billingAddress->setTitle('');
$billingAddress->setFirstName($form->get('firstName')->getData());
$billingAddress->setLastName($form->get('lastName')->getData());
$billingAddress->setBusinessName($form->get('businessName')->getData());
$billingAddress->setStreet($form->get('address')->getData());
$billingAddress->setCity($form->get('city')->getData());
$billingAddress->setZip($form->get('postalCode')->getData());
$billingAddress->setCountry($form->get('country')->getData());
// District
$billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
$billingAddress->setPhone('');
$billingAddress->setEmail('');
$entityManager->persist($billingAddress);
$entityManager->flush();
} else { // Update Existing
$billingAddress->setFirstName($form->get('firstName')->getData());
$billingAddress->setLastName($form->get('lastName')->getData());
$billingAddress->setBusinessName($form->get('businessName')->getData());
$billingAddress->setStreet($form->get('address')->getData());
$billingAddress->setCity($form->get('city')->getData());
$billingAddress->setZip($form->get('postalCode')->getData());
$billingAddress->setCountry($form->get('country')->getData());
// District
$billingAddress->setDistrict(OrderHelper::findDistrict($billingAddress->getZip(), $billingAddress->getCountry(), $request));
$entityManager->flush();
}
// Update Customer
$customer->setFirstName($form->get('firstName')->getData());
$customer->setLastName($form->get('lastName')->getData());
$customer->setBusinessName($form->get('businessName')->getData());
$customer->setBusinessId(str_replace([' ', '-'], '', $form->get('businessId')->getData()));
$customer->setTaxId($form->get('taxId')->getData());
$customer->setVatId($form->get('vatNumber')->getData());
// Phone Number
$phoneNumber = $form->get('phoneNumber')->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 ($domainLanguageCode == 'cz') {
$phoneNumber = '+420' . preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = '+36' . preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'sk') {
$phoneNumber = '+421' . preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
} else {
$phoneNumber = $_phoneNumber;
}
$customer->setPhone($phoneNumber);
// Update Password
if (!empty($form->get('password')->get('first')->getData())) {
$password = Registration::encodePassword(
$form->get('password')->get('first')->getData(),
$customer,
$passwordHasher
);
$customer->setPassword($password);
}
$entityManager->flush();
if ($this->getEnvironment() == 'prod') {
$klaviyo = $this->getKlaviyoConnect($request);
if ($originalEmail && $originalEmail != $customer->getEmail()) {
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $originalEmail]);
}
else {
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $customer->getEmail()]);
}
if (isset($klaviyoProfile[0])) {
$klaviyo->updateProfile($customer, $klaviyoProfile[0]);
} else if ($customer->isWantsNewsletter()) {
$klaviyo->createProfile($customer);
}
}
$this->addFlash(
'success',
$this->getTranslator()->trans('Your account has been successfully updated')
);
return $this->redirectToRoute('customer_account_edit');
}
$data['form'] = $form->createView();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
if ($domainLanguageCode == 'cz') {
$data['callingCountryCode'] = '+420';
} elseif ($domainLanguageCode == 'hu') {
$data['callingCountryCode'] = '+36';
} else {
$data['callingCountryCode'] = '+421';
}
$data['domainLanguageCode'] = $domainLanguageCode;
$data['insecurePasswords'] = SecurityHelper::getMostCommonPasswords();
return $this->render('AtechNetCoreBundle/Customer/accountEdit.html.twig', $data);
}
/**
* @Route("/account/address", name="customer_address", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/address", name="customer_address_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function addressAction(Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Shipping Addresses'),
'href' => $this->generateUrl('customer_address'),
];
$data['heading_title'] = $translator->trans('Shipping Addresses');
// Logged in Customer
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
// Countries
$countries = $this->getMultiStoreHelper($request)->getDomain()->getId() == 11
? CustomerAddress::EU_COUNTRIES
: CustomerAddress::getCountries();
// Shipping Addresses
$data['addresses'] = [];
foreach ($customer->getAddresses() as $address) {
if ($address->getType() == CustomerAddress::AddressType_Shipping_Id) {
if (!empty($address->getTitle())) {
$format = '{title}' . "\n\n" . '{firstname} {lastname}' . "\n" . '{street}' . "\n" . '{postalcode} {city}' . "\n" . '{country}';
} else {
$format = '{firstname} {lastname}' . "\n" . '{street}' . "\n" . '{postalcode} {city}' . "\n" . '{country}';
}
$find = [
'{title}',
'{firstname}',
'{lastname}',
'{street}',
'{city}',
'{postalcode}',
'{country}',
];
$replace = [
'title' => '<strong>' . $address->getTitle() . '</strong>',
'firstname' => $address->getFirstName(),
'lastname' => $address->getLastName(),
'street' => $address->getStreet(),
'city' => $address->getCity(),
'postalcode' => $address->getZip(),
'country' => $countries[$address->getCountry()],
];
$data['addresses'][] = [
'addressId' => $address->getId(),
'address' => str_replace(
["\r\n", "\r", "\n"],
'<br />',
preg_replace(
["/\s\s+/", "/\r\r+/", "/\n\n+/"],
'<br />',
trim(str_replace($find, $replace, $format))
)
),
'edit' => $this->generateUrl('customer_address_edit', [
'addressId' => $address->getId(),
]),
'delete' => $this->generateUrl('customer_address_delete', [
'addressId' => $address->getId(),
]),
];
}
}
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/address.html.twig', $data);
}
/**
* @Route("/account/address/add", name="customer_address_add", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/address/add", name="customer_address_add_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function addressAddAction(Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$multiStore = $this->getMultiStoreHelper($request);
$translator = $this->getTranslator();
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Shipping Addresses'),
'href' => $this->generateUrl('customer_address'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Add new address'),
'href' => $this->generateUrl('customer_address_add'),
];
$data['heading_title'] = $translator->trans('Add new address');
// Logged in Customer
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
// Add new Address
$customerAddress = new CustomerAddress();
if ($this->getMultiStoreHelper($request)->getDomain()->getId() != 11) {
// Set Default Country, if the domain is not EU
$customerAddress->setCountry($multiStore->getDefaultCountry());
}
$form = $this->createForm(CustomerAddressType::class, $customerAddress, [
'locale' => $request->getLocale(),
'isEuDomain' => $this->getMultiStoreHelper($request)->getDomain()->getId() == 11,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getEntityManager();
$customerAddress->setCustomer($customer);
$customerAddress->setType(CustomerAddress::AddressType_Shipping_Id);
$entityManager->persist($customerAddress);
$entityManager->flush();
if ($this->getEnvironment() == 'prod') {
$klaviyo = $this->getKlaviyoConnect($request);
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $customer->getEmail()]);
if (isset($klaviyoProfile[0])) {
$klaviyo->updateProfile($customer, $klaviyoProfile[0]);
} else if ($customer->isWantsNewsletter()) {
$klaviyo->createProfile($customer);
}
}
$this->addFlash(
'success',
$translator->trans('Your address has been successfully added')
);
return $this->redirectToRoute('customer_address');
}
$data['form'] = $form->createView();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/addressForm.html.twig', $data);
}
/**
* @Route("/account/address/{addressId}/edit", name="customer_address_edit", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/address/{addressId}/edit", name="customer_address_edit_locale", defaults={"_locale":""})
* @param int $addressId
* @param Request $request
* @return Response
* @throws \Exception
*/
public function addressEditAction(int $addressId, Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$customerAddress = $this->getEntityManager()->getRepository(CustomerAddress::class)->findOneById($addressId);
if ($customerAddress) {
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Shipping Addresses'),
'href' => $this->generateUrl('customer_address'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Edit Address'),
'href' => $this->generateUrl('customer_address_edit', [
'addressId' => $customerAddress->getId(),
]),
];
$data['heading_title'] = $translator->trans('Edit Address');
// Edit Address
$form = $this->createForm(CustomerAddressType::class, $customerAddress, [
'locale' => $request->getLocale(),
'isEuDomain' => $this->getMultiStoreHelper($request)->getDomain()->getId() == 11,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getEntityManager();
$entityManager->persist($customerAddress);
$entityManager->flush();
if ($this->getEnvironment() == 'prod') {
$customer = $customerAddress->getCustomer();
$klaviyo = $this->getKlaviyoConnect($request);
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $customer->getEmail()]);
if (isset($klaviyoProfile[0])) {
$klaviyo->updateProfile($customer, $klaviyoProfile[0]);
} else if ($customer->isWantsNewsletter()) {
$klaviyo->createProfile($customer);
}
}
$this->addFlash(
'success',
$translator->trans('Your address has been successfully edited')
);
return $this->redirectToRoute('customer_address');
}
$data['form'] = $form->createView();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/addressForm.html.twig', $data);
}
$this->addFlash(
'error',
$translator->trans('Your address has not been found:')
);
return $this->redirectToRoute('customer_address');
}
/**
* @Route("/account/address/{addressId}/delete", name="customer_address_delete", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/address/{addressId}/delete", name="customer_address_delete_locale", defaults={"_locale":""})
* @param int $addressId
* @param Request $request
* @return Response
*/
public function addressDeleteAction(int $addressId, Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$customerAddress = $this->getEntityManager()->getRepository(CustomerAddress::class)->findOneById($addressId);
if ($customerAddress) {
$entityManager = $this->getEntityManager();
$customerId = $customerAddress->getCustomer()->getId();
$entityManager->remove($customerAddress);
$entityManager->flush();
if ($this->getEnvironment() == 'prod') {
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
$klaviyo = $this->getKlaviyoConnect($request);
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $customer->getEmail()]);
if (isset($klaviyoProfile[0])) {
$klaviyo->updateProfile($customer, $klaviyoProfile[0]);
} else if ($customer->isWantsNewsletter()) {
$klaviyo->createProfile($customer);
}
}
$this->addFlash(
'success',
$translator->trans('Your address has been successfully deleted')
);
return $this->redirectToRoute('customer_address');
}
$this->addFlash(
'error',
$translator->trans('Your address has not been found:')
);
return $this->redirectToRoute('customer_address');
}
/**
* @Route("/account/newsletter", name="customer_newsletter", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/newsletter", name="customer_newsletter_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function newsletterAction(Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('My Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Newsletter Subscription'),
'href' => $this->generateUrl('customer_newsletter'),
];
$data['heading_title'] = $translator->trans('Newsletter Subscription');
// Logged in Customer
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$entityManager = $this->getEntityManager();
// Edit Subscription
$form = $this->createForm(
NewsletterType::class,
[
'subscribe' => $customer->isWantsNewsletter(),
],
[
'locale' => $request->getLocale(),
]
);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$customer->setWantsNewsletter($form->get('subscribe')->getData());
if ($this->getEnvironment() == 'prod') {
$klaviyo = $this->getKlaviyoConnect($request);
$klaviyoProfile = $klaviyo->getProfileWithFilter(['email' => $customer->getEmail()]);
if (isset($klaviyoProfile[0])) {
$klaviyo->updateProfile(
$customer,
$klaviyoProfile[0],
$customer->isWantsNewsletter()
);
}
}
$entityManager->persist($customer);
$entityManager->flush();
$this->addFlash(
'success',
$translator->trans('Your newsletter subscription has been successfully updated')
);
return $this->redirectToRoute('customer_newsletter');
}
$data['form'] = $form->createView();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/newsletter.html.twig', $data);
}
/**
* @Route("/account/order", name="customer_orders", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/order", name="customer_orders_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function orderAction(Request $request): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$multiStore = $this->getMultiStoreHelper($request);
$domainId = $multiStore->getDomainId();
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Orders');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Orders'),
'href' => $this->generateUrl('customer_orders'),
];
if ($request->get('page')) {
$page = $request->get('page');
} else {
$page = 1;
}
$limit = 15;
$domain = $multiStore->getDomain();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
$data['orders'] = [];
$results = $this->getEntityManager()->getRepository(Order::class)->findBy(
[
'customer' => $customer->getId(),
'domain' => $domain->getId(),
],
[
'created' => 'DESC',
],
$limit,
(($page - 1) * $limit)
);
$total = $this->getEntityManager()->getRepository(Order::class)->findBy([
'customer' => $customer->getId(),
'domain' => $domain->getId(),
]);
/**
* @var Order $result
* @var Document $document
* @var CustomerBillingoData $billingoDocument
*/
foreach ($results as $result) {
$invoiceLink = '';
if ($result->getStatus() == Order::STATUS_FINISHED) {
if ($result->getDocuments()->count() > 0 || $result->getBillingoDocuments()->count() > 0) {
if (in_array($domainId, [1, 2, 5, 9, 3, 4]) && $result->getDocuments()->count() > 0) { // Centralis documents
$invoiceId = 0;
foreach ($result->getDocuments() as $document) {
if ($invoiceId == 0) {
$invoiceId = $document->getId();
} elseif ($invoiceId != 0 && $document->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_OUT) {
$invoiceId = $document->getId();
}
}
$invoiceLink = $this->generateUrl('customer_invoice_pdf', [
'id' => $invoiceId,
'type' => self::INVOICE_TYPE_CENTRALIS,
]);
} elseif (in_array($domainId, [3, 4]) || $result->getBillingoDocuments()->count()) { // Billingo documents
$invoiceId = 0;
foreach ($result->getBillingoDocuments() as $billingoDocument) {
if ($invoiceId == 0) {
$invoiceId = $billingoDocument->getId();
} elseif ($invoiceId != 0 && $billingoDocument->getType() == BillingoOperation::TYPE_NORMAL) {
$invoiceId = $billingoDocument->getId();
}
}
$invoiceLink = $this->generateUrl('customer_invoice_pdf', [
'id' => $invoiceId,
'type' => self::INVOICE_TYPE_BILLINGO,
]);
}
}
}
$statusTitle = '';
$waitingStatuses = [
Order::STATUS_TRIAGE,
Order::STATUS_WAITING,
Order::STATUS_WAITING_FOR_PARTNER,
Order::STATUS_WAITING_FOR_PRODUCTION,
Order::STATUS_WAITING_FOR_PRODUCTION_SALES,
Order::STATUS_WAITING_FOR_PRODUCTION_QUARANTINE,
Order::STATUS_WAITING_FOR_PRODUCTION_AIKEN,
Order::STATUS_WAITING_FOR_ANSWER_SALES,
Order::STATUS_WAITING_FOR_ANSWER_SERVICE,
Order::STATUS_WAITING_FOR_ANSWER_ADMIN,
Order::STATUS_WAITING_FOR_ANSWER,
];
if ($result->getStatus() > 0) {
if (
$result->getStatus() <= Order::STATUS_WAITING_FOR_ANSWER_SALES
|| in_array($result->getStatus(), $waitingStatuses)
) {
$statusTitle = $this->getTranslator()->trans('Processing');
} else {
$statusTitle = $this->getTranslator()->trans($result->getStatusTitle());
}
}
if ($result->getPickupPointSetting()) {
$pickupPointId = $result->getPickupPointSetting()->getValue();
$pickupPoint = $this->getEntityManager()->getRepository(PickupPoint::class)->findOneById($pickupPointId);
$statusTitle .= ' - ' . $pickupPoint->getStreet() . ', ' . $pickupPoint->getCity() . ', ' . $pickupPoint->getZip() . ', ' . CustomerAddress::getCountries()[$pickupPoint->getCountry()];
}
$data['orders'][] = [
'orderId' => $result->getId(),
'dateAdded' => $result->getCreated()->format($this->getTranslator()->trans('datetime.format')),
'status' => $statusTitle,
'statusId' => $result->getStatus(),
'total' => $result->getFullPrice(),
'view' => $this->generateUrl('customer_order_show', [
'orderId' => $result->getId(),
]),
'invoiceLink' => $invoiceLink,
];
}
$data['pagination'] = [
'total' => count($total),
'page' => $page,
'limit' => $limit,
'url' => $this->generateUrl('customer_orders', [
'page' => '{page}',
]),
'noInfinite' => 1,
];
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/orders.html.twig', $data);
}
/**
* @Route("/account/invoice/{id}/{type}/{token}", name="customer_invoice_pdf", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/invoice/{id}/{type}/{token}", name="customer_invoice_pdf_locale", defaults={"_locale":""})
* @param Request $request
* @param int $id
* @param int $type
* @param string|null $token
* @return RedirectResponse|Response
* @throws \Mpdf\MpdfException
*/
public function downloadInvoiceAction(Request $request, int $id, int $type, ?string $token = null): RedirectResponse|Response
{
// Order Repository
$orderRepository = $this->getEntityManager()->getRepository(Order::class);
// Show Public Order
if (!is_null($token)) {
$publicOrder = $orderRepository->decodePublicLinkToken($token);
if (is_null($publicOrder) || !isset($publicOrder['orderId']) || !isset($publicOrder['documentId']) || !isset($publicOrder['type']) || (isset($publicOrder['documentId']) && $id !== (int)$publicOrder['documentId']) || (isset($publicOrder['type']) && $type !== (int)$publicOrder['type'])) {
return $this->redirectToRoute('not_found');
}
} elseif (!$this->getLoginHelper($request)->isLoggedIn()) { // Otherwise: Logged-in Customer
return $this->redirectToRoute('customer_login');
}
$entityManager = $this->getEntityManager();
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
if (!is_numeric($id)) {
throw new InvalidParameterException();
}
if ($type == self::INVOICE_TYPE_CENTRALIS) {
if (!is_null($token)) {
$document = $entityManager->getRepository(Document::class)->findOneBy([
'id' => $id,
]);
} else {
$document = $entityManager->getRepository(Document::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
}
if ($document) {
// Validate public link
if (isset($publicOrder['orderId']) && $document->getOrder()->getId() !== (int)$publicOrder['orderId']) {
return $this->redirectToRoute('not_found');
}
$documentRepo = $entityManager->getRepository(Document::class);
$pdf = $documentRepo->createPdf($document, 0, $this->getSquarePay());
return new Response(
$pdf->output(sprintf(
'%s-%s-%d.pdf',
($document->getBusinessName() != '' ? $document->getBusinessName() : $document->getFirstName() . '-' . $document->getLastName()),
strtolower(
iconv(
'utf-8',
'us-ascii//TRANSLIT',
$this->getTranslator()->trans(DocumentGroup::TYPES[$document->getGroup()->getType()])
)
),
$document->getCode()
), 'I'),
Response::HTTP_OK,
[
'content-type' => 'application/pdf',
]
);
}
} elseif ($type == self::INVOICE_TYPE_BILLINGO) {
/**
* @var CustomerBillingoData $billingoInvoice
*/
if (!is_null($token)) {
$billingoInvoice = $entityManager->getRepository(CustomerBillingoData::class)->findOneBy([
'id' => $id,
]);
} else {
$billingoInvoice = $entityManager->getRepository(CustomerBillingoData::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
}
if ($billingoInvoice) {
// Validate public link
if (isset($publicOrder['orderId']) && $billingoInvoice->getOrder()->getId() !== (int)$publicOrder['orderId']) {
return $this->redirectToRoute('not_found');
}
return new Response(
$this->getBillingo()->downloadDocument($billingoInvoice->getInvoiceV3Id()),
200,
[
'Content-type' => 'application/pdf',
]
);
}
}
return $this->redirectToRoute('not_found');
}
/**
* @Route("/account/order/{orderId}/{token}", name="customer_order_show", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/order/{orderId}/{token}", name="customer_order_show_locale", defaults={"_locale":""})
*
* @param Request $request
* @param int $orderId
* @param string|null $token
* @return Response
* @throws \Exception
*/
public function showOrderAction(Request $request, int $orderId, ?string $token = null): Response
{
// Order Repository
$orderRepository = $this->getEntityManager()->getRepository(Order::class);
// Show Public Order
if (!is_null($token)) {
$publicOrder = $orderRepository->decodePublicLinkToken($token);
if (is_null($publicOrder) || !isset($publicOrder['orderId']) || (isset($publicOrder['orderId']) && $orderId !== (int)$publicOrder['orderId'])) {
return $this->redirectToRoute('not_found');
}
// Put Order ID to the Session for later use on Payment Result Page
$request->getSession()->set('paymentOrderId', $orderId);
} // Otherwise: Logged-in Customer
elseif (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$multiStore = $this->getMultiStoreHelper($request);
$productHelper = $this->getProductHelper($request);
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$translator = $this->getTranslator();
$seoUrlHelper = $this->getSeoUrlHelper($request);
$domainId = $multiStore->getDomainId();
$data = [];
$data['errorMessage'] = '';
$data['heading_title'] = $translator->trans('Order') . ': ' . $orderId;
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Orders'),
'href' => $this->generateUrl('customer_orders'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Order') . ': ' . $orderId,
'href' => $this->generateUrl('customer_order_show', [
'orderId' => $orderId,
]),
];
$domain = $multiStore->getDomain();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
$entityManager = $this->getEntityManager();
if (!is_null($token)) {
/**
* @var Order $order
*/
$order = $entityManager->getRepository(Order::class)->findOneBy([
'id' => $orderId,
'domain' => $domain->getId(),
]);
} else {
/**
* @var Order $order
*/
$order = $entityManager->getRepository(Order::class)->findOneBy([
'id' => $orderId,
'customer' => $customer->getId(),
'domain' => $domain->getId(),
]);
}
if ($order) {
// Countries
$countries = CustomerAddress::getCountries();
$data['orderId'] = $order->getId();
$data['orderStatusTitle'] = '';
$orderStatus = $order->getStatus();
if ($orderStatus > 0) {
if ((Order::STATUS_PRE_PROCESSING_ISSUE <= $orderStatus && $orderStatus <= Order::STATUS_WAITING_FOR_ANSWER) || $orderStatus == Order::STATUS_TRIAGE || $orderStatus == Order::STATUS_PROCESSING_ISSUES) {
$data['orderStatusTitle'] = $this->getTranslator()->trans('Processing');
} else {
$data['orderStatusTitle'] = $this->getTranslator()->trans($order->getStatusTitle());
}
}
$warrantyEnd = $order->getWarrantyEnd();
$data['orderInWarranty'] = (new \DateTime()) < $warrantyEnd;
$data['productInWarranty'] = (new \DateTime()) < $warrantyEnd;
$data['warrantyEnd'] = $warrantyEnd->format($translator->trans('datetime.format'));
$data['dateAdded'] = $order->getCreated()->format($translator->trans('datetime.format'));
$defaultFormat = '{firstname} {lastname}' . "\n" . '{street}' . "\n" . '{postalcode} {city}' . "\n" . '{country}';
$format = false;
$find = [
'{firstname}',
'{lastname}',
'{street}',
'{city}',
'{postalcode}',
'{country}',
'{company}',
];
if ($order->getShippingBusinessName() != '') {
$format = '{company}' . "\n" . $defaultFormat;
}
$countrySelection = CustomerAddress::getCountries();
$country = $countrySelection[$order->getShippingCountry()] ?? $order->getShippingCountry();
$replace = [
'firstname' => $order->getShippingFirstName(),
'lastname' => $order->getShippingLastName(),
'street' => $order->getShippingStreet(),
'city' => $order->getShippingCity(),
'postalcode' => $order->getShippingZip(),
'country' => $country,
'company' => $order->getShippingBusinessName(),
];
$data['shippingAddress'] = str_replace(
["\r\n", "\r", "\n"],
'<br />',
preg_replace(
["/\s\s+/", "/\r\r+/", "/\n\n+/"],
'<br />',
trim(str_replace(
$find,
$replace,
($format ? $format : $defaultFormat)
))
)
);
$translationKey = 'shipping.method.type.' . $order->getShippingType();
if (($data['shippingMethod'] = $translator->trans($translationKey)) == $translationKey) {
$data['shippingMethod'] = $translator->trans('Delivery method');
}
$data['shippingCost'] = $order->getShippingPrice();
if ($order->getBillingBusinessName() != '') {
$format = '{company}' . "\n" . $defaultFormat;
} else {
$format = $defaultFormat;
}
$replace = [
'firstname' => $order->getBillingFirstName(),
'lastname' => $order->getBillingLastName(),
'street' => $order->getBillingStreet(),
'city' => $order->getBillingCity(),
'postalcode' => $order->getBillingZip(),
'country' => in_array($domainId, [Domain::DOMAIN_ID_RT_EU, Domain::DOMAIN_ID_WS_EU]) ? CustomerAddress::EU_COUNTRIES[$order->getBillingCountry()] : $countries[$order->getBillingCountry()],
'company' => $order->getBillingBusinessName(),
];
$data['billingAddress'] = str_replace(
["\r\n", "\r", "\n"],
'<br />',
preg_replace(
["/\s\s+/", "/\r\r+/", "/\n\n+/"],
'<br />',
trim(str_replace($find, $replace, ($format ? $format : $defaultFormat)))
)
);
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();
}
if (($data['paymentMethod'] = $translator->trans($translationKey)) == $translationKey) {
$data['paymentMethod'] = $translator->trans('Payment method');
}
$data['paymentCost'] = $order->getPaymentPrice();
$data['products'] = [];
$dbTranslator = $this->getDatabaseTranslator($request);
/** @var OrderItem $item */
foreach ($order->getOrderItems() as $item) {
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($dbTranslator);
if (!$optionValue) {
$optionValue = $option->getTitle($dbTranslator);
}
$optionTitle = $option->getAttribute()->getTitle();
//-> Warranty
$warranty = false;
if ($option->getId() == 2226) { // +1 year
$warranty = (clone $warrantyEnd)->add(new \DateInterval('P1Y'));
} elseif ($option->getId() == 2227) { // +2 year
$warranty = (clone $warrantyEnd)->add(new \DateInterval('P2Y'));
} elseif ($option->getId() == 2228) { // +3 year
$warranty = (clone $warrantyEnd)->add(new \DateInterval('P3Y'));
}
if ($data['productInWarranty'] === false) {
$data['productInWarranty'] = (new \DateTime()) < $warranty;
}
//<- Warranty
$options[] = [
'id' => $attribute->getId(),
'title' => $optionTitle,
'value' => $optionValue,
'warranty' => ($warranty !== false ? $warranty->format($translator->trans('datetime.format')) : false),
'inWarranty' => ($warranty !== false && $warrantyEnd !== $warranty && (new \DateTime()) < $warranty),
];
}
}
$data['items'][] = [
'id' => $item->getId(),
'code' => $product['code'],
'href' => $seoUrlHelper->link('product', [
'product_id' => $product['id'],
'isBazaar' => $product['isBazaar'] ?? 0
]),
'name' => ($product['vendor'] !== '' && $product['vendor'] !== 'VARIOUS' ? $product['vendor'] . ' ' : '') . $product['title'],
'description' => !is_null($item->getCustomConfiguration()) && $item->getCustomConfiguration() != '' ? $item->getCustomConfiguration() : $product['shortDescription'],
'quantity' => $item->getQuantity(),
'price' => $item->getItemFullPrice(),
'options' => $options,
];
}
}
}
if (!empty($order->getCouponCode())) {
$data['coupon'] = $order->getCouponCode();
$coupon = $order->getCouponCodeSetting();
if ($coupon) {
$data['discount'] = $coupon->getValue();
} else {
$data['discount'] = 0;
}
} else {
$data['coupon'] = '';
$data['discount'] = 0;
}
// Payment Status
$data['paymentStatus'] = -1;
if (in_array((int)$order->getPaymentType(), [PaymentType::DebitCard->value, PaymentType::DebitCard3Percent->value])) {
$data['paymentStatus'] = (int)$order->getPaymentStatus();
if ((int)$order->getPaymentStatus() == Order::PAYMENT_STATUS_PAID) {
// GoPay
if (in_array((int)$order->getDomain()->getId(), [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ, Domain::DOMAIN_ID_B2C_EU])) {
$orderSetting = $order->getGoPayTransactionIdSetting();
if ($orderSetting) {
$data['datePaid'] = $orderSetting->getCreated()->format($translator->trans('datetime.format'));
}
}
} elseif (in_array((int)$order->getPaymentStatus(), [Order::PAYMENT_STATUS_PENDING, Order::PAYMENT_STATUS_FAILED])) {
// GoPay
if (in_array((int)$order->getDomain()->getId(), [Domain::DOMAIN_ID_RT_HU, Domain::DOMAIN_ID_WS_HU, Domain::DOMAIN_ID_RT_SK, Domain::DOMAIN_ID_WS_SK, Domain::DOMAIN_ID_RT_CZ, Domain::DOMAIN_ID_WS_CZ, Domain::DOMAIN_ID_B2C_EU, Domain::DOMAIN_ID_RT_EU, Domain::DOMAIN_ID_WS_EU])) {
// Helper
$gopayHelper = $this->getGopayHelper($request);
// Payment
$data['gopay_data'] = $gopayHelper->getInlineGatewayDataForOrder($order);
}
}
}
if ($order->getPaymentType() == PaymentType::Klarna->value) {
$data['paymentStatus'] = (int)$order->getPaymentStatus();
$orderSetting = $order->getKlarnaPaymentSessionIdSetting();
if ($orderSetting) {
if ((int)$order->getPaymentStatus() == Order::PAYMENT_STATUS_PAID) {
$klarnaOrderId = $order->getKlarnaOrderIdSetting();
$data['datePaid'] = $klarnaOrderId->getCreated()->format($translator->trans('datetime.format'));
$data['klarna_order_id'] = $klarnaOrderId->getValue();
} elseif (in_array((int)$order->getPaymentStatus(), [Order::PAYMENT_STATUS_PENDING, Order::PAYMENT_STATUS_FAILED])) {
$klarna = $this->getKlarna($domainId, $request, $order->getShippingCountry());
$klarnaSession = $klarna->getKlarnaSession($orderSetting->getValue());
if ($klarna->isValidKlarnaSession($klarnaSession, $order->getShippingCountry())) {
$data['klarna_data'] = $klarnaSession;
}
}
}
}
if ($order->getPaymentType() == PaymentType::PayPal->value) {
$data['paymentStatus'] = (int)$order->getPaymentStatus();
if ((int)$order->getPaymentStatus() == Order::PAYMENT_STATUS_PENDING) {
$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->getPaymentType() == PaymentType::Milpay->value && $order->getPaymentStatus() == Order::PAYMENT_STATUS_ID_PENDING) {
$milpay = $this->getMilpay($domain->getLanguage()->getCode());
$application = $milpay->getApplicationStatus($order->getMilpayApplicationIdSetting()->getValue());
$data['milpay_data'] = [
'redirect_url' => $milpay->getRedirectToMerchantUrl($application['publicId'], $application['financier'])
];
dd($milpay->cancelApplication($order));
}*/
$data['subTotal'] = $order->getSubTotal();
$data['total'] = $order->getFullPrice();
// Invoice Link
$data['invoiceLink'] = '';
if ($order->getStatus() == Order::STATUS_FINISHED) {
if ($order->getDocuments()->count() > 0 || $order->getBillingoDocuments()->count() > 0) {
if (in_array($domainId, [1, 2, 5, 9, 3, 4]) && $order->getDocuments()->count() > 0) { // Centralis documents
$invoiceId = 0;
foreach ($order->getDocuments() as $document) {
if ($invoiceId == 0) {
$invoiceId = $document->getId();
} elseif ($invoiceId != 0 && $document->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_OUT) {
$invoiceId = $document->getId();
}
}
$data['invoiceLink'] = $this->generateUrl('customer_invoice_pdf', [
'id' => $invoiceId,
'type' => self::INVOICE_TYPE_CENTRALIS,
'token' => $orderRepository->generatePublicLinkToken([
'orderId' => $order->getId(),
'documentId' => $invoiceId,
'type' => self::INVOICE_TYPE_CENTRALIS,
]),
]);
} elseif (in_array($domainId, [3, 4]) || $order->getBillingoDocuments()->count()) { // Billingo documents
$invoiceId = 0;
foreach ($order->getBillingoDocuments() as $billingoDocument) {
if ($invoiceId == 0) {
$invoiceId = $billingoDocument->getId();
} elseif ($invoiceId != 0 && $billingoDocument->getType() == BillingoOperation::TYPE_NORMAL) {
$invoiceId = $billingoDocument->getId();
}
}
$data['invoiceLink'] = $this->generateUrl('customer_invoice_pdf', [
'id' => $invoiceId,
'type' => self::INVOICE_TYPE_BILLINGO,
'token' => $orderRepository->generatePublicLinkToken([
'orderId' => $order->getId(),
'documentId' => $invoiceId,
'type' => self::INVOICE_TYPE_BILLINGO,
]),
]);
}
} else {
$data['invoiceLink'] = 'alert';
}
}
} else {
$data['errorMessage'] = $translator->trans('The order you requested could not be found');
}
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/showOrder.html.twig', $data);
}
/**
* @Route("/forgotten-password", name="customer_forgot_password", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/forgotten-password", name="customer_forgot_password_locale", defaults={"_locale":""})
* @param Request $request
* @param UserPasswordHasherInterface $passwordHasher
* @return Response
* @throws InvalidArgumentException
*/
public function forgotPasswordAction(Request $request, UserPasswordHasherInterface $passwordHasher): Response
{
if ($this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_account');
}
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Forgotten password');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Forgotten password'),
'href' => $this->generateUrl('customer_forgot_password'),
];
$data['errorMessage'] = '';
$customer = new Customer();
$form = $this->createForm(CustomerForgotPasswordType::class, $customer, [
'action' => $this->generateUrl('customer_forgot_password'),
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$email = $form->get('email')->getData();
$registration = new Registration($this->getEntityManager(), $request, $passwordHasher);
$passwordResetResult = $registration->resetPassword(
$email,
$this->getTranslator(),
$this->getMailer(),
$this->getParameter('mailer_reply_to')
);
if ($passwordResetResult['success']) {
return $this->redirectToRoute('customer_password_reset');
}
$data['errorMessage'] = $passwordResetResult['errorMessage'];
}
$data['form'] = $form->createView();
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/forgotPassword.html.twig', $data);
}
/**
* @Route("/password-reset", name="customer_password_reset", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/password-reset", name="customer_password_reset_locale", defaults={"_locale":""})
* @param Request $request
* @return Response
* @throws \Exception
*/
public function passwordResetAction(Request $request): Response
{
if ($this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_account');
}
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Forgotten password');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Forgotten password'),
'href' => $this->generateUrl('customer_password_reset'),
];
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/passwordReset.html.twig', $data);
}
/**
* @Route("/logout", name="customer_logout", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/logout", name="customer_logout_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
* @throws OptimisticLockException
*/
public function logoutAction(Request $request): Response
{
$this->getLoginHelper($request)->logout();
$request->getSession()->invalidate();
return new JsonResponse([]);
}
/**
* @Route("/account/claims", name="customer_claims", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/claims", name="customer_claims_locale", defaults={"_locale":""})
* @param Request $request
* @return RedirectResponse|Response
* @throws \Exception
*/
public function claimsAction(Request $request)
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$data = [];
$data['heading_title'] = $translator->trans('Claims');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Claims'),
'href' => $this->generateUrl('customer_claims'),
];
$claims = $this->getEntityManager()->getRepository(Claim::class)->findBy(
[
'customer' => $this->getLoginHelper($request)->getLoggedInCustomer(),
'type' => [
Claim::TYPE_CLAIM,
Claim::TYPE_CLAIM_REMOTE,
Claim::TYPE_COMMISSION,
Claim::TYPE_UNCLAIMED_PACKAGE,
],
],
[
'created' => 'DESC',
]
);
$data['claims'] = [];
$claimStatusTypes = ClaimStatus::getStatusChoices();
$receiveTypes = Claim::getReceiveTypeChoices();
/**
* @var Claim $claim
*/
foreach ($claims as $claim) {
$data['claims'][] = [
'id' => $claim->getId(),
'code' => $claim->getCode(),
'created' => $claim->getCreated(),
'status' => ($claim->getLastStatus() ? $claimStatusTypes[$claim->getLastStatus()->getStatusType()] : ''),
'receiveType' => $receiveTypes[$claim->getReceiveType()],
'customerId' => $claim->getCustomer()->getId(),
];
}
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/claims.html.twig', $data);
}
/**
* @Route("/account/claims/new/{orderItemId}", name="customer_claims_new", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/claims/new/{orderItemId}", name="customer_claims_new_locale", defaults={"_locale":""})
* @param Request $request
* @param $orderItemId
* @return RedirectResponse|Response
* @throws InvalidArgumentException
*/
public function claimsNewAction(Request $request, int $orderItemId = 0)
{
$data = [];
$entityManager = $this->getEntityManager();
$multistore = $this->getMultiStoreHelper($request);
$domain = $multistore->getDomain();
$defaultLocale = $multistore->getDefaultLocale();
// Domain Language Code
$domainLanguageCode = $domain->getLanguage()->getCode();
$country = '';
$invoiceCode = $request->request->get('customer_claim')['invoiceCode'] ?? null;
$document = $entityManager->getRepository(Document::class)->findOneBy(['code' => $invoiceCode]);
if ($this->getLoginHelper($request)->isLoggedIn()) {
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$data['isLoggedIn'] = true;
if ($domain->getId()) {
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$country = 'SK';
break;
case Domain::DOMAIN_ID_RT_HU:
$country = 'HU';
break;
case Domain::DOMAIN_ID_RT_CZ:
$country = 'CZ';
break;
}
}
} else {
$customer = null;
if (!is_null($request->request->get('customer_claim'))) {
$email = $request->request->get('customer_claim')['email'];
if ($email) {
$customer = $entityManager->getRepository(Customer::class)->findOneBy([
'email' => $email,
'domain' => $domain->getId(),
]);
}
}
if (is_null($customer) && !is_null($request->request->get('customer_claim'))
&& strlen($request->request->get('customer_claim')['order_id']) == "9") {
$orderId = $request->request->get('customer_claim')['order_id'];
$order = $entityManager->getRepository(Order::class)->findOneById($orderId);
$customer = $order ? $order->getCustomer() : null;
}
//if $orderItemId != 0 than I get the customer when the order is found below ↓
if (!$customer) {
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$customerId = MultiStore::GUEST_CUSTOMER_ID_SK;
$country = 'SK';
break;
case Domain::DOMAIN_ID_RT_HU:
$customerId = MultiStore::GUEST_CUSTOMER_ID_HU;
$country = 'HU';
break;
case Domain::DOMAIN_ID_RT_CZ:
$customerId = MultiStore::GUEST_CUSTOMER_ID_CZ;
$country = 'CZ';
break;
default:
$customerId = false;
}
if (!$customerId && $orderItemId == 0) {
return $this->redirectToRoute('customer_login');
}
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
}
$data['isLoggedIn'] = false;
}
$translator = $this->getTranslator();
$data['heading_title'] = $translator->trans('Create claim');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Create claim'),
'href' => $this->generateUrl('customer_claims_new'),
];
$data['orderItemId'] = $orderItemId;
if ($defaultLocale != 'en') {
$data['packetaApiKey'] = $this->getParameter('packeta')['api_key'];
$data['shippingCountry'] = $defaultLocale;
}
$claim = new Claim();
if (is_null($request->request->get('customer_claim')) || is_null($request->request->get('customer_claim')['firstName'])) {
/**
* @var Order $order
*/
$orderItem = false;
$order = false;
if ($orderItemId != 0) {
$orderItem = $entityManager->getRepository(OrderItem::class)->findOneById($orderItemId);
if ($orderItem) {
$order = $orderItem->getOrder();
$claim->setBoughtDate($order->getCreated()->format('Y-m-d'));
$customer = $order->getCustomer();
}
}
if ($order) {
$data['orderNumber'] = $order->getId();
$claim->setOrder($order);
if ($order->useBillingAddressAsShippingAddress()) {
$claim->setCountry($order->getBillingCountry());
$claim->setStreet($order->getBillingStreet());
$claim->setCity($order->getBillingCity());
$claim->setZip($order->getBillingZip());
} else {
$claim->setCountry($order->getShippingCountry());
$claim->setStreet($order->getShippingStreet());
$claim->setCity($order->getShippingCity());
$claim->setZip($order->getShippingZip());
}
} else {
/**
* @var CustomerAddress $customerAddress
*/
$customerAddress = is_null($customer->getAddresses()) && !in_array($customer->getId(), [MultiStore::GUEST_CUSTOMER_ID_SK, MultiStore::GUEST_CUSTOMER_ID_HU, MultiStore::GUEST_CUSTOMER_ID_CZ]) ? false : $customer->getAddresses()->first();
if ($customerAddress) {
$claim->setCountry($customerAddress->getCountry());
$claim->setStreet($customerAddress->getStreet());
$claim->setCity($customerAddress->getCity());
$claim->setZip($customerAddress->getZip());
} else {
$claim->setCountry($customer->getCountry());
}
}
if (in_array($customer->getId(), [MultiStore::GUEST_CUSTOMER_ID_SK, MultiStore::GUEST_CUSTOMER_ID_HU, MultiStore::GUEST_CUSTOMER_ID_CZ])) {
$claim->setFirstName('');
$claim->setLastName('');
$claim->setBusinessName('');
$claim->setPhone('');
$claim->setEmail('');
$claim->setBoughtDate((new \DateTime())->format('Y-m-d'));
} else {
$claim->setFirstName($customer->getFirstName());
$claim->setLastName($customer->getLastName());
$claim->setBusinessName($customer->getBusinessName());
// Phone Number
$phoneNumber = $customer->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 ($domainLanguageCode == 'cz') {
$phoneNumber = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$phoneNumber = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
$claim->setPhone($phoneNumber);
$claim->setEmail($customer->getEmail());
$claim->setBoughtDate((new \DateTime())->format('Y-m-d'));
}
if ($orderItem) {
if (!is_null($orderItem->getStockMovementItem()) && $orderItem->getStockMovementItem()->getItems()->count() > 0) {
$claim->setSerialNumber($orderItem->getStockMovementItem()->getItems()->first()->getSerialNumber());
}
$claim->setBoughtDate($order->getCreated()->format('Y-m-d'));
$product = $orderItem->getProduct();
if ($product) {
$claim->setProductTitle($product->getVendor()->getName() . ' ' . $product->getName());
switch ($product->getType()->getId()) {
case ProductType::PRODUCT_TYPE_ID_PC:
case ProductType::PRODUCT_TYPE_ID_ALL_IN_ONE:
$claim->setProductType(Claim::PRODUCT_TYPE_PC);
break;
case ProductType::PRODUCT_TYPE_ID_NOTEBOOK:
$claim->setProductType(Claim::PRODUCT_TYPE_NOTEBOOK);
break;
case ProductType::PRODUCT_TYPE_ID_MONITOR:
$claim->setProductType(Claim::PRODUCT_TYPE_MONITOR);
break;
case ProductType::PRODUCT_TYPE_ID_PRINTER:
$claim->setProductType(Claim::PRODUCT_TYPE_PRINTER);
break;
default:
$claim->setProductType(Claim::PRODUCT_TYPE_COMPONENT);
}
}
if ($order->getBillingoDocuments()->count() > 0) {
$claim->setInvoiceCode($order->getBillingoDocuments()->first()->getInvoiceCode());
}
if ($order->getDocuments()->count() > 0) {
$claim->setInvoiceCode($order->getDocuments()->first()->getCode());
}
}
}
$form = $this->createForm(CustomerClaimType::class, $claim, [
'locale' => $request->getLocale(),
'defaultLocale' => $defaultLocale,
'domainType' => $domain->getType(),
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() && !is_null($request->request->get('g-recaptcha-response'))) {
$captchaResponse = $request->request->get('g-recaptcha-response');
$captchaResult = $this->verifyGoogleCaptcha($captchaResponse);
if ($captchaResult) {
$claim->setBoughtDate(str_replace('.', '-', $claim->getBoughtDate()));
$boughtDateArray = explode('-', $claim->getBoughtDate());
$boughDate = (new \DateTime())->setDate($boughtDateArray[0], $boughtDateArray[1], $boughtDateArray[2]);
$claim->setBoughtDate($boughDate);
$claim->setCustomer($customer);
$claim->setReceiveType(Claim::RECEIVE_TYPE_SHIPPED_BY_PARCEL);
$claim->setReturnType(Claim::RETURN_TYPE_PARCEL);
$countryData = $form->has('country') ? $form->get('country')->getData() : null;
$claim->setCountry(
$country == ''
? (array_key_exists($countryData, CustomerAddress::EU_COUNTRIES) ? $countryData : strtoupper($domain->getLanguage()->getCode()))
: $country
);
// Phone Number
$phoneNumber = $form->get('phone')->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 ($domainLanguageCode == 'cz') {
$phoneNumber = '+420' . preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = '+36' . preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'sk') {
$phoneNumber = '+421' . preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
} else {
$phoneNumber = $_phoneNumber;
}
$claim->setPhone($phoneNumber);
if ($defaultLocale != 'en') {
$claim->setIncomingPacketaBranchId((int)$form->getViewData()->getIncomingPacketaBranchId());
$claim->setIncomingPacketaBranchLabel((string)$form->getViewData()->getIncomingPacketaBranchLabel());
}
$claim->setCode($entityManager->getRepository(Claim::class)->createCode($claim));
if ($document) {
$claim->setDocument($document);
$claim->setInvoiceCode('');
}
$claim->setLastStatusId(ClaimStatus::STATUS_TYPE_REGISTERED);
$entityManager->persist($claim);
$entityManager->flush();
$claimStatus = new ClaimStatus();
$claimStatus->setClaim($claim);
$claimStatus->setStatusType(ClaimStatus::STATUS_TYPE_REGISTERED);
$entityManager->persist($claimStatus);
$notificationIds = [785, 3055];
foreach ($notificationIds as $notificationId) {
$notificationConfig = $entityManager->getRepository(NotificationConfig::class)->findOneById($notificationId);
$notification = new Notification();
$notification->setText('New claim #' . $claim->getCode());
$notification->setNotificationConfig($notificationConfig);
$notification->setActive(true);
$notification->setUrl('https://www.atechcomp.eu/centralis/web/claim/edit/' . $claim->getId());
$entityManager->persist($notification);
}
$entityManager->flush();
if ($customer->getDomain()->getType() == 'wholesale' && $this->getEnvironment() == 'prod' && in_array($claim->getType(), [Claim::TYPE_CLAIM, Claim::TYPE_WITHDRAWAL])) {
$mailer = $this->getMailer();
$emailTo = $customer->getDomain()->getId() != Domain::DOMAIN_ID_WS_EU ? $customer->getSalesManager()->getEmail() : 'export@furbify.eu';
$email = (new TemplatedEmail())
->subject('New claim ' . $customer->getDomain()->getShortTitle() . ' - ' . $customer->getBusinessName())
->to($emailTo)
->html('New claim on ' . $customer->getDomain()->getShortTitle() . ' - ' . $customer->getBusinessName() . '<br> https://www.atechcomp.eu/centralis/web/claim/edit/' . $claim->getId());
$mailer->send($email);
}
$subDirectory = 'claim-images/' . $claim->getId();
$files = $request->files->get('claimMedias');
$fileCount = 0;
foreach ($files as $file) {
$response = $this->uploadFile($file, $subDirectory, ['image/jpeg', 'image/jpg', 'image/png']);
if ($response && $fileCount < 3) {
$claimMedia = new ClaimMedia();
$claimMedia->setClaim($claim);
$claimMedia->setFilename($response['filename']);
$claimMedia->setDirectory('uploads/' . $subDirectory);
$claimMedia->setMimeType($response['mimeType']);
// Upload Image to DigitalOcean Space
if ($this->getEnvironment() == 'prod') {
$result = $this->getDigitalOceanSpace()->claimMedia($claimMedia, 'upload');
// Update DigitalOcean Flag
if (!empty($result['success'])) {
$claimMedia->setDigitalOcean(true);
// Delete Local File - Enable after the test period
// @unlink(DigitalOceanSpaces::getUploadDirectory() . $subDirectory . '/' . $response['filename']);
}
}
$entityManager->persist($claimMedia);
$fileCount++;
}
}
if ($claim->getIncomingPacketaBranchId() == 0) {
$mailer = $this->getMailer();
$emailTo = 'katarina.jobbagyova@furbify.eu';
$email = (new TemplatedEmail())
->subject(
'New claim '
. $customer->getDomain()->getShortTitle()
. ' - '
. $customer->getBusinessName()
. ' (GLS courier service)'
)
->to($emailTo)
->html(
'New <a href="https://www.atechcomp.eu/centralis/web/claim/edit/' . $claim->getId() . '">claim</a> on ' . $customer->getDomain()->getShortTitle() . ' - ' . $customer->getBusinessName() . '<br>' .
'<br>' .
'<b>Please note:</b> You need to order <b> GLS courier service</b>.'
);
$mailer->send($email);
}
$entityManager->flush();
if ($this->getEnvironment() == 'prod') {
$this->getKlaviyoConnect($request)->createNewClaimEvent($claim);
}
$this->addFlash(
'success',
$translator->trans('Your claim has been successfully added. Please print the protocol and send it with the product!')
);
return $this->redirectToRoute('customer_claims_success', [
'id' => $claim->getId(),
'customerId' => $customer->getId(),
]);
} else {
$this->addFlash(
'error',
$translator->trans('Captcha check failed, please try again!')
);
}
}
$data['form'] = $form->createView();
$data['domainId'] = $domain->getId();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['precision'] = $domain->getPricePrecision();
$data['currency'] = $domain->getCurrency();
$data['deliveryPrice'] = [
Domain::DOMAIN_ID_RT_SK => 5.90,
Domain::DOMAIN_ID_WS_SK => 5.90,
Domain::DOMAIN_ID_RT_HU => 2790,
Domain::DOMAIN_ID_WS_HU => 2790,
Domain::DOMAIN_ID_RT_CZ => 149,
Domain::DOMAIN_ID_WS_CZ => 149,
Domain::DOMAIN_ID_RT_EU => 10,
Domain::DOMAIN_ID_WS_EU => 10,
];
if ($domainLanguageCode == 'cz') {
$data['callingCountryCode'] = '+420';
} elseif ($domainLanguageCode == 'hu') {
$data['callingCountryCode'] = '+36';
} else {
$data['callingCountryCode'] = '+421';
}
$data['domainLanguageCode'] = $domainLanguageCode;
return $this->render('AtechNetCoreBundle/Customer/claimsNew.html.twig', $data);
}
/**
* @Route("/account/claims/{id}/pdf/{customerId}", name="customer_claims_pdf", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/claims/{id}/pdf/{customerId}", name="customer_claims_pdf_locale", defaults={"_locale":""})
* @param Request $request
* @param int $id
* @param null $customerId
* @return Response
* @throws \Mpdf\MpdfException
*/
public function claimsPdfAction(Request $request, int $id, $customerId = null): Response
{
$entityManager = $this->getEntityManager();
if (!is_null($customerId)) {
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
} else {
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
}
if (!$customer) {
return $this->redirectToRoute('customer_login');
}
$claim = $entityManager->getRepository(Claim::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
if (!$claim) {
return $this->redirectToRoute('not_found');
}
$data = [];
/**
* @var Claim $claim
*/
$data['claim'] = $claim;
$data['customerAddress'] = $claim->getCustomer()->getAddresses()->first();
$data['statusChoices'] = ClaimStatus::getStatusChoices();
$data['testTypes'] = ClaimTest::getTestTypes();
$data['testStates'] = ClaimTest::getTestStates();
$data['packetaCode'] = $claim->getIncomingPacketaBranchId() > 0 ? DomainShippingType::getPacketaReturnCodeForDomain($claim->getCustomer()->getDomain()) : false;
$html = $this->render('AtechNetCoreBundle/PDF/claims.html.twig', $data);
$pdf = new Mpdf([
'mode' => '',
'format' => 'A4',
'default_font_size' => 9,
'defualt_font' => 'dejavusans',
'mgl' => 10,
'mgr' => 10,
]);
$pdf->shrink_tables_to_fit = false;
$pdf->WriteHTML($html);
return new Response(
$pdf->output(
$this->getTranslator()->trans('Claim') . '_furbify_' . $request->getLocale() . '_' . $claim->getCode() . '.pdf',
'I'
),
Response::HTTP_OK,
[
'content-type' => 'application/pdf',
]
);
}
/**
* @Route("/account/claims/success/{id}/{customerId}", name="customer_claims_success", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/claims/success/{id}/{customerId}", name="customer_claims_success_locale", defaults={"_locale":""})
* @param Request $request
* @param int $id
* @param int $customerId
* @return Response
* @throws InvalidArgumentException
*/
public function claimsSuccessAction(Request $request, int $id, int $customerId): Response
{
$data = [];
$translator = $this->getTranslator();
if ($this->getLoginHelper($request)->isLoggedIn()) {
$data['isLoggedIn'] = true;
} else {
$data['isLoggedIn'] = false;
}
$data['heading_title'] = $translator->trans('Claim created');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Claim created'),
'href' => $this->generateUrl('customer_claims_success', [
'id' => $id,
'customerId' => $customerId,
]),
];
$entityManager = $this->getEntityManager();
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
$claim = $entityManager->getRepository(Claim::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
$data['claimId'] = $claim->getCode();
$data['claimPdfUrl'] = $this->generateUrl('customer_claims_pdf', [
'id' => $id,
'customerId' => $customerId,
]);
$data['claimTrackingUrl'] = $this->generateUrl('customer_claim_tracking', [
'token' => $this->getEntityManager()->getRepository(Claim::class)->createClaimToken($claim),
], UrlGeneratorInterface::ABSOLUTE_URL);
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/claimsSuccess.html.twig', $data);
}
/**
* @Route("/account/withdrawal/new", name="customer_withdrawal_new", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/withdrawal/new", name="customer_withdrawal_new_locale", defaults={"_locale":""})
* @param Request $request
* @return RedirectResponse|Response
* @throws InvalidArgumentException
*/
public function withdrawalNewAction(Request $request)
{
$data = [];
$translator = $this->getTranslator();
$entityManager = $this->getEntityManager();
$multistore = $this->getMultiStoreHelper($request);
$domain = $multistore->getDomain();
// Doman Language Code
$domainLanguageCode = $domain->getLanguage()->getCode();
$country = '';
if ($this->getLoginHelper($request)->isLoggedIn()) {
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$data['isLoggedIn'] = true;
if ($domain->getId()) {
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$country = 'SK';
break;
case Domain::DOMAIN_ID_RT_HU:
$country = 'HU';
break;
case Domain::DOMAIN_ID_RT_CZ:
$country = 'CZ';
break;
}
}
} else {
switch ($domain->getId()) {
case Domain::DOMAIN_ID_RT_SK:
$customerId = MultiStore::GUEST_CUSTOMER_ID_SK;
$country = 'SK';
break;
case Domain::DOMAIN_ID_RT_HU:
$customerId = MultiStore::GUEST_CUSTOMER_ID_HU;
$country = 'HU';
break;
case Domain::DOMAIN_ID_RT_CZ:
$customerId = MultiStore::GUEST_CUSTOMER_ID_CZ;
$country = 'CZ';
break;
default:
$customerId = false;
}
if (!$customerId) {
return $this->redirectToRoute('customer_login');
}
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
$data['isLoggedIn'] = false;
}
$data['shippingCountry'] = $domain->getLanguage()->getCode();
$data['packetaApiKey'] = $this->getParameter('packeta')['api_key'];
$data['heading_title'] = $translator->trans('Create withdrawal');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Create claim'),
'href' => $this->generateUrl('customer_claims_new'),
];
$claim = new Claim();
// Step
$step = $request->request->get('step', 1);
// First Step Form
if ( $step == 1 ) {
$firstStepForm = $this->createForm(CustomerWithdrawalType::class, $claim, [
'locale' => $request->getLocale(),
'defaultLocale' => $multistore->getDefaultLocale(),
'domainType' => $domain->getType(),
'step' => 1
]);
$data['step'] = 1;
$firstStepForm->handleRequest($request);
if ( $firstStepForm->isSubmitted() && $firstStepForm->isValid() ) {
/** @var Document $document */
$document = $entityManager->getRepository(Document::class)->findOneByCode($claim->getInvoiceCode());
if ( is_null($document) ) {
/** @var Order $order */
$order = $entityManager->getRepository(Order::class)->find($claim->getInvoiceCode());
if ( $order ) {
/** @var Document $_document */
foreach ( $order->getDocuments() as $_document ) {
if ( $_document->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_OUT ) {
$document = $_document;
break;
}
}
}
}
if ( $document ) {
// Email
if ( $document->getEmail() !== $claim->getEmail() ) {
$this->addFlash('error', $translator->trans('No order was found in the system based on the information provided. Please check the order number/invoice number and email address.'));
}
// Captcha
$captchaResponse = $request->request->get('g-recaptcha-response');
if ( !is_null($captchaResponse) ) {
$captchaResult = $this->verifyGoogleCaptcha($captchaResponse);
if ( $captchaResult ) {
$captchaIsOK = true;
} else {
$captchaIsOK = false;
}
} else {
$captchaIsOK = true;
}
// Check Date
if ( $captchaIsOK ) {
// Created
$invoiceCreated = $document->getCreated();
// Start
$withdrawalStart = clone $invoiceCreated;
for ( $i = 0; $i < 3; $i++ ) {
$withdrawalStart->modify('+1 weekday');
}
// End
$withdrawalEnd = clone $withdrawalStart;
$withdrawalEnd->modify('+14 days');
$withdrawalEnd->setTime(23, 59, 59);
// Today
$today = new \DateTime();
if ( $today <= $withdrawalEnd ) {
// Next Step
$step = 2;
// Fill Claim from document
$claim->setFirstName($document->getFirstName());
$claim->setLastName($document->getLastName());
$claim->setBusinessName($document->getBusinessName());
$claim->setStreet($document->getStreet());
$claim->setCity($document->getCity());
$claim->setZip($document->getZip());
$claim->setBoughtDate($document->getOrder()?->getCreated());
// Phone Number
$phoneNumber = $document->getOrder()?->getBillingPhone();
// 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 ($domainLanguageCode == 'cz') {
$phoneNumber = preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$phoneNumber = preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
$claim->setPhone($phoneNumber);
// Products
$data['products'] = [];
/** @var DocumentItem $documentItem */
foreach ( $document->getItems() as $documentItem ) {
if ( $documentItem->getParent() ) {
continue;
}
if ( $documentItem->getStockMovementItem() ) {
if ( $documentItem->getStockMovementItem()->getItems()->count() > 0 ) {
/** @var StockItem $stockItem */
foreach ( $documentItem->getStockMovementItem()->getItems() as $stockItem ) {
if ( !in_array($documentItem->getProduct()->getType()->getId(), [ ProductType::PRODUCT_TYPE_ID_PC, ProductType::PRODUCT_TYPE_ID_PC_SET, ProductType::PRODUCT_TYPE_ID_ALL_IN_ONE, ProductType::PRODUCT_TYPE_ID_NOTEBOOK, ProductType::PRODUCT_TYPE_ID_MONITOR, ProductType::PRODUCT_TYPE_ID_PRINTER, ProductType::PRODUCT_TYPE_ID_SMARTPHONE ]) ) {
continue;
}
$data['products'][] = [
'id' => $documentItem->getId(),
'productId' => $documentItem->getProduct()->getId(),
'stockItemId' => $stockItem->getId(),
'product' => $documentItem->getProduct()->getFullTitle(),
'typeId' => $documentItem->getProduct()->getType()->getId(),
'serialNumber' => $stockItem->getSerialNumber(),
'quantity' => 1,
'entity' => $documentItem->getProduct()
];
}
} else {
if ( !in_array($documentItem->getProduct()->getType()->getId(), [ ProductType::PRODUCT_TYPE_ID_PC, ProductType::PRODUCT_TYPE_ID_PC_SET, ProductType::PRODUCT_TYPE_ID_ALL_IN_ONE, ProductType::PRODUCT_TYPE_ID_NOTEBOOK, ProductType::PRODUCT_TYPE_ID_MONITOR, ProductType::PRODUCT_TYPE_ID_PRINTER, ProductType::PRODUCT_TYPE_ID_SMARTPHONE ]) ) {
continue;
}
$data['products'][] = [
'id' => $documentItem->getId(),
'productId' => $documentItem->getProduct()->getId(),
'product' => $documentItem->getProduct()->getFullTitle(),
'typeId' => $documentItem->getProduct()->getType()->getId(),
'code' => $documentItem->getProduct()->getCode(),
'quantity' => $documentItem->getQuantity(),
'entity' => $documentItem->getProduct()
];
}
}
}
if ( count($data['products']) == 1 ) {
$product = $data['products'][0];
$claim->setProductTitle($product['product']);
$claim->setSerialNumber($product['serialNumber']);
switch ( $product['typeId'] ) {
case ProductType::PRODUCT_TYPE_ID_PC:
case ProductType::PRODUCT_TYPE_ID_PC_SET:
case ProductType::PRODUCT_TYPE_ID_ALL_IN_ONE:
$claim->setProductType(Claim::PRODUCT_TYPE_PC);
break;
case ProductType::PRODUCT_TYPE_ID_NOTEBOOK:
$claim->setProductType(Claim::PRODUCT_TYPE_NOTEBOOK);
break;
case ProductType::PRODUCT_TYPE_ID_MONITOR:
$claim->setProductType(Claim::PRODUCT_TYPE_MONITOR);
break;
case ProductType::PRODUCT_TYPE_ID_PRINTER:
$claim->setProductType(Claim::PRODUCT_TYPE_PRINTER);
break;
default:
$claim->setProductType(Claim::PRODUCT_TYPE_COMPONENT);
}
$claim->setProduct($product['entity'] ?? null);
} elseif ( empty($data['products']) ) {
$step = 1;
$this->addFlash('error', $translator->trans('Something went wrong during getting debtor status. Please contact customer support'));
}
} else {
$this->addFlash('error', $translator->trans('Unfortunately, but the 30-day return period has expired.'));
}
} else {
$this->addFlash('error', $translator->trans('Captcha check failed, please try again!'));
}
} else {
$this->addFlash('error', $translator->trans('No order was found in the system based on the information provided. Please check the order number/invoice number and email address.'));
}
}
$data['form'] = $firstStepForm->createView();
}
// Second Step Form
if ( $step == 2 ) {
$data['step'] = 2;
$secondStepForm = $this->createForm(CustomerWithdrawalType::class, $claim, [
'locale' => $request->getLocale(),
'defaultLocale' => $multistore->getDefaultLocale(),
'domainType' => $domain->getType(),
'step' => 2
]);
if ( $request->request->has('customer_withdrawal') && isset($request->request->all()['customer_withdrawal']['bankAccountHolder']) ) {
$secondStepForm->handleRequest($request);
if ( $secondStepForm->isSubmitted() && $secondStepForm->isValid() ) {
// Captcha
$captchaResponse = $request->request->get('g-recaptcha-response');
if ( !is_null($captchaResponse) ) {
$captchaResult = $this->verifyGoogleCaptcha($captchaResponse);
if ( $captchaResult ) {
$captchaIsOK = true;
} else {
$captchaIsOK = false;
}
} else {
$captchaIsOK = true;
}
if ( $captchaIsOK ) {
/** @var Document $document */
$document = $entityManager->getRepository(Document::class)->findOneByCode($claim->getInvoiceCode());
if ( is_null($document) ) {
/** @var Order $order */
$order = $entityManager->getRepository(Order::class)->find($claim->getInvoiceCode());
if ( $order ) {
/** @var Document $_document */
foreach ( $order->getDocuments() as $_document ) {
if ( $_document->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_OUT ) {
$document = $_document;
break;
}
}
}
}
if ( $document ) {
// Created
$invoiceCreated = $document->getCreated();
// Start
$withdrawalStart = clone $invoiceCreated;
for ( $i = 0; $i < 3; $i++ ) {
$withdrawalStart->modify('+1 weekday');
}
// End
$withdrawalEnd = clone $withdrawalStart;
$withdrawalEnd->modify('+14 days');
$withdrawalEnd->setTime(23, 59, 59);
// Today
$today = new \DateTime();
// Date
if ( $today > $withdrawalEnd ) {
$this->addFlash('error', $translator->trans('Unfortunately, but the 30-day return period has expired.'));
}
// Check Email
elseif ( $document->getEmail() !== $claim->getEmail() ) {
$this->addFlash('error', $translator->trans('No order was found in the system based on the information provided. Please check the order number/invoice number and email address.'));
}
// Process Claim
else {
$customer = $document->getOrder()?->getCustomer();
$claim->setInvoiceCode($document->getCode());
$claim->setType(Claim::TYPE_WITHDRAWAL);
$claim->setReceiveType(Claim::RECEIVE_TYPE_SHIPPED_BY_PARCEL);
$claim->setReturnType(Claim::RETURN_TYPE_PARCEL);
$claim->setCustomer($customer);
$claim->setCountry($document->getCountry());
$claim->setIncomingPacketaBranchId((int)$secondStepForm->getViewData()->getIncomingPacketaBranchId());
$claim->setIncomingPacketaBranchLabel((string)$secondStepForm->getViewData()->getIncomingPacketaBranchLabel());
$claim->setDocument($document);
$claim->setOrder($document->getOrder());
// Phone Number
$phoneNumber = $claim->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 ($domainLanguageCode == 'cz') {
$phoneNumber = '+420' . preg_replace('/^(\+420|00420)/', '', $_phoneNumber);
} elseif ($domainLanguageCode == 'hu') {
$phoneNumber = '+36' . preg_replace('/^(\+36|0036|06)/', '', $_phoneNumber);
} else {
$phoneNumber = '+421' . preg_replace('/^(\+421|00421|0)/', '', $_phoneNumber);
}
$claim->setPhone($phoneNumber);
$claim->setLastStatusId(ClaimStatus::STATUS_TYPE_REGISTERED);
if (
empty($request->request->get('stockItems')) &&
empty($request->request->get('products')) &&
!empty($claim->getProductType()) &&
!empty($claim->getProductTitle())
) {
$claim->setCode($entityManager->getRepository(Claim::class)->createCode($claim));
// Check claim product title length
$title = $secondStepForm->getViewData()->getProductTitle();
if ( mb_strlen($title) > 128 ) {
$claim->setProductTitle(mb_substr($title, 0, 128));
}
// Save
$entityManager->persist($claim);
$entityManager->flush();
// Status
$claimStatus = new ClaimStatus();
$claimStatus->setClaim($claim);
$claimStatus->setStatusType(ClaimStatus::STATUS_TYPE_REGISTERED);
$entityManager->persist($claimStatus);
$notificationIds = [785, 3055];
foreach ( $notificationIds as $notificationId ) {
$notificationConfig = $entityManager->getRepository(NotificationConfig::class)->findOneById($notificationId);
if ( $notificationConfig ) {
$notification = new Notification();
$notification->setText('New withdrawal #' . $claim->getCode());
$notification->setNotificationConfig($notificationConfig);
$notification->setActive(true);
$notification->setUrl('https://www.atechcomp.eu/centralis/web/claim/edit/' . $claim->getId());
$entityManager->persist($notification);
}
}
$entityManager->flush();
$this->addFlash('success', $translator->trans('Your withdrawal has been successfully added. Please print the protocol and send it with the product!'));
return $this->redirectToRoute('customer_withdrawal_success', [
'id' => $claim->getId(),
'customerId' => $customer->getId()
]);
}
else {
$products = [];
if ( !empty($request->request->get('stockItems')) ) {
foreach ( (array)$request->request->get('stockItems', []) as $stockItemId ) {
$documentItemId = $request->request->get('stockItemDocument', [])[$stockItemId] ?? 0;
if ( $documentItemId ) {
/** @var DocumentItem $documentItem */
foreach ( $document->getItems() as $documentItem ) {
if ( $documentItem->getId() == $documentItemId ) {
if ( $documentItem->getStockMovementItem() ) {
/** @var StockItem $stockItem */
foreach ( $documentItem->getStockMovementItem()->getItems() as $stockItem ) {
if ( $stockItem->getId() == $stockItemId ) {
$products[] = [
'serialNumber' => $stockItem->getSerialNumber(),
'typeId' => $documentItem->getProduct()->getType()->getId(),
'title' => $documentItem->getProduct()?->getFullTitle(),
'entity' => $documentItem->getProduct()
];
break;
}
}
}
}
}
}
}
}
if ( !empty($request->request->get('products')) ) {
foreach ( (array)$request->request->get('products', []) as $productId ) {
$documentItemId = $request->request->get('productDocument', [])[$productId] ?? 0;
if ( $documentItemId ) {
/** @var DocumentItem $documentItem */
foreach ( $document->getItems() as $documentItem ) {
if ( $documentItem->getId() == $documentItemId && $documentItem->getProduct()?->getId() == $productId ) {
$products[] = [
'serialNumber' => '',
'typeId' => $documentItem->getProduct()->getType()->getId(),
'title' => $documentItem->getProduct()?->getFullTitle(),
'entity' => $documentItem->getProduct()
];
}
}
}
}
}
if ( empty($products) ) {
$this->addFlash('error', $translator->trans('No product selected.'));
} else {
foreach ( $products as $product ) {
$_claim = clone $claim;
$_claim->setProductTitle($product['title']);
$_claim->setSerialNumber($product['serialNumber']);
switch ( $product['typeId'] ) {
case ProductType::PRODUCT_TYPE_ID_PC:
case ProductType::PRODUCT_TYPE_ID_PC_SET:
case ProductType::PRODUCT_TYPE_ID_ALL_IN_ONE:
$_claim->setProductType(Claim::PRODUCT_TYPE_PC);
break;
case ProductType::PRODUCT_TYPE_ID_NOTEBOOK:
$_claim->setProductType(Claim::PRODUCT_TYPE_NOTEBOOK);
break;
case ProductType::PRODUCT_TYPE_ID_MONITOR:
$_claim->setProductType(Claim::PRODUCT_TYPE_MONITOR);
break;
case ProductType::PRODUCT_TYPE_ID_PRINTER:
$_claim->setProductType(Claim::PRODUCT_TYPE_PRINTER);
break;
default:
$_claim->setProductType(Claim::PRODUCT_TYPE_COMPONENT);
}
$_claim->setCode($entityManager->getRepository(Claim::class)->createCode($_claim));
// Check claim product title length
$title = $_claim->getProductTitle();
if ( mb_strlen($title) > 128 ) {
$_claim->setProductTitle(mb_substr($title, 0, 128));
}
$_claim->setProduct($product['entity'] ?? null);
// Save
$entityManager->persist($_claim);
$entityManager->flush();
// Status
$claimStatus = new ClaimStatus();
$claimStatus->setClaim($_claim);
$claimStatus->setStatusType(ClaimStatus::STATUS_TYPE_REGISTERED);
$entityManager->persist($claimStatus);
$notificationIds = [785, 3055];
foreach ( $notificationIds as $notificationId ) {
$notificationConfig = $entityManager->getRepository(NotificationConfig::class)->findOneById($notificationId);
if ( $notificationConfig ) {
$notification = new Notification();
$notification->setText('New withdrawal #' . $_claim->getCode());
$notification->setNotificationConfig($notificationConfig);
$notification->setActive(true);
$notification->setUrl('https://www.atechcomp.eu/centralis/web/claim/edit/' . $_claim->getId());
$entityManager->persist($notification);
}
}
$entityManager->flush();
}
$entityManager->flush();
$this->addFlash('success', $translator->trans('Your withdrawal has been successfully added. Please print the protocol and send it with the product!'));
return $this->redirectToRoute('customer_withdrawal_success', [
'id' => $_claim->getId() ?? 0,
'customerId' => $customer->getId()
]);
}
}
}
} else {
$this->addFlash('error', $translator->trans('No order was found in the system based on the information provided. Please check the order number/invoice number and email address.'));
}
} else {
$this->addFlash('error', $translator->trans('Captcha check failed, please try again!'));
}
}
}
$data['form'] = $secondStepForm->createView();
}
if ( $domainLanguageCode == 'cz' ) {
$data['callingCountryCode'] = '+420';
} elseif ( $domainLanguageCode == 'hu' ) {
$data['callingCountryCode'] = '+36';
} else {
$data['callingCountryCode'] = '+421';
}
// Carrier
$carrierExpressShippingType = $entityManager->getRepository(DomainShippingType::class)->findOneBy([
'domain' => $domain->getId(),
'activeOnWeb' => true,
'type' => DomainShippingType::SHIPPING_TYPE_CARRIER_EXPRESS_ID
]);
if ( $carrierExpressShippingType ) {
$data['deliveryPrice'] = $carrierExpressShippingType->getPrice() . ' ' . $domain->getCurrency();
} else {
$data['deliveryPrice'] = '0 ' . $domain->getCurrency();
}
$data['precision'] = $domain->getPricePrecision();
$data['currency'] = $domain->getCurrency();
$data['domainLanguageCode'] = $domainLanguageCode;
// Common
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/withdrawalNew.html.twig', $data);
}
/**
* @Route("/ajax-check-order-number", name="ajax_check_order_number", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/ajax-check-order-number", name="ajax_check_order_number_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse|null
*/
public function ajaxCheckOrderNumber(Request $request): ?JsonResponse
{
$orderId = $request->request->get('orderNumber');
/**
* @var $order Order
*/
$order = $this->getEntityManager()->getRepository(Order::class)->findOneById($orderId);
if (is_null($order)) {
return new JsonResponse([
'success' => false,
'message' => $this->getTranslator()->trans('order_number_alert.order_not_found'),
]);
} elseif ($order->getWarrantyEnd() < new \DateTime()) {
return new JsonResponse([
'success' => false,
'message' => $this->getTranslator()->trans('order_number_alert.warranty_is_ended'),
]);
}
return new JsonResponse([
'success' => true,
]);
}
/**
* @Route("/account/withdrawal/success/{id}/{customerId}", name="customer_withdrawal_success", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/withdrawal/success/{id}/{customerId}", name="customer_withdrawal_success_locale", defaults={"_locale":""})
* @param Request $request
* @param int $id
* @param int $customerId
* @return Response
* @throws InvalidArgumentException
*/
public function withdrawalSuccessAction(Request $request, int $id, int $customerId): Response
{
$data = [];
$translator = $this->getTranslator();
if ($this->getLoginHelper($request)->isLoggedIn()) {
$data['isLoggedIn'] = true;
} else {
$data['isLoggedIn'] = false;
}
$data['heading_title'] = $translator->trans('Withdrawal created');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Withdrawal created'),
'href' => $this->generateUrl('customer_withdrawal_success', [
'id' => $id,
'customerId' => $customerId,
]),
];
$entityManager = $this->getEntityManager();
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
$withdrawal = $entityManager->getRepository(Claim::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
$data['withdrawalId'] = $withdrawal->getCode();
$data['withdrawalPdfUrl'] = $this->generateUrl('customer_withdrawal_pdf', [
'id' => $id,
'customerId' => $customerId,
]);
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/withdrawalSuccess.html.twig', $data);
}
/**
* @Route("/account/withdrawal/{id}/pdf/{customerId}", name="customer_withdrawal_pdf", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/withdrawal/{id}/pdf/{customerId}", name="customer_withdrawal_pdf_locale", defaults={"_locale":""})
* @param Request $request
* @param int $id
* @param int|null $customerId
* @return Response
* @throws MpdfException
*/
public function withdrawalPdfAction(Request $request, int $id, int $customerId = null): Response
{
$entityManager = $this->getEntityManager();
if (!is_null($customerId)) {
$customer = $entityManager->getRepository(Customer::class)->findOneById($customerId);
} else {
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
}
if (!$customer) {
return $this->redirectToRoute('customer_login');
}
$withdrawal = $entityManager->getRepository(Claim::class)->findOneBy([
'id' => $id,
'customer' => $customer,
]);
if (!$withdrawal) {
return $this->redirectToRoute('not_found');
}
$data = [];
/**
* @var Claim $withdrawal
*/
$data['withdrawal'] = $withdrawal;
$data['customerAddress'] = $withdrawal->getCustomer()->getAddresses()->first();
$data['statusChoices'] = ClaimStatus::getStatusChoices();
$data['withdrawalReasonChoices'] = Claim::getWithdrawalReasonChoices();
$html = $this->render('AtechNetCoreBundle/PDF/withdrawal.html.twig', $data);
$pdf = new Mpdf([
'mode' => '',
'format' => 'A4',
'default_font_size' => 9,
'defualt_font' => 'dejavusans',
'mgl' => 10,
'mgr' => 10,
]);
$pdf->shrink_tables_to_fit = false;
$pdf->WriteHTML($html);
return new Response(
$pdf->output(
$this->getTranslator()->trans('Withdrawal') . '_furbify_' . $request->getLocale() . '_' . $withdrawal->getCode() . '.pdf',
'I'
),
Response::HTTP_OK,
[
'content-type' => 'application/pdf',
]
);
}
/**
* @Route("/account/claim/{claimId}", name="customer_claim_show", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/claim/{claimId}", name="customer_claim_show_locale", defaults={"_locale":""})
* @param Request $request
* @param int $claimId
* @return Response
* @throws InvalidArgumentException
*/
public function showClaimAction(Request $request, int $claimId): Response
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
$translator = $this->getTranslator();
$multiStore = $this->getMultiStoreHelper($request);
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Claims'),
'href' => $this->generateUrl('customer_claims'),
];
$domain = $multiStore->getDomain();
$data['languageCode'] = $domain->getLanguage()->getCode();
$data['currency'] = $domain->getCurrency();
$data['precision'] = $domain->getPricePrecision();
$claim = $this->getEntityManager()->getRepository(Claim::class)->findOneBy([
'id' => $claimId,
'customer' => $customer->getId(),
]);
if ($claim) {
$data['heading_title'] = $translator->trans('Claim') . ': ' . $claim->getCode();
$data['breadcrumbs'][] = [
'text' => $translator->trans('Claim') . ': ' . $claim->getCode(),
'href' => $this->generateUrl('customer_claim_show', [
'claimId' => $claimId,
]),
];
// Claim Details
$data['claimCode'] = $claim->getCode();
$data['dateAdded'] = $claim->getCreated()->format($translator->trans('datetime.format'));
$data['returnType'] = $claim->getReturnType();
$data['receiveType'] = $claim->getReceiveType();
// Customer Details
$data['firstName'] = $claim->getFirstName();
$data['lastName'] = $claim->getLastName();
$data['address'] = $claim->getStreet();
$data['city'] = $claim->getCity();
$data['postalCode'] = $claim->getZip();
$data['telephone'] = $claim->getPhone();
$data['email'] = $claim->getEmail();
// Order & Product Details
if (!is_null($claim->getBoughtDate())) {
$data['boughtDate'] = $claim->getBoughtDate()->format($translator->trans('datetime.format'));
} else {
$data['boughtDate'] = '-';
}
$data['invoiceCode'] = $claim->getInvoiceCode();
$data['productType'] = $claim->getProductType();
$data['productTitle'] = $claim->getProductTitle();
$data['serialNumber'] = $claim->getSerialNumber();
$data['cable'] = $claim->isCable();
$data['customerNote'] = $claim->getCustomerNote();
// Claim Status
$data['technicianNote'] = $claim->getTechnicNote();
$data['solution'] = $claim->getSolution();
$lastStatus = $claim->getLastStatus();
if ($lastStatus) {
if ($lastStatus->getStatusType() >= ClaimStatus::STATUS_TYPE_WAITING_FOR_SALES
&& $lastStatus->getStatusType() <= ClaimStatus::STATUS_TYPE_WAITING_FOR_REFUND) {
$data['status'] = 'Waiting';
}
else {
$data['status'] = ClaimStatus::getStatusChoices()[$lastStatus->getStatusType()];
}
} else {
$data['status'] = '';
}
$data['updated'] = '-';
if (!is_null($claim->getUpdated()) && $claim->getCreated() != $claim->getUpdated()) {
$data['updated'] = $claim->getUpdated()->format($translator->trans('datetime.format'));
}
$data['hasTest'] = $claim->hasTest();
$data['returnTypeChoices'] = Claim::getReturnTypeChoices();
$data['receiveTypeChoices'] = Claim::getReceiveTypeChoices();
$data['productTypeChoices'] = Claim::getProductTypeChoices();
$data['solutionChoices'] = Claim::getSolutionChoices();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/showClaim.html.twig', $data);
}
return $this->forward('App\AtechNet\CoreBundle\Controller\DefaultController::notFoundAction', []);
}
/**
* @Route("/claim/tracking/{token}", name="customer_claim_tracking", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/claim/tracking/{token}", name="customer_claim_tracking_locale", defaults={"_locale":""})
* @param Request $request
* @param string $token
* @return Response
* @throws InvalidArgumentException
*/
public function claimTrackingAction(Request $request, string $token): Response
{
$claim = $this->getEntityManager()->getRepository(Claim::class)->findOneById(
$this->getEntityManager()->getRepository(Claim::class)->getClaimIdFromToken($token)
);
if ($claim) {
if ($this->getEntityManager()->getRepository(Claim::class)->validateClaimToken($claim, $token)) {
$translator = $this->getTranslator();
$multiStore = $this->getMultiStoreHelper($request);
$data = [];
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Guest'),
'href' => $this->generateUrl('customer_account'),
];
$domain = $multiStore->getDomain();
$data['languageCode'] = $domain->getLanguage()->getCode();
$data['heading_title'] = $translator->trans('Claim') . ': ' . $claim->getCode();
$data['breadcrumbs'][] = [
'text' => $translator->trans('Claim') . ': ' . $claim->getCode(),
'href' => $this->generateUrl('customer_claim_tracking', [
'token' => $token,
]),
];
// Claim Details
$data['claimCode'] = $claim->getCode();
$data['dateAdded'] = $claim->getCreated()->format($translator->trans('datetime.format'));
$data['returnType'] = $claim->getReturnType();
$data['receiveType'] = $claim->getReceiveType();
// Customer Details
$data['firstName'] = $claim->getFirstName();
$data['lastName'] = $claim->getLastName();
$data['address'] = $claim->getStreet();
$data['city'] = $claim->getCity();
$data['postalCode'] = $claim->getZip();
$data['telephone'] = $claim->getPhone();
$data['email'] = $claim->getEmail();
// Order & Product Details
if (!is_null($claim->getBoughtDate())) {
$data['boughtDate'] = $claim->getBoughtDate()->format($translator->trans('datetime.format'));
} else {
$data['boughtDate'] = '-';
}
$data['invoiceCode'] = $claim->getInvoiceCode();
$data['productType'] = $claim->getProductType();
$data['productTitle'] = $claim->getProductTitle();
$data['serialNumber'] = $claim->getSerialNumber();
$data['cable'] = $claim->isCable();
$data['customerNote'] = $claim->getCustomerNote();
// Claim Status
$data['technicianNote'] = $claim->getTechnicNote();
$data['solution'] = $claim->getSolution();
$lastStatus = $claim->getLastStatus();
if ($lastStatus) {
if ($lastStatus->getStatusType() >= ClaimStatus::STATUS_TYPE_WAITING_FOR_SALES
&& $lastStatus->getStatusType() <= ClaimStatus::STATUS_TYPE_WAITING_FOR_REFUND) {
$data['status'] = 'Waiting';
}
else {
$data['status'] = ClaimStatus::getStatusChoices()[$lastStatus->getStatusType()];
}
} else {
$data['status'] = '';
}
$data['updated'] = '-';
if (!is_null($claim->getUpdated()) && $claim->getCreated() != $claim->getUpdated()) {
$data['updated'] = $claim->getUpdated()->format($translator->trans('datetime.format'));
}
$data['hasTest'] = $claim->hasTest();
$data['tests'] = $claim->getTests();
$data['returnTypeChoices'] = Claim::getReturnTypeChoices();
$data['receiveTypeChoices'] = Claim::getReceiveTypeChoices();
$data['productTypeChoices'] = Claim::getProductTypeChoices();
$data['solutionChoices'] = Claim::getSolutionChoices();
$data['testTypes'] = ClaimTest::getTestTypes();
$data['testStates'] = ClaimTest::getTestStates();
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['guest'] = true;
return $this->render('AtechNetCoreBundle/Customer/showClaim.html.twig', $data);
}
}
return $this->forward('App\AtechNet\CoreBundle\Controller\DefaultController::notFoundAction', []);
}
/**
* @Route("/account/commissions", name="customer_commissions", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/account/commissions", name="customer_commissions_locale", defaults={"_locale":""})
* @param Request $request
* @return RedirectResponse|Response
* @throws \Exception
*/
public function commissionsAction(Request $request)
{
if (!$this->getLoginHelper($request)->isLoggedIn()) {
return $this->redirectToRoute('customer_login');
}
if ($request->getSession()->get('customerTypeId') != MultiStore::CUSTOMER_TYPE_WHOLESALE) {
return $this->redirectToRoute('homepage');
}
$customer = $this->getLoginHelper($request)->getLoggedInCustomer();
$translator = $this->getTranslator();
$entityManager = $this->getEntityManager();
$filterStatus = ProductCommission::Status_AtPartner;
if (!is_null($request->get('filter-status')) && is_numeric($request->get('filter-status'))) {
$filterStatus = $request->get('filter-status');
}
if (!is_null($request->request->get('commission-status-change'))
&& is_numeric($request->request->get('commission-status-change'))
&& $request->request->get('commission-status-change') != ProductCommission::Status_Returned
&& !is_null($request->request->get('commission-status-change-id'))
&& is_numeric($request->request->get('commission-status-change-id'))) {
$commissionId = $request->request->get('commission-status-change-id');
$commission = $entityManager->getRepository(ProductCommission::class)->findOneBy([
'id' => $commissionId,
'customer' => $customer,
]);
if ($commission) {
$commission->setStatus($request->request->get('commission-status-change'));
$this->getEntityManager()->flush();
if ($commission->getChildren()->count() > 0) {
foreach ($commission->getChildren() as $child) {
$child->setStatus($request->request->get('commission-status-change'));
$this->getEntityManager()->flush();
}
}
$this->addFlash(
'success',
$this->getTranslator()->trans('Your commission staus was successfully changed!')
);
$mailer = $this->getMailer();
$subject = 'Commission status change for ' . $customer->getFirstName() . ' ' . $customer->getLastName() . ' (' . $customer->getBusinessName() . ') ID: ' . $commission->getId();
$email = (new TemplatedEmail())
->subject($subject)
->to('webshop@furbify.eu')
->addTo($customer->getSalesManager()->getEmail())
->replyTo($this->getParameter('mailer_reply_to'))
->html('New commission set to ' . ProductCommission::getStatusChoices()[$commission->getStatus()] . ': <a href="https://www.atechcomp.eu/centralis/web/product/commission/edit/' . $commission->getId() . '">LINK</a>');
$mailer->send($email);
}
}
$data = [];
$data['heading_title'] = $translator->trans('Commissions');
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Commissions'),
'href' => $this->generateUrl('customer_commissions'),
];
$commissionCounts = $this->getEntityManager()
->createQuery("SELECT pc.status, COUNT(pc.id) AS statusCount
FROM AtechNetCoreBundle:ProductCommission pc
WHERE pc.customer = :customer AND pc.parent IS NULL
GROUP BY pc.status")
->setParameters([
'customer' => $customer,
])
->getResult();
$data['statusCounts'] = [];
foreach ($commissionCounts as $commissionCount) {
$data['statusCounts'][$commissionCount['status']] = $commissionCount['statusCount'];
}
$commissions = $entityManager->getRepository(ProductCommission::class)->findBy(
[
'customer' => $customer,
'status' => $filterStatus,
'parent' => null,
],
[
'created' => 'DESC',
]
);
$data['commissionCount'] = $this->getCommissionsCount($request);
$data['commissions'] = [];
$dbTranslator = $this->getDatabaseTranslator($request);
/**
* @var ProductCommission $commission
*/
foreach ($commissions as $commission) {
$productTypeTitle = $commission->getProduct()->getType()->getTitle($dbTranslator);
if (!isset($data['commissions'][$productTypeTitle])) {
$data['commissions'][$productTypeTitle] = [];
}
// Product
$product = $commission->getProduct();
// Price
$price = 0;
// Stock Movement Price
if ($commission->getStockMovement()) {
foreach ($commission->getStockMovement()->getMovementItems() as $stockMovementItem) {
if ($stockMovementItem->getProduct()->getId() == $product->getId()) {
// Scannable Product
if ($stockMovementItem->getItems()) {
foreach ($stockMovementItem->getItems() as $stockItem) {
if ($commission->getSerialNumber() == $stockItem->getSerialNumber()) {
$price = $stockMovementItem->getVatPricePerItem();
break 2;
}
}
} // Non-scannable Product
else {
$price = $stockMovementItem->getVatPricePerItem();
break;
}
}
}
}
// Product Container Children have Neutral Stock Movement
$neutralStockMovement = false;
// Children Price
$childrenPrice = 0;
// Children
$children = [];
if ($commission->getChildren()->count() > 0) {
foreach ($commission->getChildren() as $child) {
// Product
$productChild = $child->getProduct();
// Price
$priceChild = 0;
if ($child->getStockMovement()) {
foreach ($child->getStockMovement()->getMovementItems() as $mic) {
if ($mic->getProduct()->getId() == $productChild->getId()) {
$priceChild = $mic->getVatPricePerItem();
}
}
if ($child->getStockMovement()->getType() == StockMovement::TYPE_NEUTRAL) {
$neutralStockMovement = true;
}
}
// Child
$children[] = [
'id' => $child->getId(),
'productId' => $productChild->getId(),
'productCode' => $productChild->getCode(),
'productTitle' => $productChild->getFullTitle($dbTranslator),
'productDescription' => $productChild->getDescription(),
'price' => $priceChild . ' ' . $child->getCustomer()->getDomain()->getCurrency(),
'serialNumber' => $child->getSerialNumber(),
'statusId' => $child->getStatus(),
'created' => $child->getCreated(),
'updated' => $child->getUpdated(),
];
$childrenPrice += $priceChild;
}
}
if ($childrenPrice > 0 && $price <= 0) {
$price = $childrenPrice;
}
//-> Order Item
$orderItem = null;
// Determine Order Item only for parent Product Containers and Product Containers with neutral Stock Movement
if (is_null($commission->getParent()) && ((!is_null($commission->getStockMovement()) && $commission->getStockMovement()->getType() == StockMovement::TYPE_NEUTRAL) || ($commission->isContainer() && $neutralStockMovement))) {
// Determine Order Item of Product Container
if (!is_null($commission->getChildren()) && $commission->getChildren()->count() > 0) {
foreach ($commission->getChildren() as $child) {
// Child Product
$childProduct = $child->getProduct();
if ($child->getStockMovement()) {
foreach ($child->getStockMovement()->getMovementItems() as $childStockMovementItem) {
if ($childStockMovementItem->getProduct()->getId() == $childProduct->getId()) {
// Scannable Product
if ($childStockMovementItem->getItems()) {
foreach ($childStockMovementItem->getItems() as $childStockItem) {
if ($child->getSerialNumber() == $childStockItem->getSerialNumber()) {
$childOrderItem = $childStockMovementItem->getOrderItem();
if ($childOrderItem) {
$orderItem = $childOrderItem->getParent();
break 3;
}
}
}
} // Non-scannable Product
else {
$childOrderItem = $childStockMovementItem->getOrderItem();
if ($childOrderItem) {
$orderItem = $childOrderItem->getParent();
break 2;
}
}
}
}
}
}
} // Determine Order Item of single Product
elseif ($commission->getStockMovement()) {
foreach ($commission->getStockMovement()->getMovementItems() as $stockMovementItem) {
if ($stockMovementItem->getProduct()->getId() == $product->getId()) {
// Scannable Product
if ($stockMovementItem->getItems()) {
foreach ($stockMovementItem->getItems() as $stockItem) {
if ($commission->getSerialNumber() == $stockItem->getSerialNumber()) {
$orderItem = $stockMovementItem->getOrderItem();
break 2;
}
}
} // Non-scannable Product
else {
$orderItem = $stockMovementItem->getOrderItem();
break;
}
}
}
}
}
//<- Order Item
// Container Accessories Price
$accessoriesPrice = 0;
// Container Accessories
$containerAccessories = [];
foreach ($commission->getAccessories() as $commissionAccessory) {
// Accessory Price
$accessoryPrice = 0;
// Determine Stock Movement Item based on Order Item
$stockMovementItem = null;
if (!is_null($orderItem) && $orderItem->getItemAttributes()) {
foreach ($orderItem->getItemAttributes() as $orderItemAttribute) {
$attributeOption = $orderItemAttribute->getAttributeOption();
if ($attributeOption) {
$attributeOptionProduct = $attributeOption->getProduct();
if ($attributeOptionProduct) {
if ($commissionAccessory->getProduct()->getId() == $attributeOptionProduct->getId()) {
$stockMovementItem = $orderItemAttribute->getStockMovementItem();
break;
}
}
}
}
}
if (!is_null($stockMovementItem)) {
$accessoryPrice = $stockMovementItem->getVatPricePerItem();
} else {
$stockMovement = $commissionAccessory->getStockMovement();
if ($stockMovement) {
foreach ($stockMovement->getMovementItems() as $stockMovementItem) {
if ($stockMovementItem->getProduct()->getId() == $commissionAccessory->getProduct()->getId()) {
$accessoryPrice = $stockMovementItem->getVatPricePerItem();
break;
}
}
}
}
$containerAccessories[] = [
'title' => $commissionAccessory->getProduct()->getFullTitle(),
'price' => $accessoryPrice . ' ' . $commission->getCustomer()->getDomain()->getCurrency(),
];
$accessoriesPrice += $accessoryPrice;
}
if ($accessoriesPrice > 0) {
$price += $accessoriesPrice;
}
$data['commissions'][$productTypeTitle][] = [
'id' => $commission->getId(),
'productId' => $product->getId(),
'productCode' => $product->getCode(),
'productTitle' => $product->getFullTitle($dbTranslator),
'productDescription' => $product->getDescription(),
'price' => $price . ' ' . $commission->getCustomer()->getDomain()->getCurrency(),
'serialNumber' => $commission->getSerialNumber(),
'statusId' => $commission->getStatus(),
'created' => $commission->getCreated(),
'updated' => $commission->getUpdated(),
'children' => $children,
'accessories' => $containerAccessories,
];
}
$data['statuses'] = ProductCommission::getStatusChoices();
$data['filterStatus'] = $filterStatus;
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
$data['userWithZeroVat'] = $customer && $customer->useZeroVat($customer->getVatId());
return $this->render('AtechNetCoreBundle/Customer/commission.html.twig', $data);
}
/**
* @Route("/order/payment-check/{orderId}/{paymentId}", name="customer_payment_check", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/order/payment-check/{orderId}/{paymentId}", name="customer_payment_check_locale", defaults={"_locale":""})
* @param Request $request
* @param $orderId
* @param $paymentId
* @return mixed
* @throws \Exception
*/
public function orderPaymentStatusAction(Request $request, $orderId, $paymentId)
{
$entityManager = $this->getEntityManager();
$translator = $this->getTranslator();
$order = $entityManager->getRepository(Order::class)->findOneBy([
'id' => $orderId,
'customer' => $this->getLoginHelper($request)->getLoggedInCustomer(),
]);
if ($order) {
$gopayHelper = $this->getGopayHelper($request);
$data['payment_status'] = $gopayHelper->checkPaymentStatus($paymentId);
$data['heading_title'] = $translator->trans('Check payment') . ' - ' . $translator->trans('Order') . ' #' . $orderId;
$data['breadcrumbs'] = [];
$data['breadcrumbs'][] = $this->getBreadCrumbsBase($request);
$data['breadcrumbs'][] = [
'text' => $translator->trans('Account'),
'href' => $this->generateUrl('customer_account'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Orders'),
'href' => $this->generateUrl('customer_orders'),
];
$data['breadcrumbs'][] = [
'text' => $translator->trans('Check payment') . ' - ' . $translator->trans('Order') . ' #' . $orderId,
'href' => $this->generateUrl('customer_payment_check', [
'orderId' => $orderId,
'paymentId' => $paymentId,
]),
];
$data['header'] = $this->getHeader($request);
$data['footer'] = $this->getFooter($request);
$data['contentBottom'] = $this->getContentBottom($request);
return $this->render('AtechNetCoreBundle/Customer/orderCheckPayment.html.twig', $data);
} else {
return $this->forward('App\AtechNet\CoreBundle\Controller\DefaultController::notFoundAction', []);
}
}
/**
* @Route("/customer/find-postal-code-or-city", name="customer_find_postal_code_city", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/customer/find-postal-code-or-city", name="customer_find_postal_code_city_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
*/
public function findPostalCodeOrCityAction(Request $request): JsonResponse
{
// Multi-Store
$multiStoreHelper = $this->getMultiStoreHelper($request);
// Load Database
$database = $this->getPostalCodeAndCityDatabaseByDomain(
$multiStoreHelper->getDomainId(),
$multiStoreHelper->getDefaultLocale()
);
// Find Cities By Postal Code
if ($request->request->get('filterPostalCode')) {
$postalCode = urldecode($request->request->get('filterPostalCode'));
$postalCode = str_replace(' ', '', $postalCode);
$response = array_filter($database, function ($row) use ($postalCode) {
return preg_match('/^(' . $postalCode . ')/', $row['postalCode']) == 1;
});
}
// Find Postal Codes by City
if ($request->request->get('filterCity')) {
$city = str_replace(' ', '', $request->request->get('filterCity'));
$response = array_filter($database, function ($row) use ($city) {
return preg_match('/^(' . $city . ')/', $row['city']) == 1;
});
}
return new JsonResponse(array_values($response));
}
/**
* @Route("/customer/check-valid-postal-code", name="customer_check_valid_postal_code")
* @param Request $request
*
* @return Response
*/
public function checkValidPostalCodeAction(Request $request): Response
{
$checkout = $request->query->get('checkout');
if (!is_array($checkout) && (!isset($checkout['shippingPostalCode']) && !isset($checkout['billingPostalCode']))) {
return new JsonResponse([
'valid' => false,
]);
}
$postalCode = $checkout['shippingPostalCode'] ?? $checkout['billingPostalCode'];
$postalCode = str_replace(' ', '', $postalCode);
$multiStoreHelper = $this->getMultiStoreHelper($request);
$data = $this->getPostalCodeAndCityDatabaseByDomain(
$multiStoreHelper->getDomainId(),
$multiStoreHelper->getDefaultLocale()
);
unset($data[0]);
foreach ($data as $row) {
if ($row['postalCode'] == $postalCode) {
return new JsonResponse([
'valid' => true,
]);
}
}
return new JsonResponse([
'valid' => false,
]);
}
/**
* @Route("/check-unique-business-id", name="check_unique_business_id", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/check-unique-business-id", name="check_unique_business_id_locale", defaults={"_locale":""})
* @param $request
* return JsonResponse
*/
public function checkUniqueBusinessIdAction(Request $request): JsonResponse
{
$businessId = $request->get('businessId') ?? 0;
if ($businessId === 0) {
return new JsonResponse([
'error' => 'Missing business id',
]);
}
$multiStore = $this->getMultiStoreHelper($request);
$domainLanguage = $multiStore->getDomain()->getLanguage();
$duplicateBusinessIdCheck = $this->getEntityManager()
->createQuery("SELECT c.id
FROM AtechNetCoreBundle:Customer c
LEFT JOIN c.domain d
WHERE (c.businessId = :businessId OR c.businessId = :trimmedBusinessId) AND d.language = :domainLanguage")
->setParameters([
'businessId' => $businessId,
'trimmedBusinessId' => str_replace(' ', '', $businessId),
'domainLanguage' => $domainLanguage,
])
->getResult();
return new JsonResponse([
'state' => (count($duplicateBusinessIdCheck) > 0 ? 'error' : 'success'),
]);
}
/**
* @Route("/customer/finstat-lookup", name="customer_finstat_lookup", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/customer/finstat-lookup", name="customer_finstat_lookup_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
*/
public function finstatLookupAction(Request $request, FinstatService $finstatService): JsonResponse
{
$businessId = trim((string) $request->get('businessId'));
if ($businessId === '') {
return new JsonResponse(['error' => 'Missing businessId'], Response::HTTP_BAD_REQUEST);
}
$multiStore = $this->getMultiStoreHelper($request);
$country = strtoupper($multiStore->getDefaultLanguage()->getCode());
if (!in_array($country, ['SK', 'CZ'], true)) {
return new JsonResponse(['error' => 'Not supported for this domain'], Response::HTTP_BAD_REQUEST);
}
$result = $finstatService->getVatAndTaxIdByBusinessId($country, $businessId);
if ($result === null) {
return new JsonResponse(['error' => 'Not found'], Response::HTTP_NOT_FOUND);
}
return new JsonResponse([
'vatId' => $result['vatId'],
'taxId' => $result['taxId'],
]);
}
/**
* @Route("/customer/vat-number-check", name="atech_net_core_customer_vat_number_check", defaults={"_locale":""})
* @Route("/{_locale<%supported_locales%>?}/customer/vat-number-check", name="atech_net_core_customer_vat_number_check_locale", defaults={"_locale":""})
* @param Request $request
* @return JsonResponse
* @throws \Exception
*/
public function vatNumberCheckAction(Request $request): JsonResponse
{
if ($request->request->get('countryCode') == 'GR') {
$countryCode = 'EL';
} else {
$countryCode = $request->request->get('countryCode');
}
$valid = $this->getEntityManager()->getRepository(Customer::class)->isVatNumberValid(
$countryCode,
$request->request->get('vatNumber')
);
return new JsonResponse([
'state' => $valid ? 'valid' : 'invalid',
]);
}
/**
* @Route("/customer/generate-new-klarna-session/{orderId}", name="atech_net_core_customer_generate_new_klarna_session")
*/
public function generateNewKlarnaSession(Request $request, $orderId){
$order = $this->getEntityManager()->getRepository(Order::class)->findOneById($orderId);
$domain = $order->getDomain();
$orderSetting = $order->getKlarnaPaymentSessionIdSetting();
$klarna = $this->getKlarna($domain->getId(), $request, $order->getShippingCountry());
$klarnaSessionData = $klarna->getKlarnaSession($orderSetting->getValue());
$newKlarnaSession = $klarna->createNewKlarnaSessionFromTheOldOne($klarnaSessionData);
$redirectUrl = $this->generateUrl('checkout_payment_check', [
'paymentTypeId' => PaymentType::Klarna->value,
'orderId' => $order->getId(),
]);
if (!isset($newKlarnaSession['session_id'])){
return $this->redirect($redirectUrl);
}
$klarnaUrl = $klarna->createKlarnaUrl($redirectUrl, $newKlarnaSession['session_id']);
$newOrderSetting = new OrderSetting();
$newOrderSetting->setOrder($order);
$newOrderSetting->setType(OrderSetting::TYPE_KLARNA_PAYMENT_SESSION_ID);
$newOrderSetting->setValue($newKlarnaSession['session_id']);
$entityManager = $this->getEntityManager();
$entityManager->persist($newOrderSetting);
$entityManager->flush();
return $this->redirect($klarnaUrl['redirect_url']);
}
//KLAVIYO WEBHOOK
/**
* @Route("/customer/klaviyo/bnpl-check/{token}", name="app_atechnet_core_customer_klaviyobnplcheckwebhook")
*
* @param string $token
* @param Request $request
*
* @return JsonResponse
* @throws NotSupported
*/
public function klaviyoBnplCheckWebhookAction(string $token, Request $request): JsonResponse
{
if ($token !== KlaviyoConnect::WEBHOOK_TOKEN) {
return new JsonResponse('Invalid token', Response::HTTP_FORBIDDEN);
}
$data = json_decode($request->getContent(), true);
if (!isset($data['bnpl_value']) || !in_array($data['bnpl_value'], PaymentType::getBnplPaymentTypeIds())) {
return new JsonResponse('Invalid or missing BNPL value', Response::HTTP_BAD_REQUEST);
}
if (!isset($data['order_id']) || !is_numeric($data['order_id'])) {
return new JsonResponse('Invalid or missing order_id', Response::HTTP_BAD_REQUEST);
}
$entityManager = $this->getEntityManager();
$order = $entityManager->getRepository(Order::class)->findOneById($data['order_id']);
if (!$order || $order->getPaymentType() != $data['bnpl_value']) {
return new JsonResponse('Order not found or payment type mismatch', Response::HTTP_NOT_FOUND);
}
if ($order->getPaymentStatus() == Order::PAYMENT_STATUS_PAID) {
return new JsonResponse('Payment already completed', Response::HTTP_OK);
}
// Generate Furbify link
$orderRepository = $entityManager->getRepository(Order::class);
$orderLink = $order->getDomain()->getUrl() . '/account/order/' . $order->getId() . '/' .
$orderRepository->generatePublicLinkToken([
'orderId' => $order->getId(),
], (7 * 24 * 60 * 60));
// Send to Klaviyo
$this->getKlaviyoConnect($request)->createBnplNotPayedEvent(
$order,
PaymentType::from($data['bnpl_value']),
$orderLink
);
return new JsonResponse('Success', Response::HTTP_OK);
}
/**
* @Route("/customer/klaviyo/rental-email-send/{token}", name="app_atechnet_core_customer_klaviyorentalnotificationwebhook")
* @param string $token
* @param Request $request
*
* @return JsonResponse
* @throws TransportExceptionInterface
*/
public function klaviyoRentalNotificationWebhookAction(string $token, Request $request): JsonResponse
{
if ($token !== KlaviyoConnect::WEBHOOK_TOKEN) {
return new JsonResponse('Invalid token', Response::HTTP_FORBIDDEN);
}
$data = json_decode($request->getContent(), true);
$mailer = $this->getMailer();
// Email
$email = (new TemplatedEmail())
->subject('Rental notification from ' . $data['data']['domain'] . ' domain')
->to('webshop@furbify.eu')
->cc(['katarina.jobbagyova@furbify.eu'])
->replyTo($data['email'])
->htmlTemplate('AtechNetCoreBundle/Email/rentalNotification.html.twig')
->context(['data' => $data]);
// Send Notification
$mailer->send($email);
return new JsonResponse('Success', Response::HTTP_OK);
}
#[Route('/customer/klaviyo/unas/claim-form/{token}', name: 'app_atechnet_core_customer_klaviyorentalunasclaimformwebhook')]
public function klaviyoClaimFormWebhookAction(string $token, Request $request): JsonResponse
{
if ($token !== KlaviyoConnect::WEBHOOK_TOKEN) {
return new JsonResponse('Invalid token', Response::HTTP_FORBIDDEN);
}
$entityManager = $this->getEntityManager();
$data = json_decode($request->getContent(), true);
$formId = $data['formId'];
$claimTYpe = KlaviyoConnect::getClaimTypeFromFormId($formId);
$language = KlaviyoConnect::getLanguageFromFormId($formId);
$country = strtoupper($language);
$customer = $entityManager->getRepository(Customer::class)->findOneBy([
'email' => $data['email'],
]);
$order = $entityManager->getRepository(Order::class)->createQueryBuilder('o')
->where('o.id = :orderId or o.externalOrderCode = :orderId')
->setParameter('orderId', $data['orderNumber'])
->getQuery()->getOneOrNullResult();
if (!$customer && $order) {
$customer = $order->getCustomer();
}
$claim = new Claim();
$claim->setType($claimTYpe);
$claim->setProductTitle($data['productName']);
$claim->setProductType($data['productType']);
$claim->setSerialNumber($data['serialNumber']);
if ($claimTYpe == Claim::TYPE_WITHDRAWAL) {
$comment = "Comment: {$data['returnComment']} \n";
$returnReason = html_entity_decode($data['returnReason'] ?? '', ENT_QUOTES | ENT_HTML5, 'UTF-8');
$comment .= "Return reasons: $returnReason";
$claim->setBankAccount($data['bankAccount']);
$claim->setBankAccountHolder($data['bankAccountHolder']);
}
else {
$comment = $data['issueDescription'];
}
$claim->setCustomerNote($comment);
if ($order) {
$claim->setOrder($order);
if ($order->useBillingAddressAsShippingAddress()) {
$claim->setCountry($order->getBillingCountry());
$claim->setStreet($order->getBillingStreet());
$claim->setCity($order->getBillingCity());
$claim->setZip($order->getBillingZip());
} else {
$claim->setCountry($order->getShippingCountry());
$claim->setStreet($order->getShippingStreet());
$claim->setCity($order->getShippingCity());
$claim->setZip($order->getShippingZip());
}
if ($order->getBillingoDocuments()->count() > 0) {
$claim->setInvoiceCode($order->getBillingoDocuments()->first()->getInvoiceCode());
}
if ($order->getDocuments()->count() > 0) {
$claim->setInvoiceCode($order->getDocuments()->first()->getCode());
}
} else {
/**
* @var CustomerAddress $customerAddress
*/
$customerAddress = is_null($customer->getAddresses()) ? false : $customer->getAddresses()->first();
if ($customerAddress) {
$claim->setCountry($customerAddress->getCountry());
$claim->setStreet($customerAddress->getStreet());
$claim->setCity($customerAddress->getCity());
$claim->setZip($customerAddress->getZip());
} else {
$claim->setCountry($customer->getCountry());
}
$claim->setInvoiceCode($data['invoiceNumber']);
}
$claim->setFirstName($customer->getFirstName());
$claim->setLastName($customer->getLastName());
$claim->setBusinessName($customer->getBusinessName());
// Phone Number
$phoneNumber = $customer->getPhone();
// Remove non-numeric characters
$_phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
// Add plus sign if was removed
if (substr($phoneNumber, 0, 1) == '+') {
$_phoneNumber = '+' . $_phoneNumber;
}
$claim->setPhone($_phoneNumber);
$claim->setEmail($customer->getEmail());
$claim->setBoughtDate((new \DateTime($data['orderDate'])));
$claim->setCustomer($customer);
$claim->setReceiveType(Claim::RECEIVE_TYPE_SHIPPED_BY_PARCEL);
$claim->setReturnType(Claim::RETURN_TYPE_PARCEL);
if ($order) {
$claim->setCountry($order->getShippingCountry());
}
else {
$claim->setCountry($country);
}
$claim->setCode($entityManager->getRepository(Claim::class)->createCode($claim));
$claim->setLastStatusId(ClaimStatus::STATUS_TYPE_REGISTERED);
$entityManager->persist($claim);
$entityManager->flush();
$claimStatus = new ClaimStatus();
$claimStatus->setClaim($claim);
$claimStatus->setStatusType(1);
$entityManager->persist($claimStatus);
$notificationIds = [785, 3055];
foreach ($notificationIds as $notificationId) {
$notificationConfig = $entityManager->getRepository(NotificationConfig::class)->findOneById($notificationId);
if ($notificationConfig) {
$notification = new Notification();
$notification->setText('New withdrawal #' . $claim->getCode());
$notification->setNotificationConfig($notificationConfig);
$notification->setActive(true);
$notification->setUrl('https://www.atechcomp.eu/centralis/web/claim/edit/' . $claim->getId());
$entityManager->persist($notification);
}
}
$entityManager->flush();
$this->getKlaviyoConnect($request)
->createNewExpansionClaimEvent($claim, $formId);
return new JsonResponse([$claim->getId()], Response::HTTP_OK);
}
}