ldc-legaulois/app/Http/Controllers/ClubController.php
2023-06-26 16:02:23 +02:00

579 lines
20 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\ArticleCategory;
use App\Enums\NotificationType;
use App\Events\NewNotification;
use App\Http\Requests\BlockCustomerRequest;
use App\Http\Requests\DeleteMessagesRequest;
use App\Http\Requests\DownloadBRFileRequest;
use App\Http\Requests\SendMessageRequest;
use App\Http\Requests\SurveyAnswersRequest;
use App\Http\Requests\UpdateInfosRequest;
use App\Models\Articles;
use App\Models\BlockList;
use App\Models\Customers;
use App\Models\Message;
use App\Models\Reduction;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
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;
use RuntimeException;
use Snipe\BanBuilder\CensorWords;
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();
}
/**
* Index
*
* @param \App\Enums\ArticleCategory|null $tag
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
public function index(ArticleCategory $tag = null)
{
self::getNotifications();
$articles = Articles::where('status', 1)->orderBy('updated_at', 'DESC')->get();
$categories = Articles::select('type')->where('status', true)->groupBy('type')->get()->pluck('type');
$montantReduction = Reduction::whereStatus(true)->sum('value');
$nbCustomers = Customers::count();
// Cas de catégorie d'article.
$category = $tag;
return view('front.club.index', compact(
'montantReduction',
'nbCustomers',
'articles',
'categories',
'category'
));
}
/**
* infos
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws Exception Exception.
*/
public function infos()
{
self::getNotifications();
/** @var \App\Models\Customers */
$customer = auth('customer')->user();
if (!$customer) {
abort(404);
}
$crmCustomer = $customer->apiData;
if (!$crmCustomer) {
throw new Exception('CRM get Customer returned null');
}
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
*
* @param \App\Http\Requests\UpdateInfosRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Illuminate\Validation\ValidationException ValidationException.
*/
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
*
* @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
*
* @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)
{
/** @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;
}
return true;
}
/**
* Call the notifications page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function notifications()
{
self::getNotifications();
/** @var \App\Models\Customers */
$customer = auth('customer')->user();
$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();
return view('front.club.notifications');
}
/**
* Call the cart page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function cart()
{
self::getNotifications();
$products = Auth::guard('customer')->user()->products;
return view('front.club.cart', compact('products'));
}
/**
* Call the favorites recipes page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function favoritesRecipes()
{
self::getNotifications();
$recipes = Auth::guard('customer')->user()->recipes;
return view('front.club.favorites-recipes', compact('recipes'));
}
/**
* Call the reductions page
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
* @throws Exception Exception.
*/
public function reductions()
{
self::getNotifications();
/** @var \App\Lib\MesBR */
$mesBR = app('mesBR');
/** @var \App\Models\Customers $customer */
$customer = Auth::guard('customer')->user();
/** @var \LDC\LDCCRM\Models\Customer */
$crmCustomer = $customer->apiData;
$murBr = [];
$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)
));
}
return view('front.club.reductions', compact('murBr'));
}
/**
* reductionsGet
*
* @param \App\Http\Requests\DownloadBRFileRequest $request
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
* @throws \Exception Exception.
*/
public function reductionsGet(DownloadBRFileRequest $request)
{
/** @var \App\Lib\MesBR */
$mesBR = app('mesBR');
/** @var \App\Models\Customers $customer */
$customer = Auth::guard('customer')->user();
$crmCustomer = $customer->apiData;
if ($crmCustomer->status === "KO") {
throw new Exception(
sprintf(
'CRM call error %s',
json_encode($crmCustomer)
)
);
}
$coupons = $mesBR->printCoupons($crmCustomer->hashcode, $request->coupons);
if (!isset($coupons->pdf)) {
throw new Exception(
sprintf(
'MesBR call error %s',
json_encode($coupons)
)
);
}
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\""
]);
}
/**
* Call the article page with a slug for the article to print
*
* @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
*/
public function article(ArticleCategory $tag, Articles $publishedArticle)
{
// phpcs:enable
self::getNotifications();
// Check si le customer connecté a déjà répondu.
$alreadyAnswered = false;
if (Auth::guard('customer')->check()) {
$answersIds = $publishedArticle->answers()->pluck('id')->toArray();
/** @var \App\Models\Customers */
$customer = Auth::guard('customer')->user();
$alreadyAnswered = $customer->surveysAnswers()
->whereIn('surveys_answer_id', $answersIds)->count() > 0 ? true : false;
}
$linkedArticles = Articles::where([
['status', true], ['type', $publishedArticle->type], ['id', '<>', $publishedArticle->id]
])->get();
$categories = Articles::select('type')->where('status', true)->groupBy('type')->get()->pluck('type');
return view('front.club.article', compact(
'publishedArticle',
'categories',
'linkedArticles',
'alreadyAnswered'
));
}
/**
* Handle the request of a customer that answered a survey
*
* @param \App\Http\Requests\SurveyAnswersRequest $request
* @return \Illuminate\Http\RedirectResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \InvalidArgumentException InvalidArgumentException.
*/
public function answerSurvey(SurveyAnswersRequest $request)
{
$answers = $request->answers;
if (empty($answers)) {
return back()->withErrors(__("Votre réponse est incomplète. Merci de corriger"));
}
/** @var \App\Models\Customers $customer */
$customer = Auth::guard('customer')->user();
if (is_array($answers)) {
$customer->surveysAnswers()->syncWithoutDetaching($answers);
} else {
$customer->surveysAnswers()->syncWithoutDetaching($answers);
}
return back();
}
/**
* Show messagerie
*
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function messages()
{
self::getNotifications();
/** @var \App\Models\Customers */
$customer = Auth::guard('customer')->user();
$conversations = $customer->conversations();
$ids = collect($conversations)->pluck('to_id');
$blockList = BlockList::where('customer_id', $customer->id)
->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();
return view('front.club.messages', compact('conversations', 'blockList'));
}
/**
* Send a message to a user
*
* @param \App\Http\Requests\SendMessageRequest $request
* @return \Illuminate\Http\JsonResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
* @throws \Throwable Throwable.
*/
public function sendMessage(SendMessageRequest $request)
{
$customer = Customers::where('username', $request->to)->firstOrFail();
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);
}
$message = new Message($request->all());
$message->to = $customer->id;
$message->from = Auth::guard('customer')->user()->id;
$censor = new CensorWords();
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'];
$message->saveOrFail();
event(new NewNotification(
NotificationType::message(),
route('account.messages', ['m' => $message->id]),
$message,
$customer
));
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
*
* @param \App\Http\Requests\DeleteMessagesRequest $request
* @return \Illuminate\Http\JsonResponse
* @throws \LogicException LogicException.
* @throws \Throwable Throwable.
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
public function deleteMessage(DeleteMessagesRequest $request)
{
/** @var \App\Models\Customers */
$customer = Auth::guard('customer')->user();
$message = Message::findOrFail($request->message);
$conversations = (object)$customer->conversations();
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
*
* @param \App\Http\Requests\BlockCustomerRequest $request
* @param boolean $status
* @return \Illuminate\Http\JsonResponse
* @throws \Illuminate\Contracts\Container\BindingResolutionException BindingResolutionException.
*/
public function blockCustomer(BlockCustomerRequest $request, bool $status)
{
/** @var \App\Models\Customers */
$customer = Auth::guard('customer')->user();
$customerToBlock = Customers::where('username', $request->username)->firstOrFail();
$blockCustomer = BlockList::firstOrNew([
'customer_id' => $customer->id,
'blocked_id' => $customerToBlock->id,
]);
if ($status) {
$blockCustomer->saveOrFail();
} else {
$blockCustomer->delete();
}
return response()->json($blockCustomer);
}
/**
* getNotifications
*
* @return void
*/
public static function getNotifications()
{
if (!Auth::guard('customer')->check()) {
return;
}
/** @var \App\Models\Customers */
$customer = Auth::guard('customer')->user();
$notifications = $customer->getAllNotifications();
View::share('notifications', count($notifications) - $customer->readNotifications()->count());
View::share('notificationsList', $notifications);
}
}