From 8b96ce90be99da2f564a1a79fbdf68f1e1516ea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Fri, 2 Oct 2026 12:14:48 +0200 Subject: [PATCH] test(casts): add tests for EmployeeSitesCast functionality test(casts): add tests for ShopperEstablishmentCodeCast functionality test(casts): add tests for ShopperServiceCodeCast functionality test(casts): add tests for ShopperSiteCodeCast functionality test(dto): update ProductDtoTest to include additional fields test(dto): update SettingDtoTest to remove arcadiaSites assertions test(events): update AnOrderHasBeenPlacedTest to use value objects test(entities): update OrderTest to use value objects for employee details test(value-objects): update EmployeeUpsertDataTest to use value objects test(pagination): update PaginationTest to access value properties test(services): update AppCustomerAuthServiceTest to use CrmHashcode test(services): update CrmServiceTest to use CrmHashcode for customer retrieval --- app/Actions/Settings/UpdateSettingsInput.php | 6 - app/Casts/EmployeeSitesCast.php | 81 ++++++++++ app/Dto/SettingDto.php | 16 +- .../Bo/Settings/UpdateSettingsRequest.php | 3 +- .../Fo/Customer/UpdateInfosRequest.php | 8 +- app/Models/Setting.php | 52 ++----- .../Slides/GetPaginatedSlidesQuery.php | 2 +- .../Slides/GetPaginatedSlidesQueryInput.php | 2 +- domain/Models/ValueObjects/Slug.php | 3 +- .../EloquentEmployeeImportStorageService.php | 2 +- phpunit.xml | 1 + tests/Architecture/NamingConventionsTest.php | 6 +- .../Bo/EmployeesControllerTest.php | 46 +++--- .../Fo/Auth/LoginControllerTest.php | 20 ++- .../Fo/Customers/CustomerControllerTest.php | 11 +- .../Fo/Customers/PasswordControllerTest.php | 8 +- .../Fo/NewsletterControllerTest.php | 27 +++- .../Controllers/Fo/TunnelControllerTest.php | 21 +-- .../Bo/Employees/ImportRequestTest.php | 58 ------- .../Fo/Customer/UpdateInfosRequestTest.php | 37 +++-- .../Fo/Orders/PickTimeSlotRequestTest.php | 9 +- .../Fo/UnsubscribeNewsletterRequestTest.php | 43 ++--- .../Bo/Employees/EmployeeSyncFeatureTest.php | 6 +- .../Actions/Settings/UpdateSettingsTest.php | 3 +- .../GetPaginatedDiscountsQueryTest.php | 5 +- .../Faqs/GetPaginatedFaqsQueryTest.php | 9 +- .../GetTunnelOrderConfirmedQueryTest.php | 22 +-- .../Queries/Pages/GetPageBySlugQueryTest.php | 8 +- .../GetPaginatedPickupExceptionsQueryTest.php | 5 +- .../Ranges/GetPaginatedRangesQueryTest.php | 9 +- .../Queries/Settings/GetSettingsQueryTest.php | 3 +- .../Shops/GetPaginatedShopsQueryTest.php | 7 +- .../Slides/GetPaginatedSlidesQueryTest.php | 9 +- .../WithApp/App/Services/OrderServiceTest.php | 147 ++++++++++++------ .../EloquentOrderDirectoryTest.php | 7 +- .../EloquentOrderRepositoryTest.php | 4 +- tests/Pest.php | 4 - tests/TestCase.php | 36 +++++ .../App/Actions/Orders/FinalizeOrderTest.php | 11 +- .../Settings/UpdateSettingsInputTest.php | 3 +- .../Unit/App/Casts/EmployeeSitesCastTest.php | 105 +++++++++++++ .../ShopperEstablishmentCodeCastTest.php | 12 +- .../App/Casts/ShopperServiceCodeCastTest.php | 12 +- .../App/Casts/ShopperSiteCodeCastTest.php | 12 +- tests/Unit/App/Dto/ProductDtoTest.php | 24 ++- tests/Unit/App/Dto/SettingDtoTest.php | 3 - .../Events/AnOrderHasBeenPlacedTest.php | 7 +- .../Unit/Domain/Models/Entities/OrderTest.php | 9 +- .../Models/ValueObjects/CsvImportFileTest.php | 71 --------- .../ValueObjects/EmployeeUpsertDataTest.php | 32 ++-- .../ValueObjects/ImportRowResultTest.php | 94 ----------- .../Models/ValueObjects/OrderEmployeeTest.php | 63 ++++---- .../Models/ValueObjects/PaginationTest.php | 20 +-- .../Services/AppCustomerAuthServiceTest.php | 33 ++-- tests/Unit/Services/CrmServiceTest.php | 41 +++-- 55 files changed, 693 insertions(+), 605 deletions(-) create mode 100644 app/Casts/EmployeeSitesCast.php delete mode 100644 tests/Feature/App/Http/Requests/Bo/Employees/ImportRequestTest.php create mode 100644 tests/Unit/App/Casts/EmployeeSitesCastTest.php delete mode 100644 tests/Unit/Domain/Models/ValueObjects/CsvImportFileTest.php delete mode 100644 tests/Unit/Domain/Models/ValueObjects/ImportRowResultTest.php diff --git a/app/Actions/Settings/UpdateSettingsInput.php b/app/Actions/Settings/UpdateSettingsInput.php index a3fcc315..28b113f1 100644 --- a/app/Actions/Settings/UpdateSettingsInput.php +++ b/app/Actions/Settings/UpdateSettingsInput.php @@ -10,18 +10,12 @@ use Webmozart\Assert\Assert; final readonly class UpdateSettingsInput implements ActionInput { - /** @var array */ - public array $arcadiaSites; - /** * @param array $employeeSites - * @param array|null $arcadiaSites */ public function __construct( public array $employeeSites = [], - ?array $arcadiaSites = null, ) { - $this->arcadiaSites = $arcadiaSites ?? $this->employeeSites; Assert::allIsInstanceOf($this->employeeSites, ShopperSiteCode::class); } } diff --git a/app/Casts/EmployeeSitesCast.php b/app/Casts/EmployeeSitesCast.php new file mode 100644 index 00000000..f9e139e6 --- /dev/null +++ b/app/Casts/EmployeeSitesCast.php @@ -0,0 +1,81 @@ +, array|string|null> + */ +class EmployeeSitesCast implements CastsAttributes +{ + /** + * Cast the given value. + * + * @param array $attributes + * @return string[] + */ + public function get(Model $model, string $key, mixed $value, array $attributes) + { + if ($value === null || $value === '') { + return []; + } + + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : []; + } + + if (! is_array($value)) { + return []; + } + + $sites = []; + foreach ($value as $item) { + if (is_string($item)) { + $sites[] = $item; + } elseif (is_scalar($item) || $item instanceof \Stringable) { + $sites[] = (string) $item; + } + } + + return $sites; + } + + /** + * Prepare the given value for storage. + * + * @param array $attributes + */ + public function set(Model $model, string $key, mixed $value, array $attributes): string + { + if ($value === null) { + return (string) json_encode([]); + } + + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : [$value]; + } + + if (! is_array($value)) { + throw new \UnexpectedValueException('Employee sites must be an array, string or null.'); + } + + $sites = []; + foreach ($value as $item) { + if (is_string($item)) { + $sites[] = $item; + } elseif (is_scalar($item) || $item instanceof \Stringable) { + $sites[] = (string) $item; + } else { + throw new \UnexpectedValueException('Each employee site must be convertable to string.'); + } + } + + return (string) json_encode($sites); + } +} diff --git a/app/Dto/SettingDto.php b/app/Dto/SettingDto.php index 2f33f050..be99389e 100644 --- a/app/Dto/SettingDto.php +++ b/app/Dto/SettingDto.php @@ -14,26 +14,20 @@ use Illuminate\Contracts\Support\Arrayable; */ final readonly class SettingDto implements Arrayable, UrlRoutable { - /** @var array */ - public array $arcadiaSites; - /** * @param array $employeeSites - * @param array|null $arcadiaSites */ public function __construct( public int $id, public array $employeeSites = [], - ?array $arcadiaSites = null, ) { - $this->arcadiaSites = $arcadiaSites ?? $this->employeeSites; } public static function fromModel(Setting $setting): self { return new self( id: $setting->id, - employeeSites: $setting->employee_sites ?? $setting->arcadia_sites ?? [], + employeeSites: $setting->employee_sites ?? [], ); } @@ -42,11 +36,6 @@ final readonly class SettingDto implements Arrayable, UrlRoutable return implode(', ', $this->employeeSites); } - public function arcadiaSitesAsString(): string - { - return $this->employeeSitesAsString(); - } - /** * @return array */ @@ -83,7 +72,7 @@ final readonly class SettingDto implements Arrayable, UrlRoutable } /** - * @return array{id: int, employee_sites: array, arcadia_sites: array} + * @return array{id: int, employee_sites: array} */ #[\Override] public function toArray(): array @@ -91,7 +80,6 @@ final readonly class SettingDto implements Arrayable, UrlRoutable return [ 'id' => $this->id, 'employee_sites' => $this->employeeSites, - 'arcadia_sites' => $this->arcadiaSites, ]; } } diff --git a/app/Http/Requests/Bo/Settings/UpdateSettingsRequest.php b/app/Http/Requests/Bo/Settings/UpdateSettingsRequest.php index 1c6d0795..8e2f6c5a 100644 --- a/app/Http/Requests/Bo/Settings/UpdateSettingsRequest.php +++ b/app/Http/Requests/Bo/Settings/UpdateSettingsRequest.php @@ -24,7 +24,7 @@ class UpdateSettingsRequest extends FormRequest #[\Override] protected function prepareForValidation(): void { - $rawSites = $this->input('employee_sites') ?? $this->input('arcadia_sites'); + $rawSites = $this->input('employee_sites'); if (is_string($rawSites)) { $split = preg_split('/[\s,]+/', $rawSites) ?: []; @@ -45,7 +45,6 @@ class UpdateSettingsRequest extends FormRequest $this->merge([ 'employee_sites' => $sites, - 'arcadia_sites' => $sites, ]); } diff --git a/app/Http/Requests/Fo/Customer/UpdateInfosRequest.php b/app/Http/Requests/Fo/Customer/UpdateInfosRequest.php index 84c98e6c..361c2ac7 100644 --- a/app/Http/Requests/Fo/Customer/UpdateInfosRequest.php +++ b/app/Http/Requests/Fo/Customer/UpdateInfosRequest.php @@ -35,11 +35,11 @@ class UpdateInfosRequest extends FormRequest firstname: $this->string('firstname')->value(), lastname: $this->string('lastname')->value(), birthDate: $this->string('birth_date')->value(), - phone: $this->string('phone')->value(), + phone: ! $this->string('phone')->isEmpty() ? + $this->string('phone')->value() : null, city: $this->string('city')->value(), - postcode: ! empty($this->string('postcode')) ? - $this->string('postcode')->value() : null, - address: ! empty($this->string('address')) ? + postcode: $this->string('postcode')->value(), + address: ! $this->string('address')->isEmpty() ? $this->string('address')->value() : null, optIn: $this->boolean('opt_in'), ); diff --git a/app/Models/Setting.php b/app/Models/Setting.php index 66a50036..38a37906 100644 --- a/app/Models/Setting.php +++ b/app/Models/Setting.php @@ -4,15 +4,14 @@ declare(strict_types=1); namespace App\Models; -use Domain\Models\ValueObjects\ShopperSiteCode; +use App\Casts\EmployeeSitesCast; use Illuminate\Database\Eloquent\Model; /** * @property int $id - * @property array|null $employee_sites + * @property string[]|null $employee_sites * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at - * @property array|null $arcadia_sites * * @mixin \Eloquent */ @@ -25,56 +24,23 @@ class Setting extends Model ]; /** - * @return array + * @return array */ #[\Override] protected function casts(): array { return [ - 'employee_sites' => 'array', + 'employee_sites' => EmployeeSitesCast::class, ]; } - /** - * Backward-compatibility accessor - * - * @return array|null - */ - public function getArcadiaSitesAttribute(): ?array - { - return $this->employee_sites; - } - - /** - * Backward-compatibility mutator - * - * @param array|null $value - */ - public function setArcadiaSitesAttribute(?array $value): void - { - $this->employee_sites = $value; - } - public static function getSingleton(): self { - /** @var self $setting */ - $setting = self::query()->firstOrCreate(['id' => self::SINGLETON_ID], [ - 'employee_sites' => [], - ]); - - return $setting; - } - - /** - * @return array - */ - public function getShopperSiteCodes(): array - { - $sites = $this->employee_sites ?? []; - - return array_map( - static fn (string $site): ShopperSiteCode => new ShopperSiteCode($site), - $sites + return self::query()->firstOrCreate( + ['id' => self::SINGLETON_ID], + [ + 'employee_sites' => [], + ] ); } } diff --git a/app/Queries/Slides/GetPaginatedSlidesQuery.php b/app/Queries/Slides/GetPaginatedSlidesQuery.php index 63466f65..50905074 100644 --- a/app/Queries/Slides/GetPaginatedSlidesQuery.php +++ b/app/Queries/Slides/GetPaginatedSlidesQuery.php @@ -37,7 +37,7 @@ final readonly class GetPaginatedSlidesQuery implements Query $query->where('status', true); } - if (! $input->forConnectedCustomers) { + if ($input->forConnectedCustomers === false) { $query->where('connected', false); } diff --git a/app/Queries/Slides/GetPaginatedSlidesQueryInput.php b/app/Queries/Slides/GetPaginatedSlidesQueryInput.php index 03774c23..4b93fc68 100644 --- a/app/Queries/Slides/GetPaginatedSlidesQueryInput.php +++ b/app/Queries/Slides/GetPaginatedSlidesQueryInput.php @@ -12,7 +12,7 @@ final readonly class GetPaginatedSlidesQueryInput implements QueryInput public function __construct( public Pagination $pagination, public bool $publishedOnly = false, - public bool $forConnectedCustomers = false, + public ?bool $forConnectedCustomers = null, ) { } } diff --git a/domain/Models/ValueObjects/Slug.php b/domain/Models/ValueObjects/Slug.php index f691f84c..ae07b19f 100644 --- a/domain/Models/ValueObjects/Slug.php +++ b/domain/Models/ValueObjects/Slug.php @@ -4,10 +4,9 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; -use Stringable; use Webmozart\Assert\Assert; -final readonly class Slug implements Stringable +final readonly class Slug implements \Stringable { public function __construct(public string $value) { diff --git a/infra/Adapters/Services/EloquentEmployeeImportStorageService.php b/infra/Adapters/Services/EloquentEmployeeImportStorageService.php index 8908efc7..7e00ff99 100644 --- a/infra/Adapters/Services/EloquentEmployeeImportStorageService.php +++ b/infra/Adapters/Services/EloquentEmployeeImportStorageService.php @@ -16,7 +16,7 @@ class EloquentEmployeeImportStorageService implements EmployeeImportStorageServi */ public function upsertEmployees(array $upsertData): void { - $now = CarbonImmutable::now()->format('Y-m-d H:i:s'); + $now = CarbonImmutable::now()->format('Y-m-d H:i:s'); $mappedData = array_map(static function (EmployeeUpsertData $data) use ($now): array { return [ 'matricule' => $data->matricule->value, diff --git a/phpunit.xml b/phpunit.xml index 3fa956df..a0328cd8 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -42,6 +42,7 @@ ./app ./domain ./infra + ./shared ./config diff --git a/tests/Architecture/NamingConventionsTest.php b/tests/Architecture/NamingConventionsTest.php index 29ac29dd..0e108688 100644 --- a/tests/Architecture/NamingConventionsTest.php +++ b/tests/Architecture/NamingConventionsTest.php @@ -3,6 +3,8 @@ declare(strict_types=1); use App\Exceptions\GlobalHandler; +use App\Services\ArcadiaEmployee; +use App\Services\EmployeeSyncServiceResult; use Symfony\Component\Finder\Finder; describe('naming conventions in app', function (): void { @@ -49,8 +51,8 @@ describe('naming conventions in app', function (): void { ->expect("App\Services") ->toHaveSuffix('Service') ->ignoring([ - App\Services\ArcadiaEmployee::class, - App\Services\EmployeeSyncServiceResult::class, + ArcadiaEmployee::class, + EmployeeSyncServiceResult::class, ]); arch('queries have Query, QueryInput or QueryOutput suffix', function (): void { diff --git a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php index a54b4286..5391cbe6 100644 --- a/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/EmployeesControllerTest.php @@ -2,9 +2,10 @@ declare(strict_types=1); +use App\Jobs\FetchAndUpsertArcadiaEmployees; use App\Models\User; use Domain\Enums\UserRole; -use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Queue; describe('EmployeesController', function () { beforeEach(function () { @@ -14,38 +15,29 @@ describe('EmployeesController', function () { $this->actingAs($this->user, 'backend'); }); - it('can access import form', function () { - // WHEN - /** @var \Tests\TestCase $this */ - $response = $this->get('/bo/settings/employees'); - - // THEN - $response->assertOk(); - $response->assertViewHas('importColumns'); - }); - - it('can download example file', function () { - // WHEN - /** @var \Tests\TestCase $this */ - $response = $this->get('/bo/settings/employees/import-example'); - - // THEN - $response->assertOk(); - }); - - it('can import employees file', function () { + it('can launch employee sync job', function () { // GIVEN /** @var \Tests\TestCase $this */ - $csvContent = "identifiant;nom;prenom;solde\nEMP001;Dupont;Jean;100.00\n"; - $file = UploadedFile::fake()->createWithContent('employees.csv', $csvContent); + Queue::fake(); // WHEN - $response = $this->post('/bo/settings/employees/file', [ - 'import' => $file, - ]); + $response = $this->post('/bo/settings/employees/sync'); // THEN $response->assertSessionHasNoErrors(); - $response->assertRedirect('/bo/settings/employees'); + $response->assertRedirect(route('bo.dashboard')); + Queue::assertPushed(FetchAndUpsertArcadiaEmployees::class); + }); + + it('redirects unauthenticated users to login', function () { + // GIVEN + /** @var \Tests\TestCase $this */ + auth()->guard('backend')->logout(); + + // WHEN + $response = $this->post('/bo/settings/employees/sync'); + + // THEN + $response->assertRedirect('/bo/login'); }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php index a57962ea..ab011f18 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Auth/LoginControllerTest.php @@ -14,6 +14,9 @@ use Domain\Models\ValueObjects\CrmCustomer; use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\ShopperService; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; @@ -21,6 +24,7 @@ use Illuminate\Support\Str; describe('LoginController', function () { it('can access get /auth/connexion', function () { + /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() @@ -37,6 +41,7 @@ describe('LoginController', function () { }); it('can access post /auth/connexion', function () { + /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() @@ -53,6 +58,7 @@ describe('LoginController', function () { }); it('can access post /auth/deconnexion', function () { + /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() @@ -74,6 +80,7 @@ describe('LoginController', function () { }); it('throws CustomerNotEmployedException when shopper is not active during login', function () { + /** @var \Tests\TestCase $this */ // GIVEN $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() @@ -88,7 +95,7 @@ describe('LoginController', function () { ]); $crmCustomer = new CrmCustomer( - hashcode: $customer->hashcode, + hashcode: $customer->hashcode->value, email: 'test@example.com', password: 'password', firstname: 'John', @@ -118,7 +125,7 @@ describe('LoginController', function () { // WHEN $this->withoutExceptionHandling(); - $response = $this->post('/auth/connexion', [ + $this->post('/auth/connexion', [ 'email' => 'test@example.com', 'password' => 'password', ]); @@ -126,6 +133,7 @@ describe('LoginController', function () { it('flashes success message when shopper is active during login', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -139,7 +147,7 @@ describe('LoginController', function () { ]); $crmCustomer = new CrmCustomer( - hashcode: $customer->hashcode, + hashcode: $customer->hashcode->value, email: 'test2@example.com', password: 'password', firstname: 'John', @@ -167,9 +175,9 @@ describe('LoginController', function () { prenom: 'John', startDate: CarbonImmutable::now()->subDays(1), endDate: null, - etablissement: 'Etab', - site: 'Site', - service: 'Service' + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $shopperService = \Mockery::mock(ShopperService::class); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php index e06b6711..08b6f02c 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/CustomerControllerTest.php @@ -9,10 +9,13 @@ use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; describe('CustomerController', function () { it('can access get /compte', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -21,7 +24,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -37,6 +40,7 @@ describe('CustomerController', function () { it('can access get /compte/profil', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -45,7 +49,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -61,6 +65,7 @@ describe('CustomerController', function () { it('can access post /compte/profil', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -69,7 +74,7 @@ describe('CustomerController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); diff --git a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php index 2e72c154..4a6250e1 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Customers/PasswordControllerTest.php @@ -9,10 +9,13 @@ use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; describe('PasswordController', function () { it('can access get /compte/mot-de-passe', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -21,7 +24,7 @@ describe('PasswordController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); @@ -37,6 +40,7 @@ describe('PasswordController', function () { it('can access post /compte/mot-de-passe', function () { // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -45,7 +49,7 @@ describe('PasswordController', function () { Cache::flush(); $user = \Mockery::mock(Customer::class)->makePartial(); $user->shouldReceive('getAuthIdentifier')->andReturn(1); - $user->hashcode = 'dummy_hashcode'; + $user->hashcode = new CrmHashcode(Uuid::uuid4()); $user->shouldReceive('getAuthPassword')->andReturn('dummy'); $this->actingAs($user, 'frontend'); $crmMock = \Mockery::mock(CrmService::class)->makePartial(); diff --git a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php index e8736e05..6ed3777e 100644 --- a/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/NewsletterControllerTest.php @@ -3,13 +3,36 @@ declare(strict_types=1); use App\Models\Page; +use App\Services\CrmService; use Database\Seeders\ContentSeeder; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Ramsey\Uuid\Uuid; describe('NewsletterController', function () { - it('can access get /unsubscribe', function () { + it('can access get /unsubscribe with valid hashcode', function () { // GIVEN + /** @var \Tests\TestCase $this */ + $crmMock = $this->mock(CrmService::class); + $crmMock->shouldReceive('unsubscribeCustomer')->andReturn(true); + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + $hashcode = Uuid::uuid4()->toString(); + + // WHEN + $response = $this->get('/unsubscribe?hashcode=' . $hashcode); + + // THEN + $response->assertStatus(200); + }); + + it('redirects when hashcode is missing', function () { + // GIVEN + /** @var \Tests\TestCase $this */ $this->seed(ContentSeeder::class); View::share('PageList', Page::getCached() ->mapWithKeys(fn ($page) => [ @@ -21,6 +44,6 @@ describe('NewsletterController', function () { $response = $this->get('/unsubscribe'); // THEN - $response->assertStatus(200); + $response->assertStatus(302); }); }); diff --git a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php index 45a9a079..a26d215a 100644 --- a/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/TunnelControllerTest.php @@ -27,6 +27,9 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\ShopperRepository; use Domain\Services\OrderTunnelService; use Illuminate\Support\Facades\Cache; @@ -318,9 +321,9 @@ describe('TunnelController', function (): void { prenom: 'Jean', startDate: now()->subMonth(), endDate: null, - etablissement: 'Fac', - site: 'Site', - service: 'Service', + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $this->mock(ShopperRepository::class, function ($mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); @@ -375,9 +378,9 @@ describe('TunnelController', function (): void { prenom: 'Jean', startDate: now()->subMonth(), endDate: null, - etablissement: 'Fac', - site: 'Site', - service: 'Service', + etablissement: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $this->mock(ShopperRepository::class, function ($mock) use ($shopper): void { $mock->shouldReceive('getByIdOrFail')->andReturn($shopper); @@ -580,9 +583,9 @@ describe('TunnelController', function (): void { firstname: 'Jean', lastname: 'Dupont', matricule: new Matricule('1234567'), - facility: 'Fac', - site: 'Site', - service: 'Service', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $order->delivery_address = new DeliveryAddress( name: $shop->name, diff --git a/tests/Feature/App/Http/Requests/Bo/Employees/ImportRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Employees/ImportRequestTest.php deleted file mode 100644 index 292d7343..00000000 --- a/tests/Feature/App/Http/Requests/Bo/Employees/ImportRequestTest.php +++ /dev/null @@ -1,58 +0,0 @@ -shouldReceive('check')->once()->andReturn(true); - - $request = new ImportRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect($request->authorize())->toBeTrue(); - }); - - it('fails getSalarieImportFile if not set', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new ImportRequest($authService); - - // WHEN - $request->initialize(); - - // THEN - expect(fn () => $request->getSalarieImportFile())->toThrow(\UnexpectedValueException::class, 'importedFile should not be null'); - }); - - it('passes validation sets importedFile with valid file', function () { - // GIVEN - $authService = mock(AppAdminAuthService::class); - $request = new ImportRequest($authService); - $request->initialize(); - - $file = UploadedFile::fake()->createWithContent('import.csv', 'col1,col2' . "\n" . 'val1,val2'); - $request->files->set('import', $file); - - $reflection = new \ReflectionClass($request); - $passedMethod = $reflection->getMethod('passedValidation'); - $passedMethod->setAccessible(true); - $passedMethod->invoke($request); - - // WHEN - $importedFile = $request->getSalarieImportFile(); - - // THEN - expect($importedFile->fileContent)->toBe("col1,col2\nval1,val2"); - }); -}); diff --git a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php index 37dd3e88..df6f6ea2 100644 --- a/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Customer/UpdateInfosRequestTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use App\Actions\Crm\UpdateCustomerInput; use App\Http\Requests\Fo\Customer\UpdateInfosRequest; use Infrastructure\Adapters\Services\AppCustomerAuthService; @@ -52,7 +53,7 @@ describe('UpdateInfosRequest', function () { expect($request->input('opt_in'))->toBeTrue(); }); - it('converts to crm data', function () { + it('converts to UpdateCustomerInput', function () { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new UpdateInfosRequest($authService); @@ -69,23 +70,21 @@ describe('UpdateInfosRequest', function () { ]); // WHEN - $data = $request->toCrmData(); + $input = $request->toUpdateCustomerInput(); // THEN - expect($data)->toBeArray() - ->and($data)->toMatchArray([ - 'firstname' => 'John', - 'lastname' => 'Doe', - 'birth_date' => '1990-01-01', - 'phone' => '0102030405', - 'city' => 'Paris', - 'postcode' => '75000', - 'address' => '123 Main St', - 'opt_in' => true, - ]); + expect($input)->toBeInstanceOf(UpdateCustomerInput::class) + ->and($input->firstname)->toBe('John') + ->and($input->lastname)->toBe('Doe') + ->and($input->birthDate)->toBe('1990-01-01') + ->and($input->phone)->toBe('0102030405') + ->and($input->city)->toBe('Paris') + ->and($input->postcode)->toBe('75000') + ->and($input->address)->toBe('123 Main St') + ->and($input->optIn)->toBeTrue(); }); - it('converts to crm data with empty postcode and address as null', function () { + it('converts to UpdateCustomerInput with empty address and phone as null', function () { // GIVEN $authService = \Mockery::mock(AppCustomerAuthService::class); $request = new UpdateInfosRequest($authService); @@ -96,18 +95,18 @@ describe('UpdateInfosRequest', function () { 'birth_date' => '1990-01-01', 'phone' => '', 'city' => 'Paris', - 'postcode' => '', + 'postcode' => '75000', 'address' => '', 'opt_in' => false, ]); // WHEN - $data = $request->toCrmData(); + $input = $request->toUpdateCustomerInput(); // THEN - expect($data)->toBeArray() - ->and($data['postcode'])->toBe('') - ->and($data['address'])->toBe(''); + expect($input)->toBeInstanceOf(UpdateCustomerInput::class) + ->and($input->phone)->toBeNull() + ->and($input->address)->toBeNull(); }); it('validates rules', function () { diff --git a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php index c9453192..08862a8f 100644 --- a/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/Orders/PickTimeSlotRequestTest.php @@ -13,6 +13,9 @@ use Domain\Models\ValueObjects\Email; use Domain\Models\ValueObjects\Entities\BasketId; use Domain\Models\ValueObjects\Entities\ShopperId; use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Ports\Repositories\ShopperRepository; use Domain\Services\BasketService; use Domain\Services\OrderTunnelService; @@ -146,9 +149,9 @@ describe('PickTimeSlotRequest', function () { 'Prenom', now(), null, - 'Etablissement', - 'Site', - 'Service', + new ShopperEstablishmentCode('FAC01'), + new ShopperSiteCode('SITE'), + new ShopperServiceCode('101'), ); $authService = \Mockery::mock(AppCustomerAuthService::class); diff --git a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php index a62e0845..38a9c610 100644 --- a/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php +++ b/tests/Feature/App/Http/Requests/Fo/UnsubscribeNewsletterRequestTest.php @@ -5,6 +5,7 @@ declare(strict_types=1); use App\Http\Requests\Fo\UnsubscribeNewsletterRequest; use Illuminate\Support\Facades\Validator; use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; describe('UnsubscribeNewsletterRequest', function () { it('validates correct rules', function () { @@ -38,60 +39,34 @@ describe('UnsubscribeNewsletterRequest', function () { ->and($validator->errors()->keys())->toContain('hashcode'); }); - it('returns null for hashcode if not validated', function () { + it('returns null for hashcode if invalid or missing', function () { // GIVEN $request = new UnsubscribeNewsletterRequest(); $request->initialize(); // WHEN $request->merge([ - 'hashcode' => Uuid::uuid4()->toString(), + 'hashcode' => 'not-a-uuid', ]); // THEN expect($request->getHashcode())->toBeNull(); }); - it('returns hashcode if validated', function () { + it('returns CrmHashcode if valid uuid', function () { // GIVEN $request = new UnsubscribeNewsletterRequest(); $request->initialize(); - $hashcode = Uuid::uuid4()->toString(); + $uuid = Uuid::uuid4(); $request->merge([ - 'hashcode' => $hashcode, + 'hashcode' => $uuid->toString(), ]); - $reflection = new \ReflectionClass($request); - $method = $reflection->getMethod('passedValidation'); - $method->setAccessible(true); - // WHEN - $method->invoke($request); + $result = $request->getHashcode(); // THEN - expect($request->getHashcode())->toBe($hashcode); - }); - - it('sets validated to false on failed validation', function () { - // GIVEN - $request = new UnsubscribeNewsletterRequest(); - $request->initialize(); - - $reflection = new \ReflectionClass($request); - - $property = $reflection->getProperty('validated'); - $property->setAccessible(true); - $property->setValue($request, true); - - $method = $reflection->getMethod('failedValidation'); - $method->setAccessible(true); - - $validator = Validator::make([], []); - - // WHEN - $method->invoke($request, $validator); - - // THEN - expect($property->getValue($request))->toBeFalse(); + expect($result)->toBeInstanceOf(CrmHashcode::class) + ->and($result->value)->toBe($uuid->toString()); }); }); diff --git a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php b/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php index 51c71429..e9fd3f45 100644 --- a/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php +++ b/tests/Feature/Bo/Employees/EmployeeSyncFeatureTest.php @@ -40,10 +40,10 @@ describe('Employee Sync Feature E2E', function (): void { expect($setting->employee_sites)->toBe(['PA', 'LY']); // 2. Mock ArcadiaEmployeeService to return employee data for site PA - $mockArcadia = Mockery::mock(ArcadiaEmployeeService::class); + $mockArcadia = \Mockery::mock(ArcadiaEmployeeService::class); $mockArcadia->shouldReceive('getEmployeesOfSiteSince') ->once() - ->with(Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), Mockery::any()) + ->with(\Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'PA'), \Mockery::any()) ->andReturn([ new ArcadiaEmployee( matricule: new Matricule('7654321'), @@ -59,7 +59,7 @@ describe('Employee Sync Feature E2E', function (): void { $mockArcadia->shouldReceive('getEmployeesOfSiteSince') ->once() - ->with(Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), Mockery::any()) + ->with(\Mockery::on(static fn (ShopperSiteCode $code): bool => $code->value === 'LY'), \Mockery::any()) ->andReturn([]); $this->app->instance(ArcadiaEmployeeService::class, $mockArcadia); diff --git a/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php b/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php index 9a282047..5c1df5c5 100644 --- a/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php +++ b/tests/Integration/WithApp/App/Actions/Settings/UpdateSettingsTest.php @@ -26,8 +26,7 @@ describe('UpdateSettings', function (): void { // THEN expect($setting)->toBeInstanceOf(Setting::class) - ->and($setting->employee_sites)->toBe(['PA', 'LY']) - ->and($setting->arcadia_sites)->toBe(['PA', 'LY']); + ->and($setting->employee_sites)->toBe(['PA', 'LY']); $this->assertDatabaseHas('settings', [ 'id' => Setting::SINGLETON_ID, diff --git a/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php b/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php index e0c33d10..139cf3bf 100644 --- a/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php @@ -12,6 +12,9 @@ use App\Queries\Discounts\GetPaginatedDiscountsQueryInput; use App\Services\DataTableService; use Domain\Enums\DiscountType; use Domain\Models\ValueObjects\DiscountValue; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; describe('GetPaginatedDiscountsQuery', function (): void { it('returns a paginator of DiscountDto instances', function (): void { @@ -30,7 +33,7 @@ describe('GetPaginatedDiscountsQuery', function (): void { $query = new GetPaginatedDiscountsQuery(app(DataTableService::class)); $input = new GetPaginatedDiscountsQueryInput( - pagination: Pagination::ofPage(1, 10), + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); // WHEN diff --git a/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php b/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php index a48db8de..c191c6d2 100644 --- a/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Faqs/GetPaginatedFaqsQueryTest.php @@ -5,6 +5,10 @@ declare(strict_types=1); use App\Dto\FaqDto; use App\Models\Faq; use App\Queries\Faqs\GetPaginatedFaqsQuery; +use App\Queries\Faqs\GetPaginatedFaqsQueryInput; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; describe('GetPaginatedFaqsQuery', function (): void { it('returns a paginator of FaqDto instances', function (): void { @@ -21,9 +25,12 @@ describe('GetPaginatedFaqsQuery', function (): void { /** @var GetPaginatedFaqsQuery $query */ $query = app(GetPaginatedFaqsQuery::class); + $input = new GetPaginatedFaqsQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + ); // WHEN - $paginator = $query->execute(); + $paginator = $query($input); // THEN expect($paginator->total())->toBe(2); diff --git a/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php b/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php index d86e46c2..74061bf2 100644 --- a/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Orders/GetTunnelOrderConfirmedQueryTest.php @@ -17,9 +17,11 @@ use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; use Symfony\Component\Uid\Uuid; -use UnexpectedValueException; describe('GetTunnelOrderConfirmedQuery', function (): void { it('returns order confirmed output with step, orderDto, shopDto and mapUrl', function (): void { @@ -47,12 +49,12 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { city: $shop->city, ); $order->employee = new OrderEmployee( + matricule: new Matricule('1234567'), firstname: 'Jean', lastname: 'Dupont', - matricule: new Matricule('1234567'), - facility: 'Fac', - site: 'Site', - service: 'Service', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $order->save(); @@ -84,12 +86,12 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $order->pickup_day = now()->addDays(2); $order->shop_id = null; $order->employee = new OrderEmployee( + matricule: new Matricule('1234567'), firstname: 'Jean', lastname: 'Dupont', - matricule: new Matricule('1234567'), - facility: 'Fac', - site: 'Site', - service: 'Service', + facility: new ShopperEstablishmentCode('FAC01'), + site: new ShopperSiteCode('SITE'), + service: new ShopperServiceCode('101'), ); $order->delivery_address = new DeliveryAddress( name: 'Nom', @@ -104,6 +106,6 @@ describe('GetTunnelOrderConfirmedQuery', function (): void { $input = new GetTunnelOrderConfirmedQueryInput($order); // WHEN & THEN - expect(fn () => $query($input))->toThrow(UnexpectedValueException::class); + expect(fn () => $query($input))->toThrow(\UnexpectedValueException::class); }); }); diff --git a/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php b/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php index 18258ae6..bac78717 100644 --- a/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Pages/GetPageBySlugQueryTest.php @@ -5,7 +5,9 @@ declare(strict_types=1); use App\Dto\PageDto; use App\Models\Page; use App\Queries\Pages\GetPageQuery; +use App\Queries\Pages\GetPageQueryInput; use Domain\Enums\StaticPageSlug; +use Domain\Models\ValueObjects\Slug; use Illuminate\Database\Eloquent\ModelNotFoundException; describe('GetPageBySlugQuery', function (): void { @@ -23,7 +25,7 @@ describe('GetPageBySlugQuery', function (): void { $query = app(GetPageQuery::class); // WHEN - $dto = $query->execute(StaticPageSlug::LEGALS); + $dto = $query(new GetPageQueryInput(new Slug(StaticPageSlug::LEGALS->value))); // THEN expect($dto)->toBeInstanceOf(PageDto::class) @@ -47,7 +49,7 @@ describe('GetPageBySlugQuery', function (): void { $query = app(GetPageQuery::class); // WHEN - $dto = $query->execute('cgv'); + $dto = $query(new GetPageQueryInput(new Slug('cgv'))); // THEN expect($dto)->toBeInstanceOf(PageDto::class) @@ -61,7 +63,7 @@ describe('GetPageBySlugQuery', function (): void { $query = app(GetPageQuery::class); // WHEN - expect(fn () => $query->execute('non-existent-slug')) + expect(fn () => $query(new GetPageQueryInput(new Slug('non-existent-slug')))) // THEN ->toThrow(ModelNotFoundException::class); }); diff --git a/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php b/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php index b16480d7..66104389 100644 --- a/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/PickupExceptions/GetPaginatedPickupExceptionsQueryTest.php @@ -9,6 +9,9 @@ use App\Queries\PickupExceptions\GetPaginatedPickupExceptionsQueryInput; use App\Services\DataTableService; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Foundation\Testing\RefreshDatabase; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; uses(RefreshDatabase::class); @@ -20,7 +23,7 @@ describe('GetPaginatedPickupExceptionsQuery', function () { $dataTableService = resolve(DataTableService::class); $query = new GetPaginatedPickupExceptionsQuery($dataTableService); $input = new GetPaginatedPickupExceptionsQueryInput( - pagination: \Pagination::ofPage(1, 10), + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); // WHEN diff --git a/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php b/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php index 1797f3fa..0e501014 100644 --- a/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Ranges/GetPaginatedRangesQueryTest.php @@ -5,8 +5,12 @@ declare(strict_types=1); use App\Dto\RangeDto; use App\Models\Range; use App\Queries\Ranges\GetPaginatedRangesQuery; +use App\Queries\Ranges\GetPaginatedRangesQueryInput; use App\Services\DataTableService; use Illuminate\Foundation\Testing\RefreshDatabase; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; uses(RefreshDatabase::class); @@ -29,9 +33,12 @@ describe('GetPaginatedRangesQuery', function () { $dataTableService = resolve(DataTableService::class); $query = new GetPaginatedRangesQuery($dataTableService); + $input = new GetPaginatedRangesQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + ); // WHEN - $result = $query->execute(); + $result = $query($input); // THEN expect($result->total())->toBe(2) diff --git a/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php b/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php index 08ccf68a..82ec5574 100644 --- a/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Settings/GetSettingsQueryTest.php @@ -25,7 +25,6 @@ describe('GetSettingsQuery', function (): void { // THEN expect($dto)->toBeInstanceOf(SettingDto::class) ->and($dto->id)->toBe(Setting::SINGLETON_ID) - ->and($dto->employeeSites)->toBe(['NA', 'BO']) - ->and($dto->arcadiaSites)->toBe(['NA', 'BO']); + ->and($dto->employeeSites)->toBe(['NA', 'BO']); }); }); diff --git a/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php b/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php index 7e1121f1..e7025210 100644 --- a/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Shops/GetPaginatedShopsQueryTest.php @@ -11,6 +11,9 @@ use App\Queries\Shops\GetPaginatedShopsQueryInput; use App\Queries\Shops\GetPaginatedShopsQueryOutput; use App\Services\DataTableService; use Illuminate\Foundation\Testing\RefreshDatabase; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; uses(RefreshDatabase::class); @@ -24,7 +27,7 @@ describe('GetPaginatedShopsQuery', function () { $dataTableService = resolve(DataTableService::class); $query = new GetPaginatedShopsQuery($dataTableService); $input = new GetPaginatedShopsQueryInput( - pagination: \Pagination::ofPage(1, 10), + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), ); // WHEN @@ -50,7 +53,7 @@ describe('GetPaginatedShopsQuery', function () { $dataTableService = resolve(DataTableService::class); $query = new GetPaginatedShopsQuery($dataTableService); $input = new GetPaginatedShopsQueryInput( - pagination: \Pagination::ofPage(1, 10), + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), pickupExceptionId: $exception->getId(), ); diff --git a/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php b/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php index 87a327d4..275df894 100644 --- a/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php +++ b/tests/Integration/WithApp/App/Queries/Slides/GetPaginatedSlidesQueryTest.php @@ -5,6 +5,10 @@ declare(strict_types=1); use App\Dto\SlideDto; use App\Models\Slide; use App\Queries\Slides\GetPaginatedSlidesQuery; +use App\Queries\Slides\GetPaginatedSlidesQueryInput; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; describe('GetPaginatedSlidesQuery', function (): void { it('returns a paginator of SlideDto instances', function (): void { @@ -23,9 +27,12 @@ describe('GetPaginatedSlidesQuery', function (): void { /** @var GetPaginatedSlidesQuery $query */ $query = app(GetPaginatedSlidesQuery::class); + $input = new GetPaginatedSlidesQueryInput( + pagination: Pagination::ofPage(new PageNumber(1), new PageSize(10)), + ); // WHEN - $paginator = $query->execute(); + $paginator = $query($input); // THEN expect($paginator->total())->toBe(2) diff --git a/tests/Integration/WithApp/App/Services/OrderServiceTest.php b/tests/Integration/WithApp/App/Services/OrderServiceTest.php index 7c2e4a33..42e0756e 100644 --- a/tests/Integration/WithApp/App/Services/OrderServiceTest.php +++ b/tests/Integration/WithApp/App/Services/OrderServiceTest.php @@ -2,60 +2,63 @@ declare(strict_types=1); -use App\Contracts\Directories\OrderDirectory; use App\Models\Customer; +use App\Models\Employee; use App\Models\Order; use App\Services\OrderService; -use Illuminate\Pagination\LengthAwarePaginator; +use Carbon\CarbonImmutable; +use Domain\Enums\OrderStatus; +use Domain\Models\ValueObjects\Code; +use Domain\Models\ValueObjects\DeliveryAddress; +use Domain\Models\ValueObjects\Email; +use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\OrderEmployee; +use Domain\Models\ValueObjects\OrderReference; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Money\Currency; +use Money\Money; use Ramsey\Uuid\Uuid; +uses(RefreshDatabase::class); + covers(OrderService::class); describe('OrderService', function () { - afterEach(function () { - \Mockery::close(); - }); - - it('paginates orders for a customer', function () { - // GIVEN - $orderDirectory = \Mockery::mock(OrderDirectory::class); - - $customer = new Customer(); - $customer->id = (string) Uuid::uuid7(); - - $pagination = new \Pagination(0, 15); - $paginator = new LengthAwarePaginator([], 0, 15); - - $orderDirectory->shouldReceive('getPaginatedOrdersOf') - ->with($customer, $pagination, true) - ->once() - ->andReturn($paginator); - - $service = new OrderService($orderDirectory); - - // WHEN - $result = $service->paginateOrdersFor($customer, $pagination); - - // THEN - expect($result)->toBe($paginator); - }); - it('returns true if order is owned by customer', function () { // GIVEN - $orderDirectory = \Mockery::mock(OrderDirectory::class); + $customer = Customer::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('owner@example.com'), + ]); - $customer = new Customer(); - $customer->id = (string) Uuid::uuid7(); + Employee::forceCreate([ + 'id' => 301, + 'customer_id' => $customer->id, + 'matricule' => new Matricule('1000301'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'code' => new Code('ABCDEF31'), + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'created_at' => CarbonImmutable::now(), + 'updated_at' => CarbonImmutable::now(), + ]); - $order = new Order(); - $order->id = (string) Uuid::uuid7(); + $order = Order::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'reference' => new OrderReference(\Symfony\Component\Uid\Uuid::v7()->toBase58()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(1000, new Currency('EUR')), + 'employee' => new OrderEmployee(new Matricule('1000301'), 'John', 'Doe', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), + ]); - $orderDirectory->shouldReceive('findOf') - ->with($customer, $order->id) - ->once() - ->andReturn($order); - - $service = new OrderService($orderDirectory); + $service = new OrderService(); // WHEN $result = $service->isOrderOwnedBy($order, $customer); @@ -66,20 +69,62 @@ describe('OrderService', function () { it('returns false if order is not owned by customer', function () { // GIVEN - $orderDirectory = \Mockery::mock(OrderDirectory::class); + $customer = Customer::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('notowner@example.com'), + ]); - $customer = new Customer(); - $customer->id = (string) Uuid::uuid7(); + Employee::forceCreate([ + 'id' => 302, + 'customer_id' => $customer->id, + 'matricule' => new Matricule('1000302'), + 'nom' => 'Doe', + 'prenom' => 'John', + 'code' => new Code('ABCDEF32'), + 'etablissement' => 'ETAB', + 'site' => 'SITE', + 'service' => '101', + 'created_at' => CarbonImmutable::now(), + 'updated_at' => CarbonImmutable::now(), + ]); - $order = new Order(); - $order->id = (string) Uuid::uuid7(); + $order = Order::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'reference' => new OrderReference(\Symfony\Component\Uid\Uuid::v7()->toBase58()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(1000, new Currency('EUR')), + 'employee' => new OrderEmployee(new Matricule('1000999'), 'Other', 'Person', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), + ]); - $orderDirectory->shouldReceive('findOf') - ->with($customer, $order->id) - ->once() - ->andReturn(null); + $service = new OrderService(); - $service = new OrderService($orderDirectory); + // WHEN + $result = $service->isOrderOwnedBy($order, $customer); + + // THEN + expect($result)->toBeFalse(); + }); + + it('returns false if customer has no employee', function () { + // GIVEN + $customer = Customer::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'hashcode' => Uuid::uuid4()->toString(), + 'email' => new Email('noemp@example.com'), + ]); + + $order = Order::forceCreate([ + 'id' => Uuid::uuid7()->toString(), + 'reference' => new OrderReference(\Symfony\Component\Uid\Uuid::v7()->toBase58()), + 'status' => OrderStatus::VALIDATED->value, + 'total' => new Money(1000, new Currency('EUR')), + 'employee' => new OrderEmployee(new Matricule('1000999'), 'Other', 'Person', new ShopperEstablishmentCode('FAC01'), new ShopperSiteCode('SITE'), new ShopperServiceCode('101')), + 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), + ]); + + $service = new OrderService(); // WHEN $result = $service->isOrderOwnedBy($order, $customer); diff --git a/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php b/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php index aafd06ee..d946bbc5 100644 --- a/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php +++ b/tests/Integration/WithApp/Directories/EloquentOrderDirectoryTest.php @@ -29,6 +29,9 @@ use Illuminate\Database\Eloquent\Collection; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +use Shared\Pagination\PageNumber; +use Shared\Pagination\PageSize; +use Shared\Pagination\Pagination; describe('EloquentOrderDirectory', function () { it('returns empty paginator if customer has no employee matricule', function () { @@ -40,7 +43,7 @@ describe('EloquentOrderDirectory', function () { 'email' => new Email('noemp@example.com'), ]); - $pagination = \Shared\Pagination\Pagination::ofPage(new \Shared\Pagination\PageNumber(1), new \Shared\Pagination\PageSize(10)); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); // WHEN $result = $directory->getPaginatedOrdersOf($customer, $pagination); @@ -89,7 +92,7 @@ describe('EloquentOrderDirectory', function () { 'delivery_address' => new DeliveryAddress('Name', 'Addr', '00000', 'City'), ]); - $pagination = \Shared\Pagination\Pagination::ofPage(new \Shared\Pagination\PageNumber(1), new \Shared\Pagination\PageSize(10)); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); // WHEN $result = $directory->getPaginatedOrdersOf($customer, $pagination); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php index 015bce9f..9bbec2a6 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentOrderRepositoryTest.php @@ -74,9 +74,9 @@ it('updates an existing order in the repository', function () { 'matricule' => '1234567', 'firstname' => 'Jean', 'lastname' => 'Dupont', - 'facility' => 'Main Facility', + 'facility' => 'FAC01', 'site' => 'HQ', - 'service' => 'IT', + 'service' => '101', ]), 'delivery_address' => '{}', 'pickup_day' => '2023-01-05', diff --git a/tests/Pest.php b/tests/Pest.php index 2bcc396a..b27afdfe 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -2,11 +2,9 @@ declare(strict_types=1); -use App\Services\CrmService; use DG\BypassFinals; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Http; -use LDC\LDCCRM\CrmApiV4; use PHPUnit\Framework\TestCase as BasePHPUnitTestCase; use Tests\TestCase as LaravelTestCase; @@ -24,8 +22,6 @@ pest() ->use(RefreshDatabase::class) ->beforeEach(function (): void { Http::preventStrayRequests(); - mock(CrmApiV4::class); - mock(CrmService::class); }) ->in('Feature'); diff --git a/tests/TestCase.php b/tests/TestCase.php index 53411164..d5ffe68f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -4,9 +4,45 @@ declare(strict_types=1); namespace Tests; +use GuzzleHttp\Psr7\Response as GuzzleResponse; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; +use LDC\LDCCRM\CrmApiV4; +use LDC\LDCCRM\Enums\ApiStatus; +use LDC\LDCCRM\Models\ClientModel; +use LDC\LDCCRM\Transport\ApiInterface; +use LDC\LDCCRM\Transport\Response as CrmResponse; +use LDC\LDCCRM\Utils; +use Mockery; abstract class TestCase extends BaseTestCase { use CreatesApplication; + + #[\Override] + protected function setUp(): void + { + parent::setUp(); + + $this->mockCrmTransport(); + } + + private function mockCrmTransport(): void + { + $apiInterface = Mockery::mock(ApiInterface::class); + $apiInterface->shouldReceive('call')->byDefault()->andReturn( + new CrmResponse( + ApiStatus::OK, + new GuzzleResponse(200, [], (string) json_encode([ + 'version' => Utils::getPackageInfo()['version'], + 'data' => [], + ])) + ) + ); + + $refClientModel = new \ReflectionProperty(ClientModel::class, 'apiInterface'); + $refClientModel->setValue(null, $apiInterface); + + $refCrmApi = new \ReflectionProperty(CrmApiV4::class, 'apiInterface'); + $refCrmApi->setValue(null, $apiInterface); + } } diff --git a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php index 2bd69e88..2a89c097 100644 --- a/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php +++ b/tests/Unit/App/Actions/Orders/FinalizeOrderTest.php @@ -14,6 +14,9 @@ use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Domain\Services\OrderTunnelService; use Money\Money; use Ramsey\Uuid\Uuid; @@ -30,12 +33,12 @@ describe('FinalizeOrder', function (): void { shopId: new ShopId(Uuid::uuid7()), reference: $orderReference, employee: new OrderEmployee( + matricule: new Matricule('1234567'), firstname: 'Jean', lastname: 'Dupont', - matricule: new Matricule('1234567'), - facility: 'Fac', - site: 'Site', - service: 'Service', + facility: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101'), ), deliveryAddress: new DeliveryAddress( name: 'Shop', diff --git a/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php b/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php index b3816a17..5904f798 100644 --- a/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php +++ b/tests/Unit/App/Actions/Settings/UpdateSettingsInputTest.php @@ -17,8 +17,7 @@ describe('UpdateSettingsInput', function (): void { $input = new UpdateSettingsInput(employeeSites: $sites); // THEN - expect($input->employeeSites)->toBe($sites) - ->and($input->arcadiaSites)->toBe($sites); + expect($input->employeeSites)->toBe($sites); }); it('creates an empty input', function (): void { diff --git a/tests/Unit/App/Casts/EmployeeSitesCastTest.php b/tests/Unit/App/Casts/EmployeeSitesCastTest.php new file mode 100644 index 00000000..8928b119 --- /dev/null +++ b/tests/Unit/App/Casts/EmployeeSitesCastTest.php @@ -0,0 +1,105 @@ +get($model, 'employee_sites', null, []); + $resultEmpty = $cast->get($model, 'employee_sites', '', []); + + // THEN + expect($resultNull)->toBe([]) + ->and($resultEmpty)->toBe([]); +}); + +it('gets array of strings from json string', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + $json = json_encode(['PA', 'LY', 'NA']); + + // WHEN + $sites = $cast->get($model, 'employee_sites', $json, []); + + // THEN + expect($sites)->toBe(['PA', 'LY', 'NA']); +}); + +it('gets array of strings from mixed array', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + $input = ['PA', new ShopperSiteCode('LY'), 123]; + + // WHEN + $sites = $cast->get($model, 'employee_sites', $input, []); + + // THEN + expect($sites)->toBe(['PA', 'LY', '123']); +}); + +it('sets json empty array when value is null', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $value = $cast->set($model, 'employee_sites', null, []); + + // THEN + expect($value)->toBe('[]'); +}); + +it('sets json array from array of strings', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $value = $cast->set($model, 'employee_sites', ['PA', 'LY', 'NA'], []); + + // THEN + expect($value)->toBe(json_encode(['PA', 'LY', 'NA'])); +}); + +it('sets json array from array of Stringable objects', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + $value = $cast->set($model, 'employee_sites', [new ShopperSiteCode('PA'), new ShopperSiteCode('LY')], []); + + // THEN + expect($value)->toBe(json_encode(['PA', 'LY'])); +}); + +it('throws exception when setting invalid type', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + expect(fn () => $cast->set($model, 'employee_sites', 12345, [])) + // THEN + ->toThrow(\UnexpectedValueException::class, 'Employee sites must be an array, string or null.'); +}); + +it('throws exception when setting array with non-convertible items', function (): void { + // GIVEN + $cast = new EmployeeSitesCast(); + $model = \Mockery::mock(Model::class); + + // WHEN + expect(fn () => $cast->set($model, 'employee_sites', [new \stdClass()], [])) + // THEN + ->toThrow(\UnexpectedValueException::class, 'Each employee site must be convertable to string.'); +}); diff --git a/tests/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php b/tests/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php index d62bcf7d..5c8576be 100644 --- a/tests/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php +++ b/tests/Unit/App/Casts/ShopperEstablishmentCodeCastTest.php @@ -9,7 +9,7 @@ use Illuminate\Database\Eloquent\Model; it('gets a ShopperEstablishmentCode', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $code = $cast->get($model, 'etablissement', 'ETAB01', []); @@ -22,7 +22,7 @@ it('gets a ShopperEstablishmentCode', function () { it('throws exception when getting invalid ShopperEstablishmentCode type', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'etablissement', 123, []); @@ -33,7 +33,7 @@ it('throws exception when getting invalid ShopperEstablishmentCode type', functi it('throws exception when getting null ShopperEstablishmentCode', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'etablissement', null, []); @@ -44,7 +44,7 @@ it('throws exception when getting null ShopperEstablishmentCode', function () { it('sets a ShopperEstablishmentCode from instance', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); $vo = new ShopperEstablishmentCode('ETAB01'); // WHEN @@ -57,7 +57,7 @@ it('sets a ShopperEstablishmentCode from instance', function () { it('sets a ShopperEstablishmentCode from valid string', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $value = $cast->set($model, 'etablissement', 'ETAB01', []); @@ -69,7 +69,7 @@ it('sets a ShopperEstablishmentCode from valid string', function () { it('throws exception when setting invalid ShopperEstablishmentCode type', function () { // GIVEN $cast = new ShopperEstablishmentCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->set($model, 'etablissement', 123, []); diff --git a/tests/Unit/App/Casts/ShopperServiceCodeCastTest.php b/tests/Unit/App/Casts/ShopperServiceCodeCastTest.php index 306974c1..02c3ad3c 100644 --- a/tests/Unit/App/Casts/ShopperServiceCodeCastTest.php +++ b/tests/Unit/App/Casts/ShopperServiceCodeCastTest.php @@ -9,7 +9,7 @@ use Illuminate\Database\Eloquent\Model; it('gets a ShopperServiceCode', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $code = $cast->get($model, 'service', '101', []); @@ -22,7 +22,7 @@ it('gets a ShopperServiceCode', function () { it('throws exception when getting invalid ShopperServiceCode type', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'service', 123, []); @@ -33,7 +33,7 @@ it('throws exception when getting invalid ShopperServiceCode type', function () it('throws exception when getting null ShopperServiceCode', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'service', null, []); @@ -44,7 +44,7 @@ it('throws exception when getting null ShopperServiceCode', function () { it('sets a ShopperServiceCode from instance', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); $vo = new ShopperServiceCode('101'); // WHEN @@ -57,7 +57,7 @@ it('sets a ShopperServiceCode from instance', function () { it('sets a ShopperServiceCode from valid string', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $value = $cast->set($model, 'service', '101', []); @@ -69,7 +69,7 @@ it('sets a ShopperServiceCode from valid string', function () { it('throws exception when setting invalid ShopperServiceCode type', function () { // GIVEN $cast = new ShopperServiceCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->set($model, 'service', 123, []); diff --git a/tests/Unit/App/Casts/ShopperSiteCodeCastTest.php b/tests/Unit/App/Casts/ShopperSiteCodeCastTest.php index 50f02808..2209806c 100644 --- a/tests/Unit/App/Casts/ShopperSiteCodeCastTest.php +++ b/tests/Unit/App/Casts/ShopperSiteCodeCastTest.php @@ -9,7 +9,7 @@ use Illuminate\Database\Eloquent\Model; it('gets a ShopperSiteCode', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $code = $cast->get($model, 'site', 'PA', []); @@ -22,7 +22,7 @@ it('gets a ShopperSiteCode', function () { it('throws exception when getting invalid ShopperSiteCode type', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'site', 123, []); @@ -33,7 +33,7 @@ it('throws exception when getting invalid ShopperSiteCode type', function () { it('throws exception when getting null ShopperSiteCode', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->get($model, 'site', null, []); @@ -44,7 +44,7 @@ it('throws exception when getting null ShopperSiteCode', function () { it('sets a ShopperSiteCode from instance', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); $vo = new ShopperSiteCode('PA'); // WHEN @@ -57,7 +57,7 @@ it('sets a ShopperSiteCode from instance', function () { it('sets a ShopperSiteCode from valid string', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $value = $cast->set($model, 'site', 'PA', []); @@ -69,7 +69,7 @@ it('sets a ShopperSiteCode from valid string', function () { it('throws exception when setting invalid ShopperSiteCode type', function () { // GIVEN $cast = new ShopperSiteCodeCast(); - $model = Mockery::mock(Model::class); + $model = \Mockery::mock(Model::class); // WHEN $cast->set($model, 'site', 123, []); diff --git a/tests/Unit/App/Dto/ProductDtoTest.php b/tests/Unit/App/Dto/ProductDtoTest.php index 323adcbd..0ca9fce3 100644 --- a/tests/Unit/App/Dto/ProductDtoTest.php +++ b/tests/Unit/App/Dto/ProductDtoTest.php @@ -29,9 +29,27 @@ describe('ProductDto', function () { $array = $dto->toArray(); expect($array)->toBe([ - 'id' => $id, - 'name' => $name, - 'slug' => $slug, + 'id' => $id, + 'name' => $name, + 'slug' => $slug, + 'brand' => null, + 'inco' => null, + 'picture' => null, + 'picture_alt' => null, + 'picture_title' => null, + 'picture_large' => null, + 'picture_large_alt' => null, + 'picture_large_title' => null, + 'price' => null, + 'discount' => null, + 'stock' => 0, + 'sell_unit' => null, + 'range' => null, + 'order' => 0, + 'status' => false, + 'star' => false, + 'short_description' => null, + 'description' => null, ]); }); }); diff --git a/tests/Unit/App/Dto/SettingDtoTest.php b/tests/Unit/App/Dto/SettingDtoTest.php index e9bd8bf8..f7d35f6e 100644 --- a/tests/Unit/App/Dto/SettingDtoTest.php +++ b/tests/Unit/App/Dto/SettingDtoTest.php @@ -17,9 +17,7 @@ describe('SettingDto', function (): void { // THEN expect($dto->id)->toBe(1) ->and($dto->employeeSites)->toBe(['PA', 'LY']) - ->and($dto->arcadiaSites)->toBe(['PA', 'LY']) ->and($dto->employeeSitesAsString())->toBe('PA, LY') - ->and($dto->arcadiaSitesAsString())->toBe('PA, LY') ->and($dto->getShopperSiteCodes())->toHaveCount(2) ->and($dto->getShopperSiteCodes()[0])->toBeInstanceOf(ShopperSiteCode::class) ->and($dto->getShopperSiteCodes()[0]->value)->toBe('PA') @@ -31,7 +29,6 @@ describe('SettingDto', function (): void { ->and($dto->toArray())->toBe([ 'id' => 1, 'employee_sites' => ['PA', 'LY'], - 'arcadia_sites' => ['PA', 'LY'], ]); }); }); diff --git a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php index 6ec3ce4a..0c484df0 100644 --- a/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php +++ b/tests/Unit/Domain/Events/AnOrderHasBeenPlacedTest.php @@ -13,6 +13,9 @@ use Domain\Models\ValueObjects\IncoId; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; use Domain\Models\ValueObjects\OrderReference; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; @@ -25,7 +28,7 @@ describe('AnOrderHasBeenPlaced', function () { $reference = new OrderReference(\Symfony\Component\Uid\Uuid::v7()->toBase58()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); - $employee = new OrderEmployee($matricule, 'John', 'Doe', 'Facility', 'Site', 'Service'); + $employee = new OrderEmployee($matricule, 'John', 'Doe', new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITEA'), new ShopperServiceCode('101')); $shop = new OrderPlacedShop('Shop', 'Address', '12345', 'City'); $pickupDay = new \DateTimeImmutable(); $lines = [ @@ -47,7 +50,7 @@ describe('AnOrderHasBeenPlaced', function () { $reference = new OrderReference(\Symfony\Component\Uid\Uuid::v7()->toBase58()); $totalTtc = new Money(1000, new Currency('EUR')); $matricule = new Matricule('1234567'); - $employee = new OrderEmployee($matricule, 'John', 'Doe', 'Facility', 'Site', 'Service'); + $employee = new OrderEmployee($matricule, 'John', 'Doe', new ShopperEstablishmentCode('ETAB01'), new ShopperSiteCode('SITEA'), new ShopperServiceCode('101')); $shop = new OrderPlacedShop('Shop', 'Address', '12345', 'City'); $pickupDay = new \DateTimeImmutable(); $lines = []; diff --git a/tests/Unit/Domain/Models/Entities/OrderTest.php b/tests/Unit/Domain/Models/Entities/OrderTest.php index adf291a3..706e84b3 100644 --- a/tests/Unit/Domain/Models/Entities/OrderTest.php +++ b/tests/Unit/Domain/Models/Entities/OrderTest.php @@ -21,6 +21,9 @@ use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Models\ValueObjects\ProductWeight; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; use Money\Money; use Ramsey\Uuid\Uuid; use Symfony\Component\Uid\UuidV7; @@ -65,9 +68,9 @@ function makeOrder(array $overrides = []): Order matricule: new Matricule('1234567'), firstname: 'Jean', lastname: 'Dupont', - facility: 'Usine A', - site: 'Lyon', - service: 'Logistique', + facility: new ShopperEstablishmentCode('ETAB01'), + site: new ShopperSiteCode('SITEA'), + service: new ShopperServiceCode('101'), ), deliveryAddress: $overrides['deliveryAddress'] ?? new DeliveryAddress( name: 'Cocotte Lyon', diff --git a/tests/Unit/Domain/Models/ValueObjects/CsvImportFileTest.php b/tests/Unit/Domain/Models/ValueObjects/CsvImportFileTest.php deleted file mode 100644 index e72b148e..00000000 --- a/tests/Unit/Domain/Models/ValueObjects/CsvImportFileTest.php +++ /dev/null @@ -1,71 +0,0 @@ - $path, - 'fileContent' => "header\nvalue", - ], $overrides); - - return new CsvImportFile(...$data); - } - - it('can instantiate', function () { - // GIVEN - $path = tempnam(sys_get_temp_dir(), 'csv'); - file_put_contents($path, 'dummy'); - $content = "header\nvalue"; - - // WHEN - $vo = new CsvImportFile( - realPath: $path, - fileContent: $content - ); - - // THEN - expect($vo)->toBeInstanceOf(CsvImportFile::class); - unlink($path); - }); - - it('throws exception if file path is not readable', function () { - // GIVEN - $invalidPath = '/invalid/path/to/file.csv'; - - // WHEN - $action = fn () => getNewCsvImportFile($invalidPath); - - // THEN - expect($action)->toThrow(\DomainException::class); - }); - - it('throws exception if content is empty', function () { - // GIVEN - $path = tempnam(sys_get_temp_dir(), 'csv'); - file_put_contents($path, 'dummy'); - $emptyContent = ' '; - - // WHEN - $action = function () use ($path, $emptyContent) { - try { - getNewCsvImportFile($path, [ - 'fileContent' => $emptyContent, - ]); - } finally { - if (file_exists($path)) { - unlink($path); - } - } - }; - - // THEN - expect($action)->toThrow(\DomainException::class); - }); -}); diff --git a/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php b/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php index 8a30200f..89091dc6 100644 --- a/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/EmployeeUpsertDataTest.php @@ -8,32 +8,40 @@ use Carbon\CarbonImmutable; use Domain\Models\ValueObjects\Code; use Domain\Models\ValueObjects\EmployeeUpsertData; use Domain\Models\ValueObjects\Matricule; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; describe('EmployeeUpsertData', function (): void { it('can be instantiated', function (): void { // GIVEN - $matricule = new Matricule('1234567'); - $code = new Code('ABCDEFGH12'); - $start = CarbonImmutable::now(); + $matricule = new Matricule('1234567'); + $code = new Code('ABCDEFGH12'); + $start = CarbonImmutable::now(); + $etablissement = new ShopperEstablishmentCode('ETAB01'); + $service = new ShopperServiceCode('101'); + $site = new ShopperSiteCode('SITEA'); + // WHEN $data = new EmployeeUpsertData( $matricule, - 'Dupont', 'Jean', - 'Etab', - 'Service', - 'Site', + 'Dupont', + $etablissement, + $service, + $site, $start, null, $code ); + // THEN expect($data->matricule)->toBe($matricule) - ->and($data->nom)->toBe('Dupont') - ->and($data->prenom)->toBe('Jean') - ->and($data->etablissement)->toBe('Etab') - ->and($data->service)->toBe('Service') - ->and($data->site)->toBe('Site') + ->and($data->firstname)->toBe('Jean') + ->and($data->lastname)->toBe('Dupont') + ->and($data->etablissement)->toBe($etablissement) + ->and($data->service)->toBe($service) + ->and($data->site)->toBe($site) ->and($data->startDate)->toBe($start) ->and($data->endDate)->toBeNull() ->and($data->code)->toBe($code); diff --git a/tests/Unit/Domain/Models/ValueObjects/ImportRowResultTest.php b/tests/Unit/Domain/Models/ValueObjects/ImportRowResultTest.php deleted file mode 100644 index 70737afa..00000000 --- a/tests/Unit/Domain/Models/ValueObjects/ImportRowResultTest.php +++ /dev/null @@ -1,94 +0,0 @@ - 1, - 'mappedResult' => ['data' => 'value'], - 'error' => null, - ], $overrides); - - return new ImportRowResult(...$data); - } - - it('can instantiate for success', function () { - // GIVEN - $lineNumber = 1; - $mappedResult = 'data'; - $error = null; - - // WHEN - $vo = new ImportRowResult( - lineNumber: $lineNumber, - mappedResult: $mappedResult, - error: $error - ); - - // THEN - expect($vo)->toBeInstanceOf(ImportRowResult::class); - expect($vo->isSuccess())->toBeTrue(); - }); - - it('can instantiate for error', function () { - // GIVEN - $lineNumber = 1; - $mappedResult = null; - $error = 'Invalid format'; - - // WHEN - $vo = new ImportRowResult( - lineNumber: $lineNumber, - mappedResult: $mappedResult, - error: $error - ); - - // THEN - expect($vo)->toBeInstanceOf(ImportRowResult::class); - expect($vo->isSuccess())->toBeFalse(); - }); - - it('throws exception if line number is zero or negative', function () { - // GIVEN - $lineNumber = 0; - $mappedResult = 'data'; - - // WHEN - $action = fn () => new ImportRowResult( - lineNumber: $lineNumber, - mappedResult: $mappedResult - ); - - // THEN - expect($action)->toThrow(\DomainException::class); - }); - - it('is not success if mappedResult is null', function () { - // GIVEN - $overrides = ['mappedResult' => null]; - - // WHEN - $vo = getNewImportRowResult($overrides); - - // THEN - expect($vo->isSuccess())->toBeFalse(); - }); - - it('is not success if error is present', function () { - // GIVEN - $overrides = ['error' => 'some error']; - - // WHEN - $vo = getNewImportRowResult($overrides); - - // THEN - expect($vo->isSuccess())->toBeFalse(); - }); -}); diff --git a/tests/Unit/Domain/Models/ValueObjects/OrderEmployeeTest.php b/tests/Unit/Domain/Models/ValueObjects/OrderEmployeeTest.php index a8bc4381..3d9e01bc 100644 --- a/tests/Unit/Domain/Models/ValueObjects/OrderEmployeeTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/OrderEmployeeTest.php @@ -6,67 +6,62 @@ namespace Tests\Unit\Domain\Models\ValueObjects; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderEmployee; +use Domain\Models\ValueObjects\ShopperEstablishmentCode; +use Domain\Models\ValueObjects\ShopperServiceCode; +use Domain\Models\ValueObjects\ShopperSiteCode; describe('OrderEmployee', function (): void { it('can instantiate correctly', function (): void { // GIVEN $matricule = new Matricule('1234567'); + $facility = new ShopperEstablishmentCode('ETAB01'); + $site = new ShopperSiteCode('SITEA'); + $service = new ShopperServiceCode('101'); + + // WHEN $employee = new OrderEmployee( $matricule, 'John', 'Doe', - 'Facility', - 'Site', - 'Service' - // WHEN + $facility, + $site, + $service ); - // THEN + // THEN expect($employee->matricule)->toBe($matricule) ->and($employee->firstname)->toBe('John') ->and($employee->lastname)->toBe('Doe') - ->and($employee->facility)->toBe('Facility') - ->and($employee->site)->toBe('Site') - ->and($employee->service)->toBe('Service'); + ->and($employee->facility)->toBe($facility) + ->and($employee->site)->toBe($site) + ->and($employee->service)->toBe($service); }); it('throws exception if firstname is empty', function (): void { // GIVEN + $matricule = new Matricule('1234567'); + $facility = new ShopperEstablishmentCode('ETAB01'); + $site = new ShopperSiteCode('SITEA'); + $service = new ShopperServiceCode('101'); + // WHEN - $action = fn () => new OrderEmployee(new Matricule('1234567'), '', 'Doe', 'Facility', 'Site', 'Service'); + $action = fn () => new OrderEmployee($matricule, '', 'Doe', $facility, $site, $service); + // THEN expect($action)->toThrow(\DomainException::class, 'firstname cannot be empty'); }); it('throws exception if lastname is empty', function (): void { // GIVEN + $matricule = new Matricule('1234567'); + $facility = new ShopperEstablishmentCode('ETAB01'); + $site = new ShopperSiteCode('SITEA'); + $service = new ShopperServiceCode('101'); + // WHEN - $action = fn () => new OrderEmployee(new Matricule('1234567'), 'John', '', 'Facility', 'Site', 'Service'); + $action = fn () => new OrderEmployee($matricule, 'John', '', $facility, $site, $service); + // THEN expect($action)->toThrow(\DomainException::class, 'lastname cannot be empty'); }); - - it('throws exception if facility is empty', function (): void { - // GIVEN - // WHEN - $action = fn () => new OrderEmployee(new Matricule('1234567'), 'John', 'Doe', '', 'Site', 'Service'); - // THEN - expect($action)->toThrow(\DomainException::class, 'facility cannot be empty'); - }); - - it('throws exception if site is empty', function (): void { - // GIVEN - // WHEN - $action = fn () => new OrderEmployee(new Matricule('1234567'), 'John', 'Doe', 'Facility', '', 'Service'); - // THEN - expect($action)->toThrow(\DomainException::class, 'site cannot be empty'); - }); - - it('throws exception if service is empty', function (): void { - // GIVEN - // WHEN - $action = fn () => new OrderEmployee(new Matricule('1234567'), 'John', 'Doe', 'Facility', 'Site', ''); - // THEN - expect($action)->toThrow(\DomainException::class, 'service cannot be empty'); - }); }); diff --git a/tests/Unit/Domain/Models/ValueObjects/PaginationTest.php b/tests/Unit/Domain/Models/ValueObjects/PaginationTest.php index f0cccc99..482fe15f 100644 --- a/tests/Unit/Domain/Models/ValueObjects/PaginationTest.php +++ b/tests/Unit/Domain/Models/ValueObjects/PaginationTest.php @@ -22,8 +22,8 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe(20) ->and($pagination->to())->toBe(39) - ->and($pagination->pageSize())->toBe(20) - ->and($pagination->pageNumber())->toBe(2); + ->and($pagination->pageSize()->value)->toBe(20) + ->and($pagination->pageNumber()->value)->toBe(2); }); it('can be created from offset and limit', function (): void { @@ -37,8 +37,8 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe(20) ->and($pagination->to())->toBe(29) - ->and($pagination->pageSize())->toBe(10) - ->and($pagination->pageNumber())->toBe(3); + ->and($pagination->pageSize()->value)->toBe(10) + ->and($pagination->pageNumber()->value)->toBe(3); }); it('can be created from explicit indexes using ofIndexes', function (): void { @@ -52,7 +52,7 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe(5) ->and($pagination->to())->toBe(14) - ->and($pagination->pageSize())->toBe(10); + ->and($pagination->pageSize()->value)->toBe(10); }); it('can be created using first page helper with default size', function (): void { @@ -62,8 +62,8 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe(0) ->and($pagination->to())->toBe(24) - ->and($pagination->pageSize())->toBe(25) - ->and($pagination->pageNumber())->toBe(1); + ->and($pagination->pageSize()->value)->toBe(25) + ->and($pagination->pageNumber()->value)->toBe(1); }); it('can be created using first page helper with explicit size', function (): void { @@ -76,8 +76,8 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe(0) ->and($pagination->to())->toBe(14) - ->and($pagination->pageSize())->toBe(15) - ->and($pagination->pageNumber())->toBe(1); + ->and($pagination->pageSize()->value)->toBe(15) + ->and($pagination->pageNumber()->value)->toBe(1); }); it('formats pagination as string representation via __toString', function (): void { @@ -111,7 +111,7 @@ describe('Pagination Value Object Unit Tests', function (): void { // THEN expect($pagination->from())->toBe($expectedFrom) - ->and($pagination->pageSize())->toBe($expectedSize); + ->and($pagination->pageSize()->value)->toBe($expectedSize); })->with([ 'negative offset clamped to 0' => [-1, 10, 0, 10], 'limit 0 clamped to 1' => [0, 0, 0, 1], diff --git a/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php b/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php index e263dddf..016f247d 100644 --- a/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php +++ b/tests/Unit/Infra/Adapters/Services/AppCustomerAuthServiceTest.php @@ -19,7 +19,7 @@ use Illuminate\Contracts\Debug\ExceptionHandler; use Infrastructure\Adapters\Services\AppCustomerAuthService; use Mockery; use Ramsey\Uuid\Uuid; -use stdClass; +use Shared\ValueObjects\CrmHashcode; describe('AppCustomerAuthService', function (): void { it('checks abilities with customer', function (): void { @@ -264,11 +264,12 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); - $customer->hashcode = 'hash123'; + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = $hashcode; // DO NOT MOCK CrmCustomer $crmCustomer = new CrmCustomer( - hashcode: 'hash123', + hashcode: $hashcode->value, email: 'test@example.com', password: 'password', firstname: 'John', @@ -285,7 +286,7 @@ describe('AppCustomerAuthService', function (): void { lastConnection: null ); - $crmService->shouldReceive('getCustomerFromHashCode')->with('hash123')->andReturn($crmCustomer); + $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($crmCustomer); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -302,9 +303,10 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); - $customer->hashcode = 'hash123'; + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = $hashcode; - $crmService->shouldReceive('getCustomerFromHashCode')->with('hash123')->andReturn(null); + $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -321,10 +323,11 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); - $customer->hashcode = 'hash123'; + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = $hashcode; $crmCustomer = new CrmCustomer( - hashcode: 'hash123', + hashcode: $hashcode->value, email: 'test@example.com', password: 'password', firstname: 'John', @@ -341,9 +344,9 @@ describe('AppCustomerAuthService', function (): void { lastConnection: null ); - $crmService->shouldReceive('getCustomerFromHashCode')->with('hash123')->andReturn($crmCustomer); + $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($crmCustomer); - $activation = new stdClass(); + $activation = new \stdClass(); $activation->result = true; $crmService->shouldReceive('activate')->with($crmCustomer)->andReturn($activation); @@ -362,9 +365,10 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); - $customer->hashcode = 'hash123'; + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = $hashcode; - $crmService->shouldReceive('getCustomerFromHashCode')->with('hash123')->andReturn(null); + $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn(null); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); @@ -381,12 +385,13 @@ describe('AppCustomerAuthService', function (): void { $crmService = Mockery::mock(CrmService::class); $shopperService = Mockery::mock(ShopperService::class); $customer = new Customer(); - $customer->hashcode = 'hash123'; + $hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->hashcode = $hashcode; app()->instance(ExceptionHandler::class, Mockery::mock(ExceptionHandler::class)->shouldIgnoreMissing()); $exception = new CrmServiceException('Crm Error'); - $crmService->shouldReceive('getCustomerFromHashCode')->with('hash123')->andReturn($exception); + $crmService->shouldReceive('getCustomerFromHashCode')->with($customer->hashcode)->andReturn($exception); $service = new AppCustomerAuthService($guard, $crmService, $shopperService); diff --git a/tests/Unit/Services/CrmServiceTest.php b/tests/Unit/Services/CrmServiceTest.php index 5674061c..b8a1b546 100644 --- a/tests/Unit/Services/CrmServiceTest.php +++ b/tests/Unit/Services/CrmServiceTest.php @@ -7,14 +7,20 @@ namespace Tests\Unit\Services; use App\Services\CrmService; use Domain\Enums\Country; use Domain\Models\ValueObjects\CrmCustomer; +use GuzzleHttp\Psr7\Response; use Illuminate\Contracts\Cache\Repository as CacheRepository; use LDC\LDCCRM\CrmApiV4; use LDC\LDCCRM\Enums\ApiError; +use LDC\LDCCRM\Enums\ApiStatus; use LDC\LDCCRM\Enums\Country as EnumsCountry; use LDC\LDCCRM\Exceptions\ApiErrorException; +use LDC\LDCCRM\Models\ClientModel; use LDC\LDCCRM\Models\Customer; +use LDC\LDCCRM\Transport\ApiInterface; +use LDC\LDCCRM\Utils; use Mockery; use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; describe('CrmService', function (): void { it('returns customer from hashcode and caches it', function (): void { @@ -22,7 +28,8 @@ describe('CrmService', function (): void { $crmApi = Mockery::mock(CrmApiV4::class); $cacheRepository = Mockery::mock(CacheRepository::class); - $uuid = (string) Uuid::uuid4(); + $uuidObj = Uuid::uuid4(); + $uuid = $uuidObj->toString(); $libCustomer = new Customer([ 'hashcode' => $uuid, @@ -47,13 +54,13 @@ describe('CrmService', function (): void { $cacheRepository->shouldReceive('remember') ->once() ->with($cacheKey, Mockery::any(), Mockery::on(function ($closure) use ($crmApi, $libCustomer, $uuid) { - $crmApi->shouldReceive('getCustomer')->with($uuid)->once()->andReturn($libCustomer); + $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andReturn($libCustomer); $result = $closure(); - return $result instanceof CrmCustomer && $result->hashcode === $uuid; + return $result instanceof CrmCustomer && $result->hashcode === (string) $uuid; })) ->andReturn(new CrmCustomer( - hashcode: $uuid, + hashcode: (string) $uuid, email: 'john@example.com', password: 'Secret123!', firstname: 'John', @@ -70,13 +77,14 @@ describe('CrmService', function (): void { lastConnection: null, )); - $service = new CrmService($crmApi, $cacheRepository); + $service = new CrmService($crmApi, $cacheRepository); + $hashcode = new CrmHashcode($uuidObj); // WHEN - $firstCall = $service->getCustomerFromHashCode($uuid); + $firstCall = $service->getCustomerFromHashCode($hashcode); // Second call should return from internal memory cache without querying CacheRepository again - $secondCall = $service->getCustomerFromHashCode($uuid); + $secondCall = $service->getCustomerFromHashCode($hashcode); // THEN expect($firstCall)->toBeInstanceOf(CrmCustomer::class) @@ -130,7 +138,7 @@ describe('CrmService', function (): void { $crmApi = Mockery::mock(CrmApiV4::class); $cacheRepository = Mockery::mock(CacheRepository::class); - $uuid = (string) Uuid::uuid4(); + $uuid = Uuid::uuid4(); $cacheKey = "crm_customer_hashcode_{$uuid}"; $cacheRepository->shouldReceive('remember') @@ -138,7 +146,7 @@ describe('CrmService', function (): void { ->with($cacheKey, Mockery::any(), Mockery::on(function ($closure) use ($crmApi, $uuid) { $exception = Mockery::mock(ApiErrorException::class); $exception->shouldReceive('getApiError')->andReturn(ApiError::modelNotFound); - $crmApi->shouldReceive('getCustomer')->with($uuid)->once()->andThrow($exception); + $crmApi->shouldReceive('getCustomer')->with((string) $uuid)->once()->andThrow($exception); $res = $closure(); return $res === null; @@ -148,7 +156,7 @@ describe('CrmService', function (): void { $service = new CrmService($crmApi, $cacheRepository); // WHEN - $result = $service->getCustomerFromHashCode($uuid); + $result = $service->getCustomerFromHashCode(new CrmHashcode($uuid)); // THEN expect($result)->toBeNull(); @@ -185,6 +193,19 @@ describe('CrmService', function (): void { $cacheRepository->shouldReceive('delete')->with($expectedHashKey)->once(); $cacheRepository->shouldReceive('delete')->with($expectedEmailKey)->once(); + $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