473 lines
15 KiB
PHP
473 lines
15 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\Lib\Utils;
|
|
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\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();
|
|
}
|
|
|
|
|
|
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'
|
|
));
|
|
}
|
|
|
|
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 Request $request
|
|
*/
|
|
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.")
|
|
);
|
|
}
|
|
|
|
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'));
|
|
}
|
|
|
|
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 UpdateInfosRequest $request
|
|
* @return boolean|string return strictly true if success,
|
|
* false il failed, could be a string with message error if failed
|
|
*/
|
|
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();
|
|
}
|
|
Utils::sendEmailErrorManually($e);
|
|
return false;
|
|
} catch (CrmException | \TypeError $e) {
|
|
Utils::sendEmailErrorManually($e);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Call the notifications page
|
|
*/
|
|
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
|
|
*/
|
|
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 \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'));
|
|
}
|
|
|
|
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 $slug Slug of the article
|
|
* @return View The view that the article have to print
|
|
*/
|
|
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
|
|
public function article(ArticleCategory $tag, 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);
|
|
}
|
|
}
|