<?php
namespace App\project\OfficeBrain\CustomBundle\ProductBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use App\OfficeBrain\Bundle\ProductBundle\Controller\ProductController as BaseProductController;
use Symfony\Component\HttpFoundation\Response;
use DateTime;
use App\OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Aws\S3\S3Client;
use Aws\Credentials\Credentials as Credentials;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use App\OfficeBrain\Bundle\ProductBundle\Manager\Service\ProductAdminManager;
use App\OfficeBrain\Bundle\EmailBundle\Manager\Service\EmailService;
use App\OfficeBrain\Bundle\ProductTagBundle\Manager\Service\ProductTagManager;
use App\project\OfficeBrain\CustomBundle\ProductBundle\Manager\Service\ProductDetailService as CustomProductDetailService;
use App\OfficeBrain\Bundle\ProductBundle\Manager\Service\ProductDetailService;
use App\OfficeBrain\Bundle\SearchBundle\Manager\Service\SearchManager;
use App\OfficeBrain\Bundle\SolrBundle\Manager\Service\SolrService;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
*
* @author Employee Id: 4464
*
* To create custom code
*
* @return NULL
*
* @Route("/{_locale}")
*/
class ProductController extends BaseProductController
{
/**
*
* @author Employee Id: 4464
*
* To set member variables default value
*
* @return NULL
*
*/
public function __construct(Container $serviceContainer, SearchManager $searchManager, CustomProductDetailService $customProductDetailService, EmailService $emailService, ProductAdminManager $productAdminManager, SolrService $solrService, RouterInterface $router, ValidatorInterface $validator, RequestStack $requestStack, ProductTagManager $productTagManager, ProductDetailService $productDetailService)
{
parent::__construct($serviceContainer, $searchManager, $productDetailService, $emailService, $productAdminManager, $solrService, $router, $validator, $requestStack);
$this->statsh_cache_wrapper = RedisCacheService::create();
$this->moduleCachePrefix = '__RelatedProducts__';
$this->wasabiCredentials = new Credentials('RXKLAMY4M3FSY3XXR2AW', 'Xh9z0rX7EFPLrBlcpM5ec5DpJ3rRndwGz93K8w4O');
$this->s3Client = new S3Client([
'endpoint' => 'http://s3.us-west-1.wasabisys.com',
'region' => 'us-west-1',
'version' => 'latest',
'credentials' => $this->wasabiCredentials
]);
$this->productApiManager = $productAdminManager;
$this->productDetailManager = $customProductDetailService->getProductApiExtended(); //
$this->productTagManager = $productTagManager->getProductTagManagerExtended(); // symfony 4
$this->emailService = $emailService->getEmailExtended();
$this->wasabiBucket = 'ob-aakronftp';
}
/**
*
* @author Employee Id: 4464
*
* To unseset member variables
*
* @return NULL
*/
public function __destruct()
{
parent::__destruct();
}
/**
*
* @author Employee Id: 4464
*
* To Initialize the member variables
*
* @return NULL
*/
public function initAction(Request $request)
{
parent::initAction($request);
// $this->productDetailManager = $this->serviceContainer->get('office_brain_product_detail_manager_custom'); // project\OfficeBrain\CustomBundle\ProductBundle\Manager\Extended\ProductApiExtended
$this->productDetailManager = $this->productDetailManager; // project\OfficeBrain\CustomBundle\ProductBundle\Manager\Extended\ProductApiExtended
// $this->productApiManager = $this->serviceContainer->get("office_brain_product_admin_manager");
$this->productApiManager = $this->productApiManager;
// $this->productTagManager = $this->serviceContainer->get('office_brain_product_tag_manager'); // symfony 4
$this->productTagManager = $this->productTagManager; // symfony 4
// $this->productTagManager = $this->get('office_brain_private_tag_extended');
$this->categoryApi = $this->serviceContainer->get("officebrain_category_api");
$this->userId = $this->projectSetting['user_id'];
// $this->emailService = $this->serviceContainer->get('office_brain_email_service');
$this->emailService = $this->emailService;
$this->languageId = $this->projectSetting['culture_id'];
}
/**
*
* @author Employee Id: 4464
*
* Product Detail data.
*
* @param
* string product slug
*
* @return product detail information
*
* @Route("/similar-sku/{productSku}",name="officebrain_product_bundle_similarproductsku", methods={"GET"})
*
* @Template()
*
*/
public function similarProductSkuAction(Request $request)
{
$this->initAction($request);
$this->responseArray['similarSkuProducts'] = null;
$productSku = $orgProductSKU = $this->request->get('productSku', null);
$productSku = explode('-', $productSku);
if (is_array($productSku)) {
if (count($productSku) > 1) {
// PATCH: For SKUs with closeout. Eg. 1234-Closeout
if (strtolower($productSku[1]) == 'closeout') {
unset($productSku[1]);
} else {
// unset($productSku[0]);
$productSku = (array) $productSku[count($productSku) - 1];
}
}
$productSku = implode('-', $productSku);
$similarSkuProducts = $this->productDetailManager->getSimilarSku($productSku);
$this->responseArray['productSku'] = $orgProductSKU;
$this->responseArray['similarSkuProducts'] = $similarSkuProducts['search_result_array']['data'];
}
return $this->responseArray;
}
/**
*
* @author Employee Id: 5460
*
* @param
* product_id.
*
* @return Response
*
* @Route("/general-conformity-certificate/{product_sku}",
* name="officebrain_custombundle_productbundle_productdetail_gcc", options={"expose"=true}
* )
*
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/generalConformityCertificate.html.twig")
*/
public function generalConformityCertificateAction(Request $request, $product_sku)
{
/*$resp = $this->s3Client->listObjects([
'Bucket' => $this->wasabiBucket,
'Range' => 'bytes=0-9',
]);
echo "Succeed in retrieving bucket ACL as follows: \n";
echo "<pre>";print_r($resp->get('Contents'));
//$search = 'Chem_Tests/'.$product_sku.'*'
//print_r( array_key_exists_wildcard( $array, $search ) );
die;
*/
$this->initAction($request);
$this->responseArray['gccData'] = $this->productDetailManager->getProductgeneralConformityCertificate($product_sku);
$this->responseArray['gccData'] = $this->productDetailManager->updateColorTestResultURLs($this->responseArray['gccData'],$this->s3Client);
// print_r($this->responseArray['gccData']);die;
$this->responseArray['productSku'] = $product_sku;
return $this->responseArray;
}
/**
*
* @author Employee Id: 5460
*
* Desciption: print detail of general conformity certificate
*
* @param
* product_id.
*
* @return Response
*
* @Route("/general-conformity-certificate-print/{product_sku}",
* name="officebrain_custombundle_productbundle_productdetail_gcc_print"
* )
*
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/generalConformityCertificatePrint.html.twig")
*/
public function generalConformityCertificatePrintAction(Request $request, $product_sku)
{
$this->initAction($request);
$this->responseArray['gccData'] = $this->productDetailManager->getProductGeneralConformityCertificate($product_sku);
$this->responseArray['productSku'] = $product_sku;
return $this->responseArray;
}
/**
*
* @author Employee Id: 5460
*
* Desciption: download pdf of general conformity certificate
*
* @param
* product_id.
*
* @return Response
*
* @Route("/general-conformity-certificate-pdf/{product_sku}",
* name="officebrain_custombundle_productbundle_productdetail_gcc_pdf"
* )
*/
public function generalConformityCertificatePdfAction(Request $request, $product_sku)
{
$response_array = $this->generalConformityCertificatePrintAction($product_sku);
$response = $this->render('OfficeBrainCustomBundleProductBundle:Product:generalConformityCertificatePrint.html.twig', $response_array);
return new Response($this->get('knp_snappy.pdf')->getOutputFromHtml($response->getContent()), 200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $product_sku . '-gcc.pdf"'
));
}
/**
*
* @author Employee Id: 5460
*
* Desciption: download pdf of general conformity certificate test result
*
* @param
* product_id.
*
* @return Response
*
* @Route("/general-conformity-certificate-test-result-pdf/{test_report_file_name}",
* name="officebrain_custombundle_productbundle_productdetail_gcc_test_result_pdf"
* )
*/
public function downloadTestResultPdfAction(Request $request, $test_report_file_name)
{
try {
// $resp = $this->s3Client->listObjects([
// 'Bucket' => $this->wasabiBucket,
// 'key' => "Chem_Tests/01300-30619 Blue PO#47740.pdf",
// 'Range' => 'bytes=0-9',
// ]);
$resp = $this->s3Client->getObject([
'Bucket' => $this->wasabiBucket,
'Key' => 'Chem_Tests/'.$test_report_file_name,
]);
// echo "Succeed in retrieving bucket ACL as follows: \n";exit;
// echo "<pre>";print_r($resp['Body']);exit;
return new Response($resp['Body'], 200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment;'
));
// header("Content-Type: {$result['ContentType']}");
// echo $result['Body'];
} catch (\Exception $e) {
// die('error');
// output error message if fails
return new JsonResponse($e->getMessage());
}
// $downloadTestResultBaseUrl = $this->container->getParameter('download_test_result.base_url');
// $downloadTestResultPDFUrl = $downloadTestResultBaseUrl . "/" . $test_report_file_name;
// return new Response(file_get_contents($downloadTestResultPDFUrl), 200, array(
// 'Content-Type' => 'application/pdf',
// 'Content-Disposition' => 'attachment;'
// ));
}
/**
* @Route("/product/estimator",
* name="officebrain_product_bundle_product_detail_estimator", methods={"GET"}
* )
*
* @Template("OfficeBrain/Bundle/ProductBundle/Product/productDetailEstimator.html.twig")
*
*/
public function productDetailEstimatorAction(Request $request)
{
$this->initAction($request);
$sku = $this->request->get('sku_number', null);
return array('sku_number' => $sku);
}
/**
*
* @author Employee Id: 4532
*
* Product Detail data.
*
* @param
* string product slug
*
* @return product detail information
*
* @Route("/product/{productSlug}",
* name="officebrain_product_bundle_product_detail",
* defaults={"main_image_url"=null}, methods={"GET"}
* )
*
* @Template("OfficeBrain/Bundle/ProductBundle/Product/productDetail.html.twig")
*
*/
public function productDetailAction(Request $request, $productSlug)
{
// $credentials = new Aws\Credentials\Credentials('RXKLAMY4M3FSY3XXR2AW', 'Xh9z0rX7EFPLrBlcpM5ec5DpJ3rRndwGz93K8w4O');
// $s3Client = new S3Client([
// 'endpoint' => 'http://s3.us-west-1.wasabisys.com',
// 'region' => 'us-west-1',
// 'version' => 'latest',
// 'credentials' => $credentials
// ]);
// $bucket = 'ob-aakronftp';
// try {
// $resp = $s3Client->listObjects([
// 'Bucket' => $bucket,
// 'Range' => 'bytes=0-9',
// ]);
// /* $resp = $s3Client->getObject([
// 'Bucket' => $bucket,
// 'Key' => 'Chem_Tests/# 47910 Halycon Bottle FDA.pdf'
// ]);*/
// echo "Succeed in retrieving bucket ACL as follows: \n";
// echo "<pre>";print_r($resp);
// // header("Content-Type: {$result['ContentType']}");
// // echo $result['Body'];
// } catch (AwsException $e) {
// // output error message if fails
// echo $e->getMessage();
// echo "\n";
// At start of script
//$time_start = microtime(true);
// echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);
// Anywhere else in the script
// }
$this->initAction($request);
if (is_numeric($productSlug)) {
$productDetailArrayId = $this->productDetailManager->getProductDetailById($productSlug, $this->cultureCode);
$this->responseArray = $productDetailArrayId[$productSlug];
} else {
$this->responseArray = $this->productDetailManager->getProductDetailBySlug($productSlug, $this->cultureCode);
}
if ($this->responseArray == null) {
/* if no product found Through exception */
throw $this->createNotFoundException($this->translator->trans('transaction.page_not_found.detail'));
} // elseif(($this->responseArray['basic_information']['active'] != 1 && $this->responseArray['basic_information']['active'] != true) || ($this->responseArray['is_deleted'] != 1 && $this->responseArray['is_deleted'] != false) ){
elseif (($this->responseArray['basic_information']['active'] != 1 && $this->responseArray['basic_information']['active'] != true) || ($this->responseArray['is_deleted'] != false)) {
throw $this->createNotFoundException($this->translator->trans('transaction.page_not_found.detail'));
}
/* ------------ Cache Code For Product Details Page -------------- */
$productId = $this->responseArray['product_id'];
$isUserLoggedIn = $this->userId>0?"_not_login":"_loggedin_";
$this->moduleCachePrefix = '__ProductDetailsPageOtherProducts__';
$locale = $this->request->getLocale();
$cacheSiteKey = array(
$this->moduleCachePrefix,
"product_id#" . $productId,
$locale,
$isUserLoggedIn,
$this->projectSetting['instance_id'],
// $this->container->getParameter('kernel.environment') // symfony 4
$this->projectSetting['kernelEnvironment']
);
$cacheKey = RedisCacheService::generateKey($this->statsh_cache_wrapper, $cacheSiteKey);
$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper, $cacheKey);
if ($cacheData) {
/** Update Cache data for Flyer and Image */
$productSKU = $cacheData['basic_information']['sku_number'];
$supplierId = $cacheData['supplier']['supplier_id'];
$downloadImageRelativePath = $this->serviceContainer->getParameter('product_image.zip_path');
$blankFileFullPath = $downloadImageRelativePath.$supplierId.'/blank-images/'.$productSKU.'.zip';
$cacheData['download_blank_image_status'] = file_exists($blankFileFullPath)?1:0;
$downloadPdfRelativePath = $this->serviceContainer->getParameter('product_pdf.flyer_path');
$pdfFileFullPath = $downloadPdfRelativePath.$supplierId.'/flyers/'.$productSKU.'.pdf';
$cacheData['download_flyer_status'] = file_exists($pdfFileFullPath)?1:0;
// return $cacheData;
}
/* ------------ EO: Cache Code For Product Details Page -------------- */
// feature details - made array for simply access
$featuresDetail = [];
$this->responseArray['isPackagingOpt'] = false;
$this->responseArray['isUsaConnect'] = 0;
foreach ($this->responseArray['feature_details'] as $feature) {
if($feature['label']=='Packaging Options'){
$this->responseArray['isPackagingOpt'] = true;
}
if($feature['label']=='is_usa_connect' && !empty($feature['value'])){
$this->responseArray['isUsaConnect'] = 1;
}
$featuresDetail[$feature['label']] = $feature['value'];
}
$categoryArr = array();
$categoryId = '';
if (is_array($this->responseArray['category']) && count($this->responseArray['category'])) {
foreach ($this->responseArray['category'] as $key => $value) {
if (isset($featuresDetail['Main_Category'])) {
if ($featuresDetail['Main_Category'] == $value) {
$categoryId = $key;
}
}
else {
$categoryId = $key;
}
array_push($categoryArr, $key);
}
$this->responseArray['breadcrumbs'] = $this->productDetailManager->productDetailBreadcrumbs($categoryId, $featuresDetail, $categoryArr);
}
/* Product Tag section Starts */
if ($this->productConfigurationRules['show_product_tags']['status'] == 1) {
$main_sku = explode('-', $this->responseArray['basic_information']['sku_number']);
$main_sku = $main_sku[count($main_sku) - 1];
$this->responseArray['product_tags_array'] = $this->productDetailManager->getAllTagsByProductSku($main_sku);
$tagData = $this->productTagManager->getAllTagsByProductId($this->responseArray['product_id'], $this->cultureCode);
$this->responseArray['product_tags_array'] = $tagData['private_tag'];
}
/* Product Tag section Ends */
$this->productDetailManager->recentViewProductByCookies('recent_product_cookie', $this->responseArray['product_id'], $this->cultureCode);
unset($productDetailArrayId);
/*
* Check Ob_customer id - for flyer which is visible or not
*/
/* check for Availability */
$date1 = date('Y-m-d');
if ($this->responseArray['basic_information']['valid_up_to'] != '') {
$dte = DateTime::createFromFormat('m-d-Y', $this->responseArray['basic_information']['valid_up_to']);
$date2 = $dte->format('Y-m-d');
if (strtotime($date1) > strtotime($date2)) {
// $st = 'Expired';
$st = '';
} else {
// $st = 'In-Stock';
$st = $this->responseArray['basic_information']['valid_up_to'];
}
} else {
$st = '';
}
$this->responseArray['basic_information']['valid_status'] = $st;
/* Releted Product section Starts */
$productId = $this->responseArray['product_id'];
$comproductreletedid = $this->productApiManager->productreletedid($productId);
$this->responseArray['related_product'] = count($comproductreletedid);
// if($this->userId > 0)
// {
$this->responseArray['psa_special'] = $this->productDetailManager->psaSpecialView($productId);
$this->responseArray['selling_ideas'] = $this->productDetailManager->sellingIdeasView($productId);
// }
$this->responseArray['disable_overseas_pricing'] = 0;
if (isset($this->responseArray['basic_information']['sku_number']) && ! empty($this->responseArray['basic_information']['sku_number'])) {
$disableOverseasPricingArray = $this->serviceContainer->getParameter('disable_overseas_pricing');
if (in_array($this->responseArray['basic_information']['sku_number'], $disableOverseasPricingArray)) {
$this->responseArray['disable_overseas_pricing'] = 1;
}
}
$this->responseArray['tariff_impacted_item'] = 0;
if (isset($this->responseArray['basic_information']['sku_number']) && ! empty($this->responseArray['basic_information']['sku_number'])) {
$tariffImpactesItemPricingArray = $this->serviceContainer->getParameter('tariff_impacted_item');
if (in_array($this->responseArray['basic_information']['sku_number'], $tariffImpactesItemPricingArray)) {
$this->responseArray['tariff_impacted_item'] = 1;
}
}
$this->responseArray['imprint_color_msg'] = 0;
if (isset($this->responseArray['basic_information']['sku_number']) && ! empty($this->responseArray['basic_information']['sku_number'])) {
$impintMsgArray = $this->serviceContainer->getParameter('imprint_color_msg');
if (in_array($this->responseArray['basic_information']['sku_number'], $impintMsgArray)) {
$this->responseArray['imprint_color_msg'] = 1;
}
}
$this->responseArray['virtual_hide_button_item'] = 0;
if (isset($this->responseArray['basic_information']['sku_number']) && ! empty($this->responseArray['basic_information']['sku_number'])) {
$virtualHideButtonItemArray = $this->serviceContainer->getParameter('virtual_hide_button_item');
if (in_array($this->responseArray['basic_information']['sku_number'], $virtualHideButtonItemArray)) {
$this->responseArray['virtual_hide_button_item'] = 1;
}
}
$productSKU = $this->responseArray['basic_information']['sku_number'];
$supplierId = $this->responseArray['supplier']['supplier_id'];
$downloadImageRelativePath = $this->serviceContainer->getParameter('product_image.zip_path');
$blankFileFullPath = $downloadImageRelativePath.$supplierId.'/blank-images/'.$productSKU.'.zip';
$this->responseArray['download_blank_image_status'] = file_exists($blankFileFullPath)?1:0;
$downloadPdfRelativePath = $this->serviceContainer->getParameter('product_pdf.flyer_path');
$pdfFileFullPath = $downloadPdfRelativePath.$supplierId.'/flyers/'.$productSKU.'.pdf';
$this->responseArray['download_flyer_status'] = file_exists($pdfFileFullPath)?1:0;
// kjethi
$this->responseArray['productAdvertiseData'] = $this->productDetailManager->getAdvertiseForFrontByRefId($productId, 'product'); // $productId
if(array_key_exists('breadcrumbs',$this->responseArray) && array_key_exists('productAdvertiseData',$this->responseArray)){
if (count($this->responseArray['productAdvertiseData']) == 0 && count($this->responseArray['breadcrumbs']) > 0) {
$catForAdvertise = array_keys($this->responseArray['breadcrumbs'])[0];
if ($catForAdvertise > 0) {
$this->responseArray['productAdvertiseData'] = $this->productDetailManager->getAdvertiseForFrontByRefId($catForAdvertise, 'category'); //
}
}
}
// Other Product
$mainSku = $this->responseArray['basic_information']['sku_number'] ? $this->responseArray['basic_information']['sku_number']:0;
if(strpos($this->responseArray['basic_information']['sku_number'], '-') != false){
$mainSku = explode('-', $this->responseArray['basic_information']['sku_number'])[1]; // get main sku
}
if(isset($this->responseArray['other_products']) && is_array($this->responseArray['other_products'])){
$sortOrder = array($mainSku, '80-'.$mainSku, '75-'.$mainSku, '76-'.$mainSku, '81-'.$mainSku, '82-'.$mainSku, '86-'.$mainSku, '10-'.$mainSku, '42-'.$mainSku, '20-'.$mainSku, '28-'.$mainSku, '25-'.$mainSku);
usort($this->responseArray['other_products'], function ($a, $b) use ($sortOrder) {
$pos_a = array_search($a['sku_number'], $sortOrder);
$pos_b = array_search($b['sku_number'], $sortOrder);
return $pos_a - $pos_b;
});
}
else{
$this->responseArray['other_products'] = null;
}
$sku = $this->responseArray['basic_information']['sku_number'] ? $this->responseArray['basic_information']['sku_number']:0;
$search_skus = [];
$globalConnectPrefixes = ['20', '28', '25'];
$isGlobalConnect = 0;
if (strpos($sku, '-') !== false) {
list($prefix, $sku) = explode('-', $sku);
if($prefix == '80'){
$search_skus = ['28-'.$sku, '20-'.$sku, '25-'.$sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label"] ="Current Stock";
$this->responseArray["color_label_1"] ="USA Connect";
}
else{
$this->responseArray["color_label"] ="Domestic Stock";
$this->responseArray["color_label_1"] ="Global Connect";
}
}
elseif($prefix == '75'){
$search_skus = ['25-'.$sku, '20-'.$sku, '28-'.$sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label"] ="Current Stock";
$this->responseArray["color_label_1"] ="USA Connect";
}
else{
$this->responseArray["color_label"] ="Domestic Stock";
$this->responseArray["color_label_1"] ="Global Connect";
}
}
elseif($prefix == '20'){
$isGlobalConnect = 1;
$search_skus = [$sku, '80-' . $sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label_1"] ="Current Stock";
$this->responseArray["color_label"] ="USA Connect";
}
else{
$this->responseArray["color_label_1"] ="Domestic Stock";
$this->responseArray["color_label"] ="Global Connect";
}
}
elseif($prefix == '28'){
$isGlobalConnect = 1;
$search_skus = ['80-' . $sku, $sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label_1"] ="Current Stock";
$this->responseArray["color_label"] ="USA Connect";
}
else{
$this->responseArray["color_label_1"] ="Domestic Stock";
$this->responseArray["color_label"] ="Global Connect";
}
}
elseif($prefix == '25'){
$isGlobalConnect = 1;
$search_skus = ['75-' . $sku, $sku, '80-' . $sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label_1"] ="Current Stock";
$this->responseArray["color_label"] ="USA Connect";
}
else{
$this->responseArray["color_label_1"] ="Domestic Stock";
$this->responseArray["color_label"] ="Global Connect";
}
}
else{
$search_skus = ['20-' . $sku, '28-' . $sku, '25-' . $sku];
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label_1"] ="Current Stock";
$this->responseArray["color_label"] ="USA Connect";
}
else{
$this->responseArray["color_label_1"] ="Domestic Stock";
$this->responseArray["color_label"] ="Global Connect";
}
}
}else{
$search_skus = null;
foreach($globalConnectPrefixes as $value){
$search_skus[] = $value.'-'.$sku;
}
if($this->responseArray['isUsaConnect'] == 1){
$this->responseArray["color_label"] ="Current Stock";
$this->responseArray["color_label_1"] ="USA Connect";
}
else{
$this->responseArray["color_label"] ="Domestic Stock";
$this->responseArray["color_label_1"] ="Global Connect";
}
}
// $productDetailArray = $this->solrProductManager->getProductDetailBySku($sku,$this->cultureCode,$this->responseArray['supplier']['supplier_id'],true,true);
$this->responseArray["otherProducts"] = array();//$productDetailArray;
// $productTagManager = $this->serviceContainer->get('office_brain_product_tag_manager');
$productTagManager = $this->productTagManager;
// $productTagManager = $this->get('office_brain_private_tag_extended');
$this->responseArray["laserProducts"] = $productTagManager->getAllImprintProducts();
$this->responseArray["laserProducts"] = array_column($this->responseArray["laserProducts"],'imprintMethod','productId');
$productHasGlobalConnect = 0;
foreach($globalConnectPrefixes as $globalPrefix){
$key = array_search($globalPrefix.'-'.$mainSku, array_column($this->responseArray['other_products'], 'sku_number'));
if($key !== false){
$productHasGlobalConnect = 1;
break;
}
}
$matching_products = null;
foreach ($search_skus as $sku) {
$matching_products = array_filter($this->responseArray['other_products'], function($product) use ($sku) {
return $product['sku_number'] === $sku;
});
if (!empty($matching_products)) {
break; // Stop searching if a matching product is found
}
}
// Convert the filtered result into a simple indexed array
$matching_products = array_values($matching_products);
$this->responseArray["matching_products"] = $matching_products;
$this->responseArray["main_image_url"] = $request->get('main_image_url');
$this->responseArray["is_global_connect"] = $isGlobalConnect;
$this->responseArray["has_global_connect"] = $productHasGlobalConnect;
return $this->responseArray;
}
/**
*
* @author Employee Id: 4464
* Desciption: Related Product Information.
*
* @param
* integer product id
*
* @return product related information
*
* @Route("/custom-related-product/{productId}",
* name="officebrain_custom_bundle_product_bundle_product_relatedproduct",
* )
*
* @Template("OfficeBrain/Bundle/ProductBundle/Product/relatedProduct.html.twig")
*
*/
public function customRelatedProductAction(Request $request)
{
$this->initAction($request);
$productId = $this->request->get('productId', null);
$locale = $this->request->getLocale();
// -----------------------------------------------------------------------
$cacheSiteKey = array(
$this->moduleCachePrefix,
$locale,
"id#" . $productId,
$this->projectSetting['instance_id'],
$this->projectSetting['kernelEnvironment']
// $this->container->getParameter('kernel.environment') // symfony 4
);
$cacheKey = RedisCacheService::generateKey($this->statsh_cache_wrapper, $cacheSiteKey);
$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper, $cacheKey);
if ($cacheData) {
return $cacheData;
}
// -----------------------------------------------------------------------
$comproductreletedid = $this->productApiManager->productreletedid($productId);
foreach ($comproductreletedid as $releted_productid) {
$relatedProductInfo = $this->productDetailManager->getProductDetailById($releted_productid['relatedProductId'], $releted_productid['culture']);
$this->responseArray['related_product'][] = isset($relatedProductInfo[$releted_productid['relatedProductId']]);
}
if (! empty($cacheKey)) {
RedisCacheService::saveCacheData($this->statsh_cache_wrapper, $cacheKey, $this->responseArray);
}
return $this->responseArray;
}
/**
*
* @author Employee Id: 5633
* Description : Use to show the list of product in this request quote.
* @param
* 1 : No paramater
* @return type : json
* @throws Exception: Null
*
* @Route("/product-imprint-color-chart",
* name="officebrain_custom_product_bundle_imprint_custom_color",
* options={"expose"=true}
* )
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/imprintColorCustomChart.html.twig")
*
*/
public function selectCustomColorAction(Request $request)
{
$this->initAction($request);
$product_id = $this->request->get('product_id');
$culture = $this->cultureCode;
$standardImprintColor = $this->productDetailManager->getStandardImprintColorInformation($product_id, $culture);
$this->responseArray = $this->productDetailManager->getProductDetailById($product_id, $culture);
$this->responseArray['imprint_color_msg'] = 0;
if (isset($this->responseArray[$product_id]['basic_information']['sku_number']) && ! empty($this->responseArray[$product_id]['basic_information']['sku_number'])) {
$impintMsgArray = $this->serviceContainer->getParameter('imprint_color_msg');
if (in_array($this->responseArray[$product_id]['basic_information']['sku_number'], $impintMsgArray)) {
$this->responseArray['imprint_color_msg'] = 1;
}
}
return array(
'standard_imprint_color' => $standardImprintColor,
'imprint_color_msg' => $this->responseArray['imprint_color_msg']
);
}
/**
*
* @author Employee Id: 5429
*
* @Route("/image-library/{page}",name="officebrain_custom_bundle_product_bundle_image_library",
* requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
* defaults={"records_per_page"=20,"page"=1}),
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/imageLibrary.html.twig")
*
*/
public function imageLibraryAction(Request $request)
{
$this->initAction($request);
if ($this->userId == 0) {
return $this->redirect($this->generateUrl('office_brain_userbundle_login_login'));
}
$culture = $this->cultureCode;
list ($cultureName[], $country[]) = explode("_", $culture);
$category = $this->productDetailManager->getCategoryMapping();
$masterIds = array_column($category, 'pms_id');
$params = array(
'cultures' => json_encode($cultureName),
'master_id' => json_encode($masterIds)
);
$this->categoryApi->init('list_category');
$this->categoryApi->setCallParameters($params);
$this->categoryApi->doProcess();
$data = $this->categoryApi->getResultArray();
foreach ($category as $key) {
if (array_key_exists($key['pms_id'], $data['en'])) {
$data['en'][$key['pms_id']]['parentid'] = $key['parentid'];
$data['en'][$key['pms_id']]['haschildid'] = $key['haschildid'];
}
}
return $data;
}
/**
*
* @author Employee Id: 5429
*
* Description : This function used for List Product Information
* @Route("/product/view-psa-special/",name="officebrain_custombundle_productbundle_psaSpecial_view")
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/viewPsaSpecial.html.twig")
*
*
*/
public function viewPsaSpecialAction(Request $request)
{
$this->initAction($request);
$imagename['path'] = $this->request->get('product_id', '');
return $imagename;
}
/**
*
* @author Employee Id: 5429
*
* @Route("/product/QRcode/view/{slug}",name="officebrain_custombundle_productbundle_qrcode_view", methods={"GET"}),
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/viewQRCode.html.twig")
*
*/
public function viewQRCodeAction(Request $request, $slug)
{
$this->initAction($request);
return $this->productDetailManager->getQRCodedetail($slug);
}
/**
*
* @author Employee Id: 4217
*
* Desciption: Virtual Tool
*
* @param
* video_url.
*
* @return json Response
*
* @Route("/product-virtual-tool",
* name="officebrain_product_bundle_product_virtual_tool"
* )
*
* @Template("OfficeBrain/Bundle/ProductBundle/Product/productVirtualTool.html.twig")
*/
public function productVirtualToolAction(Request $request)
{
$this->initAction($request);
$itemNo = $this->request->get("itemno");
$prodctid = $this->request->get("prodctid");
$this->responseArray['productSku'] = $itemNo;
return $this->responseArray;
}
/**
*
* @author Employee Id: 5429
*
* @Route("/product/email-factory-for-price/{product_id}",name="officebrain_custombundle_productbundle_email_factory_for_price", methods={"GET","POST"}),
*
*/
public function emailFactoryForPriceAction(Request $request)
{
$this->initAction($request);
$productId = $this->request->get('product_id');
$productDetailArrayId = $this->productDetailManager->getProductDetailById($productId, $this->cultureCode);
if (isset($productDetailArrayId[$productId]) && ! empty($productDetailArrayId[$productId])) {
$itemName = isset($productDetailArrayId[$productId]['basic_information']['title']) ? $productDetailArrayId[$productId]['basic_information']['title'] : "";
$skuNumber = isset($productDetailArrayId[$productId]['basic_information']['sku_number']) ? $productDetailArrayId[$productId]['basic_information']['sku_number'] : "";
$imprintColors = "";
$notes = "";
if ($productDetailArrayId[$productId]['feature_details']) {
foreach ($productDetailArrayId[$productId]['feature_details'] as $features) {
if (strtolower(trim($features['label'])) == "imprint colors") {
$imprintColors = $features['value'];
}
if (strtolower($features['label']) == "note") {
$notes = $features['value'];
}
}
}
$quantity = array();
if ($productDetailArrayId[$productId]['pricing']['decorative']) {
foreach ($productDetailArrayId[$productId]['pricing']['decorative'] as $pricing) {
$priceTo = ! empty($pricing['to']) ? "-" . $pricing['to'] : "+";
$quantity[] = $pricing['from'] . $priceTo;
}
}
$quantity = implode("|", $quantity);
$eventKey = 'productDetailFactoryPriceEmail';
$to = ""; // "jrathod@officebrain.com";//specialquotes@aakronline.com
$languageId = $this->languageId;
$subject = "Test Email";
$params = array(
'item_name' => $itemName,
'sku_number' => $skuNumber,
'quantity' => $quantity,
'imprint_color' => $imprintColors,
'additional_notes' => $notes
);
$from = ""; // "jrathod@officebrain.com";
$attachment = array();
$cc = ''; // array();
$bcc = ''; // array();
$this->emailService->sendMail($eventKey, $to, $params, $languageId, $from, $subject, $attachment, $cc, $bcc);
$this->responseArray['status'] = 'success';
$this->responseArray['success_message'] = $this->translator->trans('email.success');
} else {
$this->responseArray['status'] = 'error';
$this->responseArray['error_message'] = "There is some issue please try again later!";
}
return new JsonResponse($this->responseArray);
}
/**
*
* @author(Kjethi)
* @Route("/suggested-product/{productId}",
* name="office_brain_search_bundle_product_suggested_product_list",
* )
* @Template("project/OfficeBrain/CustomBundle/SearchBundle/BrowseCategory/suggestedProduct.html.twig")
*/
public function getSuggestedProductByProductAction(Request $request, $productId, $category = [])
{
$this->initAction($request);
$productId = $productId;
// $searchManager = $this->get('office_brain_custom_bundle_search_manager'); // symfony 4
// $searchManager = $this->serviceContainer->get('office_brain_search_manager_extended');
$searchManager = $this->searchManager;
$suggestedProductData = array();
$data = $this->productApiManager->getSuggestedProductByProductId($productId);
if (isset($data['suggestedProducts']) && count($data['suggestedProducts']) > 0) {
$suggestedProductData = $data['suggestedProducts'];
} else if (count($category) > 0) {
$api_manager = $this->serviceContainer->get('officebrain_category_api_manager');
$categoryWiseSuggestedArr = $api_manager->getSuggestedProductByRelatedCat($category[0]);
$categoryWiseSuggestedArr = array_column($categoryWiseSuggestedArr, 'suggestedProduct');
$suggestedProductData = '';
foreach ($categoryWiseSuggestedArr as $suggProductIdArr) {
$suggestedProductData .= ($suggestedProductData ? ',' : '') . $suggProductIdArr; // array_filter - remove blank element
}
$suggestedProductData = explode(',', $suggestedProductData);
$suggestedProductData = array_filter($suggestedProductData);
}
// $api_manager = $this->get('officebrain_category_api_manager');
// $categoryWiseSuggestedArr= $api_manager->getSuggestedProductByRelatedCat($category);
// $categoryWiseSuggestedArr= array_column($categoryWiseSuggestedArr, 'suggestedProduct');
// $suggestedProductData='';
// foreach ($categoryWiseSuggestedArr as $suggProductIdArr){
// $suggestedProductData .= ($suggestedProductData ? ',': '' ).$suggProductIdArr;//array_filter - remove blank element
// }
// $suggestedProductData = explode(',',$suggestedProductData);
// $suggestedProductData = array_filter($suggestedProductData);
// /////////////////////////////////////
// $data = $this->productApiManager->getSuggestedProductByProductId($productId);
$suggestedProductData = array_merge($suggestedProductData, $data['suggestedProducts']);
if ($data && count($suggestedProductData) > 0) {
$result = array();
if (count($suggestedProductData))
$sku = $suggestedProductData; // implode($data['suggestedProducts'], ',');
// $sku = $data['suggestedProducts'];//
$this->request->query->set('sku', $sku);
$this->request->query->set('search_type', 'exact');
// this is for remove By Default soring(which is Price:desc)
$this->request->query->set('sort_by', '1');
$this->responseArray = $searchManager->searchService(true);
$data = array();
// $data = $this->site_module->getProduct($criteria);
# print_r(array_keys((array)$this->responseArray['search_result_array']));
# echo(array_keys($this->responseArray['search_result_array']));exit;
// print_r($this->responseArray);exit;
$data['search_result_array'] = $this->responseArray['search_result_array'];
// print_r(array_keys($data['search_result_array']));exit;
$data['product_box_bootstrap_class'] = 'item';
$data['render_model'] = 0;
// echo "<pre>"; dump($data['search_result_array']); exit;
// return $this->render('OfficeBrainPageBundle:tempUIElements:recommendProducts.html.twig', $data);
$response = $this->render("project/OfficeBrain/CustomBundle/SearchBundle/BrowseCategory/suggestedProduct.html.twig", $data);
if(!empty($cacheKey))
{
RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
}
return $response;
}
else{
return array();
}
}
/**
* @author Employee Id: 6799
*
* Description : This function used for Get information about ESP
* @Route("/get-esp-data/{productSku}",name="officebrain_custombundle_productbundle_getespdata")
* @return json Response
*
*/
public function getEspDataAction(Request $request)
{
$this->initAction($request);
$productSku = $this->request->get("productSku");
$selectedData = $this->productDetailManager->getEspProductData($productSku);
$responseData = null;
if($selectedData){
$responseData["selected_esp_product_type"] = $selectedData->getEspProductType();
$responseData["selected_esp_categories"] = $selectedData->getEspProductCategory();
}
$response = new Response(json_encode($responseData));
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Status-Code', 404);
return $response;
}
/**
*
* @author Employee Id: Freelancer
* @param
* @return type : json
* @throws Exception: Null
*
* @Route("/product-hts-code",
* name="officebrain_custom_product_bundle_hts_code",
* options={"expose"=true}
* )
* @Template("project/OfficeBrain/CustomBundle/ProductBundle/Product/productHtsCode.html.twig")
*
*/
public function productHtsCodeAction(Request $request)
{
$this->initAction($request);
$product_id = $this->request->get('product_id');
$culture = $this->cultureCode;
$productDetailArray = $this->productDetailManager->getProductDetailById($product_id, $culture);
$this->responseArray = $productDetailArray[$product_id];
$this->responseArray['data'] = $this->responseArray['feature_details'];
return $this->responseArray;
}
/**
* @author Vendor
*
* Description : This function used for update Product Price
* @return array
* @Route("/product/update-tiory-price/{sku}", name="officebrain_product_update_product_pricing"),
*/
public function updateProductPricingAction(Request $request, $sku){
$this->initAction($request);
$mainSku = $sku;
// $data=$this->request->all();
$pricingYear = $this->request->get('price_year', date("Y"));
$prefixSku = substr($sku,0,2);
$hasPrefixSku = false;
if(in_array($prefixSku,["10","20","80","81","82", "75", "76", "25", "28"])){
$hasPrefixSku = true;
$prefixSku = substr($sku,0,2);
$m_sku = substr($sku,2);
$sku = $prefixSku."-". $m_sku;
}
$projectSetting = $this->request->get('project_setting');
// $sku = $this->request->get('sku', '');
// $masterProductId = $this->request->get('master_product_id', '');
$countryArray = $this->serviceContainer->getParameter('country');
$languageArray = $this->serviceContainer->getParameter('language');
$country_to_pass = array_column($countryArray,'short_name');
$language_to_pass = array_keys($languageArray);
$param = $this->request->get('_route_params');
$locale_language = $param['_locale'];
$locale = $this->request->get('_locale',$this->serviceContainer->getParameter('locale'));
@list($default_language,$default_country) = explode("_",$locale);
$cultureName = $this->projectSetting['culture_code'];
$supplier_id = 0;
// set global_pricing_keys which are active
if($sku){
$tioryPriceData = $this->callTioryPriceApiFromSku($mainSku, $pricingYear);
// echo "<pre>";print_r($tioryPriceData["BodyData"]["PriceData"]);exit;
if($tioryPriceData["status"] != "success"){
$response = array('status' => "error",'error_message'=>"Tiory price not found");
return new JsonResponse($response);
}
$withPrefix0 = false;
do {
$productInfoFromSku = $this->productDetailManager->getProductDetailBySku($sku,5,$cultureName);
if(isset($productInfoFromSku["product_id"]) || substr($sku,0,1) == "0"){
$withPrefix0 = true;
}
else {
$sku = "0".$sku;
}
} while (!$withPrefix0);
// need to check because sku has sometime prefix number in mainSku like (2020)
if(!isset($productInfoFromSku["product_id"]) && $hasPrefixSku){
$withPrefix0 = false;
$sku = $mainSku;
do {
$productInfoFromSku = $this->productDetailManager->getProductDetailBySku($sku,5,$cultureName);
if(isset($productInfoFromSku["product_id"]) || substr($sku,0,1) == "0"){
$withPrefix0 = true;
}
else {
$sku = "0".$sku;
}
} while (!$withPrefix0);
}
if(isset($productInfoFromSku["product_id"])){
$masterProductId = $productInfoFromSku["product_id"];
$productInfo = $this->productApiManager->editView($masterProductId,$language_to_pass,$country_to_pass,$default_language);
// $masterProductId
// echo "<pre>";print_r($productInfo);exit;
$updateProductArr = $this->setProductDataAsPerUpdate($productInfo,$default_country,$default_language,$tioryPriceData["BodyData"]["PriceData"]);
$apiResponse = $this->productApiManager->add($cultureName, $updateProductArr);
if ($apiResponse['status']=='success') {
$response = array('status' => $apiResponse['status'],'success_message'=>$this->get('translator')->trans($apiResponse['success_message']));
$actionPerformed = 'update';
//SOLR SYNC CODE START
$is_solr_syn_enabled = $this->serviceContainer->getParameter('solr_sync');
if($is_solr_syn_enabled){
$env = $this->serviceContainer->getParameter("kernel.environment");
$localization_to_update = $this->serviceContainer->getParameter('localization_to_fetch');
$this->productApiManager->updateSolrData($apiResponse['master_product_id'],$localization_to_update,$projectSetting['project_id'],$env,'update');
}
//SOLR SYNC CODE END
// To Integrate With ERP
$erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
$this->productApiManager->integrateWithErp($this->queueApiManager, $actionPerformed, $apiResponse['master_product_id']);
}
if($this->request->get('syncflag')==1){
if($productAddSettings['asi_call']['status']){
foreach ($apiResponse['product_slugs'] as $culture => $slug){
if($masterProductId > 0)
{
$this->productDetailManager->updateSyncDetail($this->request->get('syncflag'),$updateProductArr['sku']);
$asiurl = 'http://demoapi.officebrain.com/update_product_api.php?product_slug='.$slug;
}
else
{
$this->productDetailManager->insertSyncDetail($this->request->get('syncflag'),$updateProductArr['sku']);
$asiurl = 'http://demoapi.officebrain.com/product_api.php?product_slug='.$slug;
}
//echo $asiurl;die;
exec("curl '$asiurl' > /dev/null &");
}
}
}
else
{
if($masterProductId > 0)
{
$this->productDetailManager->updateSyncDetail(0,$updateProductArr['sku']);
}
else
{
$this->productDetailManager->insertSyncDetail(0,$updateProductArr['sku']);
}
if(isset($updateProductArr['sku']) && !empty($updateProductArr['sku'])){
$asiurl = 'http://demoapi.officebrain.com/product_delete_api.php?product_sku='.$updateProductArr['sku'];
exec("curl '$asiurl' > /dev/null &");
}
}
}
return new JsonResponse($response);;
}
}
$response = array('status' => "error",'error_message'=>"Product not found");
return new JsonResponse($response);;
}
function setProductDataAsPerUpdate($productInfo,$default_country,$default_language,$tioryPriceData){
$param = $this->request->get('_route_params');
$projectSetting = $this->request->get('project_setting');
$locale_language = $param['_locale'];
$countryArray = $this->serviceContainer->getParameter('country');
$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
$globalPricingKeys = '';
if(array_key_exists('global_pricing', $productAddSettings))
{
foreach ($productAddSettings['global_pricing'] as $key => $val)
{
if ($val['status'] == 1)
{
$globalPricingKeys .= ($val['pricing_box_id'].':'.$val['pricing_box_name']).',';
}
}
}
$productBasicInfo = $productInfo[$default_language]["basic_information"];
$updateProductArr = array();
$updateProductArr["master_product_id"] = $productInfo["product_id"];
$updateProductArr["supplier_id"] = $productInfo["supplier_id"];
$updateProductArr["product_source"] = $productInfo["product_source"];
$updateProductArr["sku"] = $productBasicInfo["sku_number"];
$updateProductArr["product_name"] = array(
$default_language => $productBasicInfo["title"]
);
$updateProductArr["country"] = array(
($countryArray[$default_country]["id"]) ."_". $default_country
);
$updateProductArr["lang"] = array(
$default_country => array($default_language)
);
$updateProductArr["brand"] = $productInfo["brand"]["id"];
$updateProductArr["category"] = array(
"country_".$default_country => $productInfo["category"][$default_country]
);
$updateProductArr["product_description"] = array(
$default_language => $productBasicInfo["description"]
);
$updateProductArr["feature_detail_label"] = array(
$default_language => array_column($productInfo[$default_language]["feature_details"],"label")
);
$updateProductArr["feature_detail"] = array(
$default_language => array_column($productInfo[$default_language]["feature_details"],"value")
);
$updateProductArr["keyword"] = array(
$default_language => $productInfo[$default_language]["keyword"]
);
$updateProductArr["video_url"] = $productBasicInfo["video_url"];
$updateProductArr["distributor_central_url"] = $productBasicInfo["distributor_url"];
$updateProductArr["details_attribute_to_add"] = array_column($productInfo["attributes"],"attribute_id");
$tmpDetaiAndValues = array_reduce($productInfo["attributes_values"][$default_country], function($carry, $item){
if(!isset($carry[$item['attribute_id']])){
$carry[$item['attribute_id']] = array();
}
array_push($carry[$item['attribute_id']],$item['attribute_val']);
return $carry;
});
$updateProductArr["DetailsAndValue"] = array(
"country_".$default_country => array_map(function ($v){ return [implode(",",$v)]; },$tmpDetaiAndValues)
);
$updateProductArr["PricingType"] = $productInfo["regular_variations_type"];
function price($obj){
$a = array(
"start" => $obj["from"],
"end" => $obj["to"],
"price" => $obj["rate"],
"code" => $obj["code"],
"decorative_new_price" => "",
"decorative_new_code" => "",
"blank_price" => "",
"blank_code" => "",
"special_price" => "",
"special_code" => "",
);
}
$mainPriceArr = array();
$regularPriceArr = array();
$aboveCatalogPriceArr = array();
foreach ($tioryPriceData as $k => $v) {
$end = $k == count($tioryPriceData)-1 ? "" : $tioryPriceData[$k+1]["quantity"]-1;
$tmpArr = array(
"start" => $v["quantity"],
"end" => $end,
'price' => $v["list"],
"code" => $v["price_discount_id"],
"decorative_new_price" => "",
"decorative_new_code" => "",
"blank_price" => "",
"blank_code" => "",
"special_price" => "",
"special_code" => ""
);
array_push($mainPriceArr,$tmpArr);
if($k <= $v["eqp"]){
array_push($regularPriceArr,$tmpArr);
}
else if($v["eqp"]+2 >= $k){
array_push($aboveCatalogPriceArr,$tmpArr);
}
}
// echo "<pre>";print_R($productBasicInfo);
// print_R($aboveCatalogPriceArr);exit;
$updateProductArr["Pricing"] = array(
"price_unit" => $productInfo["regular_price_unit"],
"regular" => array(
"country_".$default_country => $regularPriceArr
)
);
$updateProductArr["pricing_valid_until"] = isset($productBasicInfo["pricing_valid_until"]) ? $productBasicInfo["pricing_valid_until"] : "";
$updateProductArr["pricing_valid_starting"] = isset($productBasicInfo["pricing_valid_starting"]) ? $productBasicInfo["pricing_valid_starting"] :"";
$updateProductArr["chk_global_pricing2"] = "pricing2";
$updateProductArr["PricingType2"] = isset($productInfo["global_pricing"]["above_catalog"]) ? $productInfo["global_pricing"]["above_catalog"]["regular_variations_type"] : "";
$updateProductArr["Pricing2"] = array(
"price_unit" => $productInfo["global_pricing"]["above_catalog"]["regular_price_unit"],
"regular" => array(
"country_".$default_country => $aboveCatalogPriceArr
)
);
$updateProductArr["general_information"] = array(
$default_language => $productBasicInfo["general_information"]
);
$updateProductArr["sample_pricing"] = array(
"country_".$default_country => array("price" => "","max_quantity" => "")
);
function prod_img_map($imgObj){
if(isset($imgObj["image_name"])){
return array($imgObj["image_name"], $imgObj["attr_val_id"]."::SEP::".$imgObj["attribute_value"]);
}
else {
array("");
}
}
$updateProductArr["image_product"] = array();
if(isset($productInfo["prod_images"]["default_image"])){
$imgObj = $productInfo["prod_images"]["default_image"];
$updateProductArr["image_product"]["default_image"] = array($imgObj["image_name"], $imgObj["attr_val_id"]."::SEP::".$imgObj["attribute_value"]);
}
if(isset($productInfo["prod_images"]["other"])){
foreach ($productInfo["prod_images"]["other"] as $i => $imgObj){
if(isset($imgObj["image_name"])){
$otherKeyName = "other_image";
if($i){
$otherKeyName = $otherKeyName."_".$i;
}
$updateProductArr["image_product"][$otherKeyName] = array($imgObj["image_name"], $imgObj["attr_val_id"]."::SEP::".$imgObj["attribute_value"]);
}
}
}
// $updateProductArr["image_product"] = array(
// "default_image" => array_map(function ($imgObj){
// if(isset($imgObj["image_name"])){
// return array($imgObj["image_name"], $imgObj["attr_val_id"]."::SEP::".$imgObj["attribute_value"]);
// }
// else {
// array("");
// }
// },$productInfo["prod_images"]["default_image"]),
// "other_image" => array_map(function ($imgObj){
// if(isset($imgObj["image_name"])){
// return array($imgObj["image_name"], $imgObj["attr_val_id"]."::SEP::".$imgObj["attribute_value"]);
// }
// else {
// array("");
// }
// },isset($productInfo["prod_images"]["other_image"]) ? $productInfo["prod_images"]["other_image"] : array() )
// );
$charges = array();
function returnProperFormatChargePrice($priceArr){
if(is_array($priceArr)){
return array_map(function($v){
return array(
"start" => $v["from"],
"end" => $v["to"],
"price" => $v["rate"],
"code" => $v["code"],
);
}, $priceArr);
}
else {
return $priceArr;
}
}
foreach ($productInfo["imprint_method_information"] as $imprint_method_id => $value) {
// echo "<pre>";print_r($value);exit;
# code...
$chargesArr=array();
if(isset($value["charges"]["country_".$default_country]["LTM_CHARGE"])){
$chargesArr["LTM_CHARGE"] = array();
$chargesArr["LTM_CHARGE"]["charge"] = isset($value["charges"]["country_".$default_country]["LTM_CHARGE"]) ? $value["charges"]["country_".$default_country]["LTM_CHARGE"]["charge"] : "";
if(isset($value["charges"]["country_".$default_country]["LTM_CHARGE"]["code"])){
$chargesArr["LTM_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["LTM_CHARGE"]["code"];
}
};
if(isset($value["charges"]["country_".$default_country]["RUSH_CHARGE"])){
$chargesArr["RUSH_CHARGE"] = array();
$chargesArr["RUSH_CHARGE"]["charge"] = isset($value["charges"]["country_".$default_country]["RUSH_CHARGE"]) ? $value["charges"]["country_".$default_country]["RUSH_CHARGE"]["charge"] : "";
if(isset($value["charges"]["country_".$default_country]["RUSH_CHARGE"]["code"])){
$chargesArr["RUSH_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["RUSH_CHARGE"]["code"];
}
};
if(isset($value["charges"]["country_".$default_country]["PMS_CHARGE"])){
$chargesArr["PMS_CHARGE"] = array();
$chargesArr["PMS_CHARGE"]["charge"] = isset($value["charges"]["country_".$default_country]["PMS_CHARGE"]) ? $value["charges"]["country_".$default_country]["PMS_CHARGE"]["charge"] : "";
if(isset($value["charges"]["country_".$default_country]["PMS_CHARGE"]["code"])){
$chargesArr["PMS_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["PMS_CHARGE"]["code"];
}
};
if(isset($value["charges"]["country_".$default_country]["SETUP_CHARGE"])){
$chargesArr["SETUP_CHARGE"] = array();
$chargesArr["SETUP_CHARGE"]["charge"] = returnProperFormatChargePrice($value["charges"]["country_".$default_country]["SETUP_CHARGE"]["charge"]);
if(isset($value["charges"]["country_".$default_country]["SETUP_CHARGE"]["code"])){
$chargesArr["SETUP_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["SETUP_CHARGE"]["code"];
} else {
$chargesArr["SETUP_CHARGE"]["quantity_wise"] = "on";
}
};
if(isset($value["charges"]["country_".$default_country]["ADDITIONAL_LOCATION_CHARGE"])){
$chargesArr["ADDITIONAL_LOCATION_CHARGE"] = array();
$chargesArr["ADDITIONAL_LOCATION_CHARGE"]["charge"] = returnProperFormatChargePrice($value["charges"]["country_".$default_country]["ADDITIONAL_LOCATION_CHARGE"]["charge"]);
if(isset($value["charges"]["country_".$default_country]["ADDITIONAL_LOCATION_CHARGE"]["code"])){
$chargesArr["ADDITIONAL_LOCATION_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["ADDITIONAL_LOCATION_CHARGE"]["code"];
}
else {
$chargesArr["ADDITIONAL_LOCATION_CHARGE"]["quantity_wise"] = "on";
}
};
if(isset($value["charges"]["country_".$default_country]["ADDITIONAL_COLOR_CHARGE"])){
$chargesArr["ADDITIONAL_COLOR_CHARGE"] = array();
if(isset($value["charges"]["country_".$default_country]["ADDITIONAL_COLOR_CHARGE"]["code"])){
$chargesArr["ADDITIONAL_COLOR_CHARGE"]["code"] = $value["charges"]["country_".$default_country]["ADDITIONAL_COLOR_CHARGE"]["code"];
}
else {
$chargesArr["ADDITIONAL_COLOR_CHARGE"]["quantity_wise"] = "on";
}
$chargesArr["ADDITIONAL_COLOR_CHARGE"]["charge"] = returnProperFormatChargePrice($value["charges"]["country_".$default_country]["ADDITIONAL_COLOR_CHARGE"]["charge"]);
};
$charges[$imprint_method_id] = array(
"position" => implode(",",array_keys($value["imprint_location"])),
"imprint_area" => $value["imprint_area"],
"color_included" => $value["color_included_in_price"],
"maximum_color" => $value["maximum_selectable_color"],
"location_included" => $value["location_included_in_price"],
"maximum_location" => $value["maximum_selectable_location"],
"production_days" => $value["production_days"],
"production_unit" => $value["production_unit"],
"country_".$default_country => $chargesArr
);
}
$updateProductArr["imprint_information"] = array(
"method" => array_keys($productInfo["imprint_methods"]),
"charges" => $charges
);
$updateProductArr["shipping"] = array(
"fob" => $productInfo["shipping_information"]["free_on_board"],
"carton_quantity" => isset($productInfo["shipping_information"]["carton"]["quantity"]["param"]) ? $productInfo["shipping_information"]["carton"]["weight"]["param"] : "",
"carton_weight" => isset($productInfo["shipping_information"]["carton"]["weight"]["param"]) ? $productInfo["shipping_information"]["carton"]["weight"]["param"] : "",
"carton_weight_unit" => isset($productInfo["shipping_information"]["carton"]["weight"]["unit"]) ? $productInfo["shipping_information"]["carton"]["weight"]["unit"] : "",
"carton_length" => isset($productInfo["shipping_information"]["carton"]["length"]["param"]) ? $productInfo["shipping_information"]["carton"]["length"]["param"] : "",
"carton_width" => isset($productInfo["shipping_information"]["carton"]["width"]["param"]) ? $productInfo["shipping_information"]["carton"]["width"]["param"] : "",
"carton_height" => isset($productInfo["shipping_information"]["carton"]["height"]["param"]) ? $productInfo["shipping_information"]["carton"]["height"]["param"] : "",
"carton_size_unit" => isset($productInfo["shipping_information"]["carton"]["height"]["unit"]) ? $productInfo["shipping_information"]["carton"]["height"]["unit"] : "",
"product_weight" => isset($productInfo["shipping_information"]["product"]["weight"]["param"]) ? $productInfo["shipping_information"]["product"]["weight"]["param"] : "",
"product_weight_unit" => isset($productInfo["shipping_information"]["product"]["weight"]["unit"]) ? $productInfo["shipping_information"]["product"]["weight"]["unit"] : "",
"product_length" => isset($productInfo["shipping_information"]["product"]["length"]["param"]) ? $productInfo["shipping_information"]["product"]["length"]["param"] : "",
"product_width" => isset($productInfo["shipping_information"]["product"]["width"]["param"]) ? $productInfo["shipping_information"]["product"]["width"]["param"] : "",
"product_height" => isset($productInfo["shipping_information"]["product"]["height"]["param"]) ? $productInfo["shipping_information"]["product"]["height"]["param"] : "",
"product_size_unit" => isset($productInfo["shipping_information"]["product"]["width"]["unit"]) ? $productInfo["shipping_information"]["product"]["width"]["unit"] : "",
);
$updateProductArr["valid_up_to"] = $productBasicInfo["valid_up_to"];
$updateProductArr["special_price_valid_up_to"] = $productBasicInfo["special_price_valid_up_to"];
$updateProductArr["currency_array"] = array(
$default_country => 3
);
$updateProductArr["old_name"] = $productBasicInfo["title"];
$updateProductArr["global_pricing_keys"] = trim($globalPricingKeys, ',');
$updateProductArr['project_id'] = $projectSetting['project_id'];
$updateProductArr['locale_language'] = $locale_language;
$updateProductArr['instance_type'] = $projectSetting['instance_type'];
$updateProductArr['instance_id'] = $projectSetting['instance_id'];
$updateProductArr['thumb_width'] = $this->serviceContainer->getParameter('thumb_width');
$updateProductArr['medium_thumb_width'] = $this->serviceContainer->getParameter('medium_thumb_width');
// echo "<pre>";print_r($updateProductArr);exit;
return $updateProductArr;
}
public function callTioryPriceApiFromSku($sku, $pricingYear)
{
$ch = curl_init();
// $sku = str_replace("-","",$sku);
// $sku = ltrim($sku , "0");
$postData = array("pricing_year"=>$pricingYear);
$url = "https://arc1967.tiory.com/api/update-tiory-price/$sku?pricing_year=".$pricingYear;
// $url = "https://arc1967.tiory.com/api/en_us/product/update-tiory-price?item_code=71117";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "officebeacon:test123");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
$xml = curl_exec($ch);
return json_decode($xml,true);
}
/**
*
* Desciption: Order Sample
*
* @return json Response
*
* @Route("/product-order-sample",
* name="officebrain_product_bundle_product_order_sample"
* )
*
* @Template("OfficeBrain/Bundle/ProductBundle/Product/productOrderSample.html.twig")
*/
public function productOrderSampleAction(Request $request)
{
$this->initAction($request);
$itemNo = $this->request->get("itemno");
$prodctid = $this->request->get("prodctid");
$this->responseArray['productSku'] = $itemNo;
return $this->responseArray;
}
}