<?php
namespace App\OfficeBrain\Bundle\ProductBundle\Controller;
// use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use App\OfficeBrain\Bundle\CoreBundle\CustomeHandler as FormErrorManager;
use App\OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use App\OfficeBrain\Bundle\ProductTagBundle\Entity\ImprintProductMapping;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\OfficeBrain\Bundle\ProductBundle\Manager\Service\ProductAdminManager;
use App\OfficeBrain\Bundle\UserBundle\Manager\Service\UserService;
use App\OfficeBrain\Bundle\ProductBundle\Manager\Service\ProductDetailService;
use App\OfficeBrain\Bundle\ProductBundle\Manager\Service\BrandApiManager;
use App\OfficeBrain\Bundle\ProductTagBundle\Manager\Service\ProductTagManager;
use App\OfficeBrain\Bundle\SolrBundle\Manager\Service\SolrService;
use App\OfficeBrain\Bundle\QueueBundle\Manager\Service\ApiManager as QueueApiManager;
use App\OfficeBrain\Bundle\CategoryBundle\Manager\ApiManager as CategoryApiManager;
/*
* This class for base functionality related to product admin. @author Office Brain - 4808 <support@officebrain.com>
*/
/**
* @Route("/admin/{_locale}/product")
*/
class ProductConfigureController extends AbstractController
{
public function __construct(ContainerInterface $container, ProductAdminManager $productAdminManager, UserService $userService, ProductDetailService $productDetailService, BrandApiManager $brandApiManager, ProductTagManager $productTagManager, SolrService $solrService, QueueApiManager $queueApiManager)
{
$this->serviceContainer = $container;
$this->productApiManager = $productAdminManager;
$this->userService = $userService->getUserExtended();
$this->productDetailManager = $productDetailService->getProductApiExtended();
$this->brandApiManager = $brandApiManager;
$this->productTagManager = $productTagManager->getProductTagManagerExtended();
$this->solrService = $solrService->getSolrServiceExtended();
$this->queueApiManager = $queueApiManager->getQueueInstance();
}
CONST PRODUCT_CACHE_CLIENT = 'product';
/**
* @author Employee Id: 4808
*
* Description : This function used for Set and intilize variables and request array
*
**/
public function init(Request $request){
$this->request = $request;
$this->entityManager = $this->getDoctrine()->getManager();
$this->session = $this->request->getSession();
$this->translator = $this->serviceContainer->get('translator');
$this->formErrorManager = new FormErrorManager\JsonError();
// $this->productApiManager = $this->serviceContainer->get("office_brain_product_admin_manager");
$this->productApiManager = $this->productApiManager;
// $this->brandApiManager = $this->serviceContainer->get("officebrain_brand_api_manager");
$this->brandApiManager = $this->brandApiManager;
$this->categoryApiManager = $this->serviceContainer->get("officebrain_category_api_manager");
// $this->userManager = $this->serviceContainer->get("office_brain_user_manager");
$this->userManager = $this->userService;
$this->projectSetting = $this->request->get('project_setting');
$this->projectUserSetting = $this->request->get('project_user_setting');
$this->userId = $this->projectUserSetting['user_data'] ? $this->projectUserSetting['user_data']->getId() : 0;
// $this->productDetailManager = $this->serviceContainer->get('office_brain_product_detail_manager');
$this->productDetailManager = $this->productDetailManager;
$this->productTagManager = $this->productTagManager;
$this->user = $this->projectUserSetting['user_data'];
if (!$this->getUser() && $this->request->isXmlHttpRequest()) {
// throw new AccessDeniedHttpException();
}
// if ($this->serviceContainer->has('office_brain_queue_api_manager')) {
// $this->request->attributes->set('object', 'Product');
// $this->queueApiManager = $this->serviceContainer->get('office_brain_queue_api_manager');
// }
if ($this->queueApiManager) {
$this->request->attributes->set('object', 'Product');
$this->queueApiManager = $this->queueApiManager;
}
$this->statsh_cache_wrapper = RedisCacheService::create();
$this->moduleCachePrefix='__RelatedProducts__';
}
/**
* @author Employee Id: 4808
*
* Description : This function used for List Product Information
*
* @Route("/list/{page}",
* name="officebrain_bundle_product_list_product_wo_culture",
* requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
* defaults={"records_per_page"=100,"page"=1})
*
* @Route("/list/{country}/{language}/{page}",
* name="officebrain_bundle_product_list_product",
* requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
* defaults={"records_per_page"=20,"page"=1})
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/list.html.twig")
*/
public function listProductAction(Request $request){
$this->init($request);
$projectSetting = $this->request->get('project_setting');
list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
$param = $this->request->get('_route_params');
$culture = $this->request->get('language',$defaultCulture);
$country = $this->request->get('country',$defaultCountry);
$activeCulture = $culture;
$searchStatus = $this->request->query->get('search_status', '');
$searchQuery = $this->request->query->get('search_query', '');
$sortBy = $this->request->query->get('sort', 'updatedAt');
$sortType = $this->request->query->get('direction', 'desc');
$searchParam = $this->request->query->get('search_param', '');
$supplier_id = $this->request->query->get('supplier_id','');
$brandIds = $this->request->query->get('brand_id','');
$catIds = $this->request->query->get('cat_id','');
$instanceType = $projectSetting['instance_type'];
$cultureCategory = $activeCulture . "_" . $country;
// For Pagination
$page = $this->request->get('page', '1');
$records_per_page = $param['records_per_page'];
$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
$start_index = (($page - 1) * $recordsPerPage - 1);
// End Pagination
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
$supplierData = $this->productApiManager->getSupplierNameList($projectId);
$brandData = $this->brandApiManager->getList($culture);
//GET CATEGORY AND SUBCATEGORY
$categoryAndSubCategoryData = $this->categoryApiManager->getList(array($cultureCategory),array(),true);
$this->catArrayNew = array();
if ($categoryAndSubCategoryData) {
foreach($categoryAndSubCategoryData[$cultureCategory] as $catKey=>$categoryAndSubCategory){
$this->recursiveCategory($categoryAndSubCategory);
}
// Sort Category array using category name
usort($this->catArrayNew, function ($a, $b) {
return strcasecmp($a['cat_name'], $b['cat_name']);
});
}
$data['category_SubCategory_data'] = $this->catArrayNew;
$paginator = $this->serviceContainer->get('knp_paginator');
$data['pagination'] = $paginator->paginate($productData, $page, $recordsPerPage);
$data['page']=$page;
$data['search_status']=$searchStatus;
$data['search_query']=$searchQuery;
$data['sort_by']=$sortBy;
$data['sort_type']=$sortType;
$data['search_param']=$searchParam;
$data['supplier_id']=$supplier_id;
$data['records_per_page'] = $recordsPerPage;
$data['supplier_data'] = $supplierData;
$data['brand_id']=$brandIds;
$data['cat_id']=$catIds;
$data['brand_data']= $brandData[$culture];
if(array_key_exists('status',$productData) && $productData['status'] == 'error' && is_array($productData))
{
$productSentData = array();
$data['error_message'] = $productData['error_message'];
}
else
{
if($productData['data']){
$data['total_product'] = $productData['count'];
$data['image_url'] = (array_key_exists('image_url',$productData)?$productData['image_url']:'');
$productSentData = $productData['data'];
}else{
$productSentData = array();
$data['error_message'] = $this->serviceContainer->get('translator')->trans("product.RECORD_NOT_FOUND");
}
}
$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture,'productData'=>$productSentData);
}
/**
* @author Employee Id: 5406
*
* Description : This function used for List Product Information
*
* @Route("/list-product-filtered-by-category/{productId}/{page}",
* name="officebrain_bundle_product_list_product_filtered_by_category_wo_culture",
* requirements={"records_per_page"="12|24|48|100|996", "page"="\d+"},
* defaults={"records_per_page"=20,"page"=1})
*
* @Route("/list-product-filtered-by-category/{productId}/{country}/{language}/{page}",
* name="officebrain_bundle_product_list_product_filtered_by_category",
* requirements={"records_per_page"="12|24|48|100|996","page"="\d+"},
* defaults={"records_per_page"=20,"page"=1})
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/listProductFilteredByCategory.html.twig")
*/
public function listProductFilteredByCategoryAction(Request $request, $productId){
$this->init($request);
list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
$param = $this->request->get('_route_params');
$culture = $this->request->get('language',$defaultCulture);
$country = $this->request->get('country',$defaultCountry);
$countryId = $this->serviceContainer->getParameter('country')[$country]['id'];
//echo $countryId= $this->country_;exit;
$activeCulture = $culture;
$searchStatus = $this->request->query->get('search_status', '');
$searchQuery = $this->request->query->get('search_query', '');
$sortBy = $this->request->query->get('sort', 'updatedAt');
$sortType = $this->request->query->get('direction', 'desc');
$searchParam = $this->request->query->get('search_param', '');
$supplier_id = $this->request->query->get('supplier_id','');
$brandIds = $this->request->query->get('brand_id','');
$catIds = $this->request->query->get('cat_id','');
$cultureCategory = $activeCulture . "_" . $country;
// select all of the category ids from categorymapping entity, where product id of entity matches the product id passed in request, and country id of entity matches the country id passed in request
// then using those category ids we will filter out the products and then we will show only the products coming in these specific categories
$productCategoryIds = $this->productApiManager->getCategoryIds($productId,$countryId);
$catIds = implode(",",$productCategoryIds);
//print_r($productCategoryIds);exit;
$comproductreletedid = $this->productApiManager->productreletedid($productId);
$productdetails = $this->productDetailManager->getProductDetailById($productId,$cultureCategory);
$product_title = $productdetails[$productId]['basic_information']['title'];
// For Pagination
$page = $this->request->get('page', '1');
$records_per_page = $param['records_per_page'];
$recordsPerPage = $this->request->query->get('recordsPerPage',$records_per_page);
$start_index = (($page - 1) * $recordsPerPage - 1);
// End Pagination
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
$instanceType = $projectSetting['instance_type'];
$productData = $this->productApiManager->listProduct($searchStatus,$searchParam, $searchQuery, $sortType, $sortBy,$activeCulture,$country,$supplier_id,$records_per_page,$page,$projectId,$brandIds,$catIds);
/* code for not showing the parent product in related products started */
if(isset($productData['data']))
{
$productIndex = 0;
foreach($productData['data'] as $singleProductDetail)
{
if(isset($singleProductDetail['product_master_id']))
{
if($singleProductDetail['product_master_id'] == $productId)
{
unset($productData['data'][$productIndex]);
//$productData['count'] = $productData['count'] - 1;
}
}
$productIndex++;
}
}
/* code for not showing the parent product in related products ended */
$supplierData = $this->productApiManager->getSupplierNameList($projectId);
$brandData = $this->brandApiManager->getList($culture);
//GET CATEGORY AND SUBCATEGORY
$categoryAndSubCategoryData = $this->categoryApiManager->getList(array($cultureCategory),array(),true);
$this->catArrayNew = array();
if ($categoryAndSubCategoryData) {
foreach($categoryAndSubCategoryData[$cultureCategory] as $catKey=>$categoryAndSubCategory){
$this->recursiveCategory($categoryAndSubCategory);
}
// Sort Category array using category name
usort($this->catArrayNew, function ($a, $b) {
return strcasecmp($a['cat_name'], $b['cat_name']);
});
}
$data['category_SubCategory_data'] = $this->catArrayNew;
$paginator = $this->serviceContainer->get('knp_paginator');
$data['pagination'] = $paginator->paginate($productData, $page, $recordsPerPage);
$data['page']=$page;
$data['search_status']=$searchStatus;
$data['search_query']=$searchQuery;
$data['sort_by']=$sortBy;
$data['sort_type']=$sortType;
$data['search_param']=$searchParam;
$data['supplier_id']=$supplier_id;
$data['records_per_page'] = $recordsPerPage;
$data['supplier_data'] = $supplierData;
$data['brand_id']=$brandIds;
$data['cat_id']=$catIds;
$data['brand_data']= $brandData[$culture];
$data['INSTANCE_TYPE'] = $instanceType;
if(array_key_exists('status',$productData) && $productData['status'] == 'error' && is_array($productData))
{
$productSentData = array();
$data['error_message'] = $productData['error_message'];
}
else
{
if($productData['data']){
$data['total_product'] = $productData['count'];
$data['image_url'] = (array_key_exists('image_url',$productData)?$productData['image_url']:'');
$productSentData = $productData['data'];
}else{
$productSentData = array();
$data['error_message'] = $this->serviceContainer->get('translator')->trans("product.RECORD_NOT_FOUND");
}
}
$data['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
return array('data'=>$data,'activeCountry' => $country, 'activeCulture'=>$activeCulture,'productData'=>$productSentData,'productId' => $productId,'comproductreletedid'=> $comproductreletedid,'product_title'=>$product_title);
}
/**
* EMp Id : 4246
* Description : This Function is Used For Update Product Status According To Parameter
*
* @Route("/change-relation-status/{country}/{set_status}",
* requirements = {"set_status"="1|0"},
* name="officebrain_product_change_relation_status")
*/
public function changeProductRelationStatusAction(Request $request){
$this->init($request);
$param=$this->request->get('_route_params');
$productId=$this->request->get('productId');
$setStatus=$this->request->get('set_status');
$relatedProductIds = array();
$relatedProductIds = $this->request->get('ids','');
$relatedProductIds = explode("::",$relatedProductIds);
$projectSetting = $this->request->get('project_setting');
$locale_language = $projectSetting['locale_language'];
//$productAdminManager = $this->get('office_brain_product_admin_manager');
if($setStatus == 1)
{
$productData = $this->productApiManager->insertRelatedProducts($productId,$relatedProductIds,$locale_language);
}
else if($setStatus == 0)
{
$productData = $this->productApiManager->deleteRelatedProducts($productId,$relatedProductIds,$locale_language);
}
$data = array();
$data['status'] = 'success';
$data['message'] = $this->translator->trans('product.PRODUCT_RELATION_UPDATED');
RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
return new JsonResponse($data);
}
/**
* Recursive function for category list
*
* @param array $catArray
*/
public function recursiveCategory($catArray){
if (array_key_exists("child",$catArray)) {
foreach($catArray['child'] as $subCatArray){
if (array_key_exists("child",$subCatArray)) {
foreach ($subCatArray['child'] as $leafCat) {
$this->recursiveCategory($leafCat);
}
}
else{
$this->catArrayNew[] = $subCatArray;
}
}
}
else {
$this->catArrayNew[] = $catArray;
}
}
public function deleteCache($productId=0,$culture)
{
if(!RedisCacheService::isCacheEnable())
{
return null;
}
$cacheClient=RedisCacheService::create(null,self::PRODUCT_CACHE_CLIENT);
//echo "===========$productId.':*'.$culture==========";
// $cacheClient->removeCacheByPrefix($productId.':*'.$culture);
}
/**
* @author Employee Id: 4808
*
* Description : This function used for Add Product Information
* @return array
* @Route("/add", name="officebrain_product_add"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/add.html.twig")
*/
public function addAction(Request $request){
$this->init($request);
$projectSetting = $this->request->get('project_setting');
$instanceType = $projectSetting['instance_type'];
$cultureName = $this->request->get('culture_name');
$master_product_id = $this->request->get('master_product_id', '');
$param = $this->request->get('_route_params');
$route = $this->request->get('_route');
$locale_language = $param['_locale'];
$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
$supplier_id = 0;
// set global_pricing_keys which are active
$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']).',';
}
}
}
//$supplierData = $this->productApiManager->getSupplierNameList($projectSetting['project_id']);
if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
$data = $this->request->request->all();
$data['valid_up_to']=str_replace('/','-',$data['valid_up_to']);
$data['special_price_valid_up_to']=str_replace('/','-',$data['special_price_valid_up_to']);
$data['pricing_valid_until']=str_replace('/','-',$data['pricing_valid_until']);
$data['pricing_valid_starting']=str_replace('/','-',$data['pricing_valid_starting']);
$data['master_product_id'] = $master_product_id;
$data['project_id'] = $projectSetting['project_id'];
$data['locale_language'] = $locale_language;
$data['instance_type'] = $projectSetting['instance_type'];
$data['instance_id'] = $projectSetting['instance_id'];
$data['thumb_width'] = $this->serviceContainer->getParameter('thumb_width');
$data['medium_thumb_width'] = $this->serviceContainer->getParameter('medium_thumb_width');
$apiResponse = $this->productApiManager->add($cultureName, $data);
if ($apiResponse['status']=='success') {
$response = array('form_status' => $apiResponse['status'],'success_message'=>$this->serviceContainer->get('translator')->trans($apiResponse['success_message']));
$this->session->set('product-list-success', $this->serviceContainer->get('translator')->trans($apiResponse['success_message']));
$actionPerformed = 'create';
if ($master_product_id) {
$actionPerformed = 'update';
/* Remove Cache Of Product Details Page */
$statsh_cache_wrapper = RedisCacheService::create();
$moduleCachePrefix = '__ProductDetailsPageOtherProducts';
RedisCacheService::removeCacheByPrefix($statsh_cache_wrapper,$moduleCachePrefix."*product_id#".$master_product_id);
/* EO: Remove Cache Of Product Details Page */
}
if($data['product_name']['en']!=$data['old_name']){
$this->deleteCache($apiResponse['master_product_id'],'en_us');
}
//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'); // symfony 4
$this->productApiManager->updateSolrData($apiResponse['master_product_id'],$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'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($master_product_id > 0)
{
$this->productDetailManager->updateSyncDetail($this->request->get('syncflag'),$data['sku']);
$asiurl = 'http://demoapi.officebrain.com/update_product_api.php?product_slug='.$slug;
}
else
{
$this->productDetailManager->insertSyncDetail($this->request->get('syncflag'),$data['sku']);
$asiurl = 'http://demoapi.officebrain.com/product_api.php?product_slug='.$slug;
}
//echo $asiurl;die;
exec("curl '$asiurl' > /dev/null &");
}
}
}
else
{
if($master_product_id > 0)
{
$this->productDetailManager->updateSyncDetail(0,$data['sku']);
}
else
{
$this->productDetailManager->insertSyncDetail(0,$data['sku']);
}
if(isset($data['sku']) && !empty($data['sku'])){
$asiurl = 'http://demoapi.officebrain.com/product_delete_api.php?product_sku='.$data['sku'];
exec("curl '$asiurl' > /dev/null &");
}
}
} else {
$response = array('form_status' => $apiResponse['status'],'error_message'=>$this->serviceContainer->get('translator')->trans($apiResponse['message']));
}
return new JsonResponse($response);
}
$data_to_set = $this->productApiManager->preSetDataForPlugin($projectSetting['configuration_rule']['product'],$projectSetting['project_id'],'',1);
$this->viewTwigData['plugin_data'] = $data_to_set['plugin_data'];
$this->viewTwigData['ATTR_TYPE_IDS'] = $this->serviceContainer->getParameter('attributes_types');
$this->viewTwigData['ATTR_IMPRINT_POSITION'] = $this->serviceContainer->getParameter('imprint_position_master_id');
$this->viewTwigData['ATTR_COLOR_ID'] = $this->serviceContainer->getParameter('color_attribute_id');
$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
$this->viewTwigData['form_method'] = 'add';
$this->viewTwigData['global_pricing_keys'] = trim($globalPricingKeys, ',');
$this->viewTwigData['INSTANCE_TYPE'] = strtolower($instanceType);
return $this->viewTwigData;
}
/**
* @author Employee Id: 4045
*
* Description : This function used to Edit Product Information
* @return array
* @Route("/edit/{master_product_id}", name="officebrain_product_edit"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/add.html.twig")
*/
public function editNewAction(Request $request){
$this->init($request);
$projectSetting = $this->request->get('project_setting');
$countryArray = $this->serviceContainer->getParameter('country');
$languageArray = $this->serviceContainer->getParameter('language');
$country_to_pass = array_column($countryArray,'short_name');
$language_to_pass = array_keys($languageArray);
$locale = $this->request->get('_locale',$this->serviceContainer->getParameter('locale'));
@list($default_language,$default_country) = explode("_",$locale);
$cultureName = $this->request->get('culture_name');
$masterProductId = $this->request->get('master_product_id', '');
$param = $this->request->get('_route_params');
$route = $this->request->get('_route');
$quoteId = $this->request->get('quote_id',0);
// set global_pricing_keys which are active
$globalPricingKeys = '';
$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
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']).',';
}
}
}
$productInfo = $this->productApiManager->editView($masterProductId,$language_to_pass,$country_to_pass,$default_language);
$syncentityobj= $this->productDetailManager->getSyncDetail($productInfo['en']['basic_information']['sku_number']);
//$supplierData = $this->productApiManager->getSupplierNameList($projectSetting['project_id']);
if(isset($syncentityobj))
{
$productInfo['syncflag']=$syncentityobj['isSync'];
}
else
{
$productInfo['syncflag']=0;
}
if(!count($productInfo)){
throw $this->createNotFoundException('The product does not exist');
}
$data_to_set = $this->productApiManager->preSetDataForPlugin($projectSetting['configuration_rule']['product'], $projectSetting['project_id'],$productInfo);
$this->viewTwigData['plugin_data'] = $data_to_set['plugin_data'];
$this->viewTwigData['ATTR_TYPE_IDS'] = $this->serviceContainer->getParameter('attributes_types');
$this->viewTwigData['ATTR_IMPRINT_POSITION'] = $this->serviceContainer->getParameter('imprint_position_master_id');
$this->viewTwigData['ATTR_COLOR_ID'] = $this->serviceContainer->getParameter('color_attribute_id');
$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
$this->viewTwigData['master_product_id'] = $masterProductId;
$this->viewTwigData['form_method'] = 'edit';
$this->viewTwigData['global_pricing_keys'] = trim($globalPricingKeys, ',');
return $this->viewTwigData;
}
/**
* @author: Employee Id : 4808
* Description: This Function is Related For Image Library
*
* @Route("/image-library",name="officebrain_product_image_library"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/imageLibrary.html.twig")
*/
public function imageLibraryAction(Request $request){
//TODO: need to get dynamic product once listing get done
$this->init($request);
$this->viewTwigData['data']=array('productId'=>1);
$mainErrorMessage='';
$isImageUploaded = false;
if ($this->request->getMethod() == "POST" ) {
$request = $request;
$fileData = $request->files->get("FileUpload");
$zipData = $request->files->get("zipUpload");
$fileUploadType = $request->get('FileUpload_type');
//TODO: need to get dynamic product once listing get done
$productId = 1;
$index = 0;
$imageArray = array();
foreach($fileData as $image){
foreach($image as $v){
if(!empty($v)){
$isImageUploaded = true;
break;
}
}
if($isImageUploaded) break;
}
if(!$isImageUploaded){
foreach($zipData as $image){
foreach($image as $v){
if(!empty($v)){
$isImageUploaded = true;
break;
}
}
if($isImageUploaded) break;
}
}
$mainErrorMessage='';
if(!$isImageUploaded){
$mainErrorMessage = $this->serviceContainer->get('translator')->trans('admin.image_template_library.select_files_error_msg');
}
$res = $this->productApiManager->uploadfiles($productId, $fileData,'image',$fileUploadType);
$error_file_upload = $res['error_file_upload'];
$res = $this->productApiManager->uploadfiles($productId, $zipData,'zip');
$error_file_upload_zip = $res['error_file_upload'];
}
$errMsg = '';
$successMsg = '';
if (!empty($error_file_upload) || !empty($error_file_upload_zip)) {
$errMsg = '<ul>';
$arrImgType = array('web' => 'Web', 'template' => 'Template', 'high_res' => 'High Res');
foreach ($arrImgType as $type => $files) {
if (isset($error_file_upload[$type]) || isset($error_file_upload_zip[$type])) {
$errMsg.="<li>" . $files . "<ul>\n";
if (isset($error_file_upload[$type])) {
foreach ($error_file_upload[$type] as $fileName => $error) {
$errMsg.="<li>" . $fileName . ":<i><b>" . $error . "</b></i></li>";
}
}
if (isset($error_file_upload_zip[$type])) {
foreach ($error_file_upload_zip[$type] as $fileName => $error) {
$errMsg.="<li>" . $fileName . ":<i><b>" . $error . "</b></i></li>";
}
}
$errMsg.="</ul></li>";
}
}
$errMsg.='</ul>';
}elseif($mainErrorMessage != '' ){
$errMsg = '<ul><li>'.$mainErrorMessage.'</li></ul>';
}elseif($isImageUploaded){
$successMsg = $this->serviceContainer->get('translator')->trans('admin.image_template_library.upload_succ');
}
return $this->viewTwigData;
}
/**
* @Route("/browse-product-image", name="OfficeBrainImageLibraryAdmin_browse_product_image", methods={"POST"})
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/browseProductImage.html.twig")
*/
public function browseProductImageAction(Request $request) {
$this->init($request);
$this->request = $request;
$productId = intval($this->request->get('id'));
$imageType = $this->request->get('type');
$data = $this->productApiManager->productImages($productId,$imageType);
$imageArray = array();
if($data){
if($imageType =='high_res'){
foreach($data as $image){
if(trim($image['fileType'])!='imprinted')
$imageArray['blank'][]=$image;
else
$imageArray['imprinted'][]=$image;
}
} else {
$imageArray = $data;
}
}
return array('imageArray' => $imageArray, 'imageType' => $imageType);
}
/**
* @Route("/remove-product-image",
* name="officebrain_image_library_admin_bundle_remove_product_image", methods={"GET","POST"}),
* @Template()
*/
public function removeProductImageAction(Request $request) {
$this->init($request);
$productId = $this->request->get('productId');
$imageType = $this->request->get('imageType');
$imageId = $this->request->get('imageId');
$result = $this->productApiManager->removeProductImage($productId,$imageId);
if ($result)
echo $this->serviceContainer->get('translator')->trans('admin.image_template_library.image_removed_succ');
else
echo $this->serviceContainer->get('translator')->trans('admin.image_template_library.image_removed_fail');
}
/**
* @author Employee Id: 4246
* Description : This function used for View Product Information
* @Route("/view",
* name="officebrain_product_view")
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/view.html.twig")
*/
public function viewAction(Request $request){
$this->init($request);
$product_culture = $this->request->get('product_culture');
$product_ids = $this->request->get('product_ids');
//$productAdminManager = $this->get('office_brain_product_admin_manager');
$productData = $this->productApiManager->view($product_ids,$product_culture,true);
$projectSetting = $this->request->get('project_setting');
$productAddSettings = $projectSetting['configuration_rule']['product']['add_update'];
if(array_key_exists('global_pricing', $productAddSettings))
{
foreach ($productAddSettings['global_pricing'] as $key => $val)
{
if ($val['status'] == 1)
{
$global_pricing_arr[$key] = 1;
}
}
}
$culture_id = $this->request->get('culture_id');
if(!count($productData)){
throw $this->createNotFoundException('The product does not exist');
}
if($productData['status'] == "success"){
$productInfo = $productData['data'];
if(array_key_exists('price_unit',$productInfo[$product_ids])){
$priceUnit = $this->serviceContainer->getParameter('price_unit');
$productInfo[$product_ids]['price_unit'] = array_key_exists(trim($productInfo[$product_ids]['price_unit']),$priceUnit)?$priceUnit[$productInfo[$product_ids]['price_unit']]:$productInfo[$product_ids]['price_unit'];
}
$this->viewTwigData['data'] = $productInfo[$product_ids];
}else{
$this->viewTwigData['error_message'] = $this->serviceContainer->get('translator')->trans('product.'.$productData['message']);
}
$this->viewTwigData['params_to_append'] = array_merge($this->request->get('_route_params'), $this->request->query->all());
$this->viewTwigData['global_pricing_arr'] = $global_pricing_arr;
return $this->viewTwigData;
}
/**
* @author Employee Id: 4246
* Description : This function used for Delete Product
* @Route("/delete",
* name="officebrain_product_delete")
*/
public function deleteAction(Request $request){
$this->init($request);
$product_master_id = $this->request->get('product_master_id');
$product_country = $this->request->get('product_country');
$projectSetting = $this->request->get('project_setting');
$project_id = $projectSetting['project_id'];
$locale_language = $projectSetting['locale_language'];
$supplier_id = $projectSetting['user_id'];
$instance_type = $projectSetting['instance_type'];
$instance_id = $projectSetting['instance_id'];
$productData = $this->productApiManager->delete($product_master_id, $project_id, $supplier_id, $locale_language, $instance_type, $instance_id, $product_country);
// Data Array Convert Object To Array
$productData['data'] = (array)$productData['data'];
if($productData['status'] == 'success'){
$data['status'] = 'success_message';
//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($product_master_id,$localization_to_update,$projectSetting['project_id'],$env,'delete');
}
//SOLR SYNC CODE END
// To Integrate with ERP
$erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
$dt = new \DateTime($productData['data']['deleted_at']);
$params = array('product_id' => $product_master_id, 'country_id' => $productData['data']['country_id'], 'deleted_at'=> $dt->format('Y-m-d H:i:s'));
$this->productApiManager->integrateWithErp($this->queueApiManager, 'remove', $product_master_id, $params);
}
}else{
$data['status'] = 'error_message';
}
$data['message'] = $this->translator->trans($productData['message']);
return new JsonResponse($data);
}
/**
* EMp Id : 4246
* Description : This Function is Used For Update Product Status According To Parameter
*
* @Route("/changestatus/{country}/{set_status}",
* requirements = {"set_status"="1|0"},
* name="officebrain_product_changestatus")
*/
public function changeProductStatusAction(Request $request){
$this->init($request);
$param=$this->request->get('_route_params');
$ids_to_pass = array();
$ids = $this->request->get('ids','');
$ids_to_pass = explode("::",$ids);
$productId = json_encode($ids_to_pass);
list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
$projectSetting = $this->request->get('project_setting');
$culture = $this->request->get('language',$defaultCulture);
$country = $this->request->get('country');
$setStatus = $this->request->get('set_status');
$cultureCategory = $culture. "_" . $country;
$project_id = $projectSetting['project_id'];
$locale_language = $projectSetting['locale_language'];
$supplier_id = $projectSetting['user_id'];
$instance_type = $projectSetting['instance_type'];
$instance_id = $projectSetting['instance_id'];
//$productAdminManager = $this->get('office_brain_product_admin_manager');
$productData = $this->productApiManager->changeProductStatus($productId,$country,$setStatus, $project_id, $supplier_id, $locale_language, $instance_type, $instance_id);
$data = array();
if($productData['status'] == 'success'){
//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');
// $solrProductManager = $this->serviceContainer->get('office_brain_solr_product_mapping_manager');
$solrProductManager = $this->solrService;
foreach($ids_to_pass as $product_id_to_process){
if(!$setStatus){
$this->productApiManager->updateSolrData($product_id_to_process,$localization_to_update,$projectSetting['project_id'],$env, $instance_id,'delete');
$productdetails = $this->productDetailManager->getProductDetailById($product_id_to_process,$cultureCategory);
if(strpos($productdetails[$product_id_to_process]['basic_information']['sku_number'], '-') != false && isset($productdetails[$product_id_to_process]['other_products'])){
$main_sku = $productdetails[$product_id_to_process]['basic_information']['sku_number'];
$main_sku = explode('-', $main_sku); // get main sku
$mainSku = $main_sku[1];
if(isset($productdetails[$product_id_to_process]['other_products']) && is_array($productdetails[$product_id_to_process]['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($productdetails[$product_id_to_process]['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{
$productdetails[$product_id_to_process]['other_products'] = null;
}
// Update other Products
if(isset($productdetails[$product_id_to_process]['other_products']) && !empty($productdetails[$product_id_to_process]['other_products'])){
foreach($productdetails[$product_id_to_process]['other_products'] as $otherProduct){
if( $otherProduct['id'] == $product_id_to_process ){
$this->productApiManager->updateSolrData($otherProduct['id'],$localization_to_update,$projectSetting['project_id'],$env, $instance_id,'delete');
}
else{
$this->productApiManager->updateSolrData($otherProduct['id'],$localization_to_update,$projectSetting['project_id'],$env, $instance_id,'update');
}
}
}
}
// update main sku
// if($productdetails[$product_id_to_process]['basic_information']['sku_number']){
// $sku_split = explode('-',$productdetails[$product_id_to_process]['basic_information']['sku_number']);
// if(count($sku_split) == 2){
// $productDetailArray =$this->productDetailManager->getProductDetailBySku($sku_split[1],$productdetails[$product_id_to_process]['supplier']['supplier_id'],$cultureCategory);
// $this->productApiManager->updateSolrData($productDetailArray['product_id'],$localization_to_update,$projectSetting['project_id'],$env,'update');
// }
// }
}else{
$this->productApiManager->updateSolrData($product_id_to_process,$localization_to_update,$projectSetting['project_id'],$env, $instance_id,'update');
$productdetails = $this->productDetailManager->getProductDetailById($product_id_to_process,$cultureCategory);
// Update other Products
if(strpos($productdetails[$product_id_to_process]['basic_information']['sku_number'], '-') != false && isset($productdetails[$product_id_to_process]['other_products'])){
$main_sku = $productdetails[$product_id_to_process]['basic_information']['sku_number'];
$main_sku = explode('-', $main_sku); // get main sku
$mainSku = $main_sku[1];
if(isset($productdetails[$product_id_to_process]['other_products']) && is_array($productdetails[$product_id_to_process]['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($productdetails[$product_id_to_process]['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{
$productdetails[$product_id_to_process]['other_products'] = null;
}
}
if(isset($productdetails[$product_id_to_process]['other_products']) && !empty($productdetails[$product_id_to_process]['other_products'])){
$index = 1;
$isFound = 0;
$operation = 'update';
foreach($productdetails[$product_id_to_process]['other_products'] as $otherProduct){
if($index == 1 && $otherProduct['id'] == $product_id_to_process){
$isFound = 1;
$operation = 'update';
}
elseif( $index > 1 && $otherProduct['id'] == $product_id_to_process){
$isFound = 1;
$operation = 'delete';
}
elseif($isFound == 1){
$operation = 'delete';
}
else{
$operation = 'update';
}
$this->productApiManager->updateSolrData($otherProduct['id'],$localization_to_update,$projectSetting['project_id'],$env, $instance_id,$operation);
if($operation == 'delete'){
$this->productApiManager->updateSolrData($otherProduct['id'],$localization_to_update,$projectSetting['project_id'],$env, $instance_id,'update');
}
$index++;
}
}
// if($productdetails[$product_id_to_process]['basic_information']['sku_number']){
// $sku_split = explode('-',$productdetails[$product_id_to_process]['basic_information']['sku_number']);
// if(count($sku_split) == 2){
// $productDetailArray =$this->productDetailManager->getProductDetailBySku($sku_split[1],$productdetails[$product_id_to_process]['supplier']['supplier_id'],$cultureCategory);
// $this->productApiManager->updateSolrData($productDetailArray['product_id'],$localization_to_update,$projectSetting['project_id'],$env,'update');
// }
// }
}
}
}
//SOLR SYNC CODE END
// To Integrate with ERP
$productIds = json_decode($productId);
$erpIntegration = $projectSetting['configuration_rule']['erp_integration'];
if($erpIntegration && $erpIntegration['productManagement'] == 1 && !empty($this->queueApiManager)) {
foreach ($productData['data'] as $key => $value) {
$params = array('product_id' => $productIds[$key], 'country_id' => $value['countryId'],'status'=> $setStatus);
$this->productApiManager->integrateWithErp($this->queueApiManager, 'updateStatus', $productIds[$key], $params);
}
}
$data['status'] = 'success';
RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
}else{
$data['status'] = 'error';
}
$data['message'] = $this->translator->trans('product.'.$productData['message']);
return new JsonResponse($data);
}
/**
* EMp Id : 4246
* Description : This Function is Used For Update Product Status According To Parameter
*
* @Route("/check-duplicate-sku",
* name="officebrain_product_check_duplicate_sku")
*/
public function checkDuplicateSKU(Request $request){
$this->init($request);
$sku = $this->request->get('sku');
$supplierId = $this->request->get('supplier_id');
$productId = $this->request->get('product_id','');
$data = $this->productApiManager->checkDuplicateSKU($sku,$supplierId,$productId);
$data['message'] = $this->translator->trans('product.'.$data['message']);
return new JsonResponse($data);
}
/**
* @author Employee Id: 5190
* Description : This function used for List Matrix Information
* @Route("/matrix/list",
* name="officebrain_product_matrix_list")
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/listMatrix.html.twig")
*/
public function listMatrixAction(Request $request){
$this->init($request);
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
$data['matrix_data'] = $this->productApiManager->getMatrixList($projectId);
return array('data'=>$data);
}
/**
* @author Employee Id: 5540
*
* Description : This function used to Edit Product Information
* @return array
* @Route("/copy/{master_product_id}/{supplier_id}", name="officebrain_product_copy"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/add.html.twig")
*/
public function copyProductAction(Request $request)
{
//$this->init($request);
$supplierId = $request->get('supplier_id');
$productId = $request->get('master_product_id','');
$projectSetting = $request->get('project_setting');
// $returnData = $this->serviceContainer->get("office_brain_product_admin_manager")->copy($supplierId, $productId);
$returnData = $this->productApiManager->copy($supplierId, $productId);
$returnData = array('status' => 'success');
/*
//SOLR SYNC CODE START
$is_solr_syn_enabled = $this->container->getParameter('solr_sync');
if($is_solr_syn_enabled)
{
$env = $this->container->getParameter("kernel.environment");
$localization_to_update = $this->container->getParameter('localization_to_fetch');
$this->get("office_brain_product_admin_manager")->updateSolrData($newProductId,$localization_to_update,$projectSetting['project_id'],$env,$projectSetting['instance_id'],'update');
}
//SOLR SYNC CODE END
*/
if($returnData['status'] == 'success')
{
$data['status'] = 'success_message';
$data['message'] = $this->serviceContainer->get('translator')->trans('product_add_edit.product_copied_successfully');
}
else
{
$data['status'] = 'error_message';
$data['message'] = $this->serviceContainer->get('translator')->trans('product_add_edit.product_not_copied');
}
return new JsonResponse($data);
}
/**
* @author Employee Id: 5190
*
* Description : This function used for Export Product data culture and country wise
* @return array
* @Route("/export", name="officebrain_product_export"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/export.html.twig")
*/
public function exportAction(Request $request)
{
$this->init($request);
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
$culture = $this->request->get('language',$defaultCulture);
$country = $this->request->get('country',$defaultCountry);
$supplier_id = $this->request->query->get('supplier_id','');
$countryArray = $this->serviceContainer->getParameter('country');
$languageArray = $this->serviceContainer->getParameter('language');
$supplierData = $this->productApiManager->getSupplierNameList($projectId);
$instanceType = $projectSetting['instance_type'];
// if ($this->user->getUserType()=='admin' && $instanceType=='association'){ // symfony 4
if ($this->user && $this->user->getUserType()=='admin' && $instanceType=='association'){
$supplier_id = $this->request->query->get('supplier_id','');
// } else if($this->user && $this->user->getUserType()=='supplier' || $this->user->getUserType()=='distributor' || ($this->user->getUserType() == 'admin' && $instanceType == 'distributor') || ($this->user->getUserType() == 'admin' && $instanceType == 'supplier')){ // symfony 4
} elseif ($this->user && (
$this->user->getUserType() == 'supplier' ||
$this->user->getUserType() == 'distributor' || (
$this->user->getUserType() == 'admin' && (
$instanceType == 'distributor' ||
$instanceType == 'supplier'
)
)
) ) {
$supplier_id = $this->user->getObCustomerId();
$supplier_id = str_replace(array('OB','ob'), '', $supplier_id);
if(empty($supplier_id)){
$supplier_id = 0;
}
}else{
$supplier_id = 0;
}
foreach($countryArray as $countryKey => $country){
$data['country_data'][] = array('id'=>$country['id'],'code'=>$country['short_name'],'title'=>$country['name'],'language'=>$country['language']);
}
if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
$data = $this->request->request->all();
$apiResponse = $this->productApiManager->getExportProduct($data);
return new JsonResponse($apiResponse);
}
$data['project_id']= $projectId;
$data['country_array'] = $countryArray;
$data['language_data'] = $languageArray;
$data['supplier_data'] = $supplierData;
$data['INSTANCE_TYPE'] = $instanceType;
$data['supplier_id']=$supplier_id;
return array('data'=>$data);
}
/**
* @author Employee Id: 5190
*
* Description : This function used for Import Product data supplier, culture and country wise
* @return array
* @Route("/import", name="officebrain_product_import"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/import.html.twig")
*/
public function importAction(Request $request){
$this->init($request);
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
$culture = $this->request->get('language',$defaultCulture);
$country = $this->request->get('country',$defaultCountry);
$supplier_id = $this->request->query->get('supplier_id','');
//echo $supplier_id;die;
$countryArray = $this->serviceContainer->getParameter('country');
$languageArray = $this->serviceContainer->getParameter('language');
$supplierData = $this->productApiManager->getSupplierNameList($projectId);
$instanceType = $projectSetting['instance_type'];
if ($this->user && $this->user->getUserType()=='admin' && $instanceType=='association'){
$supplier_id = $this->request->query->get('supplier_id','');
// } else if($this->user->getUserType()=='supplier' || $this->user->getUserType()=='distributor' || ($this->user->getUserType() == 'admin' && $instanceType == 'distributor') || ($this->user->getUserType() == 'admin' && $instanceType == 'supplier')){ // symfony 4
} elseif ($this->user && (
$this->user->getUserType() == 'supplier' ||
$this->user->getUserType() == 'distributor' || (
$this->user->getUserType() == 'admin' && (
$instanceType == 'distributor' ||
$instanceType == 'supplier'
)
)
) ) {
$supplier_id = $this->user->getObCustomerId();
$supplier_id = str_replace(array('OB','ob'), '', $supplier_id);
if(empty($supplier_id)){
$supplier_id = 0;
}
}else{
$supplier_id = 0;
}
foreach($countryArray as $countryKey => $country){
$data['country_data'][] = array('id'=>$country['id'],'code'=>$country['short_name'],'title'=>$country['name'],'language'=>$country['language']);
}
if ($this->request->isXmlHttpRequest() && $this->request->getMethod()=='POST') {
$uploadImportFilePath = $this->serviceContainer->getParameter('tmp_image_upload_path');;
$allwedImportFileMimeType = $this->serviceContainer->getParameter('allowed_import_file_mime_type');
$translator = $this->serviceContainer->get('translator');
//echo $uploadImportFilePath;die;
if(!IS_DIR($uploadImportFilePath)){
mkdir($uploadImportFilePath,0777,true);
}
$importFileName = '';
$error = false;
$supplierId = $this->request->get('supplier_id','');
$countryId = $this->request->get('country_id','');
$cultureId = $this->request->get('culture_id','');
$userId = $this->userId;
//echo $supplierId.'---'.$countryId.'---'.$cultureId.'--'.$userId;die;
if(!empty($_FILES) && $countryId >0 && $cultureId >0 && $supplierId>0){
foreach($_FILES as $file)
{
$filename = $file['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if($extension != 'xls'){
$error = true;
$error_message = $translator->trans('product_import_export.allowed_import_file_type');
}
if(!$error){
$importFileName = "import_supplierid_".$supplierId."_countryid_".$countryId."_cultureid_".$cultureId."_".time().".".$extension;
$uploadImportFile = $uploadImportFilePath.$importFileName;
$file_moved = @move_uploaded_file($file['tmp_name'], $uploadImportFile);
if($file_moved){
$response = $this->productApiManager->uploadImportFile($supplierId,$countryId,$cultureId,$projectId,$uploadImportFile,$uploadImportFilePath, $userId);
if($response['status'] == 'success'){
if(file_exists($uploadImportFile)){
@unlink($uploadImportFile);
}
$error = false;
$success_message = $translator->trans('product_import_export.import_process_start');
}
else{
$error = true;
$error_message = $translator->trans('product_import_export.file_upload_error_message');
}
}
else {
$error = true;
$error_message = $translator->trans('product_import_export.file_upload_error_message');
}
}
}
}
else{
$error = true;
$error_message = $translator->trans('product.file_not_found'); //"Please select file" ;
}
if(!$error){
$return = array (
'status' => 'success',
'success_message'=> $success_message,
);
} else {
$return = array (
'status' => 'error',
'error_message' => $error_message);
}
return new JsonResponse($return);
}
$data['country_array'] = $countryArray;
$data['language_data'] = $languageArray;
$data['supplier_data'] = $supplierData;
$data['INSTANCE_TYPE'] = $instanceType;
$data['supplier_id']=$supplier_id;
return array('data'=>$data);
}
/**
* @author Employee Id: 5190
*
* Description : This function used for Import Product data supplier, culture and country wise
* @return array
* @Route("/check_import_status", name="officebrain_product_check_import_status"),
* options={"expose"=true},
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/checkImportStatus.html.twig")
*/
public function checkImportStatusAction(Request $request){
$this->init($request);
$supplierId = $request->get('supplier_id');
$projectSetting = $this->request->get('project_setting');
$projectId = $projectSetting['project_id'];
$returnData = $this->productApiManager->checkImportStatus($supplierId,$projectId);
return array('data'=>$returnData);
}
/**
* @author Employee Id: 5190
*
* Description : This function used for add inventory message sku colour wise
* @return array
* @Route("/get-inventory-message/{sku}", name="officebrain_product_add_inventory_message"),
* options={"expose"=true},
*/
public function addInventoryMessageAction(Request $request){
$this->init($request);
$sku = $request->get('sku');
$data = json_encode(array('message'=>'','sku'=>$sku));
$obj = $this->productApiManager->getInvMessageBySku($sku);
//var_dump($obj); die;
if(count($obj)>0){
$data = json_encode(array('message'=>$obj[0]->getMessage(),'sku'=>$obj[0]->getProductSku()));
}
echo $data;
die;
//$this->productApiManager;
}
/**
* @author Employee Id: 5190
*
* Description : This function used for add inventory message sku colour wise
* @return array
* @Route("/add-inventory-message", name="officebrain_product_update_inventory_message"),
* options={"expose"=true},
*/
public function updateInventoryMessageAction(Request $request){
$this->init($request);
$parameters = $request->request->all();
/*if($parameters['inv_message']==""){
$data = json_encode(array('status'=>'error_message','message'=>'Enter Message'));
}else{*/
$object = null;
$message = $parameters['inv_message'];
$sku = $parameters['inv_sku'];
$obj = $this->productApiManager->getInvMessageBySku($sku);
if(count($obj)>0){
$object = $obj[0];
}
$this->productApiManager->updateMessage($object,$message,$sku);
$data = json_encode(array('status'=>'success_message','message'=>'Message added successfully'));
//}
echo $data;
die;
}
/**
* @author Employee Id: 5190
*
* Description : This function used for get importErrorLog using importId.
* @return array
* @Route("/import_error_log/{import_id}", name="officebrain_product_import_error_log"),
* @Template("")
*/
public function importErrorLogAction(Request $request){
$this->init($request);
$importId = $request->get('import_id');
$returnData = $this->productApiManager->importErrorLog($importId);
$filename = "import_error_log_" . $importId.".csv";
$response = $this->render('OfficeBrain/Bundle/ProductBundle/ProductAdmin/importErrorLog.csv.twig',array('data' => $returnData));
//$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
//$response->sendHeaders();
//$response->sendContent();
return $response;
//return array('data'=>$returnData);
}
/**
* @Route("/suggestedProduct/{id}",
* name="officebrain_product_bundle_get_suggested_product",
* options={"expose"=true}, methods={"GET"})
*/
public function getSuggestedProductByProductIdAction(Request $request, $id){
$this->init($request);
$data = $this->productApiManager->getSuggestedProductByProductId($id);
return new JsonResponse($data);
}
/**
* @Route("/suggestedProduct/{id}",
* name="officebrain_product_bundle_set_suggested_product",
* options={"expose"=true}, methods={"POST"})
*/
public function setSuggestedProductByProductIdAction(Request $request, $id){
$this->init($request);
$pmsId = $id;
$productsSku = $this->request->get('products_sku');
// $products =
$api_manager = $this->serviceContainer->get('officebrain_category_api_manager');
$data = $this->productApiManager->setSuggestedProductByProductId($pmsId,$productsSku);
$data['message'] = $this->translator->trans($data['message']);
return new JsonResponse($data);
}
/**
* @author Employee Id: 5429
*
* Description : This function used for add inventory message sku colour wise
* @return array
* @Route("/get-rsync-status/{sku}/{slug}", name="officebrain_product_rsync_check"),
* options={"expose"=true},
*/
public function getRsyncStatusAction(Request $request){
$this->init($request);
$sku = $request->get('sku');
$slug = $request->get('slug');
$this->productDetailManager->updateSyncDetail(1,$sku);
//$asiurl = 'http://demoapi.officebrain.com/update_product_api.php?product_slug=16-oz-victory-acrylic-tumbler-with-straw-lid-full-color-digital';
//$result = exec("curl '$asiurl' > /dev/null &",$output,$return_val);
$asiurl = 'https://demoapi.officebrain.com/update_product_api.php?product_slug='.$slug;
//$asiurl = 'http://demoapi.officebrain.com/update_product_api.php?product_slug=halcyon-r-waterproof-wireless-speaker-full-color-digital';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $asiurl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_SSL_VERIFYPEER =>0
));
$response = curl_exec($curl);
if (curl_errno($curl)) {
echo $error_msg = curl_error($curl); die;
}
curl_close($curl);
echo $response;
/* $result = exec("curl '$asiurl' 2>&1 &", $output);
if(isset($output[3]) && $output[3]!=''){
$msg = json_decode($output[3]);
$reason = $msg->Errors[0]->Reason;
$data = json_encode(array('status'=>'success_message','message'=>'Reason:'.$reason));
}else{
$data = json_encode(array('status'=>'success_message','message'=>'Product Sync Successfully'));
}*/
// echo $data;
die;
}
/**
* @author Employee Id: 5429
*
* Description : This function used for add imprint method on skus
* @return array
* @Route("/imprint-skus", name="officebrain_imprint_skus_product"),
* @Template("OfficeBrain/Bundle/ProductBundle/ProductAdmin/getImprintSkus.html.twig")
*/
public function getImprintSkusAction(Request $request){
$searchParameters = array();
// $productTagManager = $this->serviceContainer->get('office_brain_product_tag_manager');
$productTagManager = $this->productTagManager;
if(!empty($_REQUEST['sku']) && $_REQUEST['sku']!=""){
$culture = $request->get('_locale','en_us');
// $productDetailManager = $this->serviceContainer->get('office_brain_product_detail_manager');
$productDetailManager = $this->productDetailManager;
$productObj = $productDetailManager->getProductDetailBySku($_REQUEST['sku'], 5,$culture,false);
if(isset($productObj['product_id'])){
$data['product_id'] = $productObj['product_id'];
$data['imprint'] = $_REQUEST['imprint'];
$data['sku'] = $productObj['basic_information']['sku_number'];
$data['product_title'] = $productObj['basic_information']['title'];
$data['product_image'] = $productObj['basic_information']['default_image_thumb_url'];
$productImprint = $productTagManager->getImprintProductByIdAndMethod($data['product_id'],$data['imprint']);
if($productImprint==NULL){
$productTagManager->addImprintProduct($data);
//SOLR SYNC CODE START
// $productApiManager = $this->serviceContainer->get("office_brain_product_admin_manager");
$productApiManager = $this->productApiManager;
$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');
$productApiManager->updateSolrData($data['product_id'],$localization_to_update,5,$env,'update');
}
//SOLR SYNC CODE END
$this->get('session')->getflashbag()->add('success_message', 'Sku mapped successfully.');
}else{
$this->get('session')->getflashbag()->add('error_message', 'Sku already mapped.');
return $this->redirect($this->generateUrl('officebrain_imprint_skus_product'));
}
}
}
$searchParameters['search_result_array']['data'] = $productTagManager->getAllImprintProducts();
// $this->arrayToPaginationManager = $this->serviceContainer->get('office_brain_array_to_pagination_manager');
$this->arrayToPaginationManager = $this->arrayToPaginationManager;
if(!empty($searchParameters['search_result_array'])){
$this->arrayToPaginationManager->setPaginationArray($searchParameters['search_result_array']);
$this->arrayToPaginationManager->doConvert();
$searchParameters['pagination'] = $this->arrayToPaginationManager->getPagination();
}
return $searchParameters;
}
/**
* @author Employee Id: 5429
*
* Description : This function used for add imprint method on skus
* @return array
* @Route("/remove-imprint-skus/{id}", name="officebrain_product_remove_imprint_skus"),
*/
public function removeImprintSkusAction(Request $request){
$id = $request->get('id');
$productTagManager = $this->productTagManager;
$prodData = $productTagManager->getImprintProductById($id);
if($prodData!=NULL){
$productId = $prodData->getProductId();
$productTagManager->deleteImprintProductById($prodData);
//SOLR SYNC CODE START
// $productApiManager = $this->serviceContainer->get("office_brain_product_admin_manager");
$productApiManager = $this->productApiManager;
$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');
$productApiManager->updateSolrData($productId,$localization_to_update,5,$env,'update');
}
//SOLR SYNC CODE END
$this->get('session')->getflashbag()->add('success_message', 'Record deleted successfully.');
}else{
$this->get('session')->getflashbag()->add('error_message', 'no record found');
}
return $this->redirect($this->generateUrl('officebrain_imprint_skus_product'));
}
}