diff --git a/database/factories/ActivityFactory.php b/database/factories/ActivityFactory.php index 8a9dd468144b14c1763dce827119f4a2a838de54..4955794976ddf1d6408ba31d7aebd381b713435b 100644 --- a/database/factories/ActivityFactory.php +++ b/database/factories/ActivityFactory.php @@ -13,22 +13,22 @@ class ActivityFactory extends Factory { return [ 'description' => $this->faker->sentence(3), - 'details' => $this->faker->paragraph(), - 'userType' => $this->faker->randomElement(['Guest', 'Registered', 'Crawler']), - 'userId' => $this->faker->numberBetween(1, 100), - 'route' => $this->faker->url(), - 'ipAddress' => $this->faker->ipv4(), - 'userAgent' => $this->faker->userAgent(), - 'locale' => $this->faker->locale(), - 'referer' => $this->faker->optional()->url(), - 'methodType' => $this->faker->randomElement(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']), - 'created_at' => $this->faker->dateTimeBetween('-1 year', 'now'), - 'updated_at' => $this->faker->dateTimeBetween('-1 year', 'now'), + 'details' => $this->faker->paragraph(), + 'userType' => $this->faker->randomElement(['Guest', 'Registered', 'Crawler']), + 'userId' => $this->faker->numberBetween(1, 100), + 'route' => $this->faker->url(), + 'ipAddress' => $this->faker->ipv4(), + 'userAgent' => $this->faker->userAgent(), + 'locale' => $this->faker->locale(), + 'referer' => $this->faker->optional()->url(), + 'methodType' => $this->faker->randomElement(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']), + 'created_at' => $this->faker->dateTimeBetween('-1 year', 'now'), + 'updated_at' => $this->faker->dateTimeBetween('-1 year', 'now'), ]; } /** - * Create an activity for today + * Create an activity for today. */ public function today(): static { @@ -41,7 +41,7 @@ class ActivityFactory extends Factory } /** - * Create an activity for yesterday + * Create an activity for yesterday. */ public function yesterday(): static { @@ -54,7 +54,7 @@ class ActivityFactory extends Factory } /** - * Create an activity for last week + * Create an activity for last week. */ public function lastWeek(): static { @@ -67,7 +67,7 @@ class ActivityFactory extends Factory } /** - * Create an activity for last month + * Create an activity for last month. */ public function lastMonth(): static { @@ -80,7 +80,7 @@ class ActivityFactory extends Factory } /** - * Create an activity for last year + * Create an activity for last year. */ public function lastYear(): static { @@ -93,40 +93,40 @@ class ActivityFactory extends Factory } /** - * Create a guest activity + * Create a guest activity. */ public function guest(): static { return $this->state(function (array $attributes) { return [ 'userType' => 'Guest', - 'userId' => null, + 'userId' => null, ]; }); } /** - * Create a registered user activity + * Create a registered user activity. */ public function registered(): static { return $this->state(function (array $attributes) { return [ 'userType' => 'Registered', - 'userId' => $this->faker->numberBetween(1, 100), + 'userId' => $this->faker->numberBetween(1, 100), ]; }); } /** - * Create a crawler activity + * Create a crawler activity. */ public function crawler(): static { return $this->state(function (array $attributes) { return [ - 'userType' => 'Crawler', - 'userId' => null, + 'userType' => 'Crawler', + 'userId' => null, 'userAgent' => $this->faker->randomElement([ 'Googlebot/2.1', 'Bingbot/2.0', @@ -138,43 +138,43 @@ class ActivityFactory extends Factory } /** - * Create a login activity + * Create a login activity. */ public function login(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User logged in', - 'methodType' => 'POST', - 'route' => '/login', + 'methodType' => 'POST', + 'route' => '/login', ]; }); } /** - * Create a logout activity + * Create a logout activity. */ public function logout(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User logged out', - 'methodType' => 'POST', - 'route' => '/logout', + 'methodType' => 'POST', + 'route' => '/logout', ]; }); } /** - * Create a view activity + * Create a view activity. */ public function view(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User viewed page', - 'methodType' => 'GET', - 'route' => $this->faker->randomElement([ + 'methodType' => 'GET', + 'route' => $this->faker->randomElement([ '/dashboard', '/profile', '/settings', @@ -185,15 +185,15 @@ class ActivityFactory extends Factory } /** - * Create a create activity + * Create a create activity. */ public function create(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User created resource', - 'methodType' => 'POST', - 'route' => $this->faker->randomElement([ + 'methodType' => 'POST', + 'route' => $this->faker->randomElement([ '/posts', '/users', '/products', @@ -204,15 +204,15 @@ class ActivityFactory extends Factory } /** - * Create an update activity + * Create an update activity. */ public function update(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User updated resource', - 'methodType' => 'PUT', - 'route' => $this->faker->randomElement([ + 'methodType' => 'PUT', + 'route' => $this->faker->randomElement([ '/posts/1', '/users/1', '/products/1', @@ -223,15 +223,15 @@ class ActivityFactory extends Factory } /** - * Create a delete activity + * Create a delete activity. */ public function delete(): static { return $this->state(function (array $attributes) { return [ 'description' => 'User deleted resource', - 'methodType' => 'DELETE', - 'route' => $this->faker->randomElement([ + 'methodType' => 'DELETE', + 'route' => $this->faker->randomElement([ '/posts/1', '/users/1', '/products/1', diff --git a/rector.php b/rector.php index b2fce8cadc58afa71ad9823de22ea6474a598ed2..fb817f60045175f3fd68a72cbc44d34c3c43a71c 100644 --- a/rector.php +++ b/rector.php @@ -8,7 +8,7 @@ use Rector\Set\ValueObject\SetList; return static function (RectorConfig $rectorConfig): void { $rectorConfig->paths([ - __DIR__ . '/src', + __DIR__.'/src', ]); // Define what rule sets will be applied diff --git a/src/App/Http/Controllers/LaravelLoggerController.php b/src/App/Http/Controllers/LaravelLoggerController.php index f19f9e8d09d3871cd8d9d4bfeb3d5d5fa4bb360f..46584fc3ce3f48ef6acc3af22cbb755cf9964bbc 100644 --- a/src/App/Http/Controllers/LaravelLoggerController.php +++ b/src/App/Http/Controllers/LaravelLoggerController.php @@ -74,12 +74,12 @@ class LaravelLoggerController extends BaseController $totalActivities = 0; } elseif (config('LaravelLogger.loggerPaginationEnabled')) { $activities = config('LaravelLogger.defaultActivityModel')::orderBy('created_at', 'desc'); - + // Apply date filtering if (config('LaravelLogger.enableDateFiltering')) { $activities = $this->applyDateFilter($activities, $request); } - + if (config('LaravelLogger.enableSearch')) { $activities = $this->searchActivityLog($activities, $request); } @@ -143,23 +143,23 @@ class LaravelLoggerController extends BaseController } elseif (config('LaravelLogger.loggerPaginationEnabled')) { $userActivities = config('LaravelLogger.defaultActivityModel')::where('userId', $activity->userId) ->orderBy('created_at', 'desc'); - + // Apply date filtering if (config('LaravelLogger.enableDateFiltering')) { $userActivities = $this->applyDateFilter($userActivities, $request); } - + $userActivities = $userActivities->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalUserActivities = $userActivities->total(); } else { $userActivities = config('LaravelLogger.defaultActivityModel')::where('userId', $activity->userId) ->orderBy('created_at', 'desc'); - + // Apply date filtering if (config('LaravelLogger.enableDateFiltering')) { $userActivities = $this->applyDateFilter($userActivities, $request); } - + $userActivities = $userActivities->get(); $totalUserActivities = $userActivities->count(); } @@ -212,23 +212,23 @@ class LaravelLoggerController extends BaseController } elseif (config('LaravelLogger.loggerPaginationEnabled')) { $activities = config('LaravelLogger.defaultActivityModel')::onlyTrashed() ->orderBy('created_at', 'desc'); - + // Apply date filtering if (config('LaravelLogger.enableDateFiltering')) { $activities = $this->applyDateFilter($activities, $request); } - + $activities = $activities->paginate(config('LaravelLogger.loggerPaginationPerPage')); $totalActivities = $activities->total(); } else { $activities = config('LaravelLogger.defaultActivityModel')::onlyTrashed() ->orderBy('created_at', 'desc'); - + // Apply date filtering if (config('LaravelLogger.enableDateFiltering')) { $activities = $this->applyDateFilter($activities, $request); } - + $activities = $activities->get(); $totalActivities = $activities->count(); } @@ -324,6 +324,7 @@ class LaravelLoggerController extends BaseController * Apply date filtering to the activity log query. * * @param mixed $query + * * @return mixed */ private function applyDateFilter($query, Request $request) @@ -458,20 +459,21 @@ class LaravelLoggerController extends BaseController * Export activities to CSV format. * * @param mixed $activities + * * @return \Illuminate\Http\Response */ private function exportToCsv($activities) { - $filename = 'activity_log_' . now()->format('Y-m-d_H-i-s') . '.csv'; - + $filename = 'activity_log_'.now()->format('Y-m-d_H-i-s').'.csv'; + $headers = [ - 'Content-Type' => 'text/csv', - 'Content-Disposition' => 'attachment; filename="' . $filename . '"', + 'Content-Type' => 'text/csv', + 'Content-Disposition' => 'attachment; filename="'.$filename.'"', ]; - $callback = function() use ($activities): void { + $callback = function () use ($activities): void { $file = fopen('php://output', 'w'); - + // CSV Headers fputcsv($file, [ 'ID', @@ -487,7 +489,7 @@ class LaravelLoggerController extends BaseController 'Referer', 'Method Type', 'Created At', - 'Updated At' + 'Updated At', ]); // CSV Data @@ -506,7 +508,7 @@ class LaravelLoggerController extends BaseController $activity->referer, $activity->methodType, $activity->created_at, - $activity->updated_at + $activity->updated_at, ]); } @@ -520,36 +522,37 @@ class LaravelLoggerController extends BaseController * Export activities to JSON format. * * @param mixed $activities + * * @return \Illuminate\Http\Response */ private function exportToJson($activities) { - $filename = 'activity_log_' . now()->format('Y-m-d_H-i-s') . '.json'; - + $filename = 'activity_log_'.now()->format('Y-m-d_H-i-s').'.json'; + $data = $activities->map(function ($activity): array { return [ - 'id' => $activity->id, - 'description' => $activity->description, - 'details' => $activity->details, - 'user_type' => $activity->userType, - 'user_id' => $activity->userId, - 'user_email' => $activity->userDetails ? $activity->userDetails->email : null, - 'route' => $activity->route, - 'ip_address' => $activity->ipAddress, - 'user_agent' => $activity->userAgent, - 'locale' => $activity->locale, - 'referer' => $activity->referer, - 'method_type' => $activity->methodType, - 'created_at' => $activity->created_at, - 'updated_at' => $activity->updated_at, - 'time_passed' => $activity->timePassed, + 'id' => $activity->id, + 'description' => $activity->description, + 'details' => $activity->details, + 'user_type' => $activity->userType, + 'user_id' => $activity->userId, + 'user_email' => $activity->userDetails ? $activity->userDetails->email : null, + 'route' => $activity->route, + 'ip_address' => $activity->ipAddress, + 'user_agent' => $activity->userAgent, + 'locale' => $activity->locale, + 'referer' => $activity->referer, + 'method_type' => $activity->methodType, + 'created_at' => $activity->created_at, + 'updated_at' => $activity->updated_at, + 'time_passed' => $activity->timePassed, 'user_agent_details' => $activity->userAgentDetails, - 'lang_details' => $activity->langDetails, + 'lang_details' => $activity->langDetails, ]; }); return response()->json($data, 200, [ - 'Content-Disposition' => 'attachment; filename="' . $filename . '"', + 'Content-Disposition' => 'attachment; filename="'.$filename.'"', ]); } @@ -557,22 +560,23 @@ class LaravelLoggerController extends BaseController * Export activities to Excel format. * * @param mixed $activities + * * @return \Illuminate\Http\Response */ private function exportToExcel($activities) { - $filename = 'activity_log_' . now()->format('Y-m-d_H-i-s') . '.xlsx'; - + $filename = 'activity_log_'.now()->format('Y-m-d_H-i-s').'.xlsx'; + // For Excel export, we'll use a simple CSV format with .xlsx extension // In a real implementation, you might want to use Laravel Excel package $headers = [ - 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'Content-Disposition' => 'attachment; filename="' . $filename . '"', + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition' => 'attachment; filename="'.$filename.'"', ]; - $callback = function() use ($activities): void { + $callback = function () use ($activities): void { $file = fopen('php://output', 'w'); - + // Excel Headers fputcsv($file, [ 'ID', @@ -588,7 +592,7 @@ class LaravelLoggerController extends BaseController 'Referer', 'Method Type', 'Created At', - 'Updated At' + 'Updated At', ]); // Excel Data @@ -607,7 +611,7 @@ class LaravelLoggerController extends BaseController $activity->referer, $activity->methodType, $activity->created_at, - $activity->updated_at + $activity->updated_at, ]); } diff --git a/src/App/Http/Traits/ActivityLogger.php b/src/App/Http/Traits/ActivityLogger.php index 2cef96ad30146ccb2049dadc29a576413e8aede0..6350e2823dd2c4c15ef3b9aeb8f1342a18a69a83 100644 --- a/src/App/Http/Traits/ActivityLogger.php +++ b/src/App/Http/Traits/ActivityLogger.php @@ -13,12 +13,11 @@ trait ActivityLogger /** * Laravel Logger Log Activity. * - * @param null $description - * @param null $details + * @param null $description + * @param null $details * @param ?array $rel - * */ - public function activity($description = null, $details = null, array $rel = null) + public function activity($description = null, $details = null, ?array $rel = null) { $userType = trans('LaravelLogger::laravel-logger.userTypes.guest'); $userId = null; @@ -104,8 +103,6 @@ trait ActivityLogger /** * Store activity entry to database. - * - * */ private static function storeActivity(array $data): void { diff --git a/src/App/Http/Traits/IpAddressDetails.php b/src/App/Http/Traits/IpAddressDetails.php index 77a73f0462e0ae8076506b19cd7397d3f3d44162..d9fdde067d3eba2419f85527c293492aac61c6ff 100644 --- a/src/App/Http/Traits/IpAddressDetails.php +++ b/src/App/Http/Traits/IpAddressDetails.php @@ -38,7 +38,7 @@ trait IpAddressDetails 'NA' => 'North America', 'SA' => 'South America', ]; - + if (config('LaravelLogger.enableGeoPlugin', true) && filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) { $geopluginUrl = config('LaravelLogger.geoPluginUrl', 'http://www.geoplugin.net/json.gp?ip='); $ipdat = @json_decode(file_get_contents($geopluginUrl.$ip)); diff --git a/src/App/Listeners/LogAuthenticated.php b/src/App/Listeners/LogAuthenticated.php index 8d376c5644d71452cd8d0d2ddec00639ae8b9863..cb707aa54903ee5cc3cf1b2a420c5298551572d5 100644 --- a/src/App/Listeners/LogAuthenticated.php +++ b/src/App/Listeners/LogAuthenticated.php @@ -21,8 +21,6 @@ class LogAuthenticated /** * Handle ANY authenticated event. - * - * */ public function handle(Authenticated $event): void { diff --git a/src/App/Listeners/LogAuthenticationAttempt.php b/src/App/Listeners/LogAuthenticationAttempt.php index 11fe1116ce1a3858e1cbe4702817c981cebd2242..c7bb5a574284868f6d4eb029ae8dd28c39f1d7c9 100644 --- a/src/App/Listeners/LogAuthenticationAttempt.php +++ b/src/App/Listeners/LogAuthenticationAttempt.php @@ -21,8 +21,6 @@ class LogAuthenticationAttempt /** * Handle the event. - * - * */ public function handle(Attempting $event): void { diff --git a/src/App/Listeners/LogFailedLogin.php b/src/App/Listeners/LogFailedLogin.php index a5a42bc14ebc7a1f2e5f292cab8cb3030ef49d3f..629077de08894744ff67c096b33732bb71b31a58 100644 --- a/src/App/Listeners/LogFailedLogin.php +++ b/src/App/Listeners/LogFailedLogin.php @@ -21,8 +21,6 @@ class LogFailedLogin /** * Handle the event. - * - * */ public function handle(Failed $event): void { diff --git a/src/App/Listeners/LogLockout.php b/src/App/Listeners/LogLockout.php index eac04d911ca7ce0619eb8c7119a03bd0c3c29e6a..6fe475aa05c50a3abe61c59c54795bfd015a60e1 100644 --- a/src/App/Listeners/LogLockout.php +++ b/src/App/Listeners/LogLockout.php @@ -21,8 +21,6 @@ class LogLockout /** * Handle the event. - * - * */ public function handle(Lockout $event): void { diff --git a/src/App/Listeners/LogPasswordReset.php b/src/App/Listeners/LogPasswordReset.php index f1bafc54d6d78f159d128d2e633147dd34c04610..e6cc179930e4cc78b5a79b10a6a5453fab368b22 100644 --- a/src/App/Listeners/LogPasswordReset.php +++ b/src/App/Listeners/LogPasswordReset.php @@ -21,8 +21,6 @@ class LogPasswordReset /** * Handle the event. - * - * */ public function handle(PasswordReset $event): void { diff --git a/src/App/Listeners/LogSuccessfulLogin.php b/src/App/Listeners/LogSuccessfulLogin.php index 9fe92fc7229f82d300eba411f7a5dc0b68c70b97..fcee3756f472792024703357dbe821fbf11d5cb0 100644 --- a/src/App/Listeners/LogSuccessfulLogin.php +++ b/src/App/Listeners/LogSuccessfulLogin.php @@ -21,8 +21,6 @@ class LogSuccessfulLogin /** * Handle the event. - * - * */ public function handle(Login $event): void { diff --git a/src/App/Listeners/LogSuccessfulLogout.php b/src/App/Listeners/LogSuccessfulLogout.php index ab48f0f52f39e52f772966f1ee7e2b0cb167a632..6a918addd0318cef574e03712af45b7dd497b99a 100644 --- a/src/App/Listeners/LogSuccessfulLogout.php +++ b/src/App/Listeners/LogSuccessfulLogout.php @@ -21,8 +21,6 @@ class LogSuccessfulLogout /** * Handle the event. - * - * */ public function handle(Logout $event): void { diff --git a/src/LaravelLoggerServiceProvider.php b/src/LaravelLoggerServiceProvider.php index ff35012d43f849749b18115305aba6c1dfa49336..dccc9b02f962c453593056f047eb00b65f304e3b 100644 --- a/src/LaravelLoggerServiceProvider.php +++ b/src/LaravelLoggerServiceProvider.php @@ -2,7 +2,6 @@ namespace jeremykenedy\LaravelLogger; -use Illuminate\Routing\Router; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; use jeremykenedy\LaravelLogger\App\Http\Middleware\LogActivity; @@ -54,7 +53,7 @@ class LaravelLoggerServiceProvider extends ServiceProvider public function boot(): void { $this->app['router']->middlewareGroup('activity', [LogActivity::class]); - + // Load translations from new Laravel 9+ structure if available, fallback to old structure if (is_dir(__DIR__.'/lang/')) { $this->loadTranslationsFrom(__DIR__.'/lang/', 'LaravelLogger'); @@ -129,7 +128,7 @@ class LaravelLoggerServiceProvider extends ServiceProvider $this->publishes([ __DIR__.'/lang' => base_path('lang/vendor/'.$publishTag), ], $publishTag); - + // Also publish to old structure for backward compatibility $this->publishes([ __DIR__.'/lang' => base_path('resources/lang/vendor/'.$publishTag), diff --git a/src/config/laravel-logger.php b/src/config/laravel-logger.php index 9675dd38c82f2a487ea02ca431ce5efbf6d7147e..7c4b79d24239c65379e579aebe6b0fc07baf435e 100644 --- a/src/config/laravel-logger.php +++ b/src/config/laravel-logger.php @@ -103,9 +103,9 @@ return [ | Laravel Logger Pagination Settings |-------------------------------------------------------------------------- */ - 'loggerPaginationEnabled' => env('LARAVEL_LOGGER_PAGINATION_ENABLED', true), + 'loggerPaginationEnabled' => env('LARAVEL_LOGGER_PAGINATION_ENABLED', true), 'loggerCursorPaginationEnabled' => env('LARAVEL_LOGGER_CURSOR_PAGINATION_ENABLED', false), - 'loggerPaginationPerPage' => env('LARAVEL_LOGGER_PAGINATION_PER_PAGE', 25), + 'loggerPaginationPerPage' => env('LARAVEL_LOGGER_PAGINATION_PER_PAGE', 25), /* |-------------------------------------------------------------------------- diff --git a/src/lang/en/laravel-logger.php b/src/lang/en/laravel-logger.php index cfe69a3068acf8887cc282ecb6816129844f76ad..d0a5f380390cc9cd7e88fe427fffba1eec9d5903 100644 --- a/src/lang/en/laravel-logger.php +++ b/src/lang/en/laravel-logger.php @@ -194,30 +194,30 @@ return [ |-------------------------------------------------------------------------- */ 'filterAndExport' => 'Filter and Export', - 'fromDate' => 'From Date', - 'toDate' => 'To Date', - 'quickPeriod' => 'Quick Period', - 'allTime' => 'All Time', - 'today' => 'Today', - 'yesterday' => 'Yesterday', - 'last7Days' => 'Last 7 Days', - 'last30Days' => 'Last 30 Days', - 'last3Months' => 'Last 3 Months', - 'last6Months' => 'Last 6 Months', - 'lastYear' => 'Last Year', - 'filter' => 'Filter', - 'clearFilters' => 'Clear Filters', + 'fromDate' => 'From Date', + 'toDate' => 'To Date', + 'quickPeriod' => 'Quick Period', + 'allTime' => 'All Time', + 'today' => 'Today', + 'yesterday' => 'Yesterday', + 'last7Days' => 'Last 7 Days', + 'last30Days' => 'Last 30 Days', + 'last3Months' => 'Last 3 Months', + 'last6Months' => 'Last 6 Months', + 'lastYear' => 'Last Year', + 'filter' => 'Filter', + 'clearFilters' => 'Clear Filters', /* |-------------------------------------------------------------------------- | Laravel Logger Language Lines - Export |-------------------------------------------------------------------------- */ - 'exportData' => 'Export Data', - 'exportCSV' => 'Export CSV', - 'exportJSON' => 'Export JSON', - 'exportExcel' => 'Export Excel', + 'exportData' => 'Export Data', + 'exportCSV' => 'Export CSV', + 'exportJSON' => 'Export JSON', + 'exportExcel' => 'Export Excel', 'searchDescription' => 'Search by description...', - 'allUsers' => 'All Users', + 'allUsers' => 'All Users', ]; diff --git a/tests/Feature/LaravelLoggerControllerTest.php b/tests/Feature/LaravelLoggerControllerTest.php index a70659b25943ea28af907a173e463d0dcd5206ed..d3efd8d4b82653d1fe4433fd41ca6927f63d7bea 100644 --- a/tests/Feature/LaravelLoggerControllerTest.php +++ b/tests/Feature/LaravelLoggerControllerTest.php @@ -2,7 +2,6 @@ namespace jeremykenedy\LaravelLogger\Tests\Feature; -use Carbon\Carbon; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Http\Request; @@ -13,7 +12,8 @@ use jeremykenedy\LaravelLogger\Tests\TestCase; class LaravelLoggerControllerTest extends TestCase { - use RefreshDatabase, WithFaker; + use RefreshDatabase; + use WithFaker; protected $controller; protected $user; @@ -21,15 +21,15 @@ class LaravelLoggerControllerTest extends TestCase protected function setUp(): void { parent::setUp(); - + $this->controller = new LaravelLoggerController(); - + // Create a test user $this->user = \App\Models\User::factory()->create([ 'email' => 'test@example.com', - 'name' => 'Test User' + 'name' => 'Test User', ]); - + // Set up configuration Config::set('LaravelLogger.defaultActivityModel', Activity::class); Config::set('LaravelLogger.defaultUserModel', \App\Models\User::class); @@ -46,26 +46,26 @@ class LaravelLoggerControllerTest extends TestCase // Create test activities with different dates $today = Activity::factory()->create([ 'description' => 'Today activity', - 'created_at' => now(), - 'userId' => $this->user->id + 'created_at' => now(), + 'userId' => $this->user->id, ]); $yesterday = Activity::factory()->create([ 'description' => 'Yesterday activity', - 'created_at' => now()->subDay(), - 'userId' => $this->user->id + 'created_at' => now()->subDay(), + 'userId' => $this->user->id, ]); $lastWeek = Activity::factory()->create([ 'description' => 'Last week activity', - 'created_at' => now()->subWeek(), - 'userId' => $this->user->id + 'created_at' => now()->subWeek(), + 'userId' => $this->user->id, ]); // Test filtering by date range $request = new Request([ 'date_from' => now()->subDay()->format('Y-m-d'), - 'date_to' => now()->format('Y-m-d') + 'date_to' => now()->format('Y-m-d'), ]); $activities = Activity::orderBy('created_at', 'desc'); @@ -84,20 +84,20 @@ class LaravelLoggerControllerTest extends TestCase // Create test activities $today = Activity::factory()->create([ 'description' => 'Today activity', - 'created_at' => now(), - 'userId' => $this->user->id + 'created_at' => now(), + 'userId' => $this->user->id, ]); $yesterday = Activity::factory()->create([ 'description' => 'Yesterday activity', - 'created_at' => now()->subDay(), - 'userId' => $this->user->id + 'created_at' => now()->subDay(), + 'userId' => $this->user->id, ]); $lastWeek = Activity::factory()->create([ 'description' => 'Last week activity', - 'created_at' => now()->subWeek(), - 'userId' => $this->user->id + 'created_at' => now()->subWeek(), + 'userId' => $this->user->id, ]); // Test 'today' period @@ -127,14 +127,14 @@ class LaravelLoggerControllerTest extends TestCase // Create activities $recent = Activity::factory()->create([ 'description' => 'Recent activity', - 'created_at' => now()->subDays(15), - 'userId' => $this->user->id + 'created_at' => now()->subDays(15), + 'userId' => $this->user->id, ]); $old = Activity::factory()->create([ 'description' => 'Old activity', - 'created_at' => now()->subDays(45), - 'userId' => $this->user->id + 'created_at' => now()->subDays(45), + 'userId' => $this->user->id, ]); $request = new Request(['period' => 'last_30_days']); @@ -153,14 +153,14 @@ class LaravelLoggerControllerTest extends TestCase // Create activities $thisYear = Activity::factory()->create([ 'description' => 'This year activity', - 'created_at' => now()->subMonths(6), - 'userId' => $this->user->id + 'created_at' => now()->subMonths(6), + 'userId' => $this->user->id, ]); $lastYear = Activity::factory()->create([ 'description' => 'Last year activity', - 'created_at' => now()->subYear()->subMonth(), - 'userId' => $this->user->id + 'created_at' => now()->subYear()->subMonth(), + 'userId' => $this->user->id, ]); $request = new Request(['period' => 'last_year']); @@ -180,8 +180,8 @@ class LaravelLoggerControllerTest extends TestCase $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'created_at' => now()->subYear(), - 'userId' => $this->user->id + 'created_at' => now()->subYear(), + 'userId' => $this->user->id, ]); $request = new Request(['period' => 'today']); @@ -200,24 +200,24 @@ class LaravelLoggerControllerTest extends TestCase // Create test activities $activity1 = Activity::factory()->create([ 'description' => 'First activity', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test1', - 'ipAddress' => '192.168.1.1', - 'userAgent' => 'Mozilla/5.0', - 'methodType' => 'GET' + 'userId' => $this->user->id, + 'route' => 'https://example.com/test1', + 'ipAddress' => '192.168.1.1', + 'userAgent' => 'Mozilla/5.0', + 'methodType' => 'GET', ]); $activity2 = Activity::factory()->create([ 'description' => 'Second activity', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test2', - 'ipAddress' => '192.168.1.2', - 'userAgent' => 'Chrome/91.0', - 'methodType' => 'POST' + 'userId' => $this->user->id, + 'route' => 'https://example.com/test2', + 'ipAddress' => '192.168.1.2', + 'userAgent' => 'Chrome/91.0', + 'methodType' => 'POST', ]); $request = new Request(['format' => 'csv']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -232,15 +232,15 @@ class LaravelLoggerControllerTest extends TestCase // Create test activities $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test', - 'ipAddress' => '192.168.1.1', - 'userAgent' => 'Mozilla/5.0', - 'methodType' => 'GET' + 'userId' => $this->user->id, + 'route' => 'https://example.com/test', + 'ipAddress' => '192.168.1.1', + 'userAgent' => 'Mozilla/5.0', + 'methodType' => 'GET', ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -250,7 +250,7 @@ class LaravelLoggerControllerTest extends TestCase $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertIsArray($data); $this->assertCount(1, $data); $this->assertEquals($activity->id, $data[0]['id']); @@ -263,15 +263,15 @@ class LaravelLoggerControllerTest extends TestCase // Create test activities $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test', - 'ipAddress' => '192.168.1.1', - 'userAgent' => 'Mozilla/5.0', - 'methodType' => 'GET' + 'userId' => $this->user->id, + 'route' => 'https://example.com/test', + 'ipAddress' => '192.168.1.1', + 'userAgent' => 'Mozilla/5.0', + 'methodType' => 'GET', ]); $request = new Request(['format' => 'excel']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -284,7 +284,7 @@ class LaravelLoggerControllerTest extends TestCase public function it_returns_error_for_invalid_export_format() { $request = new Request(['format' => 'invalid']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(302, $response->getStatusCode()); @@ -296,35 +296,35 @@ class LaravelLoggerControllerTest extends TestCase // Create activities with different dates $today = Activity::factory()->create([ 'description' => 'Today activity', - 'created_at' => now(), - 'userId' => $this->user->id + 'created_at' => now(), + 'userId' => $this->user->id, ]); $yesterday = Activity::factory()->create([ 'description' => 'Yesterday activity', - 'created_at' => now()->subDay(), - 'userId' => $this->user->id + 'created_at' => now()->subDay(), + 'userId' => $this->user->id, ]); $lastWeek = Activity::factory()->create([ 'description' => 'Last week activity', - 'created_at' => now()->subWeek(), - 'userId' => $this->user->id + 'created_at' => now()->subWeek(), + 'userId' => $this->user->id, ]); // Export only today's activities $request = new Request([ 'format' => 'json', - 'period' => 'today' + 'period' => 'today', ]); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); - + $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(1, $data); $this->assertEquals($today->id, $data[0]['id']); } @@ -335,32 +335,32 @@ class LaravelLoggerControllerTest extends TestCase // Create activities with different descriptions $loginActivity = Activity::factory()->create([ 'description' => 'User logged in', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $logoutActivity = Activity::factory()->create([ 'description' => 'User logged out', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $viewActivity = Activity::factory()->create([ 'description' => 'User viewed page', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); // Export only login activities $request = new Request([ - 'format' => 'json', - 'description' => 'logged in' + 'format' => 'json', + 'description' => 'logged in', ]); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); - + $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(1, $data); $this->assertEquals($loginActivity->id, $data[0]['id']); } @@ -371,7 +371,7 @@ class LaravelLoggerControllerTest extends TestCase Config::set('LaravelLogger.enableExport', false); $request = new Request(['format' => 'csv']); - + $response = $this->controller->exportActivityLog($request); // Should still work but might have different behavior @@ -383,15 +383,15 @@ class LaravelLoggerControllerTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertArrayHasKey('user_email', $data[0]); $this->assertEquals($this->user->email, $data[0]['user_email']); } @@ -401,15 +401,15 @@ class LaravelLoggerControllerTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Guest activity', - 'userId' => null + 'userId' => null, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertArrayHasKey('user_email', $data[0]); $this->assertNull($data[0]['user_email']); } @@ -419,15 +419,15 @@ class LaravelLoggerControllerTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request1 = new Request(['format' => 'csv']); $response1 = $this->controller->exportActivityLog($request1); - + // Wait a second to ensure different timestamps sleep(1); - + $request2 = new Request(['format' => 'csv']); $response2 = $this->controller->exportActivityLog($request2); diff --git a/tests/Integration/LaravelLoggerIntegrationTest.php b/tests/Integration/LaravelLoggerIntegrationTest.php index 39a1cf54db94a6840fe4a675d82e48fb9258516d..f6bea25e23c0467285d804d6d5756883d87e81ce 100644 --- a/tests/Integration/LaravelLoggerIntegrationTest.php +++ b/tests/Integration/LaravelLoggerIntegrationTest.php @@ -10,19 +10,20 @@ use jeremykenedy\LaravelLogger\Tests\TestCase; class LaravelLoggerIntegrationTest extends TestCase { - use RefreshDatabase, WithFaker; + use RefreshDatabase; + use WithFaker; protected $user; protected function setUp(): void { parent::setUp(); - + $this->user = \App\Models\User::factory()->create([ 'email' => 'test@example.com', - 'name' => 'Test User' + 'name' => 'Test User', ]); - + Config::set('LaravelLogger.defaultActivityModel', Activity::class); Config::set('LaravelLogger.defaultUserModel', \App\Models\User::class); Config::set('LaravelLogger.defaultUserIDField', 'id'); @@ -36,9 +37,9 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_access_activity_log_page() { $this->actingAs($this->user); - + $response = $this->get('/activity'); - + $response->assertStatus(200); $response->assertViewIs('LaravelLogger::logger.activity-log'); } @@ -47,24 +48,24 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_filter_activities_via_web_interface() { $this->actingAs($this->user); - + // Create test activities $today = Activity::factory()->today()->create([ 'description' => 'Today activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $yesterday = Activity::factory()->yesterday()->create([ 'description' => 'Yesterday activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); // Test filtering by period $response = $this->get('/activity?period=today'); - + $response->assertStatus(200); $response->assertViewHas('activities'); - + $activities = $response->viewData('activities'); $this->assertCount(1, $activities); $this->assertEquals($today->id, $activities->first()->id); @@ -74,15 +75,15 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_export_activities_via_web_interface() { $this->actingAs($this->user); - + Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); // Test CSV export $response = $this->get('/activity/export?format=csv'); - + $response->assertStatus(200); $response->assertHeader('Content-Type', 'text/csv; charset=UTF-8'); $response->assertHeader('Content-Disposition', function ($value) { @@ -94,17 +95,17 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_export_json_via_web_interface() { $this->actingAs($this->user); - + $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get('/activity/export?format=json'); - + $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); - + $data = $response->json(); $this->assertIsArray($data); $this->assertCount(1, $data); @@ -115,14 +116,14 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_export_excel_via_web_interface() { $this->actingAs($this->user); - + Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get('/activity/export?format=excel'); - + $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); $response->assertHeader('Content-Disposition', function ($value) { @@ -134,22 +135,22 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_combine_filtering_and_export() { $this->actingAs($this->user); - + $today = Activity::factory()->today()->create([ 'description' => 'Today activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $yesterday = Activity::factory()->yesterday()->create([ 'description' => 'Yesterday activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); // Export only today's activities $response = $this->get('/activity/export?format=json&period=today'); - + $response->assertStatus(200); - + $data = $response->json(); $this->assertCount(1, $data); $this->assertEquals($today->id, $data[0]['id']); @@ -159,20 +160,20 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_search_and_export_activities() { $this->actingAs($this->user); - + $loginActivity = Activity::factory()->login()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $logoutActivity = Activity::factory()->logout()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); // Export only login activities $response = $this->get('/activity/export?format=json&description=logged in'); - + $response->assertStatus(200); - + $data = $response->json(); $this->assertCount(1, $data); $this->assertEquals($loginActivity->id, $data[0]['id']); @@ -183,7 +184,7 @@ class LaravelLoggerIntegrationTest extends TestCase { // Test without authentication $response = $this->get('/activity'); - + $response->assertStatus(302); // Redirect to login } @@ -192,7 +193,7 @@ class LaravelLoggerIntegrationTest extends TestCase { // Test export without authentication $response = $this->get('/activity/export?format=csv'); - + $response->assertStatus(302); // Redirect to login } @@ -200,13 +201,13 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_view_individual_activity() { $this->actingAs($this->user); - + $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get("/activity/log/{$activity->id}"); - + $response->assertStatus(200); $response->assertViewIs('LaravelLogger::logger.activity-log-item'); $response->assertViewHas('activity', $activity); @@ -216,15 +217,15 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_view_cleared_activities() { $this->actingAs($this->user); - + $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); - + $activity->delete(); // Soft delete $response = $this->get('/activity/cleared'); - + $response->assertStatus(200); $response->assertViewIs('LaravelLogger::logger.activity-log-cleared'); } @@ -233,23 +234,23 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_filter_cleared_activities() { $this->actingAs($this->user); - + $today = Activity::factory()->today()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); - + $yesterday = Activity::factory()->yesterday()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); - + $today->delete(); $yesterday->delete(); $response = $this->get('/activity/cleared?period=today'); - + $response->assertStatus(200); $response->assertViewHas('activities'); - + $activities = $response->viewData('activities'); $this->assertCount(1, $activities); $this->assertEquals($today->id, $activities->first()->id); @@ -259,18 +260,18 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_clear_activity_log() { $this->actingAs($this->user); - + Activity::factory()->count(5)->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $this->assertDatabaseCount('laravel_logger_activity', 5); $response = $this->delete('/activity/clear-activity'); - + $response->assertStatus(302); $response->assertRedirect('/activity'); - + // Activities should be soft deleted $this->assertDatabaseCount('laravel_logger_activity', 0); $this->assertDatabaseCount('laravel_logger_activity', 5, 'deleted_at'); @@ -280,20 +281,20 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_restore_cleared_activities() { $this->actingAs($this->user); - + $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); - + $activity->delete(); $this->assertDatabaseCount('laravel_logger_activity', 0); $response = $this->post('/activity/restore-log'); - + $response->assertStatus(302); $response->assertRedirect('/activity'); - + $this->assertDatabaseCount('laravel_logger_activity', 1); } @@ -301,21 +302,21 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_destroy_cleared_activities() { $this->actingAs($this->user); - + $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); - + $activity->delete(); $this->assertDatabaseCount('laravel_logger_activity', 0); $this->assertDatabaseCount('laravel_logger_activity', 1, 'deleted_at'); $response = $this->delete('/activity/destroy-activity'); - + $response->assertStatus(302); $response->assertRedirect('/activity'); - + // Activities should be permanently deleted $this->assertDatabaseCount('laravel_logger_activity', 0); $this->assertDatabaseCount('laravel_logger_activity', 0, 'deleted_at'); @@ -325,17 +326,17 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_can_perform_live_search() { $this->actingAs($this->user); - + $user1 = \App\Models\User::factory()->create(['email' => 'user1@example.com']); $user2 = \App\Models\User::factory()->create(['email' => 'user2@example.com']); $response = $this->post('/activity/live-search', [ - 'email' => 'user1' + 'email' => 'user1', ]); - + $response->assertStatus(200); $response->assertJsonStructure(['*' => ['email']]); - + $data = $response->json(); $this->assertCount(1, $data); $this->assertArrayHasKey($user1->id, $data); @@ -346,9 +347,9 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_handles_invalid_activity_id() { $this->actingAs($this->user); - + $response = $this->get('/activity/log/999999'); - + $response->assertStatus(404); } @@ -356,9 +357,9 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_handles_invalid_cleared_activity_id() { $this->actingAs($this->user); - + $response = $this->get('/activity/cleared/log/999999'); - + $response->assertStatus(404); } @@ -367,18 +368,18 @@ class LaravelLoggerIntegrationTest extends TestCase { // Disable date filtering Config::set('LaravelLogger.enableDateFiltering', false); - + $this->actingAs($this->user); - + $activity = Activity::factory()->yesterday()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get('/activity?period=today'); - + $response->assertStatus(200); $response->assertViewHas('activities'); - + $activities = $response->viewData('activities'); // Should return all activities when filtering is disabled $this->assertCount(1, $activities); @@ -390,18 +391,18 @@ class LaravelLoggerIntegrationTest extends TestCase { Config::set('LaravelLogger.loggerPaginationEnabled', true); Config::set('LaravelLogger.loggerPaginationPerPage', 2); - + $this->actingAs($this->user); - + Activity::factory()->count(5)->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get('/activity'); - + $response->assertStatus(200); $response->assertViewHas('activities'); - + $activities = $response->viewData('activities'); $this->assertCount(2, $activities); // Only 2 per page $this->assertTrue($activities->hasPages()); @@ -411,19 +412,19 @@ class LaravelLoggerIntegrationTest extends TestCase public function it_handles_search_when_disabled() { Config::set('LaravelLogger.enableSearch', false); - + $this->actingAs($this->user); - + $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $response = $this->get('/activity?description=Test'); - + $response->assertStatus(200); $response->assertViewHas('activities'); - + $activities = $response->viewData('activities'); // Should return all activities when search is disabled $this->assertCount(1, $activities); diff --git a/tests/TestCase.php b/tests/TestCase.php index ffe59f791da3f32d028c1a8e24815c0f8f1529ad..9ad8ae9f987492ad2a3ceecc5a1cbb70c1e818b7 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -12,7 +12,7 @@ abstract class TestCase extends BaseTestCase protected function setUp(): void { parent::setUp(); - + // Set up default configuration for testing Config::set('LaravelLogger.defaultActivityModel', \jeremykenedy\LaravelLogger\App\Models\Activity::class); Config::set('LaravelLogger.defaultUserModel', \App\Models\User::class); diff --git a/tests/Unit/DateFilteringTest.php b/tests/Unit/DateFilteringTest.php index ca51c18c6b2809b8b91ef680ac0c06bb4ec85820..4c0a8bbd2c92319fa5f9a1d704d605586a9595ce 100644 --- a/tests/Unit/DateFilteringTest.php +++ b/tests/Unit/DateFilteringTest.php @@ -19,9 +19,9 @@ class DateFilteringTest extends TestCase protected function setUp(): void { parent::setUp(); - + $this->controller = new LaravelLoggerController(); - + Config::set('LaravelLogger.defaultActivityModel', Activity::class); Config::set('LaravelLogger.enableDateFiltering', true); } @@ -30,20 +30,20 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_exact_date() { $specificDate = Carbon::parse('2024-01-15'); - + $activity1 = Activity::factory()->create([ - 'created_at' => $specificDate, - 'description' => 'Activity on specific date' + 'created_at' => $specificDate, + 'description' => 'Activity on specific date', ]); $activity2 = Activity::factory()->create([ - 'created_at' => $specificDate->addDay(), - 'description' => 'Activity on next day' + 'created_at' => $specificDate->addDay(), + 'description' => 'Activity on next day', ]); $request = new Request([ 'date_from' => '2024-01-15', - 'date_to' => '2024-01-15' + 'date_to' => '2024-01-15', ]); $query = Activity::query(); @@ -61,23 +61,23 @@ class DateFilteringTest extends TestCase $endDate = Carbon::parse('2024-01-31'); $activity1 = Activity::factory()->create([ - 'created_at' => $startDate->addDays(5), - 'description' => 'Activity in range' + 'created_at' => $startDate->addDays(5), + 'description' => 'Activity in range', ]); $activity2 = Activity::factory()->create([ - 'created_at' => $startDate->addDays(10), - 'description' => 'Another activity in range' + 'created_at' => $startDate->addDays(10), + 'description' => 'Another activity in range', ]); $activity3 = Activity::factory()->create([ - 'created_at' => $endDate->addDays(5), - 'description' => 'Activity outside range' + 'created_at' => $endDate->addDays(5), + 'description' => 'Activity outside range', ]); $request = new Request([ 'date_from' => '2024-01-01', - 'date_to' => '2024-01-31' + 'date_to' => '2024-01-31', ]); $query = Activity::query(); @@ -94,11 +94,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_today_period() { $today = Activity::factory()->today()->create([ - 'description' => 'Today activity' + 'description' => 'Today activity', ]); $yesterday = Activity::factory()->yesterday()->create([ - 'description' => 'Yesterday activity' + 'description' => 'Yesterday activity', ]); $request = new Request(['period' => 'today']); @@ -115,11 +115,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_yesterday_period() { $today = Activity::factory()->today()->create([ - 'description' => 'Today activity' + 'description' => 'Today activity', ]); $yesterday = Activity::factory()->yesterday()->create([ - 'description' => 'Yesterday activity' + 'description' => 'Yesterday activity', ]); $request = new Request(['period' => 'yesterday']); @@ -137,10 +137,10 @@ class DateFilteringTest extends TestCase { $today = Activity::factory()->today()->create(); $threeDaysAgo = Activity::factory()->create([ - 'created_at' => now()->subDays(3) + 'created_at' => now()->subDays(3), ]); $tenDaysAgo = Activity::factory()->create([ - 'created_at' => now()->subDays(10) + 'created_at' => now()->subDays(10), ]); $request = new Request(['period' => 'last_7_days']); @@ -159,11 +159,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_last_30_days_period() { $recent = Activity::factory()->create([ - 'created_at' => now()->subDays(15) + 'created_at' => now()->subDays(15), ]); $old = Activity::factory()->create([ - 'created_at' => now()->subDays(45) + 'created_at' => now()->subDays(45), ]); $request = new Request(['period' => 'last_30_days']); @@ -180,11 +180,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_last_3_months_period() { $recent = Activity::factory()->create([ - 'created_at' => now()->subMonths(1) + 'created_at' => now()->subMonths(1), ]); $old = Activity::factory()->create([ - 'created_at' => now()->subMonths(4) + 'created_at' => now()->subMonths(4), ]); $request = new Request(['period' => 'last_3_months']); @@ -201,11 +201,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_last_6_months_period() { $recent = Activity::factory()->create([ - 'created_at' => now()->subMonths(3) + 'created_at' => now()->subMonths(3), ]); $old = Activity::factory()->create([ - 'created_at' => now()->subMonths(8) + 'created_at' => now()->subMonths(8), ]); $request = new Request(['period' => 'last_6_months']); @@ -222,11 +222,11 @@ class DateFilteringTest extends TestCase public function it_filters_activities_by_last_year_period() { $recent = Activity::factory()->create([ - 'created_at' => now()->subMonths(6) + 'created_at' => now()->subMonths(6), ]); $old = Activity::factory()->create([ - 'created_at' => now()->subYear()->subMonth() + 'created_at' => now()->subYear()->subMonth(), ]); $request = new Request(['period' => 'last_year']); @@ -275,21 +275,21 @@ class DateFilteringTest extends TestCase public function it_combines_date_range_and_period_filters() { $activity1 = Activity::factory()->create([ - 'created_at' => now()->subDays(5) + 'created_at' => now()->subDays(5), ]); $activity2 = Activity::factory()->create([ - 'created_at' => now()->subDays(15) + 'created_at' => now()->subDays(15), ]); $activity3 = Activity::factory()->create([ - 'created_at' => now()->subDays(25) + 'created_at' => now()->subDays(25), ]); $request = new Request([ 'date_from' => now()->subDays(10)->format('Y-m-d'), - 'date_to' => now()->format('Y-m-d'), - 'period' => 'last_30_days' + 'date_to' => now()->format('Y-m-d'), + 'period' => 'last_30_days', ]); $query = Activity::query(); @@ -305,13 +305,13 @@ class DateFilteringTest extends TestCase public function it_preserves_query_order() { $activity1 = Activity::factory()->create([ - 'created_at' => now()->subDays(1), - 'description' => 'First activity' + 'created_at' => now()->subDays(1), + 'description' => 'First activity', ]); $activity2 = Activity::factory()->create([ - 'created_at' => now()->subDays(2), - 'description' => 'Second activity' + 'created_at' => now()->subDays(2), + 'description' => 'Second activity', ]); $request = new Request(['period' => 'last_7_days']); @@ -333,12 +333,12 @@ class DateFilteringTest extends TestCase config(['app.timezone' => 'UTC']); $activity = Activity::factory()->create([ - 'created_at' => Carbon::parse('2024-01-15 12:00:00', 'UTC') + 'created_at' => Carbon::parse('2024-01-15 12:00:00', 'UTC'), ]); $request = new Request([ 'date_from' => '2024-01-15', - 'date_to' => '2024-01-15' + 'date_to' => '2024-01-15', ]); $query = Activity::query(); diff --git a/tests/Unit/ExportFunctionalityTest.php b/tests/Unit/ExportFunctionalityTest.php index 4ece10ddeb77d7a0663025563213082fa26e1bef..b8965ae81f8c615ae97480b5c8efd5396a2de685 100644 --- a/tests/Unit/ExportFunctionalityTest.php +++ b/tests/Unit/ExportFunctionalityTest.php @@ -19,14 +19,14 @@ class ExportFunctionalityTest extends TestCase protected function setUp(): void { parent::setUp(); - + $this->controller = new LaravelLoggerController(); - + $this->user = \App\Models\User::factory()->create([ 'email' => 'test@example.com', - 'name' => 'Test User' + 'name' => 'Test User', ]); - + Config::set('LaravelLogger.defaultActivityModel', Activity::class); Config::set('LaravelLogger.defaultUserModel', \App\Models\User::class); Config::set('LaravelLogger.defaultUserIDField', 'id'); @@ -40,26 +40,26 @@ class ExportFunctionalityTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'details' => 'Test details', - 'userType' => 'Registered', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test', - 'ipAddress' => '192.168.1.1', - 'userAgent' => 'Mozilla/5.0', - 'locale' => 'en', - 'referer' => 'https://google.com', - 'methodType' => 'GET' + 'details' => 'Test details', + 'userType' => 'Registered', + 'userId' => $this->user->id, + 'route' => 'https://example.com/test', + 'ipAddress' => '192.168.1.1', + 'userAgent' => 'Mozilla/5.0', + 'locale' => 'en', + 'referer' => 'https://google.com', + 'methodType' => 'GET', ]); $request = new Request(['format' => 'csv']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); $this->assertStringContainsString('text/csv', $response->headers->get('Content-Type')); $this->assertStringContainsString('attachment', $response->headers->get('Content-Disposition')); $this->assertStringContainsString('.csv', $response->headers->get('Content-Disposition')); - + $content = $response->getContent(); $this->assertStringContainsString('ID,Description,Details,User Type', $content); $this->assertStringContainsString($activity->id, $content); @@ -72,15 +72,15 @@ class ExportFunctionalityTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id, - 'route' => 'https://example.com/test', - 'ipAddress' => '192.168.1.1', - 'userAgent' => 'Mozilla/5.0', - 'methodType' => 'GET' + 'userId' => $this->user->id, + 'route' => 'https://example.com/test', + 'ipAddress' => '192.168.1.1', + 'userAgent' => 'Mozilla/5.0', + 'methodType' => 'GET', ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -90,7 +90,7 @@ class ExportFunctionalityTest extends TestCase $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertIsArray($data); $this->assertCount(1, $data); $this->assertEquals($activity->id, $data[0]['id']); @@ -105,11 +105,11 @@ class ExportFunctionalityTest extends TestCase { $activity = Activity::factory()->create([ 'description' => 'Test activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'excel']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -122,7 +122,7 @@ class ExportFunctionalityTest extends TestCase public function it_returns_error_for_invalid_export_format() { $request = new Request(['format' => 'invalid']); - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(302, $response->getStatusCode()); @@ -134,7 +134,7 @@ class ExportFunctionalityTest extends TestCase $activity = Activity::factory()->create(); $request = new Request([]); // No format specified - + $response = $this->controller->exportActivityLog($request); $this->assertEquals(200, $response->getStatusCode()); @@ -146,20 +146,20 @@ class ExportFunctionalityTest extends TestCase { $activity1 = Activity::factory()->create([ 'description' => 'First activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $activity2 = Activity::factory()->create([ 'description' => 'Second activity', - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(2, $data); $this->assertTrue(collect($data)->contains('id', $activity1->id)); $this->assertTrue(collect($data)->contains('id', $activity2->id)); @@ -169,15 +169,15 @@ class ExportFunctionalityTest extends TestCase public function it_exports_activities_with_user_details() { $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertArrayHasKey('user_email', $data[0]); $this->assertEquals($this->user->email, $data[0]['user_email']); } @@ -188,11 +188,11 @@ class ExportFunctionalityTest extends TestCase $activity = Activity::factory()->guest()->create(); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertArrayHasKey('user_email', $data[0]); $this->assertNull($data[0]['user_email']); } @@ -201,15 +201,15 @@ class ExportFunctionalityTest extends TestCase public function it_includes_additional_details_in_json_export() { $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertArrayHasKey('time_passed', $data[0]); $this->assertArrayHasKey('user_agent_details', $data[0]); $this->assertArrayHasKey('lang_details', $data[0]); @@ -222,9 +222,9 @@ class ExportFunctionalityTest extends TestCase $request1 = new Request(['format' => 'csv']); $response1 = $this->controller->exportActivityLog($request1); - + sleep(1); // Ensure different timestamps - + $request2 = new Request(['format' => 'csv']); $response2 = $this->controller->exportActivityLog($request2); @@ -238,22 +238,22 @@ class ExportFunctionalityTest extends TestCase public function it_exports_filtered_activities_by_date() { $today = Activity::factory()->today()->create([ - 'description' => 'Today activity' + 'description' => 'Today activity', ]); $yesterday = Activity::factory()->yesterday()->create([ - 'description' => 'Yesterday activity' + 'description' => 'Yesterday activity', ]); $request = new Request([ 'format' => 'json', - 'period' => 'today' + 'period' => 'today', ]); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(1, $data); $this->assertEquals($today->id, $data[0]['id']); } @@ -262,22 +262,22 @@ class ExportFunctionalityTest extends TestCase public function it_exports_filtered_activities_by_search() { $loginActivity = Activity::factory()->login()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $logoutActivity = Activity::factory()->logout()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request([ - 'format' => 'json', - 'description' => 'logged in' + 'format' => 'json', + 'description' => 'logged in', ]); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(1, $data); $this->assertEquals($loginActivity->id, $data[0]['id']); } @@ -286,11 +286,11 @@ class ExportFunctionalityTest extends TestCase public function it_handles_empty_activities_gracefully() { $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertIsArray($data); $this->assertCount(0, $data); } @@ -299,21 +299,21 @@ class ExportFunctionalityTest extends TestCase public function it_preserves_activity_order_in_export() { $activity1 = Activity::factory()->create([ - 'created_at' => now()->subDays(2), - 'description' => 'First activity' + 'created_at' => now()->subDays(2), + 'description' => 'First activity', ]); $activity2 = Activity::factory()->create([ - 'created_at' => now()->subDays(1), - 'description' => 'Second activity' + 'created_at' => now()->subDays(1), + 'description' => 'Second activity', ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(2, $data); // Should be ordered by created_at desc (newest first) $this->assertEquals($activity2->id, $data[0]['id']); @@ -324,14 +324,14 @@ class ExportFunctionalityTest extends TestCase public function it_includes_all_required_fields_in_csv() { $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'csv']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); - + $expectedHeaders = [ 'ID', 'Description', @@ -346,7 +346,7 @@ class ExportFunctionalityTest extends TestCase 'Referer', 'Method Type', 'Created At', - 'Updated At' + 'Updated At', ]; foreach ($expectedHeaders as $header) { @@ -358,15 +358,15 @@ class ExportFunctionalityTest extends TestCase public function it_includes_all_required_fields_in_json() { $activity = Activity::factory()->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $response = $this->controller->exportActivityLog($request); $content = $response->getContent(); $data = json_decode($content, true); - + $expectedFields = [ 'id', 'description', @@ -384,7 +384,7 @@ class ExportFunctionalityTest extends TestCase 'updated_at', 'time_passed', 'user_agent_details', - 'lang_details' + 'lang_details', ]; foreach ($expectedFields as $field) { @@ -397,22 +397,22 @@ class ExportFunctionalityTest extends TestCase { // Create 100 activities Activity::factory()->count(100)->create([ - 'userId' => $this->user->id + 'userId' => $this->user->id, ]); $request = new Request(['format' => 'json']); - + $startTime = microtime(true); $response = $this->controller->exportActivityLog($request); $endTime = microtime(true); - + $this->assertEquals(200, $response->getStatusCode()); - + $content = $response->getContent(); $data = json_decode($content, true); - + $this->assertCount(100, $data); - + // Should complete within reasonable time (less than 5 seconds) $this->assertLessThan(5, $endTime - $startTime); }