Browse Source

Naming Rule API

moell 1 year ago
parent
commit
df33c2fdce

+ 87 - 0
app/Http/Controllers/API/NameRuleController.php

@@ -0,0 +1,87 @@
+<?php
+
+namespace App\Http\Controllers\API;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\API\NamingRule\CreateOrUpdateRequest;
+use App\Http\Resources\API\NamingRuleResource;
+use App\Models\NamingRule;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+
+class NameRuleController extends Controller
+{
+    /**
+     * Display a listing of the resource.
+     */
+    public function index(Request $request)
+    {
+        $namingRules = NamingRule::allowed()->with(['company'])->filter($request->all())->paginate();
+
+        return NamingRuleResource::collection($namingRules);
+    }
+
+    /**
+     * Store a newly created resource in storage.
+     */
+    public function store(CreateOrUpdateRequest $request)
+    {
+        $formData = $request->only(['name', 'status', 'company_id', 'global']);
+
+        if (! Auth::user()->super_admin) {
+            $formData['company_id'] = Auth::user()->company_id;
+            unset($formData['global']);
+        }
+
+        NamingRule::create($formData);
+
+        return $this->created();
+    }
+
+    /**
+     * Display the specified resource.
+     */
+    public function show(string $id)
+    {
+        $namingRule = NamingRule::query()->allowed()->findOrFail($id);
+
+        return new NamingRuleResource($namingRule);
+    }
+
+    /**
+     * Update the specified resource in storage.
+     */
+    public function update(CreateOrUpdateRequest $request, string $id)
+    {
+        $namingRule = NamingRule::query()->allowed()->findOrFail($id);
+
+        $namingRule->fill($request->only([
+            'name', 'status', 'global'
+        ]));
+        $namingRule->save();
+
+        return $this->noContent();
+    }
+
+    /**
+     * Remove the specified resource from storage.
+     */
+    public function destroy(string $id)
+    {
+
+    }
+
+    public function enabled()
+    {
+        $namingRules = NamingRule::where('status', 1)->where(function ($query) {
+            return $query->where("company_id", Auth::user()->company_id)->orWhere([
+                'company_id' => 0,
+                'global' => 1
+            ]);
+        })->select(['id', 'name'])->get();
+
+        return $this->success([
+            'data' => $namingRules
+        ]);
+    }
+}

+ 31 - 0
app/Http/Requests/API/NamingRule/CreateOrUpdateRequest.php

@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Http\Requests\API\NamingRule;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+class CreateOrUpdateRequest extends FormRequest
+{
+    /**
+     * Determine if the user is authorized to make this request.
+     */
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * Get the validation rules that apply to the request.
+     *
+     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
+     */
+    public function rules(): array
+    {
+        return [
+            'name' => 'required|max:50',
+            'global' => 'required|in:0,1',
+            'status' => 'required|in:0,1',
+            'company_id' => 'exists:company,id'
+        ];
+    }
+}

+ 25 - 0
app/Http/Resources/API/NamingRuleResource.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace App\Http\Resources\API;
+
+use Illuminate\Http\Request;
+use Illuminate\Http\Resources\Json\JsonResource;
+
+class NamingRuleResource extends JsonResource
+{
+    /**
+     * Transform the resource into an array.
+     *
+     * @return array<string, mixed>
+     */
+    public function toArray(Request $request): array
+    {
+        return [
+            'id' => $this->id,
+            'name' => $this->name,
+            'global' => $this->global,
+            'status' => $this->status,
+            'company' => new SimpleCompanyResource($this->company),
+        ];
+    }
+}

+ 16 - 0
app/ModelFilters/NamingRuleFilter.php

@@ -0,0 +1,16 @@
+<?php 
+
+namespace App\ModelFilters;
+
+use EloquentFilter\ModelFilter;
+
+class NamingRuleFilter extends ModelFilter
+{
+    /**
+    * Related Models that have ModelFilters as well as the method on the ModelFilter
+    * As [relationMethod => [input_key1, input_key2]].
+    *
+    * @var array
+    */
+    public $relations = [];
+}

+ 4 - 0
app/Models/Company.php

@@ -10,4 +10,8 @@ class Company extends Model
     use HasFactory;
 
     protected $table = 'company';
+
+    protected $guarded = [
+        'id'
+    ];
 }

+ 16 - 1
app/Models/NamingRule.php

@@ -2,16 +2,31 @@
 
 namespace App\Models;
 
+use EloquentFilter\Filterable;
+use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Auth;
 
 class NamingRule extends Model
 {
-    use HasFactory;
+    use HasFactory, Filterable;
 
     public $timestamps = false;
 
     protected $guarded = [
         'id'
     ];
+
+    public function scopeAllowed(Builder $query)
+    {
+        if (!Auth::user()->super_admin) {
+            $query->where("company_id", Auth::user()->company_id);
+        }
+    }
+
+    public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo
+    {
+        return $this->belongsTo(Company::class);
+    }
 }

+ 24 - 0
database/factories/CompanyFactory.php

@@ -0,0 +1,24 @@
+<?php
+
+namespace Database\Factories;
+
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Company>
+ */
+class CompanyFactory extends Factory
+{
+    /**
+     * Define the model's default state.
+     *
+     * @return array<string, mixed>
+     */
+    public function definition(): array
+    {
+        return [
+            'name' => fake()->name(),
+            'email' => fake()->email(),
+        ];
+    }
+}

+ 27 - 0
database/factories/NamingRuleFactory.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace Database\Factories;
+
+use Illuminate\Database\Eloquent\Factories\Factory;
+use Illuminate\Support\Facades\Auth;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\NamingRule>
+ */
+class NamingRuleFactory extends Factory
+{
+    /**
+     * Define the model's default state.
+     *
+     * @return array<string, mixed>
+     */
+    public function definition(): array
+    {
+        return [
+            'name' => fake()->name(),
+            'company_id' => Auth::user()->company_id,
+            'status' => 1,
+            'global' => 0,
+        ];
+    }
+}

+ 2 - 1
database/factories/UserFactory.php

@@ -2,6 +2,7 @@
 
 namespace Database\Factories;
 
+use App\Models\Company;
 use Illuminate\Database\Eloquent\Factories\Factory;
 use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Str;
@@ -30,7 +31,7 @@ class UserFactory extends Factory
             'password' => static::$password ??= Hash::make('password'),
             'remember_token' => Str::random(10),
             'username' => fake()->unique()->userName(),
-            'company_id' => 1,
+            'company_id' => Company::factory()->create(),
         ];
     }
 

+ 3 - 0
routes/api.php

@@ -31,6 +31,7 @@ Route::middleware(['auth:sanctum'])->group(function () {
             'plan' => API\PlanController::class,
             'role' => API\RoleController::class,
             'custom-field' => API\CustomFieldController::class,
+            'naming-rule' => API\NameRuleController::class,
         ]);
 
         Route::get("requirement/{asset_id}/asset", [API\RequirementController::class, "byAsset"])->name("requirement.byAsset");
@@ -62,5 +63,7 @@ Route::middleware(['auth:sanctum'])->group(function () {
         Route::put("user/{user}/assign-role", [API\UserController::class, "assignRole"])->name("user.assign-role");
 
         Route::get("custom-field-group", [API\CustomFieldController::class, "groups"])->name("custom-field.groups");
+
+        Route::get("naming-rule-enabled", [API\NameRuleController::class, "enabled"])->name("naming-rule.enabled");
     });
 });

+ 101 - 0
tests/Feature/API/NamingRuleTest.php

@@ -0,0 +1,101 @@
+<?php
+
+namespace Tests\Feature\API;
+
+use App\Models\NamingRule;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Foundation\Testing\WithFaker;
+use Tests\Feature\TestCase;
+
+class NamingRuleTest extends TestCase
+{
+    public function test_create_naming_rule(): void
+    {
+        $form = NamingRule::factory()->make();
+
+        $response = $this->post(route('naming-rule.store'), $form->toArray());
+
+        $response->assertStatus(201);
+    }
+
+    public function test_naming_rule_list()
+    {
+        NamingRule::factory(30)->create();
+
+        $response = $this->get(route('naming-rule.index'));
+
+        $response->assertStatus(200)
+            ->assertJsonStructure([
+                'data' => [
+                    '*' => [
+                        'id',
+                        'name',
+                        'global',
+                        'status',
+                        'company'
+                    ]
+                ]
+            ]);
+    }
+
+    public function test_naming_rule_enabled()
+    {
+        NamingRule::factory(30)->create();
+
+        $response = $this->get(route('naming-rule.enabled'));
+
+        $response->assertStatus(200)
+            ->assertJsonStructure([
+                'data' => [
+                    '*' => [
+                        'id',
+                        'name',
+                    ]
+                ]
+            ]);
+    }
+
+    public function test_naming_rule_show(): void
+    {
+        $namingRule = NamingRule::factory()->create();
+
+        $response = $this->get(route('naming-rule.show', ['naming_rule' => $namingRule->id]));
+
+        $response->assertStatus(200)
+            ->assertJsonStructure([
+                'data' => [
+                    'id',
+                    'name',
+                    'global',
+                    'status',
+                    'company'
+                ]
+            ]);
+    }
+
+    public function test_naming_rule_update(): void
+    {
+        $namingRule = NamingRule::factory()->create();
+
+        $form = NamingRule::factory()->make();
+
+        $response = $this->put(route('naming-rule.update', ['naming_rule' => $namingRule->id]), $form->toArray());
+
+        $response->assertStatus(204);
+
+        $newAsset = NamingRule::find($namingRule->id);
+
+        $this->assertEquals($form->name, $newAsset->name);
+    }
+
+    private function test_naming_rule_delete(): void
+    {
+        $namingRule = NamingRule::factory()->create();
+
+        $response = $this->delete(route('naming-rule.destroy', ['naming_rule' => $namingRule->id]));
+
+        $response->assertStatus(204);
+
+        $this->assertNull(NamingRule::find($namingRule->id));
+    }
+}