<?php
namespace GlobalBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\Product;
use Pimcore\Model\DataObject\Compliance;
use Pimcore\Model\DataObject\Port;
use Symfony\Component\Security\Core\User\UserInterface;
use GlobalBundle\Controller\BaseController;
use Pimcore\Model\DataObject\BookADemo;
use Pimcore\Model\DataObject\MiSourceContact;
use GlobalBundle\AppHelpers\GeneralHelper;
use Pimcore\Model\DataObject\Category;
use Pimcore\Model\DataObject\Customer;
use Pimcore\Model\DataObject\MarketingReport;
use Pimcore\Model\DataObject\MarketingReportResponses;
use Pimcore\Model\DataObject\SupplierCompany;
use Pimcore\Placeholder\DataObject as PlaceholderDataObject;
use App\Templating\ViewModel;
use GlobalBundle\Form\LoginFormType;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use CustomerManagementFrameworkBundle\Security\OAuth\Exception\AccountNotLinkedException;
use GlobalBundle\Services\CatalogServices;
use Pimcore\Model\DataObject\SalesCampaign;
use Pimcore\Model\DataObject\SalesCampaignVisitors;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use GlobalBundle\Services\ProductServices;
use Pimcore\Model\DataObject\Wishlist;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject\Country;
use Pimcore\Model\DataObject\Service;
use Pimcore\Model\Element\Note;
use App\Paginator\Paginator;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Pimcore\File;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\JsonResponse;
class DefaultController extends BaseController
{
/**
* Description:- Load Default View
*/
public function defaultFooterAction(Request $request){
}
/**
* @Route("/global")
*/
public function indexAction(Request $request)
{
return new Response('Hello world from global');
}
/**
* @Route("/getDescription")
*/
public function getDescription(Request $request)
{
$myObject = DataObject\Product::getById($request->get('id'));
if (!empty($request->get('presetId'))) {
$productData = DataObject\DescriptionPreset::getById($request->get('presetId'));
$presetDescription = $productData->getDescription('en');
}
return $this->json($presetDescription);
}
/**
* Description: Misource page not found
* @Route("/page-not-found", name="page-not-found")
*/
public function pageNotFoundAction(Request $request, UserInterface $user = null)
{
$viewModel = new ViewModel();
$homePageURL = \Pimcore\Tool::getHostUrl();
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$homePageURL = $homePageURL.'/home';
}
}
$viewModel->homePageUrl = $homePageURL;
return $viewModel->getAllParameters();
}
/**
* Description: Misource landing page
* @Route("/",name="landing");
*/
public function defaultAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
{
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('home');
}
}
$categoriesListing = new Category\Listing();
$catagories = $categoriesListing->load();
$firstLavelCatagory = [];
foreach($catagories as $category){
if($category->getParent()->getType()=='folder'){
array_push($firstLavelCatagory,$category);
}
}
$countryListing = new Country\Listing();
$countryListing->setOrderKey("o_key");
$countryListing->setOrder("ASC");
$countries = $countryListing->load();
$object = new SupplierCompany();
$markets = $object->getClass()->getFieldDefinition("markets");
$marketOptions = $markets->getOptions();
$companyType = $object->getClass()->getFieldDefinition("companyType");
$companyTypeOptions = $companyType->getOptions();
$complianceListing = new Compliance\Listing();
$complianceListing->load();
$portListing = new Port\Listing();
$portListing->load();
$salesCampaignListing = new SalesCampaign\Listing();
$salesCampaignListing->setCondition("isActive = ?", 1);
$salesCampaignListing->setCondition("isVisible = ?", 1);
// $salesCampaignListing->setOrderKey("o_creationDate");
// $salesCampaignListing->setOrder("desc");
$salesCampaignListing->setOrderKey("sequenceNumber");
$salesCampaignListing->setOrder("ASC");
$salesCampaignListing->setUnpublished(false);
$salesCampaignListing->load();
// get the login error if there is one
$url_components = parse_url($request->getUri());
parse_str($url_components['query'] ?? '', $params);
$error = $authenticationUtils->getLastAuthenticationError();
// to load the token to prepopulate the registration form with account data.
if ($error instanceof AccountNotLinkedException) {
// this can be anything - for simplicity we just use an UUID as it is unique and random
$registrationKey = (string) Uuid::uuid4();
// $oAuthHandler->saveToken($registrationKey, $error->getToken());
return $this->redirectToRoute('account-register', [
'registrationKey' => $registrationKey
]);
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
return [
'CDN_URL' => PIMCORE_CDN_BASEURL,
'categories'=>$firstLavelCatagory,
'countries'=>$countries,
'compliances' => $complianceListing,
'ports' => $portListing,
'marketOptions' => $marketOptions,
'companyTypeOptions' => $companyTypeOptions,
'form' => $form->createView(),
'error' => $error,
'dClass' => '',
'editmode'=>$this->editmode,
'salesCampaign' => $salesCampaignListing,
'errorFlag'=>$params['errorFlag'] ?? '',
'errorType'=>$params['errorType'] ?? '',
];
}
/**
* Description: Misource landing page
*/
public function defaultOldAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
{
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('home');
}
}
$categoriesListing = new Category\Listing();
$catagories = $categoriesListing->load();
$firstLavelCatagory = [];
foreach($catagories as $category){
if($category->getParent()->getType()=='folder'){
array_push($firstLavelCatagory,$category);
}
}
$object = new SupplierCompany();
$markets = $object->getClass()->getFieldDefinition("markets");
$marketOptions = $markets->getOptions();
$companyType = $object->getClass()->getFieldDefinition("companyType");
$companyTypeOptions = $companyType->getOptions();
$complianceListing = new Compliance\Listing();
$complianceListing->load();
$portListing = new Port\Listing();
$portListing->load();
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// to load the token to prepopulate the registration form with account data.
if ($error instanceof AccountNotLinkedException) {
// this can be anything - for simplicity we just use an UUID as it is unique and random
$registrationKey = (string) Uuid::uuid4();
// $oAuthHandler->saveToken($registrationKey, $error->getToken());
return $this->redirectToRoute('account-register', [
'registrationKey' => $registrationKey
]);
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
return [
'categories'=>$firstLavelCatagory,
'compliances' => $complianceListing,
'ports' => $portListing,
'marketOptions' => $marketOptions,
'companyTypeOptions' => $companyTypeOptions,
'form' => $form->createView(),
'error' => $error,
'dClass' => 'display:none;'
];
}
/**
* Description:- Misource landing page - Book A demo ajax submit action
*
* @Route("/booking",name="bookAdemo");
* @param Request $request
* @return success or error msg
*/
public function bookingAction(Request $request){
if($request->getMethod() === "POST") {
if($request->get("submitAction") == 'bookAdemo') {
$firstName = $request->get("firstName");
$lastName = $request->get("lastName");
$jobRole = $request->get("jobRole");
$companyType = $request->get("companyType");
$companySize = $request->get("companySize");
$companyName = $request->get("companyName");
$email = $request->get("email");
$unique_key = "BD-".time();
$c = new BookADemo();
$c->setFirstName($firstName);
$c->setLastName($lastName);
$c->setJobRole($jobRole);
$c->setCompanyType($companyType);
$c->setCompanySize($companySize);
$c->setCompanyName($companyName);
$c->setEmail($email);
$c->setParent(GeneralHelper::validateFolderPath(BOOKADEMO_PATH));
$c->setKey($unique_key);
$c->setPublished(true);
try {
$c->save();
return new Response('success');
} catch(\Exception $e) {
return new Response('error');
}
}
}
}
/**
* Description:- Misource landing page - footer contact form ajax submit action
*
* @Route("/contact",name="contactUs");
* @param Request $request
* @return success or error msg
*/
public function contactAction(Request $request){
if($request->getMethod() === "POST") {
if($request->get("submitAction") == 'contactUs') {
$message = $request->get("message");
$name = $request->get("name");
$email = $request->get("email");
$inquiryType = $request->get("inquiryType");
$submitBy = $request->get("submitBy");
$unique_key = "CU-".time();
$cntus = new MiSourceContact();
$cntus->setName($name);
$cntus->setEmail($email);
$cntus->setMessage($message);
$cntus->setInquiryType($inquiryType);
$cntus->setSubmitBy($submitBy);
$cntus->setParent(GeneralHelper::validateFolderPath(CONTACTUS_PATH));
$cntus->setKey($unique_key);
$cntus->setPublished(true);
try {
$cntus->save();
$websiteConfig = \Pimcore\Config::getWebsiteConfig();
$mailReciver = $websiteConfig->get('MailNotification');
$contactUs = array('name' => $name, 'email' => $email, 'message' => $message, 'inquiryType' => $inquiryType);
GeneralHelper::sendMail($mailReciver,'/'.EMAILDOCUMENT_PATH.'/Emails/ContactUs/contactUs',$contactUs);
return new Response('success');
} catch(\Exception $e) {
return new Response('error');
}
}
}
}
/**
* @Route("/product-anonymous-details", name="product-anonymous-details")
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function productDetailAnonymousAction(Request $request)
{
try {
$websiteConfig = \Pimcore\Config::getWebsiteConfig();
$showAnonymousSalePrice = $websiteConfig->get('SHOW_ANONYMOUS_USER_SALEPRICE');
$showAnonymousSalePrice = isset($showAnonymousSalePrice) && ($showAnonymousSalePrice == 'true');
$productServices = new ProductServices();
$countryListing = new Country\Listing();
$countryListing->setOrderKey("o_key");
$countryListing->setOrder("ASC");
$countries = $countryListing->load();
$productsVariantData = [];
$productId = $request->get('productId');
$product = Product::getById($productId);
if ($product === null) {
throw new \Exception('Product not found');
}
// if (!$request->get('pimcore_object_preview')) {
// $paramBag['admin_preview'] = true;
// $checkAllowed = $productServices->checkAllowedProduct($product);
// } else {
// $checkAllowed = true;
// }
// checkProd:
// if ($product->getType() == 'variant') {
// $product = $product->getParent();
// goto checkProd;
// }
// $variantType = '';
$variantType = $product->getVariantType();
$proID = $product->getId();
$proMaterial = $product->getMaterial();
$proColor = $product->getColor();
$proFinish = $product->getFinish();
if($variantType == 'Dimension'){
$prodData = $productServices->getProductChid($product);
$productsVariantData['variant'] = $prodData;
}
$productsVariantData[$proID] = [];
$productsVariantData['isCMF'] = false;
$productsVariantData['variantType'] = $variantType;
$materialData = GeneralHelper::getMasterData('Material', $proMaterial[0]);
$productsVariantData[$proID]['material'] = $materialData;
$colorData = GeneralHelper::getMasterData('color', $proColor[0]);
$finishData = GeneralHelper::getMasterData('finish', $proFinish[0]);
$productsVariantData[$proID]['color'] = $colorData;
$productsVariantData[$proID]['finish'] = $finishData;
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
$finish = $product->getFinish() ? $this->getProductCMF("Finish", $product->getFinish()) : '';
return $this->render('@Global/product/anonymous.product.details.html.twig', [
'form' => $form->createView(),
'countries'=>$countries,
'productVariant' => $productsVariantData,
'MembershipType' => 'Signature',
'editmode'=>$this->editmode ?? "",
'status'=>true,
'product'=>$product,
'showAnonymousSalePrice'=>$showAnonymousSalePrice,
'finish'=>$finish,
]);
} catch (\Exception $e) {
error_log($e->getMessage());
return $this->render('@Global/error/no_data_found.html.twig', ['message' => 'An error occurred while processing your request.']);
}
}
public function getProductCMF($class, array $fieldData): string
{
$result = array_map(function($item) use ($class) {
$masterData = GeneralHelper::getMasterData($class, $item);
return $masterData['name'];
}, $fieldData);
return implode(', ', $result);
}
/**
* @Route("/salescampaign/{campaignname}~s{campaign}", name="salesCampaign-detail", requirements={"campaignname"="[\w-]+", "campaign"="\d+"})
*
* @param Request $request
* @param HeadTitle $headTitleHelper
* @param BreadcrumbHelperService $breadcrumbHelperService
* @param Factory $ecommerceFactory
* @param SegmentTrackingHelperService $segmentTrackingHelperService
* @param Concrete $product built-in parameter conversion, please see https://github.com/pimcore/pimcore/pull/5554
*
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function campaignDetailAction(
Request $request,
UserInterface $user = null, SessionInterface $session
){
$session->remove('totalProductIds');
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$isAbleToUnpublished = false;
$viewModel = new ViewModel();
if (!empty($customer)) {
$customerId = $customer->getId();
$customerObj = Customer::getById($customerId);
$isAbleToUnpublished = $customerObj->getAbleToUnpublished();
}
$params = array_merge($request->query->all(), $request->attributes->all());
//$salesCampaignDetails = SalesCampaign::getById($params['campaign'],['o_published' => true]);
$list = new DataObject\SalesCampaign\Listing();
$list->setCondition("o_id = ?", [$params['campaign']]);
$list->addConditionParam("o_published = ?", true, "AND");
$salesCampaignDetails = $list->load()[0];
//dd($salesCampaignDetails);
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$isAbleToSequence = false;
if (!empty($customer)) {
$customerId = $customer->getId();
$customerObj = Customer::getById($customerId);
$isAbleToSequence = $customerObj->getAbleToSequenceProduct();
}
$salesCampaign = array();
$salesCampaign['status'] = '';
$salesCampaign['editmode']=false;
$salesCampaign['dClass']='';
$countryListing = new Country\Listing();
$countryListing->setOrderKey("o_key");
$countryListing->setOrder("ASC");
$countries = $countryListing->load();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
$salesCampaign['form'] = $form->createView();
$salesCampaign['isVerified'] = 1;
if(!$salesCampaignDetails){
//throw new NotFoundHttpException('SalesCampaign not found.');
//return $this->redirectToRoute('page-not-found');
$salesCampaign['status'] = 'notFound';
return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
}
$isAccountManager = "";
$customerObj = "";
if($customer){
$customerId = $customer->getId();
$customerObj = Customer::getById($customerId);
$isAccountManager= $customerObj->getIsAccountManager();
}
if($salesCampaignDetails->getIsActive() != 1 && !$isAccountManager){
//return $this->redirectToRoute('page-not-found');
$salesCampaign['status'] = 'notFound';
return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
}
if($salesCampaignDetails->getShareableLink() !== \Pimcore\Tool::getHostUrl() . '/salescampaign/'.$params['campaignname'].'~s'.$params['campaign']){
//return $this->redirectToRoute('page-not-found');
$salesCampaign['status'] = 'notFound';
return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
}
$salesCampaign['campaignType'] = $salesCampaignDetails->getCampaignType();
$salesCampaign['bgcolor'] = substr($salesCampaignDetails->getBackgroundColor(), 0, 7);
$salesCampaign['bannerimg'] = $salesCampaignDetails->getBannerImage();
$salesCampaign['bannerimgmobile'] = $salesCampaignDetails->getBannerImageMobile();
$salesCampaign['isPublic'] = $salesCampaignDetails->getIsPublic();
$salesCampaign['accessCode'] = $salesCampaignDetails->getAccessCode();
$salesCampaign['salesCampaignId'] = $salesCampaignDetails->getId();
if($salesCampaign['campaignType'] == 'Lead' && $salesCampaign['isPublic'] != 1){
$salesCampaign['isVerified'] = 0;
}
if($salesCampaign['campaignType'] == 'Lead' && $salesCampaign['accessCode'] == ''){
$salesCampaign['noAccessCode'] = 1;
}else{
$salesCampaign['noAccessCode'] = 0;
}
if($request->getMethod() === "POST") {
if($request->get("submitAction") == 'SCAccessCode') {
$accessCode = $request->get("SCaccessCode");
$firstName = $request->get("SCFirstName");
$lastName = $request->get("SCLastName");
$email = $request->get("SCemail");
$phone = $request->get("SCphone");
$phoneCode = $request->get("SCphoneCode");
$error=array();
if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['email']="*Not Valid";
}
if($salesCampaignDetails->getAccessCode() != $accessCode){
//$salesCampaign['isVerified'] = 1;
$error['accessCode']="*Not Valid";
}
if(!empty($error)){
return new Response(json_encode(array("status"=>"failed",'code'=>"400","errorData"=>$error)));
}else{
if(!empty($firstName) || !empty($lastName) || !empty($email) || !empty($phone)){
$SalesCampaignVisitor = new SalesCampaignVisitors();
$SalesCampaignVisitor->setFirstName($firstName);
$SalesCampaignVisitor->setLastName($lastName);
$SalesCampaignVisitor->setEmail($email);
$SalesCampaignVisitor->setPhone($phoneCode.$phone);
$SalesCampaignVisitor->setParent(GeneralHelper::validateFolderPath(SALES_CAMPAIGN_VISITORS));
$SalesCampaignVisitor->setSalesCampaign($salesCampaignDetails);
$SalesCampaignVisitor->setKey($firstName.' '.$lastName.' '.time());
$SalesCampaignVisitor->save();
}
return new Response(json_encode(array("status"=>"success",'code'=>"200")));
}
}
}
$salesCampaign['title'] = $salesCampaignDetails->getTitle();
$salesCampaign['subtitle'] = $salesCampaignDetails->getSubTitle();
$salesCampaign['mainTitle'] = $salesCampaignDetails->getMainTitle();
$salesCampaign['mainSubTitle'] = $salesCampaignDetails->getMainSubTitle();
$salesCampaign['shortdesc'] = $salesCampaignDetails->getShortDescription();
$salesCampaign['desc'] = $salesCampaignDetails->getDescription();
if (!empty($customer) && $customer->getCustomerType() == 'Supplier') {
if($salesCampaignDetails->getProducts()){
$newcatProduct = $salesCampaignDetails->getProducts();
foreach($newcatProduct as $k1 => $prod){
$customerSupplier = $customer->getSupplier();
$supplierCompany = $customer->getSupplier()->getParent();
$supplierCompanyId = $supplierCompany->getId();
if($prod->getSupplier()->getId() != $supplierCompanyId){
unset($newcatProduct[$k1]);
}
}
$salesCampaign['products'] = $newcatProduct;
}
}else{
$salesCampaign['products'] = $salesCampaignDetails->getProducts();
}
$totalProductIds = [];
foreach ($salesCampaign['products'] as $product) {
$totalProductIds[] = $product->getId();
}
$session->set('totalProductIds', $totalProductIds);
$salesCampaign['isAbleToSequence'] = $isAbleToSequence;
$salesCampaign['isAbleToUnpublished'] = $isAbleToUnpublished;
$salesCampaign['salesCampaignDetails'] = $salesCampaignDetails;
$salesCampaign['countries'] = $countries;
$salesCampaign['isAccountManager'] = $isAccountManager;
$salesCampaign['customerObj'] = $customerObj;
$salesCampaign['campaignWishlist'] = $this->getOptionValues("Wishlist");
//$salesCampaign['companyLists'] = $this->getOptionValues("Company");
if (!empty($customer)) {
$catalogServices = new CatalogServices();
$productServices = new ProductServices();
$catalogServices->getAllUsersByCurrentAccountManagers($viewModel, $customer);
$salesCampaign['companyLists'] = $viewModel->filterExclusiveSuppliers;
$salesCampaign['buyerAccountLoginsArr'] = $productServices->getAllBuyerAccounts(false, true);
}
$salesCampaign['embedText'] = $salesCampaignDetails->getEmbedText() ?? "";
return $this->render('@Global/default/salesCampaign.html.twig',$salesCampaign);
}
/**
* @Route("/marketingreport/{reportname}~mr{report}", name="marketingReport-detail", requirements={"reportname"=".+", "report"="\d+"})
*
* @param Request $request
* @param string $reportname
* @param int $report
*
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Exception
*/
public function marketingReportDetailAction(Request $request, string $reportname, int $report, AuthenticationUtils $authenticationUtils, SessionInterface $session)
{
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('home');
}
}
$countryListing = new Country\Listing();
$countryListing->setOrderKey("o_key");
$countryListing->setOrder("ASC");
$countries = $countryListing->load();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
$reportname = $request->get('reportname');
$reportId = $request->get('report');
$reportMarketingObj = MarketingReport::getById($reportId);
return $this->render('@Global/default/marketingReport.html.twig', [
'form' => $form->createView(),
'error' => $error,
'countries'=>$countries,
'reportname' => $reportname,
'report' => $report,
'editmode'=>$this->editmode,
'reportMarketingObj' => $reportMarketingObj
]);
}
/**
* @Route("/marketingreport/response", name="marketing_report_response", methods={"POST"})
*/
public function marketingReportResponse(Request $request)
{
$formData = $request->request->all();
$marketingReportId = $formData['marketingReportId'];
$firstName = $formData['firstName'];
$lastName = $formData['lastName'];
$marketingReportObj = MarketingReport::getById($marketingReportId);
if(!empty($marketingReportObj)){
$marketingResponses = new MarketingReportResponses();
foreach ($formData as $key => $value) {
$method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
if (method_exists($marketingResponses, $method)) {
$marketingResponses->$method($value);
}
}
$marketingResponses->setMarketingReport($marketingReportObj);
$marketingResponses->setParent(GeneralHelper::validateFolderPath(MARKETING_REPORT_RESPONSES));
$marketingResponses->setKey($firstName.' '.$lastName.' '.time());
$marketingResponses->setPublished(true);
$marketingResponses->save();
return new Response(json_encode(array("status" => "success", 'code' => "200")));
}
return new Response(json_encode(array("status" => "error", 'code' => "404")));
}
/**
* Description: Misource landing page
* @Route("/overview",name="overview");
*/
public function overviewAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
{
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('home');
}
}
$overviewData = array();
$categoriesListing = new Category\Listing();
$catagories = $categoriesListing->load();
$firstLavelCatagory = [];
foreach($catagories as $category){
if($category->getParent()->getType()=='folder'){
array_push($firstLavelCatagory,$category);
}
}
$object = new SupplierCompany();
$markets = $object->getClass()->getFieldDefinition("markets");
$marketOptions = $markets->getOptions();
$companyType = $object->getClass()->getFieldDefinition("companyType");
$companyTypeOptions = $companyType->getOptions();
$complianceListing = new Compliance\Listing();
$complianceListing->load();
$portListing = new Port\Listing();
$portListing->load();
$salesCampaignListing = new SalesCampaign\Listing();
$salesCampaignListing->setCondition("isActive = ?", 1);
// $salesCampaignListing->setOrderKey("o_creationDate");
// $salesCampaignListing->setOrder("desc");
$salesCampaignListing->setOrderKey("sequenceNumber");
$salesCampaignListing->setOrder("ASC");
$salesCampaignListing->setUnpublished(false);
$salesCampaignListing->load();
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// to load the token to prepopulate the registration form with account data.
if ($error instanceof AccountNotLinkedException) {
// this can be anything - for simplicity we just use an UUID as it is unique and random
$registrationKey = (string) Uuid::uuid4();
// $oAuthHandler->saveToken($registrationKey, $error->getToken());
return $this->redirectToRoute('account-register', [
'registrationKey' => $registrationKey
]);
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
return [
'categories'=>$firstLavelCatagory,
'compliances' => $complianceListing,
'ports' => $portListing,
'marketOptions' => $marketOptions,
'companyTypeOptions' => $companyTypeOptions,
'form' => $form->createView(),
'error' => $error,
'dClass' => '',
'salesCampaign' => $salesCampaignListing
];
}
/**
* Description: Misource landing page
* @Route("/trendingUpdate",name="trendingUpdate");
*/
public function trendingUpdateAction(Request $request){
$virtualProducts = DataObject\Product::getById($request->get('productId'));
$trending = $virtualProducts->getTrending();
if ($trending >= 0) {
$trending = $trending + 1;
} else {
$trending = 1;
}
$virtualProducts->setTrending($trending);
$virtualProducts->save();
$virtualProducts->setPublished(true);
exit;
}
/**
* @Route("/saveSalesCampaignSequence", name="saveSalesCampaignSequence")
*
* @param Request $request
* @return success or error msg
*/
public function saveSalesCampaignSequence(Request $request)
{
$productIds = $request->get('prodData');
$salesId = $request->get('salesId');
$prodArray = array_filter(explode(',',$productIds));
if(!empty($prodArray) && $salesId){
$salesCampaignData = SalesCampaign::getById($salesId, ["force" => true]);
$productIdArray = [];
if($salesCampaignData){
for($i=0;$i<count($prodArray);$i++){
foreach ($salesCampaignData->getProducts() as $v) {
if ($prodArray[$i] == $v->getId()){
$productIdArray[] = $v;
}
}
}
$salesCampaignData->setProducts($productIdArray);
$salesCampaignData->save();
}
}
return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => " Sales Campaign product sequenced successfully")));
}
/**
* Index page for account - it is restricted to ROLE_USER via security annotation
*
* @Route("/newPage", name="newPage")
*
* @param UserInterface|null $user
* @return array
*/
public function newPageAction(Request $request, UserInterface $user = null, AuthenticationUtils $authenticationUtils, SessionInterface $session)
{
if(!$this->editmode) {
if ($user && $this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('home');
}
}
$categoriesListing = new Category\Listing();
$catagories = $categoriesListing->load();
$firstLavelCatagory = [];
foreach($catagories as $category){
if($category->getParent()->getType()=='folder'){
array_push($firstLavelCatagory,$category);
}
}
$object = new SupplierCompany();
$markets = $object->getClass()->getFieldDefinition("markets");
$marketOptions = $markets->getOptions();
$companyType = $object->getClass()->getFieldDefinition("companyType");
$companyTypeOptions = $companyType->getOptions();
$salesCampaignListing = new SalesCampaign\Listing();
$salesCampaignListing->setCondition("isActive = ?", 1);
// $salesCampaignListing->setOrderKey("o_creationDate");
// $salesCampaignListing->setOrder("desc");
$salesCampaignListing->setOrderKey("sequenceNumber");
$salesCampaignListing->setOrder("ASC");
$salesCampaignListing->setUnpublished(false);
$salesCampaignListing->load();
$complianceListing = new Compliance\Listing();
$complianceListing->load();
$portListing = new Port\Listing();
$portListing->load();
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// to load the token to prepopulate the registration form with account data.
if ($error instanceof AccountNotLinkedException) {
// this can be anything - for simplicity we just use an UUID as it is unique and random
$registrationKey = (string) Uuid::uuid4();
// $oAuthHandler->saveToken($registrationKey, $error->getToken());
return $this->redirectToRoute('account-register', [
'registrationKey' => $registrationKey
]);
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
return [
'categories'=>$firstLavelCatagory,
'compliances' => $complianceListing,
'ports' => $portListing,
'marketOptions' => $marketOptions,
'companyTypeOptions' => $companyTypeOptions,
'salesCampaign' => $salesCampaignListing,
'form' => $form->createView(),
'error' => $error,
'dClass' => 'display:none;'
];
}
/**
* Description:- Customer Documents
*
* @Route("/user-documents" , name="user-documents");
* @param Request $request
*
*/
public function documents(Request $request)
{
try {
// Check if customer session exists and is an object
if (!isset($_SESSION['_pimcore_admin']['customer']) || !is_object($_SESSION['_pimcore_admin']['customer'])) {
throw new \Exception("Customer session data is invalid or missing.");
}
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$customerObj = Customer::getById($customer->getId());
// Check if customer object is retrieved successfully
if (!$customerObj instanceof Customer) {
throw new \Exception("Customer not found for the given ID: " . ($customer->getId() ?? 'null'));
}
$isAbleToComment = $customerObj->getAbleToComment();
$isAccountManager = $customerObj->getIsAccountManager();
$customerID = $customerObj->getId();
// Check if company exists before accessing getKeyAccountManager
$accountManagers = null;
$company = $customerObj->getCompany();
if ($company) {
$accountManagers = $company->getKeyAccountManager();
} else {
\Pimcore\Log\Simple::log('documents', "Company not found for customer ID: " . $customerID);
}
if ($isAccountManager) {
$allUsers = GeneralHelper::getAccountManagers($customerID, "NoDocument", true);
// $allCustomers = $allUsers['companyWiseUsers'] ?? [];
$allSuppliers = $allUsers['companyWiseSuppliers'] ?? [];
$allInternalUsers = $allUsers['allInternalUsers'] ?? [];
$allBuyers = GeneralHelper::getAllBuyersHavingKeyAccountManagers($customerID, "NoDocument", true);
$allCustomers = $allBuyers['companyWiseUsers'] ?? [];
}
// $filteredGroups = [];
// foreach ($allCustomers as $companyName => $group) {
// if (is_array($group)) {
// $filteredCustomers = [];
// foreach ($group as $cust) {
// $company = $cust->getCompany();
// $keyAccountManagers = $company ? $company->getKeyAccountManager() : [];
// $isCurrentUserKAM = false;
// if (!empty($keyAccountManagers)) {
// foreach ($keyAccountManagers as $kam) {
// if ($kam->getId() == $customerID) {
// $isCurrentUserKAM = true;
// break;
// }
// }
// }
// if ($isCurrentUserKAM) {
// $filteredCustomers[] = $cust;
// }
// }
// if (!empty($filteredCustomers)) {
// $filteredGroups[$companyName] = $filteredCustomers;
// }
// }
// }
// $allCustomers = $filteredGroups;
$filteredSupplierGroups = [];
foreach ($allSuppliers as $companyName => $group) {
if (is_array($group)) {
$filteredSuppliers = [];
foreach ($group as $supplier) {
$company = $supplier->getCompany();
$keyAccountManagers = $company ? $company->getKeyAccountManager() : [];
$isCurrentUserKAM = false;
if (!empty($keyAccountManagers)) {
foreach ($keyAccountManagers as $kam) {
if ($kam->getId() == $customerID) {
$isCurrentUserKAM = true;
break;
}
}
}
if ($isCurrentUserKAM) {
$filteredSuppliers[] = $supplier;
}
}
if (!empty($filteredSuppliers)) {
$filteredSupplierGroups[$companyName] = $filteredSuppliers;
}
}
}
$allSuppliers = $filteredSupplierGroups;
$productServices = new ProductServices();
$buyerAccountLoginsArr = $isAbleToComment ? $productServices->getAllBuyerAccounts() : [];
if ($request->get('docUser')) {
$parts = explode("/", $request->get('docUser'));
$customerID = $parts[0] ?? null;
$boardType = $parts[1] ?? null;
if ($customerID) {
$customerObj = Customer::getById($customerID);
if (!$customerObj instanceof Customer) {
throw new \Exception("Customer not found for ID: " . $customerID);
}
$companyName = $customerObj->getCompany() ? $customerObj->getCompany()->getName() : null;
$customerName = trim($customerObj->getFirstName() . " " . $customerObj->getLastName()) ?: null;
} else {
throw new \Exception("Invalid docUser parameter format.");
}
}
$allDocuments = [];
$currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
$businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
$subTypeMap = [
'productGuidesSubTypes' => 'ProductGuides',
'buyingGuidesSubTypes' => 'BuyingGuides',
'coreInstructionsSubTypes' => 'CoreInstructions',
'policiesSubTypes' => 'Policies'
];
if ($request->get('parentId') && $request->get('id')) {
$parentId = $request->get('parentId');
$subCategoryId = $request->get('id');
$subType = $subTypeMap[$parentId] ?? null;
if ($subType) {
$parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
$subTypeMethodName = 'get' . ucfirst($subType);
$customerDocuments = $customerObj->$parentMethodName();
if ($customerDocuments) {
foreach ($customerDocuments as $document) {
if ($document && $document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
$this->addAttachmentsToDocuments($document, $allDocuments);
}
}
}
}
} else {
foreach ($subTypeMap as $parentId => $subType) {
$methodName = 'get' . ucfirst($parentId) . 'Documents';
if (method_exists($customerObj, $methodName)) {
$customerDocuments = $customerObj->$methodName();
if ($customerDocuments) {
foreach ($customerDocuments as $document) {
if ($document && $document->getBusinessUnit() === $businessUnit) {
$this->addAttachmentsToDocuments($document, $allDocuments);
}
}
}
} else {
\Pimcore\Log\Simple::log('documents', "Method $methodName does not exist in class " . get_class($customerObj));
}
}
}
krsort($allDocuments);
$paginator = new Paginator($allDocuments);
$paginator->setCurrentPageNumber($request->get('page'));
$paginator->setItemCountPerPage(5);
$paginator->setPageRange(5);
return [
'customerObj' => $customerObj,
'buyerAccountLogins' => $buyerAccountLoginsArr,
'userArray' => $allCustomers ?? [],
'supplierArray' => $allSuppliers ?? [],
'allInternalUsersArray' => $allInternalUsers ?? [],
'paginationVariables' => $paginator->getPages('Sliding'),
'isAccountManager' => $isAccountManager,
'allDocument' => $paginator,
'boardType' => $boardType ?? "",
'companyName' => $companyName ?? "",
'customerName' => $customerName ?? "",
'accountManagers' => $accountManagers ?? []
];
} catch (\Exception $e) {
\Pimcore\Log\Simple::log('documents', $e->getMessage());
// return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
return $this->redirectToRoute('landing');
}
}
/* older code dated on 21/7/2025
public function documents(Request $request)
{
try {
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$customerObj = Customer::getById($customer->getId());
$isAbleToComment = $customerObj->getAbleToComment();
$isAccountManager = $customerObj->getIsAccountManager();
$customerID = $customerObj->getId();
// $accountManagers = $customerObj->getCompany()->getAccountManager();
$accountManagers = $customerObj->getCompany()->getKeyAccountManager();
if ($isAccountManager) {
$allUsers = GeneralHelper::getAccountManagers($customerID, "NoDocument", true);
$allCustomers = $allUsers['companyWiseUsers'];
$allSuppliers = $allUsers['companyWiseSuppliers'];
$allInternalUsers = $allUsers['allInternalUsers'];
}
$productServices = new ProductServices();
$buyerAccountLoginsArr = $isAbleToComment ? $productServices->getAllBuyerAccounts() : [];
if ($request->get('docUser')) {
$parts = explode("/", $request->get('docUser'));
$customerID = $parts[0];
$boardType = $parts[1];
$customerObj = Customer::getById($customerID);
$companyName = $customerObj->getCompany()->getName();
$customerName = $customerObj->getFirstName() . " " . $customerObj->getLastName();
}
$allDocuments = [];
$currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
$businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
$subTypeMap = [
'productGuidesSubTypes' => 'ProductGuides',
'buyingGuidesSubTypes' => 'BuyingGuides',
'coreInstructionsSubTypes' => 'CoreInstructions',
'policiesSubTypes' => 'Policies'
];
if ($request->get('parentId') && $request->get('id')) {
$parentId = $request->get('parentId');
$subCategoryId = $request->get('id');
$subType = $subTypeMap[$parentId] ?? null;
if ($subType) {
$parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
$subTypeMethodName = 'get' . ucfirst($subType);
$customerDocuments = $customerObj->$parentMethodName();
if ($customerDocuments) {
foreach ($customerDocuments as $document) {
if ($document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
$this->addAttachmentsToDocuments($document, $allDocuments);
}
}
}
}
} else {
foreach ($subTypeMap as $parentId => $subType) {
$methodName = 'get' . ucfirst($parentId) . 'Documents';
if (method_exists($customerObj, $methodName)) {
$customerDocuments = $customerObj->$methodName();
if ($customerDocuments) {
foreach ($customerDocuments as $document) {
if ($document->getBusinessUnit() === $businessUnit) {
$this->addAttachmentsToDocuments($document, $allDocuments);
}
}
}
} else {
\Pimcore\Log\Simple::log('documents', "Method $methodName does not exist in class " . get_class($customerObj));
}
}
}
krsort($allDocuments);
$paginator = new Paginator($allDocuments);
$paginator->setCurrentPageNumber($request->get('page'));
$paginator->setItemCountPerPage(5);
$paginator->setPageRange(5);
return [
'customerObj' => $customerObj,
'buyerAccountLogins' => $buyerAccountLoginsArr,
'userArray' => $allCustomers ?? [],
'supplierArray' => $allSuppliers ?? [],
'allInternalUsersArray' => $allInternalUsers ?? [],
'paginationVariables' => $paginator->getPages('Sliding'),
'isAccountManager' => $isAccountManager,
'allDocument' => $paginator,
'boardType' => $boardType ?? "",
'companyName' => $companyName ?? "",
'customerName' => $customerName ?? "",
'accountManagers' => $accountManagers
];
} catch (\Exception $e) {
\Pimcore\Log\Simple::log('documents', $e->getMessage());
return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
}
}
*/
private function addAttachmentsToDocuments($document, &$allDocuments)
{
if ($document->getAttachments()) {
foreach ($document->getAttachments() as $attachment) {
$documentId = $attachment->getId();
$asset = Asset::getById($documentId);
if ($asset) {
$allDocuments[$documentId] = $asset;
}
}
}
}
// public function documents(Request $request)
// {
// try {
// $customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
// $customerObj = "";
// $isAbleToComment = false;
// $customerId = $customer->getId();
// if (!empty($customer)) {
// $customerObj = Customer::getById($customerId);
// $isAbleToComment = $customerObj->getAbleToComment();
// $isAccountManager= $customerObj->getIsAccountManager();
// $customerID = $customerObj->getId();
// if($isAccountManager){
// $allUsers = GeneralHelper::getAccountManagers($customerId,"NoDocument", true);
// $allCustomers = $allUsers['companyWiseUsers'];
// $allSuppliers = $allUsers['companyWiseSuppliers'];
// $allInternalUsers = $allUsers['allInternalUsers'];
// }
// }
// $productServices = new ProductServices();
// //ALL Buyer Account
// $buyerAccountLoginsArr = [];
// if($isAbleToComment){
// $buyerAccountLoginsArr = $productServices->getAllBuyerAccounts();
// }
// if($request->get('docUser')){
// $customerID = $request->get('docUser');
// $parts = explode("/", $customerID);
// $customerID = $parts[0];
// $boardType = $parts[1];
// $customerId = $customerID;
// $docUserData = Customer::getById($customerID);
// $customerObj = $docUserData;
// $companyName = $docUserData->getCompany()->getName();
// $customerName = $docUserData->getFirstName()." ".$customerObj->getLastName();
// }
// //LOGIC NEED TO WRITE HERE IF docUser exists then need to take this id
// $allDocuments = [];
// // $db = \Pimcore\Db::get();
// $currentSite = $GLOBALS['site'];
// if(!$currentSite){
// if (\Pimcore\Model\Site::isSiteRequest()) {
// $currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
// }
// }
// $businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
// $subTypeMap = [
// 'productGuidesSubTypes' => 'ProductGuides',
// 'buyingGuidesSubTypes' => 'BuyingGuides',
// 'coreInstructionsSubTypes' => 'CoreInstructions',
// 'policiesSubTypes' => 'Policies'
// ];
// if($request->get('parentId') && $request->get('id')){
// $parentId =$request->get('parentId');
// $subCategoryId = $request->get('id');
// $subType = isset($subTypeMap[$parentId]) ? $subTypeMap[$parentId] : null;
// if ($subType) {
// $parentMethodName = 'get' . ucfirst($parentId) . 'Documents';
// $subTypeMethodName = 'get' . ucfirst($subType);
// // dd($subTypeMethodName);
// $customerDocuments = $customerObj->$parentMethodName();
// if ($customerDocuments) {
// foreach ($customerDocuments as $document) {
// if ($document->getBusinessUnit() === $businessUnit && $document->$subTypeMethodName() === $subCategoryId) {
// if ($document->getAttachments()) {
// foreach ($document->getAttachments() as $attachment) {
// $documentId = $attachment->getId();
// $asset = Asset::getById($documentId);
// if ($asset) {
// $allDocuments[$documentId] = $asset;
// }
// }
// }
// }
// }
// }
// }
// krsort($allDocuments);
// }
// else{
// foreach ($subTypeMap as $parentId => $subType) {
// $methodName = 'get' . ucfirst($parentId) . 'Documents';
// $customerDocuments = $customerObj->$methodName();
// if ($customerDocuments) {
// foreach ($customerDocuments as $document) {
// if ($document->getBusinessUnit() === $businessUnit) {
// if ($document->getAttachments()) {
// foreach ($document->getAttachments() as $attachment) {
// $documentId = $attachment->getId();
// $asset = Asset::getById($documentId);
// if ($asset) {
// $allDocuments[$documentId] = $asset;
// }
// }
// }
// }
// }
// }
// }
// krsort($allDocuments);
// }
// $paginator = new Paginator($allDocuments);
// $paginator->setCurrentPageNumber($request->get('page'));
// $paginator->setItemCountPerPage(5);
// $pageLimit = 5;
// $paginator->setPageRange($pageLimit);
// return [
// 'customerObj'=>$customerObj,
// 'buyerAccountLogins' => $buyerAccountLoginsArr,
// 'userArray' => $allCustomers,
// 'supplierArray' => $allSuppliers,
// 'allInternalUsersArray' => $allInternalUsers,
// 'paginationVariables' => $paginator->getPages('Sliding'),
// 'isAccountManager' => $isAccountManager,
// 'allDocument' => $paginator,
// 'boardType' =>$boardType ?? "",
// 'companyName' =>$companyName ?? "",
// 'customerName' =>$customerName ?? "",
// ];
// } catch (\Exception $e) {
// return new \Symfony\Component\HttpFoundation\Response("Error: " . $e->getMessage(), 500);
// }
// }
/**
* Description:- Global Documents
*
* @Route("/global-documents" , name="global-documents");
* @param Request $request
*
*/
public function globalDocuments()
{
$websiteConfig = \Pimcore\Config::getWebsiteConfig();
$globalDocumentUser = $websiteConfig->get('GLOBAL_DOCUMENT_USER');
$customerObj = "";
if ($globalDocumentUser) {
$customerId = $globalDocumentUser->getId();
$customerObj = Customer::getById($customerId);
}
return [
'customerObj'=>$customerObj
];
}
/**
* Description:- Admin PDF Generate
*
* @Route("/global/pdf/{wishlistId}" , name="admin-custom-pdf-wishlist");
* @param Request $request
*
*/
public function adminPDFGenerateAction(Request $request, Factory $ecommerceFactory, $wishlistId)
{
$websiteConfig = \Pimcore\Config::getWebsiteConfig();
$globalDocumentUser = $websiteConfig->get('GLOBAL_DOCUMENT_USER');
$_SESSION['_pimcore_admin']['customer'] = $globalDocumentUser;
$viewModel = new ViewModel();
$productServices = new ProductServices();
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$viewModel->wishlistId = $wishlistId;
$wishlistData = Wishlist::getById($wishlistId, ["force" => true]);
if ($wishlistData) {
$viewModel->wishlistName = $wishlistData->getLable();
$viewModel->wishlistComment = $wishlistData->getComment();
$wishlistProduct = [];
$wishlistProductData = "";
$viewModel->isPDF = 'yes';
$wishlistProductData = $wishlistData->getProducts();
if (!empty($wishlistProductData)) {
foreach ($wishlistProductData as $k => $v) {
$wishlistProduct[] = $v->getId();
}
}
$totalCount = count($wishlistProduct);
$productListing = $productServices->getWishlistProductListing($viewModel, $ecommerceFactory, $request, $wishlistProduct,'yes');
if (empty($productListing)) {
$viewModel->results = [];
}
} else {
$viewModel->results = [];
}
$accountManagers = GeneralHelper::myAccountManagers($customer);
$currentSite = $GLOBALS['site'];
if(!$currentSite){
if (\Pimcore\Model\Site::isSiteRequest()) {
$currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
}
$params = [];
$viewModel->type = "wishlist";
$viewModel->mainTitle = $viewModel->wishlistName ?? "";
if($currentSite == "3SWebsite"){
$html = $this->renderView('@Global/default/3SWebsite/content.html.twig', array('wishlistId' => $viewModel->getAllParameters()['wishlistId'], 'results' => $viewModel->getAllParameters()['results'], 'mainTitle' => $wishlistData->getLable(), 'wishlistComment' => $wishlistData->getComment(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers,"type"=>"wishlist"));
}
else{
$html = $this->renderView('@Global/product/wishlistCatalog.html.twig', array('wishlistId' => $viewModel->getAllParameters()['wishlistId'], 'results' => $viewModel->getAllParameters()['results'], 'wishlistName' => $wishlistData->getLable(), 'wishlistComment' => $wishlistData->getComment(),'totalCount' => $totalCount,'accountManagers'=>$accountManagers,"type"=>"wishlist"));
}
$fileName = 'wishlist-' . $wishlistId . '.pdf';
$headerCatalogName = urlencode($wishlistData->getLable());
$adapter = \Pimcore\Web2Print\Processor::getInstance();
$adapterString = "--print-media-type --page-size A4 --orientation landscape --margin-left 0mm --margin-right 0mm --margin-top 1cm --margin-bottom 1cm --header-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-header/{$currentSite}/?headerName='".( $headerCatalogName ?? '')."' --footer-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-footer/{$currentSite}/";
$adapter->setOptions($adapterString);
return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
}
/**
* @Route("/legal", name="legal")
*
* @param Request $request
*
* @return array|\Symfony\Component\HttpFoundation\Response
*/
public function legalAction(Request $request){
$viewModel = new ViewModel();
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$viewModel->CDN_URL = PIMCORE_CDN_BASEURL;
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
$viewModel->form = $form->createView();
if(!empty($customer)){
$viewModel->customer = $customer;
}
$viewModel->editmode = $this->editmode;
return $viewModel->getAllParameters();
return $this->render('@Global/default/legal.html.twig',$viewModel->getAllParameters());
}
/**
* @Route("/salesxls")
*
* @param Request $request
* @return success or error msg
*/
public function salesXlsExport(Request $request){
$salesCampaignId = $request->get("salesCampaignId");
$object = DataObject\SalesCampaign::getById($salesCampaignId);
if($object){
$productData= $object->getProducts();
$title=$object->getTitle();
$spreadsheet = new Spreadsheet();
// if($exportType=='CSV'){
// $Excel_writer = new Csv($spreadsheet);
// }else{
$Excel_writer = new Xlsx($spreadsheet);
// }
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
$activeSheet->setCellValue('A1', 'SKU ID');
$activeSheet->setCellValue('B1', 'EAN Code');
$activeSheet->setCellValue('C1', 'Factory Item No');
$activeSheet->setCellValue('D1', 'Product Name');
$activeSheet->setCellValue('E1', 'Supplier');
$activeSheet->setCellValue('F1', 'Category');
$activeSheet->setCellValue('G1', 'Material');
$activeSheet->setCellValue('H1', 'Product Image');
if($productData){
$i = 2;
foreach($productData as $key => $prodValue){
$material = [];
if ($prodValue->getType() == 'variant') {
$prodValue = $prodValue->getParent();
}
if($prodValue->getMaterial()){
foreach($prodValue->getMaterial() as $mValue){
$materialObject = DataObject\Material::getById($mValue);
if($materialObject){
$material[] = $materialObject->getName();
}
}
$materialValue = implode(',',$material);
}
$mainImagedata = $prodValue->getMainImage();
if($mainImagedata){
$asset = Asset::getById($mainImagedata->getId());
if (!empty($asset)) {
$pathToThumbnail = $asset->getThumbnail("productListImageNewPng")->getPath();
}
}
if($prodValue->getCategory()){
$catArr = array_slice(explode('/',$prodValue->getCategory()), 2);
$newCatValue= implode('/',$catArr);
}
$activeSheet->setCellValue('A'.$i , $prodValue->getId());
$activeSheet->setCellValue('B'.$i , $prodValue->getEanCode());
$activeSheet->setCellValue('C'.$i , $prodValue->getProductCode());
$activeSheet->setCellValue('D'.$i , $prodValue->getProductName());
$activeSheet->setCellValue('E'.$i , $prodValue->getSupplier()->getName());
$activeSheet->setCellValue('F'.$i , $newCatValue);
$activeSheet->setCellValue('G'.$i , $materialValue);
$pathToThumbnail = str_replace(' ', '%20', $pathToThumbnail);
$srcImage = imagecreatefrompng($pathToThumbnail);
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
$drawing->setImageResource($srcImage);
$drawing->setCoordinates('H'.$i);
$drawing->setWidthAndHeight(200, 200);
$drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_PNG);
$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setOffsetX(110);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
$spreadsheet->getActiveSheet()->getRowDimension($i)->setRowHeight(170);
$spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth('50');
foreach (range('A', 'G') as $letra) {
$spreadsheet->getActiveSheet()->getColumnDimension($letra)->setAutoSize(true);
}
$i++;
}
}
if($exportType=='CSV'){
$filename = $title.'_'.$salesCampaignId.'.csv';
header('Content-Type: text/csv');
}else{
$filename = $title.'_'.$salesCampaignId.'.xlsx';
header('Content-Type: application/vnd.ms-excel');
}
header('Content-Disposition: attachment;filename='.$filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('salesCampaignExport/'.$filename);
$baseUrl = \Pimcore\Tool::getHostUrl();
return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message,"ExportLink" => $baseUrl.'/salesCampaignExport/'.$filename)));
} else {
return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => "Error")));
}
}
/**
* @Route("/salesCampaignPreview/{id}")
*
* @param Request $request
* @return success or error msg
*/
public function salesCampaignPreview(Request $request, Factory $ecommerceFactory, $id)
{
$viewModel = new ViewModel();
$productServices = new ProductServices();
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$viewModel->salesId = $id;
$salesData = SalesCampaign::getById($id, ["force" => true]);
$viewModel->editmode = $this->editmode;
$viewModel->status = true;
$formData = [
'_username' => $lastUsername
];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
$viewModel->form = $form->createView();
if ($salesData) {
$viewModel->salesCampaignName = $salesData->getTitle();
$viewModel->salesCampaignComment = $salesData->getShortDescription();
$viewModel->isPDF = 'yes';
$salesProduct = [];
$salesProductData = "";
$salesProductData = $salesData->getProducts();
if (!empty($salesProductData)) {
foreach ($salesProductData as $k => $v) {
$salesProduct[] = $v->getId();
}
}
$viewModel->totalCount = count($salesProduct);
$viewModel->previewFalg = true;
$productListing = $salesData->getProducts();
// Preserve the product order configured on the sales campaign.
if (empty($productListing)) {
$viewModel->results = [];
$viewModel->status = false;
}else{
$viewModel->results = $productListing;
}
if($salesData->getCampaignType() == 'Lead' && $salesData->getIsPublic() != 1){
$viewModel->isVerified = 0;
}
if($salesData->getCampaignType() == 'Lead' && $salesData->getAccessCode() == ''){
$viewModel->noAccessCode = 1;
}else{
$viewModel->noAccessCode = 0;
}
} else {
$viewModel->results = [];
}
$accountManagers = GeneralHelper::myAccountManagers($customer);
$viewModel->accountManagers = $accountManagers;
$currentSite = $GLOBALS['site'];
if(!$currentSite){
if (\Pimcore\Model\Site::isSiteRequest()) {
$currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
}
$params = [];
$viewModel->type = "salescampaign";
$viewModel->mainTitle = $viewModel->salesCampaignName ?? "";
if($currentSite == "3SWebsite"){
return $this->render('@Global/default/3SWebsite/content.html.twig', $viewModel->getAllParameters());
}
else{
return $this->render('@Global/default/salesCampaignPreview.html.twig',$viewModel->getAllParameters());
}
}
/**
* @Route("/salesCampaignPdf/{salesCampaignId}")
*
* @param Request $request
* @return success or error msg
*/
public function salesCampaignPdfAction(Request $request, Factory $ecommerceFactory, $salesCampaignId)
{
$viewModel = new ViewModel();
$productServices = new ProductServices();
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$viewModel->salesCampaignId = $salesCampaignId;
$salesData = SalesCampaign::getById($salesCampaignId, ["force" => true]);
if ($salesData) {
$viewModel->salesCampaignName = $salesData->getTitle();
$viewModel->salesCampaignComment = $salesData->getShortDescription();
$viewModel->isPDF = 'yes';
$salesProduct = [];
$salesProductData = "";
$salesProductData = $salesData->getProducts();
if (!empty($salesProductData)) {
foreach ($salesProductData as $k => $v) {
$salesProduct[] = $v->getId();
}
}
$viewModel->totalCount = count($salesProduct);
$productListing = $salesData->getProducts();
/* foreach($productListing as $k=>$v) {
$sort['name'][$k] = $v->getProductName();
}
array_multisort($sort['name'], SORT_ASC,$productListing); */
if (empty($productListing)) {
$viewModel->results = [];
}else{
$viewModel->results = $productListing;
}
} else {
$viewModel->results = [];
}
$accountManagers = GeneralHelper::myAccountManagers($customer);
$currentSite = $GLOBALS['site'];
if(!$currentSite){
if (\Pimcore\Model\Site::isSiteRequest()) {
$currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
}
$params = [];
if($currentSite == "3SWebsite"){
$html = $this->renderView('@Global/default/3SWebsite/content.html.twig', array('salesId' => $viewModel->getAllParameters()['salesId'], 'results' => $viewModel->getAllParameters()['results'], 'mainTitle' => $salesData->getTitle(), 'salesCampaignComment' => $salesData->getShortDescription(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers,"type"=>"salescampaign"));
}
else{
$html = $this->renderView('@Global/default/salesCampaignPreview.html.twig',array('salesId' => $viewModel->getAllParameters()['salesId'], 'results' => $viewModel->getAllParameters()['results'], 'salesCampaignName' => $salesData->getTitle(), 'salesCampaignComment' => $salesData->getShortDescription(),'totalCount' => $totalCount, 'accountManagers'=>$accountManagers));
}
$fileName = 'SalesCampaign-' . $salesCampaignId . '.pdf';
$headerCatalogName = urlencode($salesData->getTitle());
$adapter = \Pimcore\Web2Print\Processor::getInstance();
$adapterString = "--print-media-type --page-size A4 --orientation landscape --margin-left 0mm --margin-right 0mm --margin-top 1cm --margin-bottom 1cm --header-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-header/{$currentSite}/?headerName='".( $headerCatalogName ?? '')."' --footer-html ".\Pimcore\Tool::getHostUrl()."/global-pdf-footer/{$currentSite}/";
$adapter->setOptions($adapterString);
return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
}
/**
* @Route("/loadSubCategory" , name="loadSubCategory")
*
* @param Request $request
* @return success or error msg
*/
public function loadSubCategory(Request $request, Factory $ecommerceFactory)
{
$category = $request->get('category');
$attr = $category.'SubTypes';
$object = new Customer();
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$customerData = $customer->getClass()->getFieldDefinition($attr);
$getSubcategory = $customerData->getChilds()[0]->getOptions();
$subcatArray = [];
foreach($getSubcategory as $subcat){
$subcatArray[$subcat['value']] = $subcat['key'];
}
return new Response(json_encode(array("status" => "success", 'code' => "200", "message" => "subcategory fetched successfully",'subcategoryArray'=>$subcatArray)));
}
/**
* @Route("/addDocuments")
*
* @param Request $request
* @return success or error msg
*/
function addDocumentsFunction(Request $request)
{
$userId = $request->get("userId");
$docCategory = $request->get("documentCategory");
$docSubcategory = $request->get("documentSubCategory");
$currentSite = $GLOBALS['site'] ?? (\Pimcore\Model\Site::isSiteRequest() ? \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey() : null);
$businessUnit = ($currentSite == "NuFind") ? "NuFind" : "3S";
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
if($userId){
$customerData = Customer::getById($userId, ["force" => true]);
}else{
$customerData = Customer::getById($customer->getId(), ["force" => true]);
}
if ($customerData) {
$attrKey = 'get'.ucfirst($docCategory).'SubTypesDocuments';
$getDocCategory = $customerData->$attrKey();
$setSubCategory = 'set'.ucfirst($docCategory);
$docCollection = ucfirst($docCategory.'SubTypesDocuments');
$setDocument = 'set'.$docCollection;
$message = "Error";
$code = "400";
try{
$bannerImage = $request->files->get('files');
if (!empty($bannerImage)) {
$campaignBannerImages = [];
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
$path = '/Documents/'.$docCategory."/".$docSubcategory."/".$userId;
$folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);
$newAsset = new \Pimcore\Model\Asset();
$filename = \Pimcore\Model\Element\Service::getValidKey($bannerImage[$i]->getClientOriginalName(), 'asset');
$filename = $this->getSafeFilename($folder->getRealFullPath(), $filename);
$newAsset->setFilename($filename);
$newAsset->setData(file_get_contents($bannerImage[$i]));
$newAsset->setParentId($folder->getId());
if ($newAsset->save()) {
if(!empty($newAsset)){
$campaignBannerImages[] = $newAsset;
}
}
}
}
$existingDocumentCollectionObj = $getDocCategory ?: new DataObject\Fieldcollection();
$collectionName = 'Pimcore\\Model\\DataObject\\Fieldcollection\\Data\\' . $docCollection;
$documentCollection = new $collectionName();
$documentCollection->$setSubCategory($docSubcategory);
$documentCollection->setAttachments($campaignBannerImages);
$documentCollection->setBusinessUnit($businessUnit);
$existingDocumentCollectionObj->add($documentCollection);
$customerData->$setDocument($existingDocumentCollectionObj);
$customerData->save();
$code = "200";
$customerId = $customer->getId();
$message = 'Documents submitted successfully';
}
catch(\Exception $e){
$message = ["message"=>$e->getMessage()];
$code = "400";
}
return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message)));
}
else {
return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => ["message"=>"Error"])));
}
}
protected function getSafeFilename($targetPath, $filename)
{
$pathinfo = pathinfo($filename);
$originalFilename = $pathinfo['filename'];
$originalFileextension = empty($pathinfo['extension']) ? '' : '.' . $pathinfo['extension'];
$count = 1;
if ($targetPath == '/') {
$targetPath = '';
}
while (true) {
if (Asset\Service::pathExists($targetPath . '/' . $filename)) {
$filename = $originalFilename . '_v' . $count . $originalFileextension;
$count++;
} else {
return $filename;
}
}
}
/**
* @Route("/loadDocData" , name="loadDocData")
*
* @param Request $request
* @return success or error msg
*/
function loadDocData(Request $request)
{
$docId = $request->get("docId");
$flag = $request->get("flag");
$document = Asset::getById($docId);
$versionsArray = [];
if($document) {
if($flag == 'documentVersion'){
$versions = $document->getVersions();
$versions = \Pimcore\Model\Element\Service::getSafeVersionInfo($versions);
$versions = array_reverse($versions); //reverse array to sort by ID DESC
foreach($versions as $versionObj){
$var = \Pimcore\Model\Version::getById($versionObj['id']);
$asset = $var->loadData();
$fileId = $var->getId();
$fileDate = date('d/m/y', $var->getDate());
$fileName = $var->getData()->getFilename();
$path = PIMCORE_CDN_BASEURL.'/assets/'.$fileName;
$fileSize = $asset->getFileSize(true);
// $modifiedUser = $var->getData()->getUser()->getFirstname();
// $modifyDate = $var->getData()->getModificationDate();
$versionsArray[] = array('id'=>$fileId,'date'=>$fileDate,'filename' => $fileName,'path' => $asset->getId(), 'fileSize'=> $fileSize);
}
}else{
$listing = new Note\Listing();
$listing->setCondition('cid LIKE '.$docId);
$listing->load();
$notes = $listing->getNotes();
if(!empty($notes)){
$comment = $notes[0]->getDescription();
}else{
$comment = '';
}
}
}
return new Response(json_encode(array("status" => "success", 'code' => '400', "comment" => $comment,'versions' => $versionsArray)));
}
/**
* @Route("/documentOprations" , name="documentOprations")
*
* @param Request $request
* @return success or error msg
*/
function documentOprations(Request $request)
{
$docId = $request->get("docId");
$flag = $request->get("flag");
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$document = Asset::getById($docId);
$files = $request->files->get('files');
$comment = $request->get('commentValue');
if($document) {
if($flag == 'delete'){
$document->delete();
$message = 'Document deleted successfully';
}elseif($flag == 'update' && !empty($files)){
$document->setData(file_get_contents($files[0]));
$document->save();
$message = 'Document updated successfully';
}elseif($flag == 'comment'){
$listing = new Note\Listing();
$listing->setCondition('cid LIKE '.$docId);
$listing->load();
$notes = $listing->getNotes();
if(!empty($notes)){
$notes[0]->setDescription($comment);
$notes[0]->setUser($customer);
$notes[0]->save();
}else{
$note = new \Pimcore\Model\Element\Note();
$note->setElement($document);
$note->setDate(time());
$note->setType("content");
$note->setTitle("Document comment");
$note->setDescription($comment);
$note->setUser($customer);
$note->save();
}
$commentBuyerAccounts = $request->get('commentBuyerAccounts') ?? [];
//SEND AN EMAIL
if(count($commentBuyerAccounts) > 0){
$bodyParams = array('commentDocument' => $comment, 'documentName'=>$document->getFilename());
$mail = new \Pimcore\Mail();
$mail->setIgnoreDebugMode(true);
$mail->setDocument(\Pimcore\Model\Document::getByPath('/'.EMAILDOCUMENT_PATH.'/Emails/Documents/DocumentReviewComments'));
$mail->addTo($commentBuyerAccounts);
$mail->setParams($bodyParams);
$mail->setSubject("Document - Review Comments");
/*try{
$currentSite = $GLOBALS['site'];
if(!$currentSite){
if (\Pimcore\Model\Site::isSiteRequest()) {
$currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
}
$siteConfig = DataObject\SiteConfig::getByPath('/Master/SiteConfig/'.$currentSite);
if($siteConfig){
$mail->addFrom($siteConfig->getFromEmail(), $siteConfig->getFromName());
}
}
catch(\Exception $e){
}*/
$mail->send();
}
// $note->setUser($customer);
$message = 'Document comment submitted successfully';
}
}
return new Response(json_encode(array("status" => "success", 'code' => '400', "message" => $message)));
}
/**
* @Route("/get_file_by_versionId" , name="getDocumentByVersionId")
*
* @param Request $request
* @return success or error msg
*/
function getFileByVersionId(Request $request)
{
// $id = intval($request->get('versionId'));
// $version = \Pimcore\Model\Version::getById($id);
// if (!$version) {
// throw $this->createNotFoundException('Version not found');
// }
// $asset = $version->loadData();
// $assetTemplate = $this->render(
// 'PimcoreAdminBundle:Admin/Asset:showVersion' . ucfirst($asset->getType()) . '.html.php',
// ['asset' => $asset]
// );
// $thumbnail = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/image-version-preview-" . uniqid() . ".webp";
// $convert = \Pimcore\Image::getInstance();
// $tempFile = $asset->getTemporaryFile();
// $convert->load($tempFile);
// $convert->save($thumbnail, "webp");
//$dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
// unlink($thumbnail);
// unlink($tempFile);
$id = intval($request->get('versionId'));
$version = \Pimcore\Model\Version::getById($id);
$dataUri = "";
if($version){
$asset = $version->loadData();
$fileMIMEType = $asset->getMimetype();
$dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
}
return new Response(json_encode(array("status" => "success", 'code' => '200', "dataUri" => $dataUri)));
}
/**
* @Route("/view_file_by_versionId" , name="viewDocumentByVersionId")
*
* @param Request $request
* @return success or error msg
*/
function viewFileByVersionId(Request $request)
{
$id = intval($request->get('versionId'));
$version = \Pimcore\Model\Version::getById($id);
$dataUri = "";
if($version){
$asset = $version->loadData();
$fileMIMEType = $asset->getMimetype();
$dataUri = "data:".$fileMIMEType.";base64," . base64_encode($asset->getData());
}
return new Response(
'<html><body><img src="'.$dataUri.'"/></body></html>'
);
}
/**
* Description:- Load view of email tempalte page
*
* @Route("/email-check", name="email_template_test_global")
* @param Request $request
*
* @return mixed
*/
public function emailCheckAction(Request $request, AuthenticationUtils $authenticationUtils, UserInterface $user = null)
{
$paramsCustomerWelcome = array('customerName'=>"TEST");
$mail = new \Pimcore\Mail();
$mail->setIgnoreDebugMode(true);
$mail->setDocument(\Pimcore\Model\Document::getByPath('/'.EMAILDOCUMENT_PATH.'/Emails/Customer/CustomerSignupWelcome'));
$mail->addTo('test@yopmail.com');
$mail->setParams($paramsCustomerWelcome);
$mail->setSubject("Document - Review Comments");
$originalEmailSubject = $mail->getSubjectRendered();
if($GLOBALS['site'] == "3SWebsite"){
$originalEmailSubject = str_replace("Nu Find","3s Global",$originalEmailSubject);
$originalEmailSubject = str_replace("NuFind","3sGlobal",$originalEmailSubject);
}
echo $mail->getBodyHtmlRendered();
exit;
}
/**
* Description:- Admin QR Code PDF Generate
*
* @Route("/global/generate-qrcode-pdf" , name="admin-custom-pdf");
* @param Request $request
*
*/
public function QRPDFGenerateAction(Request $request, Factory $ecommerceFactory)
{
$supplierId = $request->get("supplierId");
$productsIds = $request->get("productsIds");
$perPage = $request->get("perPage");
$supplierPath = '/Supplier/'.$supplierId;
$supplierObj = DataObject\SupplierCompany::getByPath($supplierPath,1);
if(!$supplierObj){
echo "Unable to find supplier";
exit;
}
else{
$supplierProductPath= '/Product/'.$supplierId;
$folder = \Pimcore\Model\DataObject\Service::createFolderByPath($supplierProductPath);
$errorProducts = [];
$productsObjs = [];
if (empty($supplierObj)) {
$errorProducts[] = "There is some issue with supplier";
} else {
$prodIds = json_decode($productsIds);
if($prodIds){
$prodIds = array_values($prodIds);
foreach($prodIds as $productId){
try{
$productObj = DataObject::getById($productId);
$productsObjs[] = $productObj;
}
catch(\Exception $e){
$errorProducts[] = $e->getMessage();
}
}
}
else{
echo "No products available for <b>".$supplierId."</b> supplier";
exit;
}
}
}
$params = [];
$currentSite = $GLOBALS['site'] ?? null;
if (!$currentSite && \Pimcore\Model\Site::isSiteRequest()) {
$currentSite = \Pimcore\Model\Site::getCurrentSite()->getRootDocument()->getKey();
}
$templatePath = '@Global/' . ($currentSite == "3SWebsite" ? 'default/3SWebsite' : 'product') . '/QRCode.html.twig';
$html = $this->renderView($templatePath, ["productsObjs" => $productsObjs, "perPage" => $perPage,'isShowPrice' => true]);
$fileName = 'Product-QRCode-' . $supplierId . '.pdf';
$adapter = \Pimcore\Web2Print\Processor::getInstance();
$adapter->setOptions("--print-media-type --page-size A4 --orientation portrait --margin-left 0.2cm --margin-right 0.15cm --margin-top 0.5cm --margin-bottom 0.5cm");
// return new \Symfony\Component\HttpFoundation\Response(
// $adapter->getPdfFromString($html),
// 200,
// array(
// 'Content-Type' => 'application/pdf',
// )
// );
return new \Symfony\Component\HttpFoundation\Response($adapter->getPdfFromString($html, $params), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename=' . $fileName)); //direct download
}
/**
* Description:- Admin PDF HEADER Generate
*
* @Route("/global-pdf-header/{currentSite}" , name="admin-custom-pdf-header-line");
* @param Request $request
*
*/
public function headerPDFAction(Request $request, $currentSite="")
{
$viewModel = new ViewModel();
$headerName = $request->get('headerName');
$viewModel->headerName = $headerName;
$viewModel->currentSite = $currentSite;
if($currentSite != "NuFind"){
return $this->render('@Global/default/3SWebsite/header.html.twig',$viewModel->getAllParameters());
}
else{
return $this->render('@Global/default/pdf/header.html.twig',$viewModel->getAllParameters());
}
}
/**
* Description:- Admin PDF HEADER Generate
*
* @Route("/global-pdf-footer/{currentSite}" , name="admin-custom-pdf-footer-line");
* @param Request $request
*
*/
public function footerPDFAction($currentSite="")
{
$viewModel = new ViewModel();
$viewModel->currentSite = $currentSite;
if($currentSite == "3SWebsite"){
return $this->render('@Global/default/3SWebsite/footer.html.twig',$viewModel->getAllParameters());
}
else{
return $this->render('@Global/default/pdf/footer.html.twig',$viewModel->getAllParameters());
}
}
public function getOptionValues($class){
$tempClass = $class;
$class = ($class == "Supplier") ? "Company" : $class;
$objectStr = 'Pimcore\\Model\\DataObject\\'.ucfirst($class).'\\Listing';
$object = new $objectStr();
$optionName = [];
$loadObjectData = $object->load();
if(!empty($loadObjectData)){
foreach($loadObjectData as $catFieldObj){
if($tempClass == "Wishlist"){
if($catFieldObj->getCustomer()){
$optionName[$catFieldObj->getId()] = ($catFieldObj->getCustomer()->getEmail()." - " ?? "").$catFieldObj->getLable();
}
}
else if($tempClass == "Customer"){
$optionName[$catFieldObj->getId()] = ($catFieldObj->getEmail())." - ".$catFieldObj->getFirstname()." ".$catFieldObj->getLastname();
}
else if($tempClass == "Supplier"){
if (str_contains($catFieldObj->getParent()->getPath(), 'supplier')) {
$optionName[$catFieldObj->getId()] = $catFieldObj->getName();
}
}
else{
$optionName[$catFieldObj->getId()] = $catFieldObj->getName();
}
}
}
return $optionName;
}
/**
* @Route("/updateCampaign")
*
* @param Request $request
* @return success or error msg
*/
function updateCampaignFunction(Request $request)
{
$salesCampaignId = $request->get("salesCampaignId");
$salesCampaignName = $request->get("salesCampaignName") ?? "";
$salesCampaignSubTitle = $request->get("salesCampaignSubTitle") ?? "";
$salesCampaignIsPublic = ($request->get("salesCampaignFor") == "true") ? true : false;
$salesCampaignAccessCode = $request->get("salesCampaignAccessCode");
$salesCampaignDescription = $request->get("salesCampaignDescription") ?? "";
$salesCampaignWishlist = $request->get("salesCampaignWishlist") ?? "";
$salesCampaignExclusiveSupplier = $request->get("salesCampaignExclusiveSupplier") ?? "";
$isActive = ($request->get("isActive") == "true") ? true : false;
$salesCampaignSubmitMode = $request->get("wishSubmitMode") ?? "";
$catalogOwners = $request->get("wishCatalogOwners");
$salesCampaignData = SalesCampaign::getById($salesCampaignId, ["force" => true]);
if ($salesCampaignData) {
$message = "Error";
$code = "400";
try{
//WISHLIST TO GET ALL PRODUCTS
if($salesCampaignWishlist){
$catalogWishlistsArray = explode(",", $salesCampaignWishlist);
$catalogProductArray = [];
foreach($catalogWishlistsArray as $wishlistId){
$wishlistData = DataObject\Wishlist::getById($wishlistId);
$catalogProduct = $wishlistData->getProducts();
foreach ($catalogProduct as $ks => $vs) {
$catalogProductArray[$vs->getId()] = $vs;
}
}
$salesCampaignData->setProducts($catalogProductArray);
$salesCampaignData->setWishlist($catalogWishlistsArray);
}
$salesCampaignData->setIsPublic($salesCampaignIsPublic);
$salesCampaignData->setAccessCode($salesCampaignAccessCode);
$salesCampaignData->setTitle($salesCampaignName);
$salesCampaignData->setSubTitle($salesCampaignSubTitle);
$salesCampaignData->setDescription($salesCampaignDescription);
$exclusiveTheseSuppliers = [];
if($salesCampaignExclusiveSupplier){
$catalogExclusiveSupplierArray = explode(",", $salesCampaignExclusiveSupplier);
foreach($catalogExclusiveSupplierArray as $companyId){
$companyObject = DataObject\Company::getById($companyId);
$exclusiveTheseSuppliers[] = $companyObject;
}
}
if(count($exclusiveTheseSuppliers) > 0){
$salesCampaignData->setExclusiveToTheseSupplier($exclusiveTheseSuppliers);
}
// $mainImage = $request->files->get('files');
// if (!empty($mainImage)) {
// for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
// $path = '/_default_upload_bucket/';
// $folder = Service::createFolderByPath($path);
// $newAsset = new \Pimcore\Model\Asset();
// $newAsset->setFilename(time() . "-" . $mainImage[$i]->getClientOriginalName());
// $newAsset->setData(file_get_contents($mainImage[$i]));
// $newAsset->setParentId($folder->getId());
// if ($newAsset->save()) {
// $assetArray[] = $newAsset;
// $catalogData->setImage($newAsset);
// }
// }
// }
$bannerImage = $request->files->get('filesBanner');
if (!empty($bannerImage)) {
$campaignBannerImages = [];
$bannerImages = $salesCampaignData->getBannerImage();
if(!empty($bannerImages->getItems())){
foreach($bannerImages->getItems() as $attKey=>$attVal){
if($attVal)
{
$advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
$advancedImage->setImage($attVal->getImage());
$campaignBannerImages[] = $advancedImage;
}
}
}
for ($i = 0; $i < count($_FILES['filesBanner']['name']); $i++) {
$path = '/_default_upload_bucket/';
$folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);
$newAsset = new \Pimcore\Model\Asset();
$newAsset->setFilename(time() . "-Banner-" . $bannerImage[$i]->getClientOriginalName());
$newAsset->setData(file_get_contents($bannerImage[$i]));
$newAsset->setParentId($folder->getId());
if ($newAsset->save()) {
if(!empty($newAsset)){
$advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
$advancedImage->setImage($newAsset);
$campaignBannerImages[] = $advancedImage;
}
}
}
$salesCampaignData->setBannerImage(new \Pimcore\Model\DataObject\Data\ImageGallery($campaignBannerImages));
}
$bannerImageMobile = $request->files->get('files');
if (!empty($bannerImageMobile)) {
$campaignBannerMobileImages = [];
$bannerImagesMobile = $salesCampaignData->getBannerImageMobile();
if(!empty($bannerImagesMobile->getItems())){
foreach($bannerImagesMobile->getItems() as $attKey=>$attVal){
if($attVal)
{
$advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
$advancedImage->setImage($attVal->getImage());
$campaignBannerMobileImages[] = $advancedImage;
}
}
}
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
$path = '/_default_upload_bucket/';
$folder = \Pimcore\Model\Asset\Service::createFolderByPath($path);
$newAsset = new \Pimcore\Model\Asset();
$newAsset->setFilename(time() . "-Banner-Mobile-" . $bannerImageMobile[$i]->getClientOriginalName());
$newAsset->setData(file_get_contents($bannerImageMobile[$i]));
$newAsset->setParentId($folder->getId());
if ($newAsset->save()) {
if(!empty($newAsset)){
$advancedImage = new \Pimcore\Model\DataObject\Data\Hotspotimage();
$advancedImage->setImage($newAsset);
$campaignBannerMobileImages[] = $advancedImage;
}
}
}
$salesCampaignData->setBannerImageMobile(new \Pimcore\Model\DataObject\Data\ImageGallery($campaignBannerMobileImages));
}
if($catalogOwners){
$campaignExclusiveOwnersArray = explode(",", $catalogOwners);
foreach($campaignExclusiveOwnersArray as $customerId){
$customerObject = DataObject\Customer::getById($customerId);
$exclusiveCatalogOwners[] = $customerObject;
}
}
if(count($exclusiveCatalogOwners) > 0){
$salesCampaignData->setCampaignOwner($exclusiveCatalogOwners);
}
$salesCampaignData->setIsActive((bool)$isActive);
$salesCampaignData->save();
$code = "200";
$customer = $_SESSION['_pimcore_admin']['customer'] ?? null;
$customerId = $customer->getId();
$message = ["message"=>"Campaign updated successfully","objectId"=>$salesCampaignData->getId(), "customerId"=>$customerId];
}
catch(\Exception $e){
$message = ["message"=>$e->getMessage()];
$code = "400";
}
return new Response(json_encode(array("status" => "success", 'code' => $code, "message" => $message)));
}
else {
return new Response(json_encode(array("status" => "success", 'code' => "400", "message" => ["message"=>"Error"])));
}
}
/**
* @Route("/deleteSalesCampaignMedia", name="delete-salescampaign-media")
*
* @param Request $request
*/
public function deleteSalesCampaignMedia(Request $request)
{
$document = $request->get('fileData');
$salesCampaignId = $request->get('salesCampaignId');
$fieldType = $request->get('fieldType');
$error = [];
$salesCampaignResult = [];
$salesCampaignData = SalesCampaign::getById($salesCampaignId, ["force" => true]);
if ($salesCampaignData) {
try{
if($fieldType == "bannerImage"){
$bannerImagesArray = [];
$bannerImages = $salesCampaignData->getBannerImage();
if(!empty($bannerImages->getItems())){
foreach($bannerImages->getItems() as $attKey=>$attVal){
if($attVal)
{
if($document == $attVal->getImage()->getId()){
$attVal->getImage()->delete();
}else{
$bannerImagesArray[] = $attVal->getImage();
}
}
}
$salesCampaignData->setBannerImage(new \Pimcore\Model\DataObject\Data\ImageGallery($bannerImagesArray));
}
}
if($fieldType == "bannerImageMobile"){
$bannerImagesMobileArray = [];
$bannerImagesMobile = $salesCampaignData->getBannerImageMobile();
if(!empty($bannerImagesMobile->getItems())){
foreach($bannerImagesMobile->getItems() as $attKey=>$attVal){
if($attVal)
{
if($document == $attVal->getImage()->getId()){
$attVal->getImage()->delete();
}else{
$bannerImagesMobileArray[] = $attVal->getImage();
}
}
}
$salesCampaignData->setBannerImageMobile(new \Pimcore\Model\DataObject\Data\ImageGallery($bannerImagesMobileArray));
}
}
}
catch(\Exception $e){
$error[] = $e->getMessage();
}
}
else{
$error[] = 'Sales campaign not available.';
}
if(count($error) > 0){
$salesCampaignResult = ["success" => false, "msg" => implode(",", $error)];
}else{
$salesCampaignResult = ["success" => true, "msg" => 'Sales Campaign update successfully.'];
}
return $this->json($salesCampaignResult);
}
/**
* @Route("/download-image-frontendthumbnail", name="download_image_frontend_thumbnail")
*
* @param Request $request
*
* @return BinaryFileResponse
*/
public function downloadImageThumbnailAction(Request $request)
{
try {
$asset = \Pimcore\Model\Asset::getById($request->get('id'));
if ($asset instanceof \Pimcore\Model\Asset\Image) {
$originalPath = $asset->getLocalFile();
$configJson = $request->get('config');
$config = json_decode($configJson, true);
$thumbnailConfig = new Asset\Image\Thumbnail\Config();
$thumbnailConfig->setName('pimcore-download-' . $asset->getId() . '-' . md5($request->get('config')));
if ($config['resize_mode'] == 'scaleByWidth') {
$thumbnailConfig->addItem('scaleByWidth', [
'width' => $config['width'],
]);
} elseif ($config['resize_mode'] == 'scaleByHeight') {
$thumbnailConfig->addItem('scaleByHeight', [
'height' => $config['height'],
]);
} else {
$thumbnailConfig->addItem('resize', [
'width' => $config['width'],
'height' => $config['height'],
]);
}
$thumbnailConfig->setQuality($config['quality']);
$thumbnailConfig->setFormat($config['format']);
$thumbnail = $asset->getThumbnail($thumbnailConfig);
$thumbnailFile = $thumbnail->getLocalFile();
$downloadFilename = preg_replace(
'/\.' . preg_quote(File::getFileExtension($asset->getFileName())) . '$/i',
'.' . $thumbnail->getFileExtension(),
$asset->getFilename()
);
$thumbnailFile = str_replace('.svg', '.png', $thumbnailFile);
$downloadUrl = $thumbnail->getFrontendPath();
$response = new BinaryFileResponse($thumbnailFile);
$response->headers->set('Content-Type', $thumbnail->getMimeType());
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,$downloadFilename);
}
$result = ["success" => true,'downloadFile' => $thumbnailFile,'downloadFileName'=> $downloadFilename,"imageUrl" => $downloadUrl];
return new Response(json_encode($result));
}
catch (\Exception $e) {
return new Response(json_encode(["success" => false, "message" => "Thumbnail not found"]));
}
}
/**
* @Route("/download-image-popup", name="download_image_popup")
*
* @param Request $request
*
* @return BinaryFileResponse
*/
public function downloadImagePopupAction(Request $request)
{
try {
$downloadFile = $request->get('downloadFile');
$downloadFileName = $request->get('downloadFileName');
$response = new BinaryFileResponse($downloadFile);
$response->headers->set('Content-Type', "image/png");
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,$downloadFileName);
return $response;
}
catch (\Exception $e) {
$this->addFlash('error', 'Thumbnail not found');
}
return $this->redirect($request->headers->get('referer'));
}
}