Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config/admin/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ services:
$decorated: '@serializer.normalizer.object'
tags:
- { name: 'serializer.normalizer', priority: 300 }
PrestaShop\Module\APIResources\ApiPlatform\Normalizer\DateTimeImmutableNormalizer:
tags:
- { name: 'serializer.normalizer', priority: 100 }

PrestaShopBundle\ApiPlatform\Serializer\CQRSApiSerializer:
class: PrestaShop\Module\APIResources\Serializer\QueryParameterTypeCastSerializer
Expand All @@ -75,3 +78,8 @@ services:
- { name: 'serializer.normalizer', priority: 100 }
arguments:
$denormalizer: '@PrestaShopBundle\ApiPlatform\Normalizer\CQRSApiNormalizer'
PrestaShop\Module\APIResources\ApiPlatform\Provider\SpecificPriceListProvider:
autowire: true
public: true
tags:
- { name: 'api_platform.state_provider' }
88 changes: 88 additions & 0 deletions src/ApiPlatform/Normalizer/DateTimeImmutableNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/

declare(strict_types=1);

namespace PrestaShop\Module\APIResources\ApiPlatform\Normalizer;

use DateTimeImmutable;
use DateTimeInterface;
use PrestaShop\PrestaShop\Core\Util\DateTime\DateTime as DateTimeUtil;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/**
* Custom normalizer for DateTimeImmutable and DateTimeInterface that handles '0000-00-00 00:00:00' as NullDateTime.
* This normalizer has higher priority than the core one (priority 100) to handle unlimited dates correctly.
* Registered in config/admin/services.yml
*
* This matches the behavior in CommandBuilder::castValue() for TYPE_DATETIME which uses DateTime::buildNullableDateTime()
*/
class DateTimeImmutableNormalizer implements DenormalizerInterface, NormalizerInterface
{
public function denormalize($data, string $type, ?string $format = null, array $context = [])
{
// Normalize ISO 8601 format to standard datetime format for null date detection
// '0000-00-00T00:00:00+00:00' should be treated as '0000-00-00 00:00:00'
if (is_string($data) && strpos($data, '0000-00-00') === 0) {
// Extract just the date part (YYYY-MM-DD) and time part if present
// Handle formats like: '0000-00-00T00:00:00+00:00', '0000-00-00T00:00:00Z', etc.
if (preg_match('/^0000-00-00(?:T00:00:00.*)?$/', $data)) {
$data = DateTimeUtil::NULL_DATETIME;
} elseif (preg_match('/^0000-00-00$/', $data)) {
$data = DateTimeUtil::NULL_DATE;
}
}

// Use buildNullableDateTime to handle '0000-00-00 00:00:00' correctly
// This matches the behavior in CommandBuilder::castValue() for TYPE_DATETIME
return DateTimeUtil::buildNullableDateTime($data);
}

public function supportsDenormalization($data, string $type, ?string $format = null)
{
// Support both DateTimeImmutable and DateTimeInterface (which is the type used in command constructors)
return \DateTimeImmutable::class === $type || \DateTimeInterface::class === $type;
}

public function normalize(mixed $object, ?string $format = null, array $context = [])
{
if (!($object instanceof \DateTimeImmutable)) {
throw new InvalidArgumentException('Expected object to be a ' . \DateTimeImmutable::class);
}

return $object->format(DateTimeUtil::DEFAULT_DATETIME_FORMAT);
}

public function supportsNormalization(mixed $data, ?string $format = null)
{
return $data instanceof \DateTimeImmutable;
}

public function getSupportedTypes(?string $format): array
{
return [
\DateTimeImmutable::class => true,
\DateTimeInterface::class => true,
];
}
}
77 changes: 77 additions & 0 deletions src/ApiPlatform/Provider/SpecificPriceListProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/

declare(strict_types=1);

namespace PrestaShop\Module\APIResources\ApiPlatform\Provider;

use ApiPlatform\Metadata\Operation;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\QueryResult\SpecificPriceList;
use PrestaShopBundle\ApiPlatform\Exception\CQRSQueryNotFoundException;
use PrestaShopBundle\ApiPlatform\NormalizationMapper;
use PrestaShopBundle\ApiPlatform\Provider\QueryProvider;

/**
* Custom provider for SpecificPriceList that extracts the specificPrices array
* from the SpecificPriceList object before denormalization
*/
class SpecificPriceListProvider extends QueryProvider
{
public function provide(Operation $operation, array $uriVariables = [], array $context = []): array|object|null
{
$CQRSQueryClass = $this->getCQRSQueryClass($operation);
if (null === $CQRSQueryClass) {
throw new CQRSQueryNotFoundException(sprintf('Resource %s has no CQRS query defined.', $operation->getClass()));
}

$filters = $context['filters'] ?? [];
$queryParameters = array_merge($uriVariables, $filters, $this->contextParametersProvider->getContextParameters());

$CQRSQuery = $this->domainSerializer->denormalize($queryParameters, $CQRSQueryClass, null, [NormalizationMapper::NORMALIZATION_MAPPING => $this->getCQRSQueryMapping($operation)]);
$CQRSQueryResult = $this->queryBus->handle($CQRSQuery);

// If the result is a SpecificPriceList object, extract the specificPrices array
if ($CQRSQueryResult instanceof SpecificPriceList) {
$CQRSQueryResult = $CQRSQueryResult->getSpecificPrices();
}

// The result may be null (for DELETE action for example)
if (null === $CQRSQueryResult) {
return new ($operation->getClass())();
}

$denormalizedResult = $this->denormalizeQueryResult($CQRSQueryResult, $operation);

// Add productId from uriVariables to each item in the collection
// This ensures consistency with POST/PATCH responses that include productId
if (is_array($denormalizedResult) && isset($uriVariables['productId'])) {
foreach ($denormalizedResult as $key => $item) {
if (is_object($item)) {
$item->productId = (int) $uriVariables['productId'];
} elseif (is_array($item)) {
$denormalizedResult[$key]['productId'] = (int) $uriVariables['productId'];
}
}
}

return $denormalizedResult;
}
}
179 changes: 179 additions & 0 deletions src/ApiPlatform/Resources/Product/SpecificPrice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/

declare(strict_types=1);

namespace PrestaShop\Module\APIResources\ApiPlatform\Resources\Product;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use PrestaShop\Decimal\DecimalNumber;
use PrestaShop\PrestaShop\Core\Domain\Product\Exception\ProductNotFoundException;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Command\AddSpecificPriceCommand;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Command\DeleteSpecificPriceCommand;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Command\EditSpecificPriceCommand;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Exception\SpecificPriceException;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Exception\SpecificPriceNotFoundException;
use PrestaShop\PrestaShop\Core\Domain\Product\SpecificPrice\Query\GetSpecificPriceForEditing;
use PrestaShopBundle\ApiPlatform\Metadata\CQRSCreate;
use PrestaShopBundle\ApiPlatform\Metadata\CQRSDelete;
use PrestaShopBundle\ApiPlatform\Metadata\CQRSGet;
use PrestaShopBundle\ApiPlatform\Metadata\CQRSPartialUpdate;
use Symfony\Component\HttpFoundation\Response;

#[ApiResource(
operations: [
new CQRSGet(
uriTemplate: '/products/specific-prices/{specificPriceId}',
CQRSQuery: GetSpecificPriceForEditing::class,
scopes: [
'product_read',
],
CQRSQueryMapping: SpecificPrice::QUERY_MAPPING,
),
new CQRSCreate(
uriTemplate: '/products/specific-prices',
CQRSCommand: AddSpecificPriceCommand::class,
CQRSQuery: GetSpecificPriceForEditing::class,
scopes: [
'product_write',
],
CQRSQueryMapping: SpecificPrice::QUERY_MAPPING,
CQRSCommandMapping: SpecificPrice::CREATE_COMMAND_MAPPING,
),
new CQRSPartialUpdate(
uriTemplate: '/products/specific-prices/{specificPriceId}',
CQRSCommand: EditSpecificPriceCommand::class,
CQRSQuery: GetSpecificPriceForEditing::class,
scopes: [
'product_write',
],
CQRSQueryMapping: SpecificPrice::QUERY_MAPPING,
CQRSCommandMapping: SpecificPrice::UPDATE_COMMAND_MAPPING,
),
new CQRSDelete(
uriTemplate: '/products/specific-prices/{specificPriceId}',
CQRSCommand: DeleteSpecificPriceCommand::class,
scopes: [
'product_write',
],
CQRSCommandMapping: SpecificPrice::DELETE_COMMAND_MAPPING,
),
],
exceptionToStatus: [
ProductNotFoundException::class => Response::HTTP_NOT_FOUND,
SpecificPriceNotFoundException::class => Response::HTTP_NOT_FOUND,
SpecificPriceException::class => Response::HTTP_UNPROCESSABLE_ENTITY,
],
)]
class SpecificPrice
{
#[ApiProperty(identifier: true)]
public int $specificPriceId;

public int $productId;

public string $reductionType;

public DecimalNumber $reductionValue;

public bool $includesTax;

public ?DecimalNumber $fixedPrice = null;

public int $fromQuantity;

public ?\DateTimeImmutable $dateTimeFrom = null;

public ?\DateTimeImmutable $dateTimeTo = null;

public ?int $combinationId = null;

public ?int $shopId = null;

public ?int $currencyId = null;

public ?int $countryId = null;

public ?int $groupId = null;

public ?int $customerId = null;

public ?array $customerInfo = null;

public const QUERY_MAPPING = [
'[specificPriceId]' => '[specificPriceId]',
'[reductionType]' => '[reductionType]',
// Map reductionAmount from QueryResult to reductionValue in API Resource
'[reductionAmount]' => '[reductionValue]',
'[includesTax]' => '[includesTax]',
'[fixedPrice][value]' => '[fixedPrice]',
'[fromQuantity]' => '[fromQuantity]',
'[dateTimeFrom]' => '[dateTimeFrom]',
'[dateTimeTo]' => '[dateTimeTo]',
'[productId]' => '[productId]',
'[customerInfo]' => '[customerInfo]',
'[combinationId]' => '[combinationId]',
'[shopId]' => '[shopId]',
'[currencyId]' => '[currencyId]',
'[countryId]' => '[countryId]',
'[groupId]' => '[groupId]',
];

public const CREATE_COMMAND_MAPPING = [
'[productId]' => '[productId]',
'[reductionType]' => '[reductionType]',
'[reductionValue]' => '[reductionValue]',
'[includeTax]' => '[includeTax]',
'[fixedPrice]' => '[fixedPrice]',
'[fromQuantity]' => '[fromQuantity]',
'[dateTimeFrom]' => '[dateTimeFrom]',
'[dateTimeTo]' => '[dateTimeTo]',
'[shopId]' => '[shopId]',
'[combinationId]' => '[combinationId]',
'[currencyId]' => '[currencyId]',
'[countryId]' => '[countryId]',
'[groupId]' => '[groupId]',
'[customerId]' => '[customerId]',
];

public const UPDATE_COMMAND_MAPPING = [
'[specificPriceId]' => '[specificPriceId]',
// EditSpecificPriceCommand::setReduction() expects 2 args: reductionType and reductionValue
'[reductionType]' => '[reduction][reductionType]',
'[reductionValue]' => '[reduction][reductionValue]',
'[includesTax]' => '[includesTax]',
'[fixedPrice]' => '[fixedPrice]',
'[fromQuantity]' => '[fromQuantity]',
'[dateTimeFrom]' => '[dateTimeFrom]',
'[dateTimeTo]' => '[dateTimeTo]',
'[shopId]' => '[shopId]',
'[combinationId]' => '[combinationId]',
'[currencyId]' => '[currencyId]',
'[countryId]' => '[countryId]',
'[groupId]' => '[groupId]',
'[customerId]' => '[customerId]',
];

public const DELETE_COMMAND_MAPPING = [
'[specificPriceId]' => '[specificPriceId]',
];
}
Loading
Loading