Skip to content

Commit

Permalink
Taxonomy API endpoints (#127) (#235)
Browse files Browse the repository at this point in the history
  • Loading branch information
NuwanJ authored Dec 4, 2024
1 parent 14ee5f9 commit 1b0ab5f
Show file tree
Hide file tree
Showing 15 changed files with 246 additions and 66 deletions.
13 changes: 10 additions & 3 deletions app/Domains/Taxonomy/Models/Taxonomy.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
*/
class Taxonomy extends Model
{
use TaxonomyScope,
HasFactory,
use HasFactory,
LogsActivity;


Expand All @@ -43,6 +42,7 @@ class Taxonomy extends Model
];

protected $casts = [
'properties' => 'json',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
Expand All @@ -69,13 +69,20 @@ public function terms()
->orderBy('code', 'asc');
}

public function first_child_terms()
{
return $this->hasMany(TaxonomyTerm::class, 'taxonomy_id')
->whereNull('parent_id')
->orderBy('code', 'asc');
}

public function to_dict()
{
$taxonomy = $this->toArray();
foreach (['properties', 'created_at', 'updated_at', 'created_by', 'updated_by'] as $attribute) {
unset($taxonomy[$attribute]);
}
$taxonomy['properties'] = json_decode($this->properties);
$taxonomy['properties'] = $this->properties;
$taxonomy['terms'] = TaxonomyTerm::getByTaxonomy($this->id);
return $taxonomy;
}
Expand Down
22 changes: 11 additions & 11 deletions app/Domains/Taxonomy/Models/TaxonomyTerm.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,15 @@ class TaxonomyTerm extends Model
public function getFormattedMetadataAttribute()
{
$response = array();
$filteredMetadata = array_filter(json_decode($this->metadata, true), function ($value) {
return !is_null($value['value']);
});
if (is_array($this->metadata)) {
$filteredMetadata = array_filter($this->metadata, function ($value) {
return !is_null($value['value']);
});

foreach ($filteredMetadata as $metadata) {
$response[$metadata['code']] = $metadata['value'];
foreach ($filteredMetadata as $metadata) {
$response[$metadata['code']] = $metadata['value'];
}
}

return $response;
}

Expand Down Expand Up @@ -74,15 +75,14 @@ public function parent()

public function children()
{
return $this->hasMany(self::class, 'parent_id');
return $this->hasMany(self::class, 'parent_id')
->orderBy('code', 'asc');;
}

public function getMetadata($code)
{
$metadata = json_decode($this->metadata, true);

if (is_array($metadata)) {
foreach ($metadata as $item) {
if (is_array($this->metadata)) {
foreach ($this->metadata as $item) {
if ($item['code'] === $code && $item['value'] != null) {
return $item['value'];
}
Expand Down
11 changes: 0 additions & 11 deletions app/Domains/Taxonomy/Models/Traits/Scope/TaxonomyScope.php

This file was deleted.

82 changes: 82 additions & 0 deletions app/Http/Controllers/API/TaxonomyApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\TaxonomyListResource;
use App\Http\Resources\TaxonomyResource;
use App\Http\Resources\TaxonomyTermResource;
use App\Domains\Taxonomy\Models\Taxonomy;
use App\Domains\Taxonomy\Models\TaxonomyTerm;
use Illuminate\Support\Facades\Log;

class TaxonomyApiController extends Controller
{

public function index()
{
try {
$result = Taxonomy::all();

if ($result) {
return response()->json(
[
'status' => 'success',
'data' => TaxonomyListResource::collection($result)
]
);
} else {
return response()->json(['status' => 'error', 'message' => 'No Taxonomies found'], 404);
}
} catch (\Exception $e) {
Log::error('Error in TaxonomyApiController@index', ['error' => $e->getMessage()]);
return response()->json(['status' => 'error', 'message' => 'An error occurred while fetching taxonomy index'], 500);
}
}

public function get_taxonomy($taxonomy_code)
{
try {
$result = Taxonomy::where('code', $taxonomy_code)->first();

if ($result) {
return response()->json(
[
'status' => 'success',
'data' => TaxonomyResource::collection([$result])->resolve()[0]
]
);
} else {
return response()->json(['status' => 'error', 'message' => 'Taxonomy not found'], 404);
}
} catch (\Exception $e) {
Log::error('Error in TaxonomyApiController@get_taxonomy', ['error' => $e->getMessage()]);
return response()->json(['status' => 'error', 'message' => 'An error occurred while fetching a taxonomy'], 500);
}
}


public function get_term($term_code)
{
try {
$result = TaxonomyTerm::where('code', $term_code)->first();

if ($result) {
$data = TaxonomyTermResource::collection([$result])->resolve()[0];
$data['taxonomy'] = $result->taxonomy->code; // Add the taxonomy code at the top-level term

return response()->json(
[
'status' => 'success',
'data' => $data
]
);
} else {
return response()->json(['status' => 'error', 'message' => 'Taxonomy term not found'], 404);
}
} catch (\Exception $e) {
Log::error('Error in TaxonomyApiController@get_term', ['error' => $e->getMessage()]);
return response()->json(['status' => 'error', 'message' => 'An error occurred while fetching a taxonomy term'], 500);
}
}
}
7 changes: 4 additions & 3 deletions app/Http/Controllers/Backend/TaxonomyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,15 @@ public function edit(Taxonomy $taxonomy)
public function update(Request $request, Taxonomy $taxonomy)
{
$data = $request->validate([
'code' => 'required',
'name' => 'required',
'code' => 'string|required',
'name' => 'string|required',
'description' => 'nullable',
'properties' => 'string'
]);

try {
$taxonomy->update($data);
$taxonomy->properties = $request->properties;
$taxonomy->properties = json_decode($request->properties);
$taxonomy->updated_by = Auth::user()->id;
$taxonomy->save();
return redirect()->route('dashboard.taxonomy.index')->with('Success', 'Taxonomy updated successfully');
Expand Down
12 changes: 6 additions & 6 deletions app/Http/Controllers/Backend/TaxonomyTermController.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function store(Request $request, Taxonomy $taxonomy, TaxonomyTerm $taxono
]);


foreach (json_decode($taxonomy->properties, true) as $property) {
foreach ($taxonomy->properties as $property) {
$metadataKey = "metadata.{$property['code']}";

switch ($property['data_type']) {
Expand Down Expand Up @@ -86,7 +86,7 @@ public function store(Request $request, Taxonomy $taxonomy, TaxonomyTerm $taxono

$metadataArray = [];

foreach (json_decode($taxonomy->properties, true) as $property) {
foreach ($taxonomy->properties as $property) {
$value = $request->input("metadata.{$property['code']}");

if ($property['data_type'] === 'boolean') {
Expand All @@ -99,7 +99,7 @@ public function store(Request $request, Taxonomy $taxonomy, TaxonomyTerm $taxono
}

$taxonomyTerm = new TaxonomyTerm($validatedData);
$taxonomyTerm->metadata = json_encode($metadataArray);
$taxonomyTerm->metadata = $metadataArray;
$taxonomyTerm->created_by = Auth::user()->id;
$taxonomyTerm->save();

Expand Down Expand Up @@ -142,7 +142,7 @@ public function update(Request $request, Taxonomy $taxonomy, TaxonomyTerm $term)
'metadata' => 'array',
]);

foreach (json_decode($taxonomy->properties, true) as $property) {
foreach ($taxonomy->properties as $property) {
$metadataKey = "metadata.{$property['code']}";

switch ($property['data_type']) {
Expand Down Expand Up @@ -179,7 +179,7 @@ public function update(Request $request, Taxonomy $taxonomy, TaxonomyTerm $term)
}

$metadataArray = [];
foreach (json_decode($taxonomy->properties, true) as $property) {
foreach ($taxonomy->properties as $property) {
$value = $request->input("metadata.{$property['code']}");

if ($property['data_type'] === 'boolean') {
Expand All @@ -193,7 +193,7 @@ public function update(Request $request, Taxonomy $taxonomy, TaxonomyTerm $term)
}

$term->update($validatedData);
$term->metadata = json_encode($metadataArray);
$term->metadata = $metadataArray;
$term->updated_by = Auth::user()->id;
$term->save();

Expand Down
28 changes: 28 additions & 0 deletions app/Http/Resources/TaxonomyListResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace App\Http\Resources;

use App\Domains\Taxonomy\Models\Taxonomy;
use Illuminate\Http\Resources\Json\JsonResource;

class TaxonomyListResource extends JsonResource
{
public $collects = Taxonomy::class;

/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{

return [
'code' => $this->code,
'name' => $this->name,
'description' => $this->description,
'api' => config('app.url', '') . "/api/taxonomy/v1/" . $this->code,
];
}
}
35 changes: 35 additions & 0 deletions app/Http/Resources/TaxonomyResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Http\Resources;

// use App\Domains\Auth\Models\User;
use App\Domains\Taxonomy\Models\Taxonomy;
use App\Http\Resources\TaxonomyTermResource;
use Illuminate\Http\Resources\Json\JsonResource;

class TaxonomyResource extends JsonResource
{
public $collects = Taxonomy::class;

/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{

return [
'code' => $this->code,
'name' => $this->name,
'description' => $this->description,
// 'properties' => $this->properties,
'terms' => TaxonomyTermResource::collection($this->first_child_terms),
// 'created_by' => User::find($this->created_by)?->name,
// 'updated_by' => User::find($this->updated_by)?->name,
// 'created_at' => $this->created_at,
// 'updated_at' => $this->updated_at,
];
}
}
38 changes: 38 additions & 0 deletions app/Http/Resources/TaxonomyTermResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\Http\Resources;

// use App\Domains\Auth\Models\User;
use Illuminate\Http\Resources\Json\JsonResource;

class TaxonomyTermResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
$metadata = $this->getFormattedMetadataAttribute();


return [
'code' => $this->code,
'name' => $this->name,
'terms' => $this->when(
sizeof($this->children) > 0,
TaxonomyTermResource::collection($this->children)
),
'metadata' => $this->when(
sizeof($metadata) > 0,
$metadata
),
// 'created_by' => User::find($this->created_by)?->name,
// 'updated_by' => User::find($this->updated_by)?->name,
// 'created_at' => $this->created_at,
// 'updated_at' => $this->updated_at,
];
}
}
2 changes: 1 addition & 1 deletion resources/views/backend/taxonomy/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
@section('title', __('Edit Taxonomy'))

@section('content')
<div x-data="{ properties: {{ $taxonomy->properties }}, is_editable: {{ $taxonomy->terms()->count() > 0 ? '0' : '1' }} }">
<div x-data="{ properties: {{ json_encode($taxonomy->properties) }}, is_editable: {{ $taxonomy->terms()->count() > 0 ? '0' : '1' }} }">
{!! Form::model($taxonomy, [
'url' => route('dashboard.taxonomy.update', $taxonomy->id),
'method' => 'PUT',
Expand Down
2 changes: 1 addition & 1 deletion resources/views/backend/taxonomy/terms/create.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
<strong>Metadata</strong>
</div>

@foreach (json_decode($taxonomy->properties, true) as $property)
@foreach ($taxonomy->properties as $property)
<div class="col-12 py-2">
<div class="col ps-0">
<label>{{ $property['name'] }}
Expand Down
6 changes: 3 additions & 3 deletions resources/views/backend/taxonomy/terms/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@
<label for="parent_term">Parent Taxonomy Term (Optional)</label>
</div>
<select name="parent_id" class="form-select">
<option value="" selected>Select</option>
<option value="">Select</option>
@foreach ($term->taxonomy->terms as $sibling)
@if ($sibling->id != $term->id)
<option value="{{ $sibling->id }}"
{{ old('parent_id', $sibling->parent_id) == $sibling->id ? 'selected' : '' }}>
{{ old('parent_id', $term->parent_id) == $sibling->id ? 'selected' : '' }}>
{{ TaxonomyTerm::getHierarchicalPath($sibling->id) }}
</option>
@endif
Expand Down Expand Up @@ -82,7 +82,7 @@
<strong>Metadata</strong>
</div>

@foreach (json_decode($taxonomy->properties, true) as $property)
@foreach ($taxonomy->properties as $property)
<div class="col-12 py-2">
<div class="col ps-0">
<label>{{ $property['name'] }}
Expand Down
Loading

0 comments on commit 1b0ab5f

Please sign in to comment.