From 0f008b0db4050582a408e302ba908feb29b66f0f Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Tue, 26 Aug 2025 17:09:03 +0200 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20=F0=9F=90=9B=20change=20the=20custom?= =?UTF-8?q?er's=20opt-in=20value=20if=20it=20exists=20when=20call=20api=20?= =?UTF-8?q?optin=20route=20#27?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/Api/V4/OptinController.php | 93 ++++++++++++------ tests/CRM/ApiV2/SingleOptinTest.php | 37 +++---- tests/CRM/ApiV4/SingleOptinTest.php | 98 +++++++++++++------ tests/Client/CrmClientSingleOptinTest.php | 90 +++++++++++------ 4 files changed, 210 insertions(+), 108 deletions(-) diff --git a/app/Http/Controllers/Api/V4/OptinController.php b/app/Http/Controllers/Api/V4/OptinController.php index 4c2272f..e3fb3b6 100644 --- a/app/Http/Controllers/Api/V4/OptinController.php +++ b/app/Http/Controllers/Api/V4/OptinController.php @@ -2,8 +2,6 @@ namespace App\Http\Controllers\Api\V4; -use App\Enums\ApiError; -use App\Exceptions\Api\V4\ApiErrorException; use App\Exceptions\Api\V4\CrmException; use App\Http\Controllers\Controller; use App\Http\Requests\Api\V4\BaseApiRequest; @@ -21,34 +19,49 @@ class OptinController extends Controller * @param \App\Http\Requests\Api\V4\SingleOptinRequest $request * @param \App\Models\Service $service * @return \Illuminate\Http\JsonResponse - * @throws \App\Exceptions\Api\V4\ApiErrorException With ApiError::singleOptinCustomerExists - * if this email already has a full account. * @throws \App\Exceptions\Api\V4\CrmException If the single optin could not be added or removed. */ public function optin(SingleOptinRequest $request, Service $service): \Illuminate\Http\JsonResponse { $validatedData = $request->validated(); - if (CustomerInfo::getFromEmail($service->brand, $validatedData['email'])->exists()) { - throw new ApiErrorException(ApiError::singleOptinCustomerExists); - } + $crmCustomer = CustomerInfo::getFromEmail($service->brand, $validatedData['email'])->first(); + if ($crmCustomer) { + // Update the optin field. + $crmCustomer->opt_in = \boolval($validatedData['opt_in']); - /** @var \App\Models\SingleOptin */ - $singleOptin = SingleOptin::query() - ->where('email', $validatedData['email']) - ->whereHas('brand', function ($q) use ($service) { - $q->whereKey($service->brand->getKey()); - }) - ->firstOrNew(); + // Check the saving. + if (!$crmCustomer->saveOrFail()) { + // @codeCoverageIgnoreStart + throw new CrmException('Api failed to update customer optin.'); + // @codeCoverageIgnoreEnd + } - if (!$this->changeOptin($service, $request, \boolval($validatedData['opt_in']), $singleOptin)) { - // @codeCoverageIgnoreStart - throw new CrmException('Api failed to update single optin.'); - // @codeCoverageIgnoreEnd - } + // Associate answers if presents. + if (isset($validatedData['answer_id'])) { + $crmCustomer->answers()->attach($validatedData['answer_id']); + } + } else { + // Get the single optin if exist or create it. + /** @var \App\Models\SingleOptin */ + $singleOptin = SingleOptin::query() + ->where('email', $validatedData['email']) + ->whereHas('brand', function ($q) use ($service) { + $q->whereKey($service->brand->getKey()); + }) + ->firstOrNew(); - if (isset($validatedData['answer_id'])) { - $singleOptin->answers()->attach($validatedData['answer_id']); - } + // Update the optin field and check the saving. + if (!$this->changeOptin($service, $request, \boolval($validatedData['opt_in']), $singleOptin)) { + // @codeCoverageIgnoreStart + throw new CrmException('Api failed to update single optin.'); + // @codeCoverageIgnoreEnd + } + + // Associate answers if presents. + if (isset($validatedData['answer_id'])) { + $singleOptin->answers()->attach($validatedData['answer_id']); + } + } //end if return response()->json(); } @@ -65,17 +78,33 @@ class OptinController extends Controller SingleOptinRemoveWithHashcodeRequest $request, Service $service ): \Illuminate\Http\JsonResponse { - /** @var \App\Models\SingleOptin */ - $singleOptin = SingleOptin::query()->where('hashcode', $request->hashcode) - ->whereHas('brand', function ($q) use ($service) { - $q->whereId($service->brand->id); - })->firstOrFail(); + $validatedData = $request->validated(); + $crmCustomer = CustomerInfo::getFromHashcode($service->brand, $validatedData['hashcode'])->first(); + if ($crmCustomer) { + // Update the optin field. + $crmCustomer->opt_in = false; - if ($singleOptin and !$this->changeOptin($service, $request, \boolval($request->opt_in), $singleOptin)) { - // @codeCoverageIgnoreStart - throw new CrmException('Api failed to update single optin.'); - // @codeCoverageIgnoreEnd - } + // Check the saving. + if (!$crmCustomer->saveOrFail()) { + // @codeCoverageIgnoreStart + throw new CrmException('Api failed to update customer optin.'); + // @codeCoverageIgnoreEnd + } + } else { + // Get the single optin if exist or create it. + /** @var \App\Models\SingleOptin */ + $singleOptin = SingleOptin::query()->where('hashcode', $validatedData['hashcode']) + ->whereHas('brand', function ($q) use ($service) { + $q->whereId($service->brand->getKey()); + })->firstOrFail(); + + // Update the optin field and check the saving. + if ($singleOptin and !$this->changeOptin($service, $request, false, $singleOptin)) { + // @codeCoverageIgnoreStart + throw new CrmException('Api failed to update single optin.'); + // @codeCoverageIgnoreEnd + } + } //end if return response()->json(); } diff --git a/tests/CRM/ApiV2/SingleOptinTest.php b/tests/CRM/ApiV2/SingleOptinTest.php index 00995dd..0f80e97 100644 --- a/tests/CRM/ApiV2/SingleOptinTest.php +++ b/tests/CRM/ApiV2/SingleOptinTest.php @@ -17,6 +17,9 @@ class SingleOptinTest extends ApiBase use CreatesApplication; use DatabaseTransactions; + /** @var string $email */ + private $email = 'singleoptin@hotmail.fr'; + /** * Test set single optin on. * route: apiV2.optin @@ -28,13 +31,13 @@ class SingleOptinTest extends ApiBase $service = Service::firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 1 + 'email' => $this->email, + 'opt_in' => 1, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertTrue( - SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->exists(), + SingleOptin::query()->where('email', $this->email)->exists(), 'Single optin should have been set for email "singleoptin@hotmail.fr"' ); } @@ -58,12 +61,12 @@ class SingleOptinTest extends ApiBase $firstAnswer = $questions->first()->answers->first(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [ - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'opt_in' => 1, 'answer_id' => [$firstAnswer->getkey()], ]); - $singleOptin = SingleOptin::query()->where('email', 'singleoptin@hotmail.fr'); + $singleOptin = SingleOptin::query()->where('email', $this->email); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertTrue( @@ -87,13 +90,13 @@ class SingleOptinTest extends ApiBase $service = Service::firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 0 + 'email' => $this->email, + 'opt_in' => 0, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertFalse( - SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->exists(), + SingleOptin::query()->where('email', $this->email)->exists(), 'Single optin should have been removed for email "singleoptin@hotmail.fr"' ); } @@ -104,20 +107,20 @@ class SingleOptinTest extends ApiBase * * @return void */ - public function testSingleOptinShouldFailIfCustomerExists(): void + public function testSingleOptinShouldFailIfOptinAlreadyExists(): void { $service = Service::firstOrFail(); $this->storeCustomer($service); // * Make sure a single optin exists. - $singleOptin = SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->firstOrNew(); + $singleOptin = SingleOptin::query()->where('email', $this->email)->firstOrNew(); $singleOptin->brand()->associate($service->brand); - $singleOptin->email = 'singleoptin@hotmail.fr'; + $singleOptin->email = $this->email; $singleOptin->saveOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 1 + 'email' => $this->email, + 'opt_in' => 1, ]); $json = $response->decodeResponseJson(); @@ -135,7 +138,7 @@ class SingleOptinTest extends ApiBase { $service = Service::query()->firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [ - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'opt_in' => 1, 'answer_id' => [0], ]); @@ -163,7 +166,7 @@ class SingleOptinTest extends ApiBase $singleOptin->refresh(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optout-hashcode'), [ - 'hashcode' => $singleOptin->hashcode + 'hashcode' => $singleOptin->hashcode, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); @@ -194,7 +197,7 @@ class SingleOptinTest extends ApiBase $singleOptin->delete(); $response = $this->callApiWithToken($service, 'post', route('apiV2.optout-hashcode'), [ - 'hashcode' => $singleOptin->hashcode + 'hashcode' => $singleOptin->hashcode, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::KO); @@ -214,7 +217,7 @@ class SingleOptinTest extends ApiBase 'lastname' => 'Bond', 'birth_date' => \date('1992-03-08'), 'address' => '10 rue des totos', - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'password' => '123.Mot.De.P4sse', 'phone' => '+33654821562', 'country' => Country::france->value(), diff --git a/tests/CRM/ApiV4/SingleOptinTest.php b/tests/CRM/ApiV4/SingleOptinTest.php index bb398f0..3cd5585 100644 --- a/tests/CRM/ApiV4/SingleOptinTest.php +++ b/tests/CRM/ApiV4/SingleOptinTest.php @@ -5,10 +5,12 @@ namespace Tests\CRM\ApiV4; use App\Enums\ApiError; use App\Enums\ApiStatus; use App\Enums\Country; +use App\Models\CustomerInfo; use App\Models\ModelAnswer; use App\Models\Question; use App\Models\Service; use App\Models\SingleOptin; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\CreatesApplication; @@ -17,6 +19,9 @@ class SingleOptinTest extends ApiBase use CreatesApplication; use DatabaseTransactions; + /** @var string $email */ + private $email = 'singleoptin@hotmail.fr'; + /** * Test set single optin on. * route: apiV4.optin @@ -28,13 +33,13 @@ class SingleOptinTest extends ApiBase $service = Service::firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 1 + 'email' => $this->email, + 'opt_in' => 1, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertTrue( - SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->exists(), + SingleOptin::query()->where('email', $this->email)->exists(), 'Single optin should have been set for email "singleoptin@hotmail.fr"' ); } @@ -58,12 +63,12 @@ class SingleOptinTest extends ApiBase $firstAnswer = $questions->first()->answers->first(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [ - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'opt_in' => 1, 'answer_id' => [$firstAnswer->getkey()], ]); - $singleOptin = SingleOptin::query()->where('email', 'singleoptin@hotmail.fr'); + $singleOptin = SingleOptin::query()->where('email', $this->email); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertTrue( @@ -87,43 +92,42 @@ class SingleOptinTest extends ApiBase $service = Service::firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 0 + 'email' => $this->email, + 'opt_in' => 0, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); $this->assertFalse( - SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->exists(), + SingleOptin::query()->where('email', $this->email)->exists(), 'Single optin should have been removed for email "singleoptin@hotmail.fr"' ); } /** - * Should throw an ApiError exception if trying to set - * optin to an email that already have an account. + * Test set single optin on when customer exist. + * route: apiV4.optin * * @return void */ - public function testSingleOptinShouldFailIfCustomerExists(): void + public function testSetSingleOptinWhenCustomerExist(): void { $service = Service::firstOrFail(); $this->storeCustomer($service); - // * Make sure a single optin exists. - $singleOptin = SingleOptin::query()->where('email', 'singleoptin@hotmail.fr')->firstOrNew(); - $singleOptin->brand()->associate($service->brand); - $singleOptin->email = 'singleoptin@hotmail.fr'; - $singleOptin->saveOrFail(); - $response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [ - 'email' => 'singleoptin@hotmail.fr', - 'opt_in' => 1 + 'email' => $this->email, + 'opt_in' => 1, ]); - - $json = $response->decodeResponseJson(); - $this->assertApiResponseStatusIs($json, ApiStatus::KO); - $this->assertEquals(ApiError::singleOptinCustomerExists->value, $json->json('data.code')); - $this->assertEquals(ApiError::singleOptinCustomerExists->label(), $json->json('data.message')); + $json = $response->decodeResponseJson(); + $this->assertApiResponseStatusIs($json, ApiStatus::OK); + $this->assertFalse(SingleOptin::query()->where('email', 'singleoptout@hotmail.fr')->exists()); + $crmCustomer = CustomerInfo::query()->whereHas('customer', function (Builder $query) { + $query->where('email', $this->email); + })->first(); + $this->assertTrue( + $crmCustomer->opt_in, + 'Single optin should have been set for customer with email "singleoptin@hotmail.fr"' + ); } /** @@ -135,7 +139,7 @@ class SingleOptinTest extends ApiBase { $service = Service::query()->firstOrFail(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [ - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'opt_in' => 1, 'answer_id' => [0], ]); @@ -163,7 +167,7 @@ class SingleOptinTest extends ApiBase $singleOptin->refresh(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optout-hashcode'), [ - 'hashcode' => $singleOptin->hashcode + 'hashcode' => $singleOptin->hashcode, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::OK); @@ -194,13 +198,49 @@ class SingleOptinTest extends ApiBase $singleOptin->delete(); $response = $this->callApiWithToken($service, 'post', route('apiV4.optout-hashcode'), [ - 'hashcode' => $singleOptin->hashcode + 'hashcode' => $singleOptin->hashcode, ]); $json = $response->decodeResponseJson(); $this->assertApiResponseStatusIs($json, ApiStatus::KO); $this->assertEquals(ApiError::modelNotFound->value, $json->json('data.code')); } + /** + * Test set single optin off using hashcode. + * route: apiV4.optout-hashcode + * + * @return void + */ + public function testSetSingleOptoutWithHashcodeWhenCustomerExists(): void + { + $service = Service::firstOrFail(); + $this->storeCustomer($service); + + $crmCustomer = CustomerInfo::query() + ->whereHas('customer', fn(Builder $query) => $query->where('email', $this->email)) + ->firstOrFail(); + + $response = $this->callApiWithToken($service, 'post', route('apiV4.optout-hashcode'), [ + 'hashcode' => $crmCustomer->hashcode, + ]); + + $json = $response->decodeResponseJson(); + $this->assertApiResponseStatusIs($json, ApiStatus::OK); + $this->assertFalse( + SingleOptin::query()->where('email', $this->email)->exists(), + 'A SingleOptin record should not exist for this email.' + ); + + $updatedCustomer = CustomerInfo::query() + ->whereHas('customer', fn(Builder $query) => $query->where('email', $this->email)) + ->firstOrFail(); + $this->assertFalse( + $updatedCustomer->opt_in, + 'Customer "opt_in" field should be set to false after opt-out with hashcode.' + ); + } + + /** * Store a customer in DB. * @@ -214,13 +254,13 @@ class SingleOptinTest extends ApiBase 'lastname' => 'Bond', 'birth_date' => \date('1992-03-08'), 'address' => '10 rue des totos', - 'email' => 'singleoptin@hotmail.fr', + 'email' => $this->email, 'password' => '123.Mot.De.P4sse', 'phone' => '+33654821562', 'country' => Country::france->value, 'city' => 'Connerré', 'postcode' => '72160', - 'opt_in' => true + 'opt_in' => true, ]; $this->callApiWithToken($service, 'post', route('apiV4.customers.store'), $data); } diff --git a/tests/Client/CrmClientSingleOptinTest.php b/tests/Client/CrmClientSingleOptinTest.php index 900f63f..27085e6 100644 --- a/tests/Client/CrmClientSingleOptinTest.php +++ b/tests/Client/CrmClientSingleOptinTest.php @@ -5,17 +5,17 @@ namespace Tests\Client; use App\Models\SingleOptin as ModelsSingleOptin; use Illuminate\Support\Str; use LDC\LDCCRM\CrmApiV4; -use LDC\LDCCRM\Enums\ApiError; use LDC\LDCCRM\Enums\Country; -use LDC\LDCCRM\Exceptions\ApiErrorException; use LDC\LDCCRM\Models\Customer; use LDC\LDCCRM\Models\SingleOptin; class CrmClientSingleOptinTest extends CrmClientTester { + /** @var string $email */ + private $email = 'singleoptin@hotmail.fr'; + /** * Create and remove single optin test - * * Calling multiple times single optin true should not fail. * * @return void @@ -23,43 +23,43 @@ class CrmClientSingleOptinTest extends CrmClientTester public function testCreateAndRemoveSingleOptin() { // Set single optin and check. - $this->assertTrue(SingleOptin::setStatus('singleoptinrandom@gmail.com', true)); - $this->assertTrue(ModelsSingleOptin::query()->where('email', 'singleoptinrandom@gmail.com')->exists()); + $this->assertTrue(SingleOptin::setStatus($this->email, true)); + $this->assertTrue(ModelsSingleOptin::query()->where('email', $this->email)->exists()); // Set single optin again should not fail. - $this->assertTrue(CrmApiV4::setStatus('singleoptinrandom@gmail.com', true)); + $this->assertTrue(CrmApiV4::setStatus($this->email, true)); // Remove single optin test and check. - $this->assertTrue(SingleOptin::setStatus('singleoptinrandom@gmail.com', false)); - $this->assertTrue(!ModelsSingleOptin::query()->where('email', 'singleoptinrandom@gmail.com')->exists()); + $this->assertTrue(SingleOptin::setStatus($this->email, false)); + $this->assertTrue(!ModelsSingleOptin::query()->where('email', $this->email)->exists()); } /** - * Test create single optin should fail if a customer exists. + * Test set single optin on when customer exists. * * @return void */ - public function testCreateSingleOptinShouldFailBecauseCustomerExists() + public function testSetSingleOptinWhenCustomerExists() { - $this->expectException(ApiErrorException::class); - $this->expectExceptionMessage(ApiError::singleOptinCustomerExists->label()); - $customer = new Customer(); - $randomMail = Str::uuid() . 'totosingleoptin.delarogerie@gmail.com'; - - $customer->firstname = 'toto singleoptin'; - $customer->lastname = 'delarogerie'; - $customer->email = $randomMail; - $customer->password = 'Complic4tEd!P4assW0rd'; - $customer->birth_date = '1992-03-08'; - $customer->phone = '0673891160'; - $customer->address = 'rue des totos'; - $customer->city = 'Toto ville'; - $customer->postcode = '72160'; - $customer->country = Country::france->value(); + $customer = new Customer(); + $customer->fill([ + 'firstname' => 'toto singleoptin', + 'lastname' => 'delarogerie', + 'email' => $randomMail, + 'password' => 'Complic4tEd!P4assW0rd', + 'birth_date' => '1992-03-08', + 'phone' => '0673891160', + 'address' => 'rue des totos', + 'city' => 'Toto ville', + 'postcode' => '72160', + 'country' => Country::france->value(), + 'opt_in' => false, + ]); $this->assertTrue($customer->save()); - $this->assertFalse(SingleOptin::setStatus($randomMail, true)); + $this->assertTrue(SingleOptin::setStatus($randomMail, true)); + $this->assertTrue(Customer::findWithEmail($randomMail)->opt_in); } /** @@ -72,14 +72,44 @@ class CrmClientSingleOptinTest extends CrmClientTester public function testRemoveSingleOptinWithHashcode() { // Set single optin and check. - $this->assertTrue(SingleOptin::setStatus('singleoptinrandom@gmail.com', true)); - $this->assertTrue(ModelsSingleOptin::query()->where('email', 'singleoptinrandom@gmail.com')->exists()); + $this->assertTrue(SingleOptin::setStatus($this->email, true)); + $this->assertTrue(ModelsSingleOptin::query()->where('email', $this->email)->exists()); $hashcode = ModelsSingleOptin::query() - ->where('email', 'singleoptinrandom@gmail.com')->sole('hashcode')->hashcode; + ->where('email', $this->email)->sole('hashcode')->hashcode; // Remove single optin test and check. $this->assertTrue(SingleOptin::unsetStatusWithHashcode($hashcode)); - $this->assertTrue(!ModelsSingleOptin::query()->where('email', 'singleoptinrandom@gmail.com')->exists()); + $this->assertTrue(!ModelsSingleOptin::query()->where('email', $this->email)->exists()); + } + + /** + * Remove single optin with hashcode test + * + * Calling multiple times single optin true should not fail. + * + * @return void + */ + public function testRemoveSingleOptinWithHashcodeWhenCustomerExists() + { + $randomMail = Str::uuid() . 'totosingleoptin.delarogerie@gmail.com'; + $customer = new Customer(); + $customer->fill([ + 'firstname' => 'toto singleoptin', + 'lastname' => 'delarogerie', + 'email' => $randomMail, + 'password' => 'Complic4tEd!P4assW0rd', + 'birth_date' => '1992-03-08', + 'phone' => '0673891160', + 'address' => 'rue des totos', + 'city' => 'Toto ville', + 'postcode' => '72160', + 'country' => Country::france->value(), + 'opt_in' => true, + ]); + + $this->assertTrue($customer->save()); + $this->assertTrue(SingleOptin::setStatus($randomMail, false)); + $this->assertFalse(Customer::findWithEmail($randomMail)->opt_in); } } From 1b9a5dacf88a467663921b63a94cb4b238e550ca Mon Sep 17 00:00:00 2001 From: Alexis Gousseau Date: Wed, 27 Aug 2025 11:27:39 +0200 Subject: [PATCH 2/3] fix: :bug: update questions/answers filters on index pages --- .../Controllers/Bo/CustomerController.php | 248 +++++++++++++----- .../Controllers/Bo/SingleOptinController.php | 95 ++++--- app/Http/Controllers/Controller.php | 2 +- resources/ts/bo/pages/search-bar.ts | 2 +- .../views/bo/modules/search-bar.blade.php | 23 +- .../bo/modules/table-col-sorter.blade.php | 10 +- .../customers/index-tableHeaders.blade.php | 30 +-- 7 files changed, 277 insertions(+), 133 deletions(-) diff --git a/app/Http/Controllers/Bo/CustomerController.php b/app/Http/Controllers/Bo/CustomerController.php index 4050a3c..a211f67 100644 --- a/app/Http/Controllers/Bo/CustomerController.php +++ b/app/Http/Controllers/Bo/CustomerController.php @@ -5,15 +5,18 @@ namespace App\Http\Controllers\Bo; use App\Enums\CustomerExportType; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\CustomerExport; +use App\Models\Answer; use App\Models\Brand; use App\Models\Customer; use App\Models\CustomerInfo; use App\Models\CustomerLogin; +use App\Models\Question; use App\Models\SingleOptin; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\JoinClause; use Illuminate\Http\Request; use Illuminate\Support\Carbon; +use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Session; @@ -39,89 +42,40 @@ class CustomerController extends Controller */ public function index(Request $request): \Illuminate\Contracts\View\View { - $modelTable = (new Customer())->getTable(); $modelClass = Customer::class; - $brands = Brand::query()->select('id', 'name')->get(); + $modelTable = (new Customer())->getTable(); + $brands = Brand::select('id', 'name')->get(); $columns = ['customer_infos.lastname', 'customer_infos.firstname']; - // * Jointure pour pouvoir trier les colonnes. - /** @var \Illuminate\Database\Eloquent\Builder */ - $query = CustomerInfo::query()->join('customer_logins', function (JoinClause $join) { - $join->on('customer_logins.brand_id', '=', 'customer_infos.brand_id') - ->on('customer_logins.customer_id', '=', 'customer_infos.customer_id'); - })->join('customers', function (JoinClause $join) { - $join->on('customers.id', '=', 'customer_infos.customer_id'); - })->join('brands', function (JoinClause $join) { - $join->on('brands.id', '=', 'customer_infos.brand_id'); - }); - - if ($request->rst) { - Session::remove("crud.$modelTable.brand"); - Session::remove("crud.$modelTable.search"); - Session::remove("crud.$modelTable.sort_way"); - Session::remove("crud.$modelTable.sort_col"); + // Reset session sorts. + if ($request->rstSrts) { + $this->resetSessionSorts($modelTable); + } + // Reset session filters. + if ($request->rstFltrs) { + $this->resetSessionFilters($modelTable); } - if (request()->brand or Session::has("crud.$modelTable.brand")) { - $brand = $request->brand ?? Session::get("crud.$modelTable.brand"); - Session::put("crud.$modelTable.brand", $brand); - $query = $query->where('customer_infos.brand_id', $brand); - } + $query = $this->buildCustomerQuery(); - // * Search on crud Label column. - if ($request->search or Session::has("crud.$modelTable.search")) { - $search = $request->search ?? Session::get("crud.$modelTable.search"); - Session::put("crud.$modelTable.search", $search); - $query->where(function ($q) use ($columns, $search) { - foreach ($columns as $column) { - $q = $q->orWhere($column, 'LIKE', "%$search%"); - } - $q = $q->orWhere('customers.email', 'LIKE', "%$search%"); - $q = $q->orWhere('customer_logins.last_connection', 'LIKE', "%$search%"); - }); - } + // Apply filters. + $questionModels = null; + $answerModels = null; + $this->applyBrandFilter($request, $query, $modelTable, $questionModels, $answerModels); + $this->applySearchFilter($request, $query, $modelTable, $columns); + $this->applySort($request, $query, $modelTable); - // * Sort columns. - if ($request->sort_col) { - Session::put("crud.$modelTable.sort_col", $request->sort_col); - } - if ($request->sort_way) { - Session::put("crud.$modelTable.sort_way", $request->sort_way); - } - - if ( - Session::has("crud.$modelTable.sort_col") and - Session::has("crud.$modelTable.sort_way") and - (Schema::hasColumn($modelTable, Session::get("crud.$modelTable.sort_col")) or - in_array(Session::get("crud.$modelTable.sort_col"), [ - 'brands.name', - 'customers.email', - 'customer_infos.firstname', - 'customer_infos.lastname', - 'customer_infos.opt_in', - 'customer_logins.last_connection', - 'customer_logins.status' - ])) - ) { - $query = $query->orderBy( - Session::get("crud.$modelTable.sort_col"), - Session::get("crud.$modelTable.sort_way") - ); - } - - $searchFields = trans('Email, Prénom, Nom'); - - $query->with(['customer', 'brand']); - - /** @var \Illuminate\Pagination\AbstractPaginator */ - $customerModels = $this->paginate($query); + $customerModels = $this->paginate($query->with(['customer', 'brand'])); + $searchFields = trans('Email, Prénom, Nom'); return view('bo.pages.customers.index', compact( 'modelClass', 'modelTable', 'customerModels', 'brands', - 'searchFields' + 'searchFields', + 'questionModels', + 'answerModels', )); } @@ -312,4 +266,158 @@ class CustomerController extends Controller }); return $response; } + + /** + * Reset all session sorts. + * + * @param string $table + * @return void + */ + private function resetSessionSorts(string $table): void + { + Session::forget([ + "crud.$table.sort_col", + "crud.$table.sort_way", + ]); + } + + /** + * Reset all session filters. + * + * @param string $table + * @return void + */ + private function resetSessionFilters(string $table): void + { + Session::forget([ + "crud.$table.brand", + "crud.$table.question", + "crud.$table.answer", + "crud.$table.search", + ]); + } + + /** + * Build the customer query. + * + * @return Builder + */ + private function buildCustomerQuery(): Builder + { + return CustomerInfo::query() + ->join('customer_logins', function (JoinClause $join) { + $join->on('customer_logins.brand_id', '=', 'customer_infos.brand_id') + ->on('customer_logins.customer_id', '=', 'customer_infos.customer_id'); + }) + ->join('customers', fn($join) => $join->on('customers.id', '=', 'customer_infos.customer_id')) + ->join('brands', fn($join) => $join->on('brands.id', '=', 'customer_infos.brand_id')); + } + + /** + * Apply all filters (brand, question, answer). + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string $table + * @param \Illuminate\Support\Collection|null $questionModels + * @param \Illuminate\Support\Collection|null $answerModels + * @return void + */ + private function applyBrandFilter( + Request $request, + Builder &$query, + string $table, + ?Collection &$questionModels, + ?Collection &$answerModels + ): void { + if ($request->filled('brand') || Session::has("crud.$table.brand")) { + $brand = $request->brand ?? Session::get("crud.$table.brand"); + Session::put("crud.$table.brand", $brand); + $query->where('customer_infos.brand_id', $brand); + + $questionModels = Question::getAllModelsFromBrand($brand); + + if (($request->filled('question') || Session::has("crud.$table.question")) && $questionModels->count()) { + $question = $request->question ?? Session::get("crud.$table.question"); + Session::put("crud.$table.question", $question); + + $answerModels = Answer::getAllAnswersFromQuestion($question); + $questionAnswers = Question::find($question)?->answers->modelKeys() ?? []; + + $query->whereHas('customer.answers', fn($q) => $q->whereIn('answer_id', $questionAnswers)); + + if ( + ($request->filled('answer') || Session::has("crud.$table.answer")) + && $questionModels->count() + && $answerModels->count() + ) { + $answer = $request->answer ?? Session::get("crud.$table.answer"); + Session::put("crud.$table.answer", $answer); + + $query->whereHas('customer.answers', fn($q) => $q->whereKey($answer)); + } + } + } //end if + } + + /** + * Apply the search filter. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string $table + * @param array $columns + * @return void + */ + private function applySearchFilter(Request $request, Builder &$query, string $table, array $columns): void + { + if ($request->filled('search') || Session::has("crud.$table.search")) { + $search = $request->search ?? Session::get("crud.$table.search"); + Session::put("crud.$table.search", $search); + + $query->where(function ($q) use ($columns, $search) { + foreach ($columns as $column) { + $q->orWhere($column, 'LIKE', "%$search%"); + } + + $q->orWhere('customers.email', 'LIKE', "%$search%") + ->orWhere('customer_logins.last_connection', 'LIKE', "%$search%"); + }); + } + } + + /** + * Apply sorts. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @param string $table + * @return void + */ + private function applySort(Request $request, Builder &$query, string $table): void + { + $sortCol = $request->sort_col ?? Session::get("crud.$table.sort_col"); + $sortWay = $request->sort_way ?? Session::get("crud.$table.sort_way"); + + if ($sortCol) { + Session::put("crud.$table.sort_col", $sortCol); + } + if ($sortWay) { + Session::put("crud.$table.sort_way", $sortWay); + } + + $sortable = [ + 'brands.name', + 'customers.email', + 'customer_infos.firstname', + 'customer_infos.lastname', + 'customer_infos.opt_in', + 'customer_logins.last_connection', + 'customer_logins.status', + ]; + + if ($sortCol && $sortWay && (Schema::hasColumn($table, $sortCol) || in_array($sortCol, $sortable))) { + $query->orderBy($sortCol, $sortWay); + } + } } diff --git a/app/Http/Controllers/Bo/SingleOptinController.php b/app/Http/Controllers/Bo/SingleOptinController.php index 29d0f39..59b75db 100644 --- a/app/Http/Controllers/Bo/SingleOptinController.php +++ b/app/Http/Controllers/Bo/SingleOptinController.php @@ -6,7 +6,9 @@ use App\Http\Controllers\Controller; use App\Models\Answer; use App\Models\Question; use App\Models\SingleOptin; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; +use Illuminate\Support\Collection; use Illuminate\Support\Str; class SingleOptinController extends Controller @@ -27,45 +29,23 @@ class SingleOptinController extends Controller */ public function index(Request $request): \Illuminate\Contracts\View\View { - /** @var \Illuminate\Database\Eloquent\Builder $query */ - $query = SingleOptin::query() - ->when( - $request->filled('brand'), - fn($q) => $q->whereHas('brand', fn($q) => $q->whereKey($request->brand)), - ) - ->when( - $request->filled('answer'), - fn($q) => $q->whereHas('answers', fn($q) => $q->whereKey($request->answer)), - ); - - if ($request->filled('search')) { - $this->searchQuery( - $query, - $request->search, - null, - 'email', - ); - } + $query = SingleOptin::query(); + $questionModels = null; + $answerModels = null; + $this->applyBrandAndAnswerFilters($request, $query, $questionModels, $answerModels); + $this->applySearch($request, $query); $this->sortQuery($query); - $query->with('brand'); + $query->with('brand'); $singleoptinModels = $this->paginate($query); $searchFields = trans('E-mail'); - if ($request->filled('brand')) { - $questionModels = Question::getAllModelsFromBrand($request->brand); - - if ($request->filled('question')) { - $answerModels = Answer::getAllAnswersFromQuestion($request->question); - } - } - return view('bo.pages.singleoptins.index', [ 'singleoptinModels' => $singleoptinModels, 'searchFields' => $searchFields, - 'questionModels' => $questionModels ?? null, - 'answerModels' => $answerModels ?? null, + 'questionModels' => $questionModels, + 'answerModels' => $answerModels, ]); } @@ -92,4 +72,59 @@ class SingleOptinController extends Controller ['model' => Str::singular(trans('models.classes.singleoptins'))] )); } + + /** + * Undocumented function + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @param \Illuminate\Support\Collection|null $questionModels + * @param \Illuminate\Support\Collection|null $answerModels + * @return void + */ + private function applyBrandAndAnswerFilters( + Request $request, + Builder $query, + ?Collection &$questionModels, + ?Collection &$answerModels + ): void { + if (!$request->filled('brand')) { + return; + } + + $brandId = $request->brand; + $query->whereHas('brand', fn($q) => $q->whereKey($brandId)); + $questionModels = Question::getAllModelsFromBrand($brandId); + + if (!$request->filled('question')) { + return; + } + + $questionId = $request->question; + $question = Question::find($questionId); + + if ($question) { + $questionAnswers = $question->answers->modelKeys(); + $query->whereHas('answers', fn($q) => $q->whereIn('answer_id', $questionAnswers)); + $answerModels = Answer::getAllAnswersFromQuestion($questionId); + } + + if ($request->filled('answer')) { + $query->whereHas('answers', fn($q) => $q->whereKey($request->answer)); + } + } + + /** + * Apply search filter. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Database\Eloquent\Builder $query + * @return void + */ + private function applySearch(Request $request, Builder $query): void + { + if ($request->filled('search')) { + $this->searchQuery($query, $request->search, null, 'email'); + } + } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index e083748..cb0a5bf 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -160,7 +160,7 @@ class Controller extends BaseController Session::put("$rName.sort_way", request()->sort_way); Session::put("$rName.sorted", true); } - if (request()->rst) { + if (request()->rstSrts) { Session::remove("$rName.sorted"); Session::remove("$rName.sort_col"); Session::remove("$rName.sort_way"); diff --git a/resources/ts/bo/pages/search-bar.ts b/resources/ts/bo/pages/search-bar.ts index bffb549..ed8a760 100644 --- a/resources/ts/bo/pages/search-bar.ts +++ b/resources/ts/bo/pages/search-bar.ts @@ -13,7 +13,7 @@ function setupFilterListener(selectId: string, paramKey: FilterKey): void { if (value !== "0") { const url = new URL(location.href); url.searchParams.set(paramKey, value); - url.searchParams.delete("rst"); + url.searchParams.delete("rstSrts"); location.assign(url.search); } }); diff --git a/resources/views/bo/modules/search-bar.blade.php b/resources/views/bo/modules/search-bar.blade.php index 29f6837..f6085a0 100644 --- a/resources/views/bo/modules/search-bar.blade.php +++ b/resources/views/bo/modules/search-bar.blade.php @@ -1,20 +1,21 @@ @php - $selectedBrand = request()->brand; - $selectedQuestion = request()->question; - $selectedAnswer = request()->answer; - $search = request()->search; - $sortCol = request()->sort_col; - $sortWay = request()->sort_way; + $selectedBrand = request()->brand ?? (isset($modelTable) ? Session::get("crud.$modelTable.brand") : null); + $selectedQuestion = request()->question ?? (isset($modelTable) ? Session::get("crud.$modelTable.question") : null); + $selectedAnswer = request()->answer ?? (isset($modelTable) ? Session::get("crud.$modelTable.answer") : null); + $search = request()->search ?? (isset($modelTable) ? Session::get("crud.$modelTable.search") : null); + $sortCol = request()->sort_col ?? (isset($modelTable) ? Session::get("crud.$modelTable.sort_col") : null); + $sortWay = request()->sort_way ?? (isset($modelTable) ? Session::get("crud.$modelTable.sort_way") : null); $routes = !request()->routeIs('bo.activity_logs.*') && !request()->routeIs('bo.users.*') && !request()->routeIs('bo.brands.*'); @endphp -
+ @if ($routes) + @php $routeCondition = request()->routeIs('bo.single_optins.*') || request()->routeIs('bo.customers.*'); @endphp
{{-- BRAND SELECT --}} - {{-- QUESTION SELECT --}} - @if (request()->routeIs('bo.single_optins.*') && $selectedBrand && $questionModels) + @if ($routeCondition && $selectedBrand && $questionModels->count()) @foreach ($answerModels as $answer) @@ -75,7 +76,7 @@
diff --git a/resources/views/bo/modules/table-col-sorter.blade.php b/resources/views/bo/modules/table-col-sorter.blade.php index e489797..cd0d478 100644 --- a/resources/views/bo/modules/table-col-sorter.blade.php +++ b/resources/views/bo/modules/table-col-sorter.blade.php @@ -1,7 +1,7 @@ @php $route = request()->route(); $routeName = $route->getName(); - $rst = !is_null(request()->rst) || !Session::has("$routeName.sorted"); + $rstSrts = !is_null(request()->rstSrts) || !Session::has("$routeName.sorted"); $noOrder = !empty($noOrder); $noOrder = $noOrder || (Session::get("$routeName.sort_col") !== 'order' and (Session::has("$routeName.sort_col") or Session::has("$routeName.sort_way"))); $noOrder = $noOrder || !empty(request()->search); @@ -37,7 +37,7 @@ session("$routeName.sort_col") !== $col or session("$routeName.sort_way") === 'desc' and session("$routeName.sort_col") === $col) + href="{{ request()->fullUrlWithQuery(array_merge($iArgs, ['sort_way' => 'asc', 'rstSrts' => null])) }}">