fix(integrity): include trashed products in max order and purge CRM email cache on deletion
This commit is contained in:
parent
3d1c798c08
commit
1ae8f65d7c
6 changed files with 215 additions and 31 deletions
|
|
@ -45,8 +45,8 @@ use Webmozart\Assert\Assert;
|
|||
#[Locked(ttlSeconds: 30, waitSeconds: 10)]
|
||||
final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey
|
||||
{
|
||||
/** @var array<int, \Shared\ValueObjects\CrmHashcode> */
|
||||
private array $createdCrmHashcodes = [];
|
||||
/** @var array<int, array{hashcode: \Shared\ValueObjects\CrmHashcode, email: \Domain\Models\ValueObjects\Email}> */
|
||||
private array $createdCrmCustomers = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly AppCustomerAuthService $authService,
|
||||
|
|
@ -89,7 +89,7 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
|
|||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
$inputKey = spl_object_id($input);
|
||||
unset($this->createdCrmHashcodes[$inputKey]);
|
||||
unset($this->createdCrmCustomers[$inputKey]);
|
||||
|
||||
$employee = Employee::query()
|
||||
->where('matricule', $input->matricule->value)
|
||||
|
|
@ -158,7 +158,10 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
|
|||
}
|
||||
|
||||
$crmHashcode = CrmHashcode::fromString($result->hashcode);
|
||||
$this->createdCrmHashcodes[$inputKey] = $crmHashcode;
|
||||
$this->createdCrmCustomers[$inputKey] = [
|
||||
'hashcode' => $crmHashcode,
|
||||
'email' => $input->email,
|
||||
];
|
||||
|
||||
$customer->hashcode = $crmHashcode;
|
||||
$customer->saveOrFail();
|
||||
|
|
@ -176,7 +179,7 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
|
|||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
Assert::isInstanceOf($result, RegisterCustomerOutput::class);
|
||||
|
||||
unset($this->createdCrmHashcodes[spl_object_id($input)]);
|
||||
unset($this->createdCrmCustomers[spl_object_id($input)]);
|
||||
|
||||
if ($result->status !== RegisterCustomerStatus::SUCCESS || ! $result->customer instanceof Customer) {
|
||||
return;
|
||||
|
|
@ -199,16 +202,16 @@ final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeo
|
|||
{
|
||||
Assert::isInstanceOf($input, RegisterCustomerInput::class);
|
||||
|
||||
$inputKey = spl_object_id($input);
|
||||
$crmHashcode = $this->createdCrmHashcodes[$inputKey] ?? null;
|
||||
unset($this->createdCrmHashcodes[$inputKey]);
|
||||
$inputKey = spl_object_id($input);
|
||||
$createdCrm = $this->createdCrmCustomers[$inputKey] ?? null;
|
||||
unset($this->createdCrmCustomers[$inputKey]);
|
||||
|
||||
if (! $crmHashcode instanceof CrmHashcode) {
|
||||
if ($createdCrm === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->crmService->deleteByHashcode($crmHashcode);
|
||||
$this->crmService->deleteByHashcode($createdCrm['hashcode'], $createdCrm['email']);
|
||||
} catch (\Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -143,7 +143,7 @@ class Product extends Model implements ModelWithOrder, ModelWithStar, ModelWithS
|
|||
$model->slug = Str::slug($model->name);
|
||||
|
||||
if ($model->order === null) {
|
||||
$max = self::query()->max('order');
|
||||
$max = self::query()->withTrashed()->max('order');
|
||||
$model->order = is_scalar($max) ? intval($max) + 1 : 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -305,14 +305,7 @@ class CrmService implements CrmCustomerGatewayService
|
|||
*/
|
||||
public function activate(CrmCustomer $customer): object
|
||||
{
|
||||
if ($customer->hashcode) {
|
||||
$this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($customer->hashcode));
|
||||
unset($this->customerByHashcodeCache[$customer->hashcode]);
|
||||
}
|
||||
if ($customer->email) {
|
||||
$this->cacheRepository->delete($this->getCustomerEmailCacheKey($customer->email));
|
||||
unset($this->customerByEmailCache[strtolower(trim($customer->email))]);
|
||||
}
|
||||
$this->forgetCustomerCache($customer->hashcode, $customer->email);
|
||||
|
||||
try {
|
||||
$libCustomer = $this->toLibCrmCustomer($customer);
|
||||
|
|
@ -348,14 +341,7 @@ class CrmService implements CrmCustomerGatewayService
|
|||
*/
|
||||
public function persist(CrmCustomer $customer): CrmCustomer
|
||||
{
|
||||
if ($customer->hashcode) {
|
||||
$this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($customer->hashcode));
|
||||
unset($this->customerByHashcodeCache[$customer->hashcode]);
|
||||
}
|
||||
if ($customer->email) {
|
||||
$this->cacheRepository->delete($this->getCustomerEmailCacheKey($customer->email));
|
||||
unset($this->customerByEmailCache[strtolower(trim($customer->email))]);
|
||||
}
|
||||
$this->forgetCustomerCache($customer->hashcode, $customer->email);
|
||||
|
||||
try {
|
||||
$customer = $this->toLibCrmCustomer($customer);
|
||||
|
|
@ -389,10 +375,27 @@ class CrmService implements CrmCustomerGatewayService
|
|||
/**
|
||||
* @throws \App\Exceptions\CrmServiceException
|
||||
*/
|
||||
public function deleteByHashcode(CrmHashcode $hashcode): bool
|
||||
public function deleteByHashcode(CrmHashcode $hashcode, ?Email $email = null): bool
|
||||
{
|
||||
$this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($hashcode->value));
|
||||
unset($this->customerByHashcodeCache[$hashcode->value]);
|
||||
$resolvedEmail = $email?->value;
|
||||
|
||||
if ($resolvedEmail === null) {
|
||||
$cachedByHashcode = array_key_exists($hashcode->value, $this->customerByHashcodeCache)
|
||||
? $this->customerByHashcodeCache[$hashcode->value]
|
||||
: $this->cacheRepository->get($this->getCustomerHashcodeCacheKey($hashcode->value));
|
||||
|
||||
if ($cachedByHashcode instanceof CrmCustomer) {
|
||||
$resolvedEmail = $cachedByHashcode->email;
|
||||
}
|
||||
}
|
||||
|
||||
$this->forgetCustomerCache($hashcode->value, $resolvedEmail);
|
||||
|
||||
foreach ($this->customerByEmailCache as $cachedEmail => $cachedCustomer) {
|
||||
if ($cachedCustomer instanceof CrmCustomer && $cachedCustomer->hashcode === $hashcode->value) {
|
||||
$this->forgetCustomerCache(null, $cachedEmail);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$customer = new Customer(['hashcode' => $hashcode->value]);
|
||||
|
|
@ -510,6 +513,20 @@ class CrmService implements CrmCustomerGatewayService
|
|||
$refProp->setValue($customer, false);
|
||||
}
|
||||
|
||||
private function forgetCustomerCache(?string $hashcode, ?string $email): void
|
||||
{
|
||||
if ($hashcode !== null && $hashcode !== '') {
|
||||
$this->cacheRepository->delete($this->getCustomerHashcodeCacheKey($hashcode));
|
||||
unset($this->customerByHashcodeCache[$hashcode]);
|
||||
}
|
||||
|
||||
if ($email !== null && $email !== '') {
|
||||
$normalizedEmail = strtolower(trim($email));
|
||||
$this->cacheRepository->delete($this->getCustomerEmailCacheKey($normalizedEmail));
|
||||
unset($this->customerByEmailCache[$normalizedEmail]);
|
||||
}
|
||||
}
|
||||
|
||||
private function getCustomerHashcodeCacheKey(string $hashcode): string
|
||||
{
|
||||
return "crm_customer_hashcode_{$hashcode}";
|
||||
|
|
|
|||
|
|
@ -646,7 +646,10 @@ describe('RegisterCustomer action', function (): void {
|
|||
));
|
||||
$crmService->shouldReceive('deleteByHashcode')
|
||||
->once()
|
||||
->withArgs(fn (CrmHashcode $hash): bool => $hash->value === $crmReturnedHashcode)
|
||||
->withArgs(
|
||||
fn (CrmHashcode $hash, ?Email $deletedEmail): bool => $hash->value === $crmReturnedHashcode
|
||||
&& $deletedEmail?->value === $email->value
|
||||
)
|
||||
->andReturnTrue();
|
||||
|
||||
$authService = \Mockery::mock(AppCustomerAuthService::class);
|
||||
|
|
|
|||
|
|
@ -79,3 +79,51 @@ describe('Product::scopeOrderable', function (): void {
|
|||
Date::setTestNow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Product order auto-increment with SoftDeletes', function (): void {
|
||||
it('computes max order including soft-deleted products when saving a new product without explicit order', function (): void {
|
||||
// GIVEN
|
||||
$range = new Range();
|
||||
$range->name = 'Gamme Order ' . uniqid();
|
||||
$range->status = true;
|
||||
$range->order = 1;
|
||||
$range->picture_alt = 'alt';
|
||||
$range->picture_title = 'title';
|
||||
$range->saveOrFail();
|
||||
|
||||
$makeProduct = static function (string $name) use ($range): Product {
|
||||
$product = new Product([
|
||||
'range_id' => $range->id,
|
||||
'name' => $name,
|
||||
'brand' => ProductBrand::loue,
|
||||
'invoicing_unit' => InvoicingUnit::PCE,
|
||||
'sell_unit' => SellUnit::PCE,
|
||||
'order_unit' => OrderUnit::PCE,
|
||||
'tax_rate' => TaxRate::TVA_20,
|
||||
'description' => 'Description',
|
||||
'status' => true,
|
||||
]);
|
||||
$product->price = Money::EUR(1000);
|
||||
$product->short_description = 'Court';
|
||||
$product->picture_alt = 'alt';
|
||||
$product->picture_title = 'title';
|
||||
$product->picture_large_alt = 'alt';
|
||||
$product->picture_large_title = 'title';
|
||||
$product->saveOrFail();
|
||||
|
||||
return $product;
|
||||
};
|
||||
|
||||
$first = $makeProduct('Produit 1 ' . uniqid());
|
||||
$second = $makeProduct('Produit 2 ' . uniqid());
|
||||
$second->delete();
|
||||
|
||||
// WHEN
|
||||
$third = $makeProduct('Produit 3 ' . uniqid());
|
||||
|
||||
// THEN
|
||||
expect($first->order)->toBe(1)
|
||||
->and($second->order)->toBe(2)
|
||||
->and($third->order)->toBe(3);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use App\Exceptions\CrmServiceException;
|
|||
use App\Services\CrmService;
|
||||
use Domain\Enums\Country;
|
||||
use Domain\Models\ValueObjects\CrmCustomer;
|
||||
use Domain\Models\ValueObjects\Email;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
use Illuminate\Cache\ArrayStore;
|
||||
use Illuminate\Cache\Repository as ArrayCacheRepository;
|
||||
|
|
@ -256,6 +257,7 @@ describe('CrmService', function (): void {
|
|||
$uuid = Uuid::uuid4();
|
||||
$expectedHashKey = "crm_customer_hashcode_{$uuid->toString()}";
|
||||
|
||||
$cacheRepository->shouldReceive('get')->with($expectedHashKey)->once()->andReturnNull();
|
||||
$cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once();
|
||||
|
||||
$apiInterface = \Mockery::mock(ApiInterface::class);
|
||||
|
|
@ -320,4 +322,115 @@ describe('CrmService', function (): void {
|
|||
expect(fn () => $service->deleteByHashcode(new CrmHashcode($uuid)))
|
||||
->toThrow(CrmServiceException::class);
|
||||
});
|
||||
|
||||
it('clears both hashcode and email caches when email is provided to deleteByHashcode', function (): void {
|
||||
// GIVEN
|
||||
/** @var CrmApiV4&\Mockery\MockInterface $crmApi */
|
||||
$crmApi = \Mockery::mock(CrmApiV4::class);
|
||||
$cacheRepository = new ArrayCacheRepository(new ArrayStore());
|
||||
$uuid = Uuid::uuid4();
|
||||
$email = new Email('Rollback@Example.com');
|
||||
$hashKey = "crm_customer_hashcode_{$uuid->toString()}";
|
||||
$emailKey = 'crm_customer_email_' . hash('sha256', 'rollback@example.com');
|
||||
|
||||
$cachedCustomer = new CrmCustomer(
|
||||
hashcode: $uuid->toString(),
|
||||
email: $email->value,
|
||||
password: null,
|
||||
firstname: 'Jane',
|
||||
lastname: 'Doe',
|
||||
birthDate: '1990-01-01',
|
||||
phone: null,
|
||||
address: null,
|
||||
address2: null,
|
||||
city: 'Paris',
|
||||
postcode: '75001',
|
||||
country: Country::france,
|
||||
optIn: false,
|
||||
status: false,
|
||||
lastConnection: null,
|
||||
);
|
||||
$crmApi->shouldReceive('getCustomer')->with('rollback@example.com')->once()->andReturnNull();
|
||||
$cacheRepository->put($hashKey, $cachedCustomer, 600);
|
||||
$cacheRepository->put($emailKey, $cachedCustomer, 600);
|
||||
|
||||
$apiInterface = \Mockery::mock(ApiInterface::class);
|
||||
$apiInterface->shouldReceive('call')->once()->andReturn(
|
||||
new \LDC\LDCCRM\Transport\Response(
|
||||
ApiStatus::OK,
|
||||
new Response(200, [], (string) json_encode([
|
||||
'version' => Utils::getPackageInfo()['version'],
|
||||
'data' => [],
|
||||
]))
|
||||
)
|
||||
);
|
||||
$refProp = new \ReflectionProperty(ClientModel::class, 'apiInterface');
|
||||
$refProp->setValue(null, $apiInterface);
|
||||
|
||||
$service = new CrmService($crmApi, $cacheRepository);
|
||||
// Prime internal in-memory email cache from repository
|
||||
expect($service->getCustomerFromEmail($email->value))->toBeInstanceOf(CrmCustomer::class);
|
||||
|
||||
// WHEN
|
||||
$deleted = $service->deleteByHashcode(new CrmHashcode($uuid), $email);
|
||||
|
||||
// THEN
|
||||
expect($deleted)->toBeTrue()
|
||||
->and($cacheRepository->has($hashKey))->toBeFalse()
|
||||
->and($cacheRepository->has($emailKey))->toBeFalse()
|
||||
->and($service->getCustomerFromEmail($email->value))->toBeNull();
|
||||
});
|
||||
|
||||
it('clears cached email entry when deleteByHashcode resolves email from hashcode cache', function (): void {
|
||||
// GIVEN
|
||||
/** @var CrmApiV4&\Mockery\MockInterface $crmApi */
|
||||
$crmApi = \Mockery::mock(CrmApiV4::class);
|
||||
$cacheRepository = new ArrayCacheRepository(new ArrayStore());
|
||||
$uuid = Uuid::uuid4();
|
||||
$hashKey = "crm_customer_hashcode_{$uuid->toString()}";
|
||||
$emailKey = 'crm_customer_email_' . hash('sha256', 'cached@example.com');
|
||||
|
||||
$cachedCustomer = new CrmCustomer(
|
||||
hashcode: $uuid->toString(),
|
||||
email: 'cached@example.com',
|
||||
password: null,
|
||||
firstname: 'Jane',
|
||||
lastname: 'Doe',
|
||||
birthDate: '1990-01-01',
|
||||
phone: null,
|
||||
address: null,
|
||||
address2: null,
|
||||
city: 'Paris',
|
||||
postcode: '75001',
|
||||
country: Country::france,
|
||||
optIn: false,
|
||||
status: false,
|
||||
lastConnection: null,
|
||||
);
|
||||
$cacheRepository->put($hashKey, $cachedCustomer, 600);
|
||||
$cacheRepository->put($emailKey, $cachedCustomer, 600);
|
||||
|
||||
$apiInterface = \Mockery::mock(ApiInterface::class);
|
||||
$apiInterface->shouldReceive('call')->once()->andReturn(
|
||||
new \LDC\LDCCRM\Transport\Response(
|
||||
ApiStatus::OK,
|
||||
new Response(200, [], (string) json_encode([
|
||||
'version' => Utils::getPackageInfo()['version'],
|
||||
'data' => [],
|
||||
]))
|
||||
)
|
||||
);
|
||||
$refProp = new \ReflectionProperty(ClientModel::class, 'apiInterface');
|
||||
$refProp->setValue(null, $apiInterface);
|
||||
|
||||
$service = new CrmService($crmApi, $cacheRepository);
|
||||
|
||||
// WHEN
|
||||
$deleted = $service->deleteByHashcode(new CrmHashcode($uuid));
|
||||
|
||||
// THEN
|
||||
expect($deleted)->toBeTrue()
|
||||
->and($cacheRepository->has($hashKey))->toBeFalse()
|
||||
->and($cacheRepository->has($emailKey))->toBeFalse();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue