ldc-legaulois/app/Http/Controllers/ClubController.php
Jérémy Munsch c5e3a834fa phpcbf fix
2021-09-15 14:27:41 +02:00

351 lines
11 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\NotificationType;
use App\Events\NewNotification;
use App\Http\Requests\BlockCustomerRequest;
use App\Http\Requests\DeleteMessagesRequest;
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\Reductions;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;
use RuntimeException;
use Snipe\BanBuilder\CensorWords;
class ClubController extends Controller
{
public function index(Request $request)
{
self::getNotifications();
$reductions = Reductions::where([
['end_date_broadcast', '>', now()],
['status', 1]
])->get();
$articles = Articles::where('status', 1)->orderBy('updated_at', 'DESC')->get();
$categories = Articles::select('type')->where('status', true)->groupBy('type')->get()->pluck('type');
$montantReductions = 0.0;
foreach ($reductions as $reduc) {
$montantReductions += $reduc->face_value;
}
$nbCustomers = Customers::count();
// Cas de catégorie d'article
$category = $request->category;
return view('front.club.index', compact(
'montantReductions',
'nbCustomers',
'articles',
'categories',
'category'
));
}
public function infos()
{
self::getNotifications();
$customer = Auth::guard('customer')->user();
if (!$customer) {
abort(404);
}
/** @var \App\Lib\LDCCRM\ApiV1 */
$crm = app('crmApi');
$crmCustomer = $crm->getCustomer($customer->crm_id);
if ($crmCustomer->status === "KO") {
abort(503);
}
$crmInfos = $crmCustomer->user;
if ($crmInfos->birth_date !== null) {
$birthDate = explode('-', $crmInfos->birth_date);
} else {
$birthDate = null;
}
return view('front.club.informations', compact('customer', 'crmInfos', 'birthDate'));
}
/**
* Send a request to the CRM to change the given customer's informations
* @param Request $request
*/
public function updateInfos(UpdateInfosRequest $request)
{
// TODO : Activer le changement d'email quand ce sera possible dans la CRM
/** @var \App\Lib\LDCCRM\ApiV1 */
$crm = app('crmApi');
$crmCustomer = $crm->updateCustomer(
Auth::guard('customer')->user()->crm_id,
$request->firstname,
$request->lastname,
$request->optin !== null ? 1 : 0,
$request->year . '-' . $request->month . '-' . $request->day,
$request->phone,
$request->address,
null,
$request->city,
$request->postcode,
null
);
if ($crmCustomer->status === "KO") {
return redirect()->route('account.infos')
->withErrors(__("Une erreur est survenue, merci de réessayer ultérieurement."));
}
return redirect()->route('account.infos')
->with('success', __("Vos informations ont bien été enregistrées."));
}
/**
* Call the notifications page
*/
public function notifications()
{
self::getNotifications();
/** @var \App\Models\Customers */
$customer = Auth::guard('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
*/
public function cart()
{
self::getNotifications();
$products = Auth::guard('customer')->user()->products;
return view('front.club.cart', compact('products'));
}
/**
* Call the favorites recipes page
*/
public function favoritesRecipes()
{
self::getNotifications();
$recipes = Auth::guard('customer')->user()->recipes;
return view('front.club.favorites-recipes', compact('recipes'));
}
/**
* Call the reductions page
*/
public function reductions()
{
self::getNotifications();
/** @var \App\Lib\MesBR */
$mesBR = app('mesBr');
/** @var \App\Models\Customers $customer */
$customer = Auth::guard('customer')->user();
/** @var \App\Lib\LDCCRM\ApiV1 */
$crm = app('crmApi');
$crmCustomer = $crm->getCustomer($customer->crm_id);
if ($crmCustomer->status === "KO") {
abort(503);
}
$crmInfos = $crmCustomer->user;
$mesBR->updateContact($crmInfos);
$urlReductions = $mesBR->getMurBdrLink($crmInfos);
return view('front.club.reductions', compact('urlReductions'));
}
/**
* Call the article page with a slug for the article to print
* @param $slug Slug of the article
* @return View The view that the article have to print
*/
public function article(Articles $publishedArticle)
{
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 $request Request
* @return View View to go to
*/
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();
}
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();
return view('front.club.messages', compact('conversations', 'blockList'));
}
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']);
}]));
}
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();
}
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);
}
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);
}
}