<?php
namespace App\Controller\API;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RequestStack;
use Pimcore\Translation\Translator;
use App\Validator\Validator;
use Pimcore\Model\DataObject\Solution;
use Pimcore\Model\DataObject\News;
use Knp\Component\Pager\PaginatorInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use App\Services\SolutionServices;
use Pimcore\Model\DataObject\Category;
use Pimcore\Model\DataObject\FilterDefinition;
use App\Helper\ObjectJson;
use App\Services\AuthServices;
use Pimcore\Model\DataObject\Request as ObjectRequest;
use Pimcore\Model\DataObject\Review;
use Pimcore\Model\Asset\Service as AssetService;
use Pimcore\Model\DataObject\Service as DataObjectService;
use Pimcore\Tool;
use App\Services\ReviewServices;
use Pimcore\Model\DataObject\FAQ;
use App\Services\VoucherService;
/**
* @Route("/api")
*/
class SolutionController extends BaseController
{
const SOLUTION_PAGE_DEFAULT = 1;
const SOLUTION_PERPAGE_DEFAULT = 10;
const SOLUTION_CLASS_NAME = 'Solution';
private $request;
private $validator;
private $translator;
public function __construct(RequestStack $requestStack, Validator $validator, Translator $translator)
{
$this->request = $requestStack->getCurrentRequest();
$this->validator = $validator;
$this->translator = $translator;
}
/**
* @Route("/solutions", name="api-solutions", methods={"GET"})
*/
public function listing(Request $request,ListHelper $listHelper,PaginatorInterface $paginator)
{
$messageError = $this->validator->validate([
'page' => $this->request->get('page') ? 'numeric|positive' : '',
'limit' => $this->request->get('limit') ? 'numeric|positive' : ''
], $request);
if ($messageError) return $this->sendError($this->translator->trans($messageError));
$params = array_merge($request->query->all(), $request->attributes->all());
$solutions = Factory::getInstance();
$indexService = $solutions->getIndexService();
$solutionsListing = $indexService->getProductListForCurrentTenant();
$solutionsListing->addCondition("o_classId ='solution'");
if (!empty($this->request->get('search')))
$solutionsListing->addCondition("text LIKE '%" . $this->request->get('search') . "%'");
if (!empty($this->request->get('email')))
$solutionsListing->addCondition("email LIKE '%" . $this->request->get('email') . "%'");
if (!empty($this->request->get('provider')) && $this->request->get('type') == "hiddenFilter")
$solutionsListing->addRelationCondition('provider', "dest IN (" . $this->request->get('provider') . ")");
$defaultOrderBy = $request->get('order_by') ?? 'text';
$defaultOrder = $request->get('order') ?? 'desc';
$njOrderKey = $defaultOrderBy . ' ' . $defaultOrder;
$solutionsListing->setOrderKey($njOrderKey, false);
$parentCategoryId = (int) $request->get('parentCategoryIds');
$parentCategory = Category::getById($parentCategoryId);
$rootCategory = Category::getByRoot(true, 1);
$category = $parentCategory ?? $rootCategory;
//get filter definition from document, category or global settings
$filterDefinition = $category->getFilter() ?? ($category->getParent() instanceof Category ? $category->getParent()->getFilter() : Category::getByRoot(true, 1)->getFilter());
$filters = [];
if ($this->request->get('type') != "hiddenFilter") {
if ($filterDefinition instanceof FilterDefinition) {
$filterList = $filterDefinition->getFilters();
$messageError = $this->validator->validate(SolutionServices::validatorFilterDefinition($filterList, $request), $request);
if ($messageError) return $this->sendError($this->translator->trans($messageError));
// create and init filter service
$filterService = $solutions->getFilterService();
$listHelper->setupProductList($filterDefinition, $solutionsListing, $params, $filterService, true);
$filters = SolutionServices::getFilterDefinition($filterList, $filterService, $solutionsListing, $params, $this->translator);
}
}
$paginator = $paginator->paginate(
$solutionsListing,
$request->get('page', self::SOLUTION_PAGE_DEFAULT),
$request->get('limit', self::SOLUTION_PERPAGE_DEFAULT),
);
$data = [];
$hiddenFields = [
'code', 'community', 'isPriority', 'segment', 'photos', 'video', 'documents', 'pricing',
'features', 'deployment', 'interactive', 'support', 'training', 'freeTrial', 'freeTrialDays', 'freeVersion', 'action', 'banner'
];
$solutionIdArr = [];
foreach ($paginator as $solution) {
$dataJson = ObjectJson::getJson($solution, $hiddenFields);
$solutionIdArr[] = $dataJson['id'];
$dataJson['totalScore'] = ReviewServices::totalStar($dataJson['id']);
array_push($data, $dataJson);
}
$data = VoucherService::getVoucherSolution($solutionIdArr, $data);
return $this->sendResponse([
'data' => $data,
'paginator' => $paginator->getPaginationData(),
'filter' => $filters
]);
}
/**
* @Route("/solution/{id}", requirements={"id"="\d+"}, methods={"GET"})
*/
public function detailAction($id, Request $request)
{
$messageError = $this->validator->validate([
'id' => 'required',
], $request);
if ($messageError) return $this->sendError($this->translator->trans($messageError));
$solution = Solution::getById($id);
if($solution){
$liked = false;
$followed = false;
if($request->headers->has('Authorization')){
$token = $request->headers->get('Authorization');
$user = AuthServices::getUserByToken($token);
if ($user) {
foreach ($user->getLikeSolution() as $solutions) {
if ($solutions->getId() == $id) {
$liked = true;
break;
}
}
foreach ($user->getFollowSolution() as $solutions) {
if ($solutions->getId() == $id) {
$followed = true;
break;
}
}
}
}
$solution->setTotalView($solution->getTotalView()+1);
if($solution->save()){
$detail = $solution ? ObjectJson::getJson($solution,['features']) : [];
// get features solution
$data=[];
$i=0;
$hiden=['category','parent_id','code'];
foreach($solution->getFeatures() as $key=>$value){
if($value->getCategory()){
$data[$value->getId()]=ObjectJson::getJson($value,$hiden);
$i++;
}
}
foreach($solution->getFeatures() as $value){
if(!$value->getCategory()){
if (array_key_exists($value->getParent()->getId(), $data)) {
$data[$value->getParent()->getId()]['children'][] =ObjectJson::getJson($value,$hiden);
}
}
}
$datafeatures=[];
$i=0;
foreach($data as $key=>$value){
$datafeatures[]=$value;
$i++;
}
$faq = FAQ::getBySolution($solution);
$detail['totalFAQ'] = $faq->count();
$detail['features']= $datafeatures;
$detail['totalScore']=ReviewServices::totalStar($detail['id']);
$detail['liked'] = $liked;
$detail['followed'] = $followed;
$detail = VoucherService::getVoucherSolution([$detail['id']], [$detail]);
return $this->sendResponse(['data' => $detail[0]]);
}
}
return $this->sendError($this->translator->trans('solution.not.exist'));
}
// /**
// * @Route("/solution/review", name="api-solution-review-listing", methods={"GET"})
// */
// public function review(Request $request, PaginatorInterface $paginator){
// $data = [];
// $response= [];
// try {
// $page = $request->get('page');
// $limit = $request->get('limit');
// $order_by = $request->get('order_by');
// $order = $request->get('order');
// $star = $request->get('star')*2;
// $messageError = $this->validator->validate([
// 'solution' => 'required',
// // 'role'=> 'choiceArray:technical_support,data_engineer,consultant,ceo,admin,normal_user',
// // 'user'=> 'choiceArray:personal,business',
// // 'star'=> 'choice:1,2,3,4,5',
// 'page' => $page ? 'numeric|positive' : '',
// 'limit' => $limit ? 'numeric|positive' : '',
// 'order_by' => $order_by ? 'choice:title' : '',
// 'order' => $order ? 'choice:desc,asc' : '',
// ], $request);
// if ($messageError) return $this->sendError($this->translator->trans($messageError));
// if(empty($page)) $page = 1;
// if(empty($limit)) $limit = 10;
// if(empty($order_by)) $order_by = 'title';
// if(empty($order)) $order = 'desc';
// $listing = new Review\Listing();
// $listing->addConditionParam("solution__id =".$request->get('solution'));
// if(!empty($request->get('role'))&& is_array($request->get('role'))){
// foreach ($request->get('role') as $key => $value) {
// if(!empty($value)) $listing->addConditionParam("role LIKE '%".$value."%'");
// }
// }
// if(!empty($request->get('star'))) $listing->addConditionParam("generalScore =".$star." OR generalScore =".$star-1);
// if(!empty($request->get('checkImage'))) $listing->addConditionParam("checkImage =".$request->get('checkImage'));
// if(!empty($request->get('user'))&& is_array($request->get('user'))){
// foreach($request->get('user') as $value){
// if(!empty($value)) $listing->addConditionParam("purpose LIKE '%".$value."%'");
// }
// }
// if(!empty($request->get('search'))) $listing->addConditionParam("title LIKE '%".$request->get('search')."%'");
// $listing->setOrderKey($order_by);
// $listing->setOrder($order);
// if ($page && $limit) {
// $pagination = $paginator->paginate(
// $listing,
// $page,
// $limit,
// );
// }
// foreach ($listing as $review) {
// // $data[] = $news->getJson();
// $dataJson = ObjectJson::getJson($review,['solution']);
// array_push($data, $dataJson);
// }
// $response['data'] = $data;
// $response['paginator'] = $pagination->getPaginationData();
// } catch (\Throwable $e) {
// return $this->sendError($e->getMessage(), 500);
// }
// return $this->sendResponse($response);
// }
/**
* @Route("/solution/share", methods={"POST"})
*/
public function share()
{
$messageError = $this->validator->validate([
'solution' => 'required'
], $this->request);
if ($messageError) return $this->sendError($this->translator->trans($messageError));
$solution = Solution::getById($this->request->get("solution"));
if ($solution) {
$solution->setTotalShare($solution->getTotalShare() + 1);
$solution->save();
return $this->sendResponse([
'message' => $this->translator->trans('solution.share.success'),
'status' => 1
]);
}
return $this->sendResponse([
'message' => $this->translator->trans('solution.not.found'),
'status' => 0
]);
}
/**
* @Route("/solution/relate-blog/{id}", methods={"GET"})
*/
public function relateBlog(Request $req)
{
$messageError = $this->validator->validate([
'id' => 'required',
], $req);
if ($messageError) return $this->sendError($this->translator->trans($messageError));
$list = new News\Listing();
$list->addConditionParam("solution__id = ?", $req->get('id'));
$list->setLimit(3);
$list->setOrder('desc');
$list->setOrderKey('o_creationDate');
$data = [];
foreach ($list as $news) {
$data[] = ObjectJson::getJson($news);
}
return $this->sendResponse($data);
}
}