<?php
namespace App\Controller;
use App\Classes\Constant;
use App\Services\BusinessCentral\Exceptions\NotFoundException;
use App\Services\Routes\ImportStocks;
use App\Services\Shopware6\Shopware6Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Vin\ShopwareSdk\Data\Filter\EqualsFilter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Throwable;
use Vin\ShopwareSdk\Data\Criteria;
use Vin\ShopwareSdk\Data\Entity\Product\ProductDefinition;
use Vin\ShopwareSdk\Factory\RepositoryFactory;
class UpdateStockController extends AbstractController
{
public function __construct(
#[Autowire("%webhookSecret%")]
protected string $webhookSecret,
protected Shopware6Client $shopware6Client,
protected ImportStocks $importStocksRoute
) {
}
/**
* @throws Throwable
*/
#[Route('/webhook/update-stock', name: 'app_webhook_update_stock')]
public function index(Request $request): Response
{
// Validation
$shopwareProductId = $request->get("id");
$preview = $request->get("preview", false);
if (!$shopwareProductId) {
return $this->json([
"success" => false,
"error" => "Product id not supplied"
], 500);
}
// Update stock
try {
$productRepository = RepositoryFactory::create(ProductDefinition::ENTITY_NAME);
$shopwareProduct = $productRepository->get(
$shopwareProductId,
new Criteria(),
$this->shopware6Client->context
);
if (!$shopwareProduct) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter("parentId", $shopwareProductId));
$shopwareProduct = $productRepository->search($criteria, $this->shopware6Client->context)->first();
if (!$shopwareProduct) {
throw new NotFoundException("Product not found");
}
}
$productNumber = $shopwareProduct->productNumber;
$payload = $this->importStocksRoute->execute($productNumber, false, $preview, false);
$statusCode = 200;
$response = [
"success" => true,
"message" => "Updated",
"data" => $payload
];
} catch (Throwable $exception) {
$statusCode = 500;
$response = [
"success" => false,
"error" => $exception->getMessage()
];
}
return $this->json($response, $statusCode);
}
}