<?php declare(strict_types=1);
namespace KmPitchPrint\Controller;
use KmPitchPrint\Services\ProductPitchPrintService;
use PhpParser\Node\Expr\AssignOp\Mul;
use PHPUnit\Util\Json;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Cart\Error\Error;
use Shopware\Core\Checkout\Cart\LineItemFactoryRegistry;
use Shopware\Core\Content\Product\Exception\ProductNotFoundException;
use Shopware\Core\Content\Seo\SeoUrlPlaceholderHandlerInterface;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Controller\StorefrontController;
use Shopware\Storefront\Framework\Routing\RequestTransformer;
use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoader;
use Shopware\Storefront\Page\Product\Configurator\ProductCombinationFinder;
use Shopware\Storefront\Page\Product\QuickView\MinimalQuickViewPageLoader;
use Swp\ProductOptionsSix\Controller\ProductOptionsSix;
use Swp\ProductOptionsSix\Core\Checkout\ProductOptions\Cart\ProductOptionsCartDataCollector;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Cookie;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Storefront\Page\Product\ProductPageLoader;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use KmPitchPrint\Services\KmHelpers;
use Shopware\Storefront\Page\Product\ProductPageLoadedHook;
/**
* @RouteScope(scopes={"storefront"})
*/
class PitchPrintController extends StorefrontController
{
/**
* @var CheckoutCartPageLoader
*/
private $cartPageLoader;
/**
* @var LineItemFactoryRegistry
*/
private $lineItemFactory;
/**
* @var CartService
*/
private $cartService;
/**
* @var MinimalQuickViewPageLoader
*/
private $minimalQuickViewPageLoader;
/**
* @var ProductPageLoader
*/
private $productPageLoader;
/**
* @var SeoUrlPlaceholderHandlerInterface
*/
private $seoUrlPlaceholderHandler;
/**
* @var ProductPitchPrintService
*/
private $productPitchPrintService;
/**
* @var PitchPrint
*/
private $pitchPrintRepository;
/**
* @var ProductCombinationFinder
*/
private $combinationFinder;
public function __construct(CartService $cartService,
EntityRepositoryInterface $pitchPrintRepository,
ProductPageLoader $productPageLoader,
MinimalQuickViewPageLoader $minimalQuickViewPageLoader,
ProductPitchPrintService $productPitchPrintService,
ProductCombinationFinder $combinationFinder,
SeoUrlPlaceholderHandlerInterface $seoUrlPlaceholderHandler,
LineItemFactoryRegistry $lineItemFactory,
CheckoutCartPageLoader $cartPageLoader
)
{
$this->minimalQuickViewPageLoader = $minimalQuickViewPageLoader;
$this->cartService = $cartService;
$this->pitchPrintRepository = $pitchPrintRepository;
$this->productPageLoader = $productPageLoader;
$this->productPitchPrintService = $productPitchPrintService;
$this->combinationFinder = $combinationFinder;
$this->seoUrlPlaceholderHandler = $seoUrlPlaceholderHandler;
$this->lineItemFactory = $lineItemFactory;
$this->cartPageLoader = $cartPageLoader;
}
private function generateSignature(): array
{
$timestamp = time();
$signature = md5(PITCH_APIKEY . PITCH_SECRETKEY . $timestamp);
return array('timestamp' => $timestamp, 'apiKey' => PITCH_APIKEY, 'signature' => $signature);
}
private function createPPCookie(): string
{
return KmHelpers::createPPCookie();
}
/**
* @Route ("/km/product/preview/{pp_mode}/{productId}/{projectId}", name="km.product.preview")
*/
public function ppProductPreviewIndex(SalesChannelContext $context, Request $request): Response
{
$criteria = $this->productPitchPrintService->getCriteria();
$criteria->addFilter(new EqualsFilter('projectId', $request->get('projectId')));
$criteria->addFilter(new EqualsFilter('cookieId', $request->cookies->get('pp_id')));
$this->productPitchPrintService->setCriteria($criteria);
$productPitchprint = $this->productPitchPrintService->getCreatedProject($context->getContext());
if (!$request->cookies->get('pp_id') && $request->get('pp_mode') == 'new') {
$this->createPPCookie();
return $this->redirectToRoute('frontend.detail.page', ['productId' => $request->get('productId')]);
}
if ($productPitchprint->getTotal() < 1) {
return $this->redirectToRoute('frontend.detail.page', ['productId' => $request->get('productId')]);
}
$page = $this->productPageLoader->load($request, $context);
$productPitchprint = $productPitchprint->first();
$previews = $productPitchprint->getPayload()['previews'];
$i = 0;
$cart = $this->cartService->getCart($context->getToken(), $context);
$lineItemQty = 1;
foreach ($cart->getLineItems() as $lineItem) {
if ($lineItem->getReferencedId() == $page->getProduct()->getId()) {
$lineItemQty = $lineItem->getQuantity();
}
}
foreach ($page->getProduct()->getMedia() as $mediaEntity) {
//replace only previews, if the mediaItems are more, skip the rest
if (isset($previews[$i])) {
$samplePreview = $previews[$i];
} else {
break;
}
foreach ($mediaEntity->getMedia()->getThumbnails() as $thumbnail) {
$thumbnail->setUrl($samplePreview);
}
$mediaEntity->getMedia()->setUrl($samplePreview);
$i++;
}
$ratingSuccess = $request->get('success');
// Fallback layout for non-assigned product layout
if (!$page->getCmsPage()) {
return $this->renderStorefront('@Storefront/storefront/page/product-detail/index.html.twig', ['page' => $page,
'ratingSuccess' => $ratingSuccess,
'pp_project_id' => $productPitchprint->getProjectId(),
'pp_mode' => $request->get('pp_mode'),
'lineItemQty' => $lineItemQty
]);
}
return $this->renderStorefront('@Storefront/storefront/page/content/product-detail.html.twig', ['page' => $page]);
}
/**
* @Route ("/km/edit/project/{projectId}", name="km.edit.project")
*/
public function editProject(string $projectId, SalesChannelContext $context, Request $request): Response
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('projectId', $projectId));
$result = $this->pitchPrintRepository->search($criteria, $context->getContext());
return $this->renderStorefront('@KmPitchPrint/storefront/page/edit-project.html.twig',
['project' => $result->first()]);
}
/**
* @Route ("/km/edit/lineItem/{lineItemId}", name="km.edit.lineItem")
*/
public function editLineItem(SalesChannelContext $context, Request $request): Response
{
$page = $this->productPageLoader->load($request, $context);
//$ratingSuccess = $request->get('success');
// Fallback layout for non-assigned product layout
if (!$page->getCmsPage()) {
return $this->renderStorefront('@Storefront/storefront/page/product-detail/index.html.twig', ['page' => $page,
]);
}
return $this->renderStorefront('@Storefront/storefront/page/content/product-detail.html.twig', ['page' => $page]);
}
/**
* @Route("/km/moveto/cart", name="km.moveto.cart.project", methods={"POST"}, defaults={"XmlHttpRequest"=true, "csrf_protected"=true}) #defaults={"csrf_protected"=false}, methods={"POST"})
*/
public function moveToCartProject(SalesChannelContext $context, RequestDataBag $requestDataBag, Request $request): JsonResponse
{
$productPitchPrintService = $this->container->get('km.services.product_pitchprint');
$projectId = $request->get('projectId');
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('projectId', $projectId));
#$criteria->addFilter(new EqualsFilter('cookieId', $request->cookies->get('pp_id')));
$ppRepository = $this->container->get('km_product_pitchprint.repository')
->search($criteria, $context->getContext());
if (array_key_exists('swoptions', $ppRepository->first()->getPayload())) {
$productOptionsData = $ppRepository->first()->getPayload()['swoptions'];
$requestDataBag->set(
ProductOptionsSix::PRODUCT_OPTIONS_REQUEST_PARAMETER, new RequestDataBag($productOptionsData)
);
}
$cart = $this->cartService->getCart($context->getToken(), $context);
$count = 0;
$pp = $ppRepository->first();
$payload = $pp->getPayload();
$payload['previews'] = explode(',', $request->get('previews'));
$productPitchPrintService->setProjectData(
[
'id' => $pp->getId(),
'payload' => serialize($payload),
'projectUpdatedAt'=>(new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]
);
$productPitchPrintService->updateProject($context->getContext());
if (!$pp->getPayload()){
$type = 'product';
$qty = (int)$requestDataBag->get('lineItems')->get($pp->getProjectId())->get('quantity');
}else{
$type = $pp->getPayload()['type'];
$qty = (int)$pp->getPayload()['qty'];
}
try {
$items = [];
//$id = \Shopware\Core\Framework\Uuid\Uuid::randomHex();
$id = $pp->getProjectId();
$lineItem = new LineItem(
$id,
$type,
$pp->getProductId(),
$qty
);
$lineItem->setStackable(true);
$lineItem->setRemovable(true);
$count += $lineItem->getQuantity();
if ($pp->getDesignId()) {
$lineItem->setPayload(
['features' =>
[
'pitch_print' => [
'customer'=> $pp->getId(),
'projectId' => $pp->getProjectId(),
'designId' => $pp->getDesignId(),
'previews' => $payload['previews']
],
],
]
);
}
//$lineItem->setPayloadValue('lineItemCreatedAt',(new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT));
$items[] = $lineItem;
/** @var RequestDataBag|null $productOptionsData */
$productOptionsData = $requestDataBag->get(
ProductOptionsSix::PRODUCT_OPTIONS_REQUEST_PARAMETER
);
if($productOptionsData!=null){
if (!empty($productOptionsData->all())) {
$cart = $productPitchPrintService->addProductOptions($requestDataBag, $context, $cart, $lineItem->getPayloadValue('features'));
}else{
$cart = $this->cartService->add($cart, $items, $context);
}
}else {
$cart = $this->cartService->add($cart, $items, $context);
}
//delete from wishlist
$this->productPitchPrintService->removeFromWishlist($pp->getId(), $context);
if (!$this->traceErrors($cart)) {
$this->addFlash(self::SUCCESS, $this->trans('checkout.addToCartSuccess', ['%count%' => $count]));
}
} catch (ProductNotFoundException $exception) {
$this->addFlash(self::DANGER, $this->trans('error.addToCartError'));
}
return $this->json(['redirectUrl' => $this->generateUrl('frontend.checkout.cart.page')]);
}
/**
* @Route("/km/update/project", name="km.update.project", methods={"POST"}, defaults={"XmlHttpRequest"=true, "csrf_protected"=true}) #defaults={"csrf_protected"=false}, methods={"POST"})
*/
public function updateProject(SalesChannelContext $context, RequestDataBag $requestDataBag, Request $request): JsonResponse
{
if (!$request->isXmlHttpRequest()) {
//errorhandling
}
$previews = explode(',', $request->get('previews'));
$projectId = $request->get('projectId');
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('projectId', $projectId));
#$criteria->addFilter(new EqualsFilter('cookieId', $request->cookies->get('pp_id')));
$pp_repo = $this->container->get('km_product_pitchprint.repository');
$projectData = $pp_repo->search($criteria, $context->getContext())->first();
$payload = $projectData->getPayload();
$payload['previews'] = $previews;
$this->productPitchPrintService->setProjectData([
'id' => $projectData->getId(),
'cookieId' => $request->cookies->get('pp_id'),
'projectId' => $projectId,
'productId' => $projectData->getProductId(),
'payload' => serialize($payload),
'projectUpdatedAt'=>(new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
$this->productPitchPrintService->updateProject($context->getContext());
/**/
$cart = $this->cartService->getCart($context->getToken(), $context);
foreach ($cart->getLineItems() as $lineItem) {
$features = $lineItem->getPayloadValue('features');
if ($features && isset($features['pitch_print'])) {
if ($projectId == $features['pitch_print']['projectId']) {
$features['pitch_print']['previews'] = $previews;
$lineItem->setPayloadValue('features', $features);
$lineItem->getCover()->setUrl($previews[0]);
foreach ($lineItem->getCover()->getThumbnails() as $thumbnail) {
$thumbnail->setUrl($previews[0]);
}
foreach ($lineItem->getChildren() as $childItem) {
if ($childItem->getCover()) {
$childItem->getCover()->setUrl($previews[0]);
foreach ($childItem->getCover()->getThumbnails() as $thumbnail) {
$thumbnail->setUrl($previews[0]);
}
//$this->cartService->changeQuantity($cart, $childItem->getId(), $childItem->getQuantity(), $context);
}
}
}
}
}
$qty = (int)$projectData->getPayload()['qty'];
if ($lineItem->getType() !='promotion')
$this->cartService->changeQuantity($cart, $lineItem->getId(), $qty, $context);
return $this->json(['redirectUrl' => $this->generateUrl('frontend.checkout.cart.page')]);
}
/**
* @Route("/km/add/project", name="km.add.project", methods={"POST"}, defaults={"XmlHttpRequest"=true, "csrf_protected"=true}) #defaults={"csrf_protected"=false}, methods={"POST"})
*/
public function addProject(SalesChannelContext $context, RequestDataBag $requestDataBag, Request $request): JsonResponse
{
if (!$request->isXmlHttpRequest()) {
//errorhandling
}
$previews = explode(',', $request->get('previews'));
/*
$previews_raw = explode(',', $request->get('previews'));
$previews = [];
foreach($previews_raw as $preview){
$previews[] = urlencode($preview);
}
*/
$projectId = $request->get('projectId');
$productId = $request->get('productId');
$designId = $request->get('designId');
if (!$request->cookies->get('pp_id')) {
$cookieId = $this->createPPCookie();
}else{
$cookieId = $request->cookies->get('pp_id');
}
$ppPayload = [
'previews' => $previews,
'type' => LineItem::PRODUCT_LINE_ITEM_TYPE,
];
$productOptionsData = $requestDataBag->get(
ProductOptionsSix::PRODUCT_OPTIONS_REQUEST_PARAMETER
);
/** @var RequestDataBag|null $lineItems */
$lineItems = $requestDataBag->get('lineItems');
if (!$lineItems) {
throw new MissingRequestParameterException('lineItems');
}
$count = 0;
try {
$items = [];
/** @var RequestDataBag $lineItemData */
foreach ($lineItems as $lineItemData) {
$lineItem = new LineItem(
$projectId,
$lineItemData->getAlnum('type'),
$lineItemData->get('referencedId'),
$lineItemData->getInt('quantity', 1)
);
$lineItem->setStackable($lineItemData->getBoolean('stackable', true));
$lineItem->setRemovable($lineItemData->getBoolean('removable', true));
$count += $lineItem->getQuantity();
//add previews to payload if the item was a pitch print designed
$lineItem->setPayload(
['features' =>
[
'pitch_print' => [
'customer'=>$request->get('uuid'),
'projectId' => $projectId,
'designId' => $designId,
'previews' => $previews,
]
]
]
);
$items[] = $lineItem;
if ($productOptionsData) {
$sWoptions = $this->productPitchPrintService->getProductOptions($productId, $context);
$ppPayload = [
'previews' => $previews,
'swoptions' => $productOptionsData->all(),
'type' => ProductOptionsCartDataCollector::PRODUCT_OPTIONS_LINE_ITEM_TYPE,
];
}
$ppPayload['qty'] = $lineItem->getQuantity();
$ppPayload = serialize($ppPayload);
$this->productPitchPrintService->setProjectData([
'cookieId' => $cookieId,
'projectId' => $projectId,
'designId' => $designId,
'productId' => $productId,
'payload' => $ppPayload,
'projectUpdatedAt' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
]);
$oldProjectId = $request->get('oldProjectId');
//hande project created from wishlist to cart
//if update failes new project will be created
if ($oldProjectId){
$this->productPitchPrintService->updateTmpProject($oldProjectId, $context, true);
}else{
$this->productPitchPrintService->createNewProject($context->getContext());
}
}
$cart = $this->cartService->getCart($context->getToken(), $context);
if ($productOptionsData) {
$lineItem->setPayloadValue('swp0ptions', $sWoptions);
$cart = $this->productPitchPrintService->addProductOptions($requestDataBag, $context, $cart, $lineItem->getPayloadValue('features'));
} else {
$cart = $this->cartService->add($cart, $items, $context);
}
if (!$this->traceErrors($cart)) {
$this->addFlash(self::SUCCESS, $this->trans('checkout.addToCartSuccess', ['%count%' => $count]));
}
} catch (ProductNotFoundException $exception) {
$this->addFlash(self::DANGER, $this->trans('error.addToCartError'));
}
return $this->json(['redirectUrl' => $this->generateUrl('frontend.checkout.cart.page')]);
}
private function traceErrors(Cart $cart): bool
{
if ($cart->getErrors()->count() <= 0) {
return false;
}
$this->addCartErrors($cart, function (Error $error) {
return $error->isPersistent();
});
return true;
}
/**
* Leiche
*/
public function switch(string $productId, Request $request, SalesChannelContext $salesChannelContext): JsonResponse
{
$switchedOption = $request->query->has('switched') ? (string) $request->query->get('switched') : null;
$options = (string) $request->query->get('options');
try {
$newOptions = json_decode($options, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $jsonException) {
$newOptions = [];
}
try {
$redirect = $this->combinationFinder->find($productId, $switchedOption, $newOptions, $salesChannelContext);
$productId = $redirect->getVariantId();
} catch (ProductNotFoundException $productNotFoundException) {
//nth
}
$host = $request->attributes->get(RequestTransformer::SALES_CHANNEL_ABSOLUTE_BASE_URL)
. $request->attributes->get(RequestTransformer::SALES_CHANNEL_BASE_URL);
$url = $this->seoUrlPlaceholderHandler->replace(
$this->seoUrlPlaceholderHandler->generate(
'frontend.detail.page',
['productId' => $productId]
),
$host,
$salesChannelContext
);
$response = [
'url' => $url,
'productId' => $productId,
];
$responseData = json_decode($request->query->get('options'), true);
if (isset($responseData['quantity'])){
$response = [
'url' => $url,
'productId' => $productId,
'quantity'=>$responseData['quantity']
];
}
$response = new JsonResponse(
$response
);
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, '1');
return $response;
}
/**
* @Route("/detail/{productId}", name="frontend.detail.page", methods={"GET"})
*/
public function index(SalesChannelContext $context, Request $request): Response
{
$preselectedQty=0;
if($request->query->get('q')){
$preselectedQty = $request->query->get('q');
}
$preselectedOpt=false;
if($request->query->get('opt')){
$preselectedOpt = $request->query->get('opt');
}
$page = $this->productPageLoader->load($request, $context);
$this->hook(new ProductPageLoadedHook($page, $context));
$ratingSuccess = $request->get('success');
// Fallback layout for non-assigned product layout
if (!$page->getCmsPage()) {
return $this->renderStorefront('@Storefront/storefront/page/product-detail/index.html.twig',
[
'page' => $page,
'ratingSuccess' => $ratingSuccess,
'preselected_quantity' => $preselectedQty,
'preselected_option'=>$preselectedOpt
]);
}
return $this->renderStorefront('@Storefront/storefront/page/content/product-detail.html.twig',
[
'page' => $page,
'preselected_quantity' => $preselectedQty,
'preselected_option'=>$preselectedOpt
]
);
}
/**
* @Route("/km/detail/{productId}/switch", name="km.detail.switch", methods={"GET"}, defaults={"XmlHttpRequest": true})
*/
public function switchPP(string $productId, Request $request, SalesChannelContext $salesChannelContext): JsonResponse
{
$switchedOption = $request->query->get('switched');
$options = $request->query->get('options');
$newOptions = $options !== null ? json_decode($options, true) : [];
$ppMode = $newOptions['pp_mode'];
$projectId = $newOptions['pp_project_id'];
try {
$redirect = $this->combinationFinder->find($productId, $switchedOption, $newOptions, $salesChannelContext);
$productId = $redirect->getVariantId();
} catch (ProductNotFoundException $productNotFoundException) {
//nth
}
$host = $request->attributes->get(RequestTransformer::SALES_CHANNEL_ABSOLUTE_BASE_URL)
. $request->attributes->get(RequestTransformer::SALES_CHANNEL_BASE_URL);
if ($projectId && $projectId) {
$url = $this->seoUrlPlaceholderHandler->replace(
$this->seoUrlPlaceholderHandler->generate(
'km.product.preview',
['productId' => $productId,
'projectId' => $projectId,
'pp_mode' => $ppMode,
]
),
$host,
$salesChannelContext
);
} else {
$url = $this->seoUrlPlaceholderHandler->replace(
$this->seoUrlPlaceholderHandler->generate(
'frontend.detail.page',
['productId' => $productId]
),
$host,
$salesChannelContext
);
}
$response = new JsonResponse(['url' => $url]);
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, '1');
return $response;
}
private function getSignature()
{
$timestamp = time();
$signature = md5(PITCH_APIKEY . PITCH_SECRETKEY . $timestamp);
return array('timestamp' => $timestamp, 'apiKey' => PITCH_APIKEY, 'signature' => $signature);
}
/**
* @Route("/km/pp/uuid", name="km.pp.uuid", methods={"GET"}, defaults={"XmlHttpRequest": true})
*/
public function generateUuid(): JsonResponse{
$uuid = Uuid::randomHex();
return $this->json([
'uuid'=>$uuid
]);
}
/**
* @Route("/km/checkout/quickview/{lineItemId}", name="km.checkout.quickview.minimal", methods={"GET"}, defaults={"XmlHttpRequest": true})
*/
public function checkoutQuickView(Request $request, SalesChannelContext $context): Response
{
//$page = $this->minimalQuickViewPageLoader->load($request, $context);
$lineItemId = $request->get('lineItemId');
/*
$cartLineItems = $this->cartService->getCart($context->getToken(), $context)->getLineItems();
foreach ($cartLineItems as $lineItem) {
if ($lineItem->getId() == $lineItemId) {
break;
}
}*/
$lineItem = $this->cartService->getCart($context->getToken(), $context)->getLineItems()->filter(function (LineItem $lineItem) use ($lineItemId) {
return $lineItem->getId() == $lineItemId;
})->first();
//dump($lineItem->getCover());exit;
return $this->renderStorefront('@KmPitchPrint/storefront/page/km_pitch_print/quickview/minimal.html.twig', ['lineItem' => $lineItem]);
}
/**
* @Route("/km/multiply/project", name="km.multiply.project", defaults={"XmlHttpRequest"=true, "csrf_protected"=true})
*/
public function multiplyProject(Request $request, SalesChannelContext $context): Response
{
$request->request->set('uuid', Uuid::randomHex());
$lineItemId = $request->get('id');
$cart = $this->cartService->getCart($context->getToken(), $context);
$lineItem = $cart->getLineItems()->filter(function (LineItem $lineItem) use ($lineItemId) {
return $lineItem->getId() == $lineItemId;
})->first();
$productId = $lineItem->getReferencedId();
$ppRepository = $this->container->get('km_product_pitchprint.repository');
$projectId = $lineItem->getId();
if (isset($lineItem->getPayload()['features']['pitch_print'])) {
$projectId = $lineItem->getPayload()['features']['pitch_print']['projectId'];
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('projectId', $projectId));
#$criteria->addFilter(new EqualsFilter('cookieId', $request->cookies->get('pp_id')));
$parentProject = $ppRepository->search($criteria, $context->getContext());
if (!$request->isXmlHttpRequest()) {
//errorhandling
}
if (isset($lineItem->getPayload()['features']['pitch_print'])) {
$criteria = $this->productPitchPrintService->getCriteria();
$criteria->addFilter(new EqualsFilter('projectId', $lineItem->getPayload()['features']['pitch_print']['projectId']));
#$criteria->addFilter(new EqualsFilter('cookieId', $request->cookies->get('pp_id')));
$this->productPitchPrintService->setCriteria($criteria);
$previews = $lineItem->getPayload()['features']['pitch_print']['previews'];
//if status == 1 and error == false
$newProject = $this->productPitchPrintService->getClonedProject($lineItem->getPayload()['features']['pitch_print']['projectId']);
$designId = $lineItem->getPayload()['features']['pitch_print']['designId'];
$payload = $parentProject->first()->getPayload();
$this->productPitchPrintService->setProjectData([
'cookieId' => $request->cookies->get('pp_id'),
'projectId' => $newProject['newId'],
'designId' => $designId,
'productId' => $productId,
'payload' => serialize($payload)
]);
$this->productPitchPrintService->createNewProject($context->getContext());
$newId = $newProject['newId'];
} else {
$newId = Uuid::randomHex();
$this->productPitchPrintService->setProjectData([
'cookieId' => $request->cookies->get('pp_id'),
'projectId' => $newId,
'productId' => $productId,
'payload' => serialize($parentProject->first()->getPayload())
]);
$this->productPitchPrintService->createNewProject($context->getContext());
}
if (!$cart->getLineItems()) {
throw new MissingRequestParameterException('lineItems');
}
$count = 0;
try {
$items = [];
$lineItems = [$lineItem->getId() => $lineItem];
foreach ($lineItems as $lineItemData) {
$newLineItem = new LineItem(
$newId,
$lineItemData->getType(),
$lineItemData->getReferencedId(),
$lineItemData->getQuantity()
);
$newLineItem->setStackable($lineItemData->isStackable());
$newLineItem->setRemovable($lineItemData->isRemovable());
$count += $lineItem->getQuantity();
//add previews to payload if the item was a pitch print designed
if (isset($lineItem->getPayload()['features']['pitch_print'])) {
$newLineItem->setPayload(
['features' =>
[
'pitch_print' => [
'customer' => $request->get('uuid'),
'projectId' => $newProject['newId'],
'designId' => $designId,
'previews' => $previews,
]
]
]
);
}
$newLineItem->setCover($lineItem->getCover());
//$lineItem->getCover()->setId(Uuid::randomHex());
$newLineItem->setQuantityInformation($lineItemData->getQuantityInformation());
if ($lineItemData->hasChildren()) {
/**
* @var $childItem LineItem
*/
foreach ($lineItemData->getChildren() as $childItem) {
$newChildItem = new LineItem(
Uuid::randomHex(),
$childItem->getType(),
$childItem->getReferencedId(),
$childItem->getQuantity()
);
$newChildItem->setLabel($childItem->getLabel());
$newChildItem->setPayload($childItem->getPayload());
$newChildItem->setPriceDefinition($childItem->getPriceDefinition());
$newChildItem->setPrice($childItem->getPrice());
$newChildItem->setGood($childItem->isGood());
$newChildItem->setDescription($childItem->getDescription());
$newChildItem->setCover($childItem->getCover());
$newChildItem->setDeliveryInformation($childItem->getDeliveryInformation());
$newChildItem->setRequirement($childItem->getRequirement());
$newChildItem->setRemovable($childItem->isRemovable());
$newChildItem->setStackable($childItem->isStackable());
$newChildItem->setQuantityInformation($childItem->getQuantityInformation());
$newLineItem->addChild($newChildItem);
$newLineItem->setDataTimestamp(new \DateTimeImmutable());
}
}
$items[] = $newLineItem;
}
$cart = $this->cartService->add($this->cartService->getCart($context->getToken(), $context), $items, $context);
if (!$this->traceErrors($cart)) {
$this->addFlash(self::SUCCESS, $this->trans('checkout.addToCartSuccess', ['%count%' => $count]));
}
} catch (ProductNotFoundException $exception) {
$this->addFlash(self::DANGER, $this->trans('error.addToCartError'));
}
return $this->json(['redirectUrl' => $this->generateUrl('frontend.checkout.cart.page')]);
}
/**
* @Route("/update/swp-option/", name="km_pitchprint.update.swp-option", defaults={"XmlHttpRequest"=true, "csrf_protected"=true} )
*/
public function updateSwpOption(Request $request, RequestDataBag $requestDataBag, SalesChannelContext $context): JsonResponse
{
$cart = $cart ?? $this->cartService->getCart($context->getToken(), $context);
$productOptionsData = $requestDataBag->get(
#'product-option',
'productOptions'
);
# dump($productOptionsData);exit;
$lineItemId = $request->request->get('lineItemId');
/**
* @var $lineItem LineItem
*/
$productOptionsLineItem = $cart->getLineItems()->filter(function (LineItem $lineItem) use ($lineItemId) {
return $lineItem->getId() == $lineItemId;
})->first();
$projectId = $lineItemId;
if (isset($productOptionsLineItem->getPayloadValue('features')['pitch_print'])) {
$projectId = $productOptionsLineItem->getPayloadValue('features')['pitch_print']['projectId'];
}
$ppRepo = $this->container->get('km_product_pitchprint.repository');
$pp = $ppRepo->search(
(new Criteria())->addFilter(new EqualsFilter('projectId', $projectId)),
$context->getContext())->first();
$payload = $pp->getPayload();
$payload['swoptions'] = $productOptionsData->all();
$ppRepo->upsert([
[
'id' => $pp->getId(),
'payload' => serialize($payload)
]
], $context->getContext());
$childLineItemId = $request->request->get('childItemId');
$result = $productOptionsLineItem->getChildren()->filter(function (LineItem $lineItem) use ($childLineItemId) {
return $lineItem->getType() == 'product-option';#&& $lineItem->getId() == $childLineItemId;
});
$qty = $result->first()->getQuantity();
//$productOptionsLineItem->getChildren()->removeElement($optionLineItem);
/**
* @var $productOptionsCartService \Swp\ProductOptionsSix\Core\Checkout\ProductOptions\ProductOptionsCartService
*/
$productOptionsCartService = $this->container->get('swp.product_options_cart_service');
/* deprecated
$productOptions = $productOptionsCartService->loadOptions(
$productOptionsData,
$context->getContext()
);
*/
$productOptions = $this->container->get('swp.product_option_loader')->loadSelectedOptions(
$productOptionsData,
$context->getContext()
);
/**/
$productOptionsCartService->addOptions(
$productOptionsLineItem,
$productOptionsData,
$productOptions,
$qty
);
//remove old child Items with old options konfigurations
$oldLineItems = $result->getElements();
foreach ($oldLineItems as $oldLineItem){
$productOptionsLineItem->getChildren()->removeElement($oldLineItem);
}
$cart = $this->cartService->changeQuantity($cart, $productOptionsLineItem->getId(), $qty, $context);
//$this->cartService->add($cart, $productOptionsLineItem, $context);
if (!$this->traceErrors($cart)) {
$this->addFlash(self::SUCCESS, $this->trans('checkout.cartUpdateSuccess'));
}
return new JsonResponse(array(
'lineItemId'=>$productOptionsLineItem->getId()
));
}
/**
* @Route("/km/pp_preview/{projectId}.jpg", name="km.load.ppPreview", defaults={"csrf_protected"=false})
*/
public function loadPpPreview(string $projectId, SalesChannelContext $context): Response
{
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('projectId',$projectId));
$result = $this->pitchPrintRepository->search($criteria, $context->getContext());
$payload = $result->first()->getPayload();
$ppPreview = $payload['previews'][0];
$imginfo = getimagesize($ppPreview);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ppPreview);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$im = imagecreatefromstring($data);
header("Content-type: {$imginfo['mime']}");
$im = imagescale($im, 300);
imagejpeg($im);
imagedestroy($im);
return new Response();
}
}