ldc-legaulois/app/Http/Controllers/ClubController.php

580 lines
20 KiB
PHP
Raw Permalink Normal View History

2021-03-01 11:51:00 +01:00
<?php
namespace App\Http\Controllers;
use App\Enums\ArticleCategory;
use App\Enums\NotificationType;
use App\Events\NewNotification;
2021-03-10 18:58:40 +01:00
use App\Http\Requests\BlockCustomerRequest;
2021-03-10 17:16:31 +01:00
use App\Http\Requests\DeleteMessagesRequest;
2021-10-13 12:06:41 +02:00
use App\Http\Requests\DownloadBRFileRequest;
2021-03-10 17:16:31 +01:00
use App\Http\Requests\SendMessageRequest;
2021-03-05 08:17:35 +01:00
use App\Http\Requests\SurveyAnswersRequest;
use App\Http\Requests\UpdateInfosRequest;
use App\Models\Articles;
2021-03-10 18:58:40 +01:00
use App\Models\BlockList;
use App\Models\Customers;
2021-03-10 17:16:31 +01:00
use App\Models\Message;
2021-10-13 12:06:41 +02:00
use App\Models\Reduction;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
2021-03-01 11:51:00 +01:00
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
2021-10-13 12:06:41 +02:00
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
2021-03-10 17:16:31 +01:00
use Illuminate\Support\Facades\View;
use LDC\LDCCRM\Enums\ApiError;
use LDC\LDCCRM\Exceptions\ApiErrorException;
use LDC\LDCCRM\Exceptions\CrmException;
use LDC\LDCCRM\Exceptions\ValidationException;
2021-03-10 17:16:31 +01:00
use RuntimeException;
use Snipe\BanBuilder\CensorWords;
2021-03-01 11:51:00 +01:00
class ClubController extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next) {
// IF session has need crm completion
// Then redirect to completion page.
if (
Session::has('needCrmInfoUpdate') and
$request->route() and
\in_array($request->route()->getName(), ['club.reductions', 'club.reductionsGet'])
) {
return response()->redirectToRoute('account.missingCrmInfos');
}
return $next($request);
});
parent::__construct();
}
/**
2023-01-11 17:45:12 +01:00
* Index
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Enums\ArticleCategory|null $tag
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
2023-01-11 17:45:12 +01:00
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
public function index(ArticleCategory $tag = null)
2021-03-08 12:00:46 +01:00
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
2022-02-10 16:14:58 +01:00
$articles = Articles::where('status', 1)->orderBy('updated_at', 'DESC')->get();
2021-04-26 10:29:34 +02:00
$categories = Articles::select('type')->where('status', true)->groupBy('type')->get()->pluck('type');
2021-10-13 12:06:41 +02:00
$montantReduction = Reduction::whereStatus(true)->sum('value');
$nbCustomers = Customers::count();
// Cas de catégorie d'article.
$category = $tag;
2021-03-03 15:26:59 +01:00
2021-03-19 21:40:10 +01:00
return view('front.club.index', compact(
2021-10-13 12:06:41 +02:00
'montantReduction',
2021-03-19 21:40:10 +01:00
'nbCustomers',
'articles',
'categories',
'category'
));
}
/**
* infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws Exception Exception.
*/
2021-03-08 12:00:46 +01:00
public function infos()
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
/** @var \App\Models\Customers */
$customer = auth('customer')->user();
2021-03-19 21:40:10 +01:00
if (!$customer) {
abort(404);
2021-03-19 21:40:10 +01:00
}
$crmCustomer = $customer->apiData;
2021-05-04 09:27:59 +02:00
if (!$crmCustomer) {
throw new Exception('CRM get Customer returned null');
2021-05-04 09:27:59 +02:00
}
return view('front.club.informations', compact('customer', 'crmCustomer'));
}
/**
* Send a request to the CRM to change the given customer's informations
*
* Les champs obligatoires, sachant que LG utilise MES BR
*
* nom, prénom, adresse, code postal, ville
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\UpdateInfosRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Illuminate\Validation\ValidationException ValidationException.
*/
2021-03-08 12:00:46 +01:00
public function updateInfos(UpdateInfosRequest $request)
{
if (($result = $this->updateUserInfo($request)) === true) {
return redirect()->back()
->with('success', __("Vos informations ont bien été enregistrées."));
}
return redirect()->back()
->withErrors(
$result !== false ?
$result :
__("Une erreur est survenue, merci de réessayer ultérieurement.")
);
}
/**
* missingCrmInfos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws Exception Exception.
*/
public function missingCrmInfos()
{
self::getNotifications();
$customer = auth()->user();
/** @var \LDC\LDCCRM\CrmApiV2 */
$crm = app('crmAPI');
if (!($crmCustomer = $crm->getCustomer($customer->hashcode))) {
throw new Exception("Could not get customer $customer->hashcode for customer $customer->id");
}
return view('front.club.missingInfos', compact('customer', 'crmCustomer'));
}
/**
* missingCrmInfosSubmit
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\UpdateInfosRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Illuminate\Validation\ValidationException ValidationException.
* @throws \Symfony\Component\Routing\Exception\RouteNotFoundException RouteNotFoundException.
*/
public function missingCrmInfosSubmit(UpdateInfosRequest $request)
{
if (($result = $this->updateUserInfo($request)) === true) {
Session::remove('needCrmInfoUpdate');
return redirect()->route('club.reductions');
}
return redirect()->back()
->withErrors(
$result !== false ?
$result :
__("Une erreur est survenue, merci de réessayer ultérieurement.")
);
}
/**
* Updates user info
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\UpdateInfosRequest $request
* @return \Illuminate\Http\RedirectResponse|string|boolean return strictly true if success,
* false il failed, could be a string with message error if failed
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Illuminate\Validation\ValidationException ValidationException.
*/
private function updateUserInfo(UpdateInfosRequest $request)
2021-03-08 12:00:46 +01:00
{
/** @var \App\Models\Customers */
$customer = auth('customer')->user();
if (!$customer) {
return \redirect()->back();
}
// TODO : Activer le changement d'email quand ce sera possible dans la CRM.
/** @var \LDC\LDCCRM\Models\Customer */
$crmCustomer = $customer->apiData;
$data = $request->validated();
unset($data['day']);
unset($data['month']);
unset($data['year']);
// Remove phone if empty.
if (isset($data['phone']) and !strlen($data['phone'])) {
unset($data['phone']);
}
try {
$crmCustomer->fill($data);
$crmCustomer->save();
} catch (ValidationException $e) {
return $e->getMessage();
} catch (ApiErrorException $e) {
if ($e->getApiError()->equals(ApiError::validationFailed())) {
return $e->getMessage();
}
if (app()->bound('sentry')) {
app('sentry')->captureException($e);
}
return false;
} catch (CrmException | \TypeError $e) {
if (app()->bound('sentry')) {
app('sentry')->captureException($e);
}
return false;
2021-03-19 21:40:10 +01:00
}
return true;
}
/**
* Call the notifications page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
2021-03-08 12:00:46 +01:00
public function notifications()
{
2021-05-10 09:23:42 +02:00
self::getNotifications();
2021-05-10 09:37:37 +02:00
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = auth('customer')->user();
2021-05-10 09:37:37 +02:00
$notificationsIds = $customer->getAllNotifications()
->pluck('id')->toArray();
// Handle multiple access to this critical part.
DB::beginTransaction();
try {
// Hack to prevent duplicates.
$customer->readNotifications()->sync([]);
// Sync notifications.
$customer->readNotifications()->sync($notificationsIds);
} catch (QueryException $e) {
DB::rollBack();
}
DB::commit();
2021-03-10 17:16:31 +01:00
return view('front.club.notifications');
}
2021-02-24 16:04:53 +01:00
/**
* Call the cart page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
2021-03-08 12:00:46 +01:00
public function cart()
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
2021-02-24 16:04:53 +01:00
$products = Auth::guard('customer')->user()->products;
2021-03-10 17:16:31 +01:00
return view('front.club.cart', compact('products'));
2021-02-24 16:04:53 +01:00
}
/**
* Call the favorites recipes page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
2021-03-08 12:00:46 +01:00
public function favoritesRecipes()
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
2021-02-24 16:04:53 +01:00
$recipes = Auth::guard('customer')->user()->recipes;
2021-03-10 17:16:31 +01:00
return view('front.club.favorites-recipes', compact('recipes'));
2021-02-24 16:04:53 +01:00
}
2021-03-03 15:26:59 +01:00
/**
* Call the reductions page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws Exception Exception.
2021-03-03 15:26:59 +01:00
*/
2021-03-08 12:00:46 +01:00
public function reductions()
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
/** @var \App\Lib\MesBR */
2021-10-13 12:06:41 +02:00
$mesBR = app('mesBR');
2021-05-03 12:16:54 +02:00
/** @var \App\Models\Customers $customer */
$customer = Auth::guard('customer')->user();
2021-10-21 15:52:24 +02:00
/** @var \LDC\LDCCRM\Models\Customer */
$crmCustomer = $customer->apiData;
2022-02-10 16:14:58 +01:00
$murBr = [];
2021-10-21 15:52:24 +02:00
$mesBR->updateCustomer(
$crmCustomer->hashcode,
$crmCustomer->email,
$crmCustomer->country
);
$murBr = $mesBR->getMurCustomer($crmCustomer->hashcode);
if ($murBr->status === 'KO') {
throw new Exception(sprintf(
'Mes BR returns error %s',
\json_encode($murBr)
2021-10-13 12:06:41 +02:00
));
2021-05-03 12:16:54 +02:00
}
2021-10-13 12:06:41 +02:00
return view('front.club.reductions', compact('murBr'));
}
2021-05-03 12:16:54 +02:00
/**
* reductionsGet
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\DownloadBRFileRequest $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
* @throws \Exception Exception.
*/
2021-10-13 12:06:41 +02:00
public function reductionsGet(DownloadBRFileRequest $request)
{
/** @var \App\Lib\MesBR */
$mesBR = app('mesBR');
/** @var \App\Models\Customers $customer */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
$crmCustomer = $customer->apiData;
2021-10-21 15:52:24 +02:00
if ($crmCustomer->status === "KO") {
2021-10-13 12:06:41 +02:00
throw new Exception(
2021-11-22 12:31:28 +01:00
sprintf(
'CRM call error %s',
json_encode($crmCustomer)
)
2021-10-13 12:06:41 +02:00
);
}
2021-10-21 15:52:24 +02:00
$coupons = $mesBR->printCoupons($crmCustomer->hashcode, $request->coupons);
if (!isset($coupons->pdf)) {
throw new Exception(
2021-11-22 12:31:28 +01:00
sprintf(
'MesBR call error %s',
json_encode($coupons)
)
2021-10-21 15:52:24 +02:00
);
}
if ($request->ajax()) {
return response()->json([$coupons->pdf]);
}
$filename = sprintf('mes_reduction_%s.pdf', \time());
return Response::make(base64_decode($coupons->pdf), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => "attachment; filename=\"$filename\""
]);
2021-03-03 15:26:59 +01:00
}
/**
* Call the article page with a slug for the article to print
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Enums\ArticleCategory $tag
* @param \App\Models\Articles $publishedArticle
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
2021-03-03 15:26:59 +01:00
*/
public function article(ArticleCategory $tag, Articles $publishedArticle)
2021-03-08 12:00:46 +01:00
{
// phpcs:enable
2021-03-21 14:14:41 +01:00
self::getNotifications();
// Check si le customer connecté a déjà répondu.
2021-03-03 15:26:59 +01:00
$alreadyAnswered = false;
if (Auth::guard('customer')->check()) {
2021-03-05 08:17:35 +01:00
$answersIds = $publishedArticle->answers()->pluck('id')->toArray();
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
2021-03-21 22:51:19 +01:00
$alreadyAnswered = $customer->surveysAnswers()
2021-03-05 08:17:35 +01:00
->whereIn('surveys_answer_id', $answersIds)->count() > 0 ? true : false;
2021-03-03 15:26:59 +01:00
}
2021-04-27 17:50:57 +02:00
$linkedArticles = Articles::where([
['status', true], ['type', $publishedArticle->type], ['id', '<>', $publishedArticle->id]
2021-03-05 08:17:35 +01:00
])->get();
2021-03-03 15:26:59 +01:00
2021-04-26 10:29:34 +02:00
$categories = Articles::select('type')->where('status', true)->groupBy('type')->get()->pluck('type');
2021-03-03 15:26:59 +01:00
2021-03-05 08:17:35 +01:00
return view('front.club.article', compact(
'publishedArticle',
'categories',
'linkedArticles',
'alreadyAnswered'
));
2021-03-03 15:26:59 +01:00
}
/**
* Handle the request of a customer that answered a survey
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\SurveyAnswersRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \InvalidArgumentException InvalidArgumentException.
2021-03-03 15:26:59 +01:00
*/
2021-03-05 08:17:35 +01:00
public function answerSurvey(SurveyAnswersRequest $request)
2021-03-08 12:00:46 +01:00
{
2021-03-03 15:26:59 +01:00
$answers = $request->answers;
2021-03-05 08:17:35 +01:00
if (empty($answers)) {
2021-03-03 15:26:59 +01:00
return back()->withErrors(__("Votre réponse est incomplète. Merci de corriger"));
2021-03-05 08:17:35 +01:00
}
2021-03-03 15:26:59 +01:00
2021-03-19 21:40:10 +01:00
/** @var \App\Models\Customers $customer */
2021-03-03 15:26:59 +01:00
$customer = Auth::guard('customer')->user();
2021-03-05 08:17:35 +01:00
if (is_array($answers)) {
2021-03-19 21:40:10 +01:00
$customer->surveysAnswers()->syncWithoutDetaching($answers);
2021-03-05 08:17:35 +01:00
} else {
2021-03-19 21:40:10 +01:00
$customer->surveysAnswers()->syncWithoutDetaching($answers);
2021-03-05 08:17:35 +01:00
}
2021-03-03 15:26:59 +01:00
return back();
}
2021-03-10 17:16:31 +01:00
/**
* Show messagerie
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
2021-03-10 17:16:31 +01:00
public function messages()
{
2021-03-21 14:14:41 +01:00
self::getNotifications();
2021-03-10 17:16:31 +01:00
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
2021-03-10 17:16:31 +01:00
$conversations = $customer->conversations();
2022-02-10 16:14:58 +01:00
$ids = collect($conversations)->pluck('to_id');
$blockList = BlockList::where('customer_id', $customer->id)
2021-03-10 18:58:40 +01:00
->whereIn('blocked_id', $ids)->get();
// * Sort In reverse order messages
$conversations = collect($conversations)->map(function (array $conversation) {
$conversation['messages'] = collect($conversation['messages'])
->sort(function ($a, $b) {
return Carbon::parse(
$a->getRawOriginal('created_at')
)->timestamp < Carbon::parse($b->getRawOriginal('created_at'))->timestamp;
})->values()->all();
return $conversation;
})->all();
2021-03-10 18:58:40 +01:00
return view('front.club.messages', compact('conversations', 'blockList'));
2021-03-10 17:16:31 +01:00
}
/**
* Send a message to a user
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\SendMessageRequest $request
* @return \Illuminate\Http\JsonResponse
2023-01-11 17:45:12 +01:00
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Throwable Throwable.
*/
2021-03-10 17:16:31 +01:00
public function sendMessage(SendMessageRequest $request)
{
$customer = Customers::where('username', $request->to)->firstOrFail();
2021-03-11 08:22:31 +01:00
if (
BlockList::where([
'customer_id' => Auth::guard('customer')->user()->id,
'blocked_id' => $customer->id
])->exists()
) {
return response()->json(-1);
}
if (
BlockList::where([
'customer_id' => $customer->id,
'blocked_id' => Auth::guard('customer')->user()->id
])->exists()
) {
return response()->json(-2);
2021-03-10 18:58:40 +01:00
}
2022-02-10 16:14:58 +01:00
$message = new Message($request->all());
$message->to = $customer->id;
2021-03-10 17:16:31 +01:00
$message->from = Auth::guard('customer')->user()->id;
2022-02-10 16:14:58 +01:00
$censor = new CensorWords();
2021-03-10 17:16:31 +01:00
try {
$censor->setDictionary(['en-us', 'en-uk', config('app.locale')]);
} catch (RuntimeException $e) {
$censor->setDictionary(['en-us', 'en-uk', 'fr']);
}
$message->message = $censor->censorString($message->message, true)['clean'];
2021-03-10 17:16:31 +01:00
$message->saveOrFail();
event(new NewNotification(
NotificationType::message(),
route('account.messages', ['m' => $message->id]),
$message,
$customer
));
2021-03-10 17:16:31 +01:00
return response()->json($message->load(['toCustomer' => function ($q) {
$q->select(['id', 'username', 'created_at']);
}, 'fromCustomer' => function ($q) {
$q->select(['id', 'username', 'created_at']);
}]));
}
/**
* Destroy a message
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\DeleteMessagesRequest $request
* @return \Illuminate\Http\JsonResponse
2023-01-11 17:45:12 +01:00
* @throws \LogicException LogicException.
* @throws \Throwable Throwable.
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
2021-03-10 17:16:31 +01:00
public function deleteMessage(DeleteMessagesRequest $request)
{
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
$message = Message::findOrFail($request->message);
2021-06-14 15:15:52 +02:00
$conversations = (object)$customer->conversations();
2021-03-10 17:16:31 +01:00
foreach ($conversations as $conversation) {
$conversation = (object)$conversation;
if ($conversation->id != $message->id) {
continue;
}
/** @var \App\Models\Message $message */
foreach ($conversation->messages as $message) {
if ($message->from == $customer->id) {
$message->hide_from = true;
}
if ($message->to == $customer->id) {
$message->hide_to = true;
}
if ($message->hide_to && $message->hide_from) {
$message->delete();
} else {
$message->saveOrFail();
}
}
}
return response()->json();
}
/**
* Block a customer to prevent him sending messages
2023-06-26 15:57:38 +02:00
*
2023-01-11 17:45:12 +01:00
* @param \App\Http\Requests\BlockCustomerRequest $request
* @param boolean $status
* @return \Illuminate\Http\JsonResponse
2023-01-11 17:45:12 +01:00
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
2021-03-10 18:58:40 +01:00
public function blockCustomer(BlockCustomerRequest $request, bool $status)
{
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
2021-03-10 18:58:40 +01:00
$customerToBlock = Customers::where('username', $request->username)->firstOrFail();
2022-02-10 16:14:58 +01:00
$blockCustomer = BlockList::firstOrNew([
2021-03-10 18:58:40 +01:00
'customer_id' => $customer->id,
'blocked_id' => $customerToBlock->id,
]);
if ($status) {
$blockCustomer->saveOrFail();
} else {
$blockCustomer->delete();
}
return response()->json($blockCustomer);
}
/**
* getNotifications
*
* @return void
*/
2021-03-21 14:14:41 +01:00
public static function getNotifications()
2021-03-10 17:16:31 +01:00
{
if (!Auth::guard('customer')->check()) {
return;
}
/** @var \App\Models\Customers */
2022-02-10 16:14:58 +01:00
$customer = Auth::guard('customer')->user();
2021-03-10 17:16:31 +01:00
$notifications = $customer->getAllNotifications();
View::share('notifications', count($notifications) - $customer->readNotifications()->count());
2021-03-10 17:16:31 +01:00
View::share('notificationsList', $notifications);
}
2021-03-01 11:51:00 +01:00
}