diff --git a/app/Cqs/Actions/Customers/RegisterCustomer.php b/app/Cqs/Actions/Customers/RegisterCustomer.php index 28015f6d..34a25a72 100644 --- a/app/Cqs/Actions/Customers/RegisterCustomer.php +++ b/app/Cqs/Actions/Customers/RegisterCustomer.php @@ -45,8 +45,8 @@ use Webmozart\Assert\Assert; #[Locked(ttlSeconds: 30, waitSeconds: 10)] final class RegisterCustomer implements Action, HandlesFailure, HandlesLockTimeout, HandlesSuccess, ProvidesLockKey { - /** @var array */ - private array $createdCrmHashcodes = []; + /** @var array */ + 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); } diff --git a/app/Models/Product.php b/app/Models/Product.php index 28890bc4..2e99e54a 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -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; } } diff --git a/app/Services/CrmService.php b/app/Services/CrmService.php index 1551355e..85e84c5a 100644 --- a/app/Services/CrmService.php +++ b/app/Services/CrmService.php @@ -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}"; diff --git a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php b/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php index e2da5b78..6cefadec 100644 --- a/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php +++ b/tests/Integration/WithApp/App/Actions/Customers/RegisterCustomerTest.php @@ -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); diff --git a/tests/Integration/WithApp/App/Models/ProductTest.php b/tests/Integration/WithApp/App/Models/ProductTest.php index 0ac00de8..4e6fd90e 100644 --- a/tests/Integration/WithApp/App/Models/ProductTest.php +++ b/tests/Integration/WithApp/App/Models/ProductTest.php @@ -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); + }); +}); diff --git a/tests/Integration/WithApp/App/Services/CrmServiceTest.php b/tests/Integration/WithApp/App/Services/CrmServiceTest.php index 766431e7..42b63aa1 100644 --- a/tests/Integration/WithApp/App/Services/CrmServiceTest.php +++ b/tests/Integration/WithApp/App/Services/CrmServiceTest.php @@ -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(); + }); });