45 lines
1.3 KiB
PHP
45 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Posts;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Post;
|
|
use App\Services\Posts\PostAnalyticsService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
/**
|
|
* POST /api/posts/{id}/impression — record an impression (throttled)
|
|
* GET /api/posts/{id}/analytics — owner analytics summary
|
|
*/
|
|
class PostAnalyticsController extends Controller
|
|
{
|
|
public function __construct(private PostAnalyticsService $analytics) {}
|
|
|
|
public function impression(Request $request, int $id): JsonResponse
|
|
{
|
|
$post = Post::where('status', Post::STATUS_PUBLISHED)->findOrFail($id);
|
|
|
|
// Session key: authenticated user ID or hashed IP
|
|
$sessionKey = $request->user()
|
|
? 'u:' . $request->user()->id
|
|
: 'ip:' . md5($request->ip());
|
|
|
|
$counted = $this->analytics->trackImpression($post, $sessionKey);
|
|
|
|
return response()->json(['counted' => $counted]);
|
|
}
|
|
|
|
public function show(Request $request, int $id): JsonResponse
|
|
{
|
|
$post = Post::findOrFail($id);
|
|
|
|
// Only the post owner can view analytics
|
|
if ($request->user()?->id !== $post->user_id) {
|
|
abort(403, 'You do not own this post.');
|
|
}
|
|
|
|
return response()->json(['data' => $this->analytics->getSummary($post)]);
|
|
}
|
|
}
|