ldc-legaulois/app/Http/Controllers/Club/CustomerController.php
2026-09-25 16:25:31 +02:00

161 lines
5.7 KiB
PHP

<?php
namespace App\Http\Controllers\Club;
use App\Http\Controllers\Controller;
use App\Http\Requests\Club\Customers\UpdateCustomerRequest;
use App\Http\Requests\Club\Customers\UpdatePasswordRequest;
use App\Models\Customer;
use App\Models\Product;
use App\Models\Recipe;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use LDC\LDCCRM\Enums\ApiError;
use LDC\LDCCRM\Exceptions\ApiErrorException;
use LDC\LDCCRM\Models\Answer;
use LDC\LDCCRM\Models\Question;
class CustomerController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
/** @var \App\Models\Customer $customer */
$customer = Auth::guard('club')->user();
/** @var \LDC\LDCCRM\Models\Customer $crmCustomer */
$crmCustomer = $customer->api_data;
$questions = Customer::cacheCrm(
$customer->hashcode,
'questions',
fn () => collect(Question::all())->filter(function ($question) {
return $question->id === intval(config('crm.question'));
})
);
/** @var array<int, \LDC\LDCCRM\Models\Answer> $crmAnswers */
$crmAnswers = [];
collect(Question::allWithCustomerAnswers($crmCustomer))->map(function ($question) use (&$crmAnswers) {
/** @var \LDC\LDCCRM\Models\Question $crmQuestion */
$crmQuestion = $question['question'];
if (intval($crmQuestion->id) === intval(config('crm.question'))) {
$crmAnswers = $question['customerAnswers'];
}
});
return view('club.pages.customers.index', compact('customer', 'crmCustomer', 'questions', 'crmAnswers'));
}
/**
* Update the specified resource in storage.
*/
public function update(
UpdateCustomerRequest $request,
): RedirectResponse {
return DB::transaction(function () use ($request) {
/** @var \App\Models\Customer $customer */
$customer = auth('club')->user();
$customer->fill(collect($request->validated())->only(['username'])->toArray());
if (
$this->updateCrmCustomerInfo($customer, collect($request->validated())->except([
'password',
'ok_cgv',
'ok_cgu',
'email',
])->toArray())
) {
if ($customer->saveOrFail()) {
/** @var \LDC\LDCCRM\Models\Customer $crmCustomer */
$crmCustomer = $customer->api_data;
if (! Answer::setQuestionAnswers($crmCustomer->hashcode, $request->question_id, $request->answers)) {
return redirect()->route('club.customers.index')
->with('error', trans('Une erreur est survenue lors de l\'enregistrement de la réponse
à la question, merci de réessayer plus tard'));
}
return redirect()->route('club.customers.index')
->with('success', trans('Vos informations ont bien été enregistrées.'));
}
return redirect()->back()
->with('error', trans('Une erreur est survenue, merci de réessayer ultérieurement.'));
}
return redirect()->back()
->with('error', trans('Une erreur est survenue, merci de réessayer ultérieurement.'));
});
}
/**
* Updates user info.
*
* @return bool
*
* @throws \Illuminate\Validation\ValidationException If something failed.
*/
private function updateCrmCustomerInfo(Customer $customer, array $data)
{
return DB::transaction(function () use ($customer, $data) {
try {
return $customer->updateApiData($data);
} catch (ApiErrorException $e) {
if ($e->getApiError()->equals(ApiError::validationFailed)) {
throw ValidationException::withMessages([
'error' => $e->getMessage(),
]);
}
report($e);
return false;
} // end try
});
}
/**
* Update customer password.
*/
public function passwordUpdate(UpdatePasswordRequest $request): RedirectResponse
{
/** @var \App\Models\Customer */
$customer = \auth('club')->user();
if ($this->updateCrmCustomerInfo($customer, ['password' => $request->input('password')])) {
event(new PasswordReset($customer));
return redirect()->back()->with('success', trans('crud.messages.has_been_updated', [
'model' => Str::ucfirst(trans('validation.attributes.password')),
]));
}
return redirect()->back()->with('error', trans('crud.messages.cannot_be_updated', [
'model' => Str::ucfirst(trans('validation.attributes.password')),
]));
}
/**
* Display a listing of the resource.
*/
public function indexProducts(): View
{
$models = Product::query()->where('published', true)->take(15)->paginate(9);
return view('club.pages.customers.favorites.products', compact('models'));
}
/**
* Display a listing of the resource.
*/
public function indexRecipes(): View
{
$models = Recipe::query()->with('products', 'consumptionMoment')
->where('published', true)->take(15)->paginate(9);
return view('club.pages.customers.favorites.recipes', compact('models'));
}
}