Check for unique among non-deleted items for subfleets (#1626)

* Check for unique among non-deleted items for subfleets

* Style fixes
This commit is contained in:
Nabeel S 2023-10-09 16:05:11 -04:00 committed by GitHub
parent a1fc564753
commit 5356d2cd89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 1 deletions

View File

@ -4,6 +4,7 @@ namespace App\Http\Requests;
use App\Contracts\FormRequest;
use App\Models\Subfleet;
use Illuminate\Validation\Rule;
class CreateSubfleetRequest extends FormRequest
{
@ -15,7 +16,10 @@ class CreateSubfleetRequest extends FormRequest
public function rules(): array
{
$rules = Subfleet::$rules;
$rules['type'] .= '|unique:subfleets';
$rules['type'] = explode('|', $rules['type']);
$rules['type'][] = Rule::unique('subfleets')->whereNull('deleted_at');
return $rules;
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace Tests;
use App\Models\Role;
use App\Models\Subfleet;
use App\Models\User;
class AdminControllerTests extends TestCase
{
public function setUp(): void
{
parent::setUp();
$this->addData('base');
}
private function addAdminUser(): User
{
$user = User::factory()->create();
$role = Role::where(['name' => 'admin'])->first();
$user->addRole($role);
return $user;
}
/**
* Test adding a subfleet, deleting it and seeing that the type
* can be added again
*
* @return void
*/
public function testAddSubfleet()
{
$user = $this->addAdminUser();
$add = Subfleet::factory()->make(['type' => 'B737'])->toArray();
$this->actingAs($user, 'web')->post('/admin/subfleets', $add);
$add = Subfleet::factory()->make(['type' => 'A320'])->toArray();
$this->actingAs($user, 'web')->post('/admin/subfleets', $add);
// Make sure it was added
$sf = Subfleet::where(['type' => $add['type']])->first();
$this->assertNotNull($sf);
$original_sf_id = $sf->id;
// delete it
$resp = $this->actingAs($user, 'web')->delete('/admin/subfleets/'.$sf->id);
$sf = Subfleet::where(['type' => $add['type']])->first();
$this->assertNull($sf);
// Try readding now, it shouldn't complain about the type being unique
// Would throw a validation error
$resp = $this->actingAs($user, 'web')->post('/admin/subfleets', $add);
$resp->assertSessionDoesntHaveErrors();
$sf = Subfleet::where(['type' => $add['type']])->first();
$this->assertNotNull($sf);
}
}