Skip to content

Commit

Permalink
refactor and update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ok200lyndon committed Aug 16, 2024
1 parent 4caf538 commit 6ba7429
Show file tree
Hide file tree
Showing 17 changed files with 253 additions and 48 deletions.
37 changes: 37 additions & 0 deletions app/Events/Users/UserWasCreated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace App\Events\Users;

use App\Models\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserWasCreated
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;

/**
* Create a new event instance.
*
* @param User|Authenticatable $user
*/
public function __construct(public User|Authenticatable $user) {}

/**
* Get the channels the event should broadcast on.
*
* @return array<int, Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('channel-name'),
];
}
}
11 changes: 6 additions & 5 deletions app/Http/Controllers/Api/V1/ApiMyTeamAuditItemsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class ApiMyTeamAuditItemsController extends Controller
*/
public function index(): JsonResponse
{
$this->query = AuditItem::where('team_id', Auth::user()->current_team_id)->with($this->associatedData);
$this->query = AuditItem::where('auditable_team_id', Auth::user()->current_team_id)->with($this->associatedData);
$this->query = $this->updateReadQueryBasedOnUrl();
$this->data = $this->query->paginate($this->limit);

Expand All @@ -53,13 +53,14 @@ public function store(): JsonResponse
/**
* GET /{id}
*
* @param int $id
* @param int $id
*
* @return JsonResponse
* @throws DisallowedApiFieldException
*/
public function show(int $id)
{
$this->query = AuditItem::where('team_id', Auth::user()->current_team_id)->with($this->associatedData);
$this->query = AuditItem::where('auditable_team_id', Auth::user()->current_team_id)->with($this->associatedData);
$this->query = $this->updateReadQueryBasedOnUrl();
$this->data = $this->query->find($id);

Expand All @@ -69,7 +70,7 @@ public function show(int $id)
/**
* PUT /{id}
*
* @param string $id
* @param string $id
*
* @return JsonResponse
*/
Expand All @@ -84,7 +85,7 @@ public function update(string $id)
/**
* DELETE / {id}
*
* @param string $id
* @param string $id
*
* @return JsonResponse
*/
Expand Down
41 changes: 41 additions & 0 deletions app/Jobs/RecordUserWasCreatedAuditItem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace App\Jobs;

use App\Models\User;
use App\Services\AuditItemService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class RecordUserWasCreatedAuditItem implements ShouldQueue
{
use Queueable;

/**
* Create a new job instance.
*
* @param User $actioningUser
* @param User $createdUser
*/
public function __construct(public User $actioningUser, public User $createdUser) {}

/**
* Execute the job.
*/
public function handle(): void
{
$eventText = '';

if ($this->actioningUser->is_admin) {
$eventText .= 'Admin ';
}

$eventText .= $this->actioningUser->name . ' created a new user ' . $this->createdUser->name . '.';

AuditItemService::createAuditItemForEvent(
actioningUser: $this->actioningUser,
model: $this->createdUser,
eventText: $eventText
);
}
}
33 changes: 33 additions & 0 deletions app/Listeners/Users/HandleUserWasCreatedEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Listeners\Users;

use App\Events\Users\UserWasCreated;
use App\Jobs\RecordUserWasCreatedAuditItem;
use Auth;
use Log;

class HandleUserWasCreatedEvent
{
/**
* Create the event listener.
*/
public function __construct() {}

/**
* Handle the event.
*
* @param UserWasCreated $event
*/
public function handle(UserWasCreated $event): void
{
if (env('APP_ENV') != 'testing') {
dispatch(
new RecordUserWasCreatedAuditItem(
actioningUser: Auth::user(),
createdUser: $event->user
)
);
}
}
}
8 changes: 8 additions & 0 deletions app/Models/AuditItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ class AuditItem extends Model
{
use HasFactory;

protected $fillable = [
'auditable_id',
'auditable_type',
'auditable_text',
'team_id',
'user_id',
];

public function auditable(): MorphTo
{
return $this->morphTo();
Expand Down
5 changes: 5 additions & 0 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Events\Users\UserWasCreated;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
Expand All @@ -16,6 +17,10 @@ class User extends Authenticatable
use HasFactory;
use Notifiable;

protected $dispatchesEvents = [
'created' => UserWasCreated::class,
];

/**
* The attributes that are mass assignable.
*
Expand Down
11 changes: 10 additions & 1 deletion app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace App\Providers;

use App\Events\Users\UserWasCreated;
use App\Listeners\Users\HandleUserWasCreatedEvent;
use Event;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
Expand All @@ -14,5 +17,11 @@ public function register(): void {}
/**
* Bootstrap any application services.
*/
public function boot(): void {}
public function boot(): void
{
Event::listen(
events: UserWasCreated::class,
listener: HandleUserWasCreatedEvent::class
);
}
}
33 changes: 33 additions & 0 deletions app/Services/AuditItemService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace App\Services;

use App\Models\AuditItem;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;

class AuditItemService
{
public static function createAuditItemForEvent(User $actioningUser, Model $model, string $eventText): AuditItem
{
$teamId = null;

if ($model->hasAttribute('team_id')) {
$teamId = $model->team_id;
}

if ($model->hasAttribute('current_team_id')) {
$teamId = $model->current_team_id;
}

$auditItem = new AuditItem();
$auditItem->auditable_type = get_class($model);
$auditItem->auditable_id = $model->id;
$auditItem->auditable_text = $eventText;
$auditItem->auditable_team_id = $teamId;
$auditItem->actioning_user_id = $actioningUser->id;
$auditItem->save();

return $auditItem;
}
}
32 changes: 7 additions & 25 deletions database/factories/AuditItemFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

namespace Database\Factories;

use App\Models\Team;
use App\Models\AuditItem;
use App\Models\User;
use App\Models\Voucher;
use App\Models\VoucherSet;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\AuditItem>
* @extends Factory<AuditItem>
*/
class AuditItemFactory extends Factory
{
Expand All @@ -20,28 +18,12 @@ class AuditItemFactory extends Factory
*/
public function definition(): array
{
$num = rand(0, 3);

// If $num == 0, stays as user
$auditable = User::factory()->createQuietly();

if ($num === 1) {
$auditable = Team::factory()->createQuietly();
}

if ($num === 2) {
$auditable = Voucher::factory()->createQuietly();
}

if ($num === 3) {
$auditable = VoucherSet::factory()->createQuietly();
}

return [
'auditable_type' => get_class($auditable),
'auditable_id' => $auditable->id,
'auditable_text' => $this->faker->randomElement(['created', 'updated', 'deleted']),
'team_id' => $this->faker->randomDigitNotNull(),
'auditable_type' => User::class,
'auditable_id' => $this->faker->randomDigitNotNull(),
'auditable_text' => $this->faker->randomElement(['created', 'updated', 'deleted']),
'auditable_team_id' => $this->faker->randomDigitNotNull(),
'actioning_user_id' => $this->faker->randomDigitNotNull(),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ public function up(): void
$table->string('auditable_type')->index('ai_at');
$table->string('auditable_id');
$table->string('auditable_text');
$table->unsignedBigInteger('team_id')->index('ai_ti');
$table->unsignedBigInteger('auditable_team_id')->nullable()->index('ai_ati');
$table->unsignedBigInteger('actioning_user_id')->index('ai_aui');
$table->timestamps();
$table->softDeletes();

$table->index(columns: ['auditable_type', 'auditable_id', 'auditable_text'], name: 'ai_ataiat');
$table->index(columns: ['auditable_type', 'auditable_id'], name: 'ai_atai');
$table->index(columns: ['auditable_text', 'team_id'], name: 'ai_atti');
$table->index(columns: ['auditable_text', 'auditable_team_id'], name: 'ai_atati');
});
}

Expand Down
2 changes: 1 addition & 1 deletion database/seeders/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function run(): void
);

foreach ($userAndTeam['users'] as $user) {
$user = User::factory()->create(
$user = User::factory()->createQuietly(
[
'name' => $user['name'],
'email' => $user['email'],
Expand Down
2 changes: 1 addition & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

Route::get('/audit-trail', function () {
return Inertia::render('AuditItems');
})->name('audit-trail');
})->name('admin.audit-trail');

Route::get('/users', function () {
return Inertia::render('Admin/Users/Users');
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/API/App/AuditItems/AuditItemPostTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function itCannotCreateWithIncorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->postJson($this->apiRoot . $this->endpoint);
Expand All @@ -67,7 +67,7 @@ public function itCannotCreateWithCorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->postJson($this->apiRoot . $this->endpoint);
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/API/App/AuditItems/AuditItemPutTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function itCannotUpdateWithIncorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->putJson($this->apiRoot . $this->endpoint . '/' . $model->id);
Expand All @@ -67,7 +67,7 @@ public function itCannotUpdateWithCorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->putJson($this->apiRoot . $this->endpoint . '/' . $model->id);
Expand Down
4 changes: 2 additions & 2 deletions tests/Feature/API/App/AuditItems/AuditItemsDeleteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function itCannotDeleteWithIncorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->deleteJson($this->apiRoot . $this->endpoint . '/' . $model->id);
Expand All @@ -67,7 +67,7 @@ public function itCannotDeleteWithCorrectToken()
);

$model = AuditItem::factory()->create([
'team_id' => $this->user->current_team_id,
'auditable_team_id' => $this->user->current_team_id,
]);

$response = $this->deleteJson($this->apiRoot . $this->endpoint . '/' . $model->id);
Expand Down
Loading

0 comments on commit 6ba7429

Please sign in to comment.