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/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/composer.json b/composer.json index 34b0378..680f37e 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "ldc/ldccrm", - "version": "4.1.1", + "version": "4.1.2", "type": "project", "description": "LDC CRM", "license": "MIT", 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 -