bind the link with the view deal button show the total redirection count reflect the total redirect count immediately add arch test so that dump statements are not left out
100 lines
3.0 KiB
PHP
100 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Enums\InteractionType;
|
|
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);
|
|
}
|
|
}
|