dealhub/app/Http/Controllers/Interaction/InteractionController.php

131 lines
3.9 KiB
PHP

<?php
namespace App\Http\Controllers\Interaction;
use App\Enums\InteractionType;
use App\Http\Controllers\Controller;
use App\Models\Deal;
use App\Models\Interaction;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class InteractionController extends Controller
{
/**
* Interact to a deal by Like or Favorite state
*
* @param InteractionType $type [InteractionType::Like, InteractionType::Favorite]
* @return \Illuminate\Http\JsonResponse
*/
public function togglesState(Deal $deal, InteractionType $type)
{
if (! in_array($type, [InteractionType::Like, InteractionType::Favorite])) {
return response()->json(['error' => 'This interaction is not supported'], 400);
}
try {
// Check for existing like of the user with deal
$existingInteraction = $deal->interactions()
->where('user_id', Auth::id())
->where('type', $type)
->first();
// Delete the existing like if exists, else add the like
$message = '';
if ($existingInteraction) {
$existingInteraction->delete();
$message = ucfirst($type->value).' removed from deal';
} else {
$data = [
'type' => $type,
'user_id' => Auth::id(),
];
Interaction::unguard();
$deal->interactions()->create($data);
Interaction::reguard();
$message = ucfirst($type->value).' added to deal';
}
return response()->json(['message' => $message]);
} catch (\Throwable $e) {
Log::error('Error when liked a deal',
[
'deal_id' => $deal->id,
'user_id' => Auth::id(),
'type' => $type,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]
);
return response()->json(['error' => 'Something went wrong.'], 500);
}
}
public function redirect(Deal $deal)
{
if (blank($deal->link)) {
abort(404);
}
\Illuminate\Support\defer(function () use ($deal) {
try {
$interaction = $deal->interactions()->firstOrCreate([
'type' => InteractionType::Redirection,
'user_id' => Auth::id(),
]);
if (! $interaction->wasRecentlyCreated) {
$interaction->increment('count');
}
} catch (\Throwable $e) {
Log::error('Error when redirecting a deal external link',
[
'deal_id' => $deal->id,
'user_id' => Auth::id(),
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]
);
abort(500);
}
});
return redirect()->away($deal->link);
}
public function view(Deal $deal)
{
try {
$interaction = $deal->interactions()->firstOrCreate([
'type' => InteractionType::View,
'user_id' => Auth::id(),
]);
if (! $interaction->wasRecentlyCreated) {
$interaction->increment('count');
}
} catch (\Throwable $e) {
Log::error('Error when view a deal',
[
'deal_id' => $deal->id,
'user_id' => Auth::id(),
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]
);
return response()->json(['error' => 'Something went wrong.'], 500);
}
return response()->json([
'message' => 'View counted',
]);
}
}