Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TM-1601] Tree species data #650

Merged
merged 6 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
namespace App\Http\Controllers\V2\Entities;

use App\Http\Controllers\Controller;
use App\Http\Resources\V2\TreeSpecies\TreeSpeciesCollection;
use App\Http\Resources\V2\TreeSpecies\TreeSpeciesTransformer;
use App\Models\V2\Disturbance;
use App\Models\V2\EntityModel;
use App\Models\V2\EntityRelationModel;
use App\Models\V2\Invasive;
use App\Models\V2\Projects\Project;
use App\Models\V2\Projects\ProjectReport;
use App\Models\V2\Seeding;
use App\Models\V2\Sites\Site;
use App\Models\V2\Stratas\Strata;
use App\Models\V2\TreeSpecies\TreeSpecies;
use Illuminate\Http\Request;
Expand All @@ -23,13 +28,49 @@ class GetRelationsForEntityController extends Controller
'seedings' => Seeding::class,
];

private const TREE_SPECIES_ENTITIES = [
Project::class,
Site::class,
ProjectReport::class,
];

public function __invoke(Request $request, string $relationType, EntityModel $entity): JsonResource
{
$this->authorize('read', $entity);

if ($relationType === 'tree-species' && in_array(get_class($entity), self::TREE_SPECIES_ENTITIES)) {
return $this->handleTreeSpecies($request, $entity);
}

/** @var EntityRelationModel $type */
$type = self::RELATIONS[$relationType];

return $type::createResourceCollection($entity);
}

private function handleTreeSpecies(Request $request, EntityModel $entity): JsonResource
{
$query = TreeSpecies::query()
->where('speciesable_type', get_class($entity))
->where('speciesable_id', $entity->id)
->visible();

if ($filter = $request->query('filter')) {
if (! empty($filter['collection'])) {
$query->where('collection', $filter['collection']);
$entityTreeSpecies = $query->get();

$transformer = new TreeSpeciesTransformer($entity, $entityTreeSpecies, $filter['collection']);
$transformedData = $transformer->transform();

return new TreeSpeciesCollection($transformedData);
}

if (! empty($filter['collection'])) {
$query->where('collection', $filter['collection']);
}
}

return new TreeSpeciesCollection($query->get());
}
}
2 changes: 2 additions & 0 deletions app/Http/Resources/V2/TreeSpecies/TreeSpeciesResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public function toArray($request)
'type' => $this->type,
'collection' => $this->collection,
'taxon_id' => $this->taxon_id,
'report_amount' => $this->report_amount ?? 0,
'is_new_species' => $this->is_new_species ?? false,
];
}
}
150 changes: 150 additions & 0 deletions app/Http/Resources/V2/TreeSpecies/TreeSpeciesTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?php

namespace App\Http\Resources\V2\TreeSpecies;

use App\Models\V2\EntityModel;
use App\Models\V2\Projects\Project;
use App\Models\V2\Projects\ProjectReport;
use App\Models\V2\Sites\Site;
use App\Models\V2\Sites\SiteReport;
use App\Models\V2\TreeSpecies\TreeSpecies;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as SupportCollection;

class TreeSpeciesTransformer
{
private EntityModel $entity;

private Collection $entityTreeSpecies;

private SupportCollection $siteReportTreeSpecies;

private string $collectionType;

public function __construct(EntityModel $entity, Collection $entityTreeSpecies, string $collectionType)
{
$validEntityTypes = [Project::class, Site::class, ProjectReport::class];

if (! in_array(get_class($entity), $validEntityTypes)) {
throw new \InvalidArgumentException(
'Entity must be an instance of Project, Site, or ProjectReport'
);
}

$this->entity = $entity;
$this->entityTreeSpecies = $entityTreeSpecies;
$this->collectionType = $collectionType;
$this->siteReportTreeSpecies = $this->getSiteReportTreeSpecies();
}

public function transform(): Collection
{
if ($this->entity instanceof ProjectReport) {
return $this->transformProjectReport();
}

// For Project and Site entities
$this->entityTreeSpecies->each(function ($species) {
$identifier = $species->taxon_id ?? $species->name;
$reportAmount = $this->getReportAmount($identifier);

$species->report_amount = $reportAmount;
$species->is_new_species = false;
});

$newSpecies = $this->getNewSpecies();

return new Collection(
$this->entityTreeSpecies->concat($newSpecies)
);
}

private function transformProjectReport(): Collection
{
return new Collection(
$this->siteReportTreeSpecies->map(function ($reportSpecies) {
$species = new TreeSpecies([
'name' => $reportSpecies['name'],
'amount' => $reportSpecies['amount'],
'collection' => $reportSpecies['collection'],
'taxon_id' => $reportSpecies['taxon_id'],
]);

$species->report_amount = $reportSpecies['amount'];
$species->is_new_species = false;

return $species;
})
);
}

private function getSiteReportTreeSpecies(): SupportCollection
{
$ids = $this->getSiteReportIds();

return TreeSpecies::whereIn('speciesable_id', $ids)
->where('collection', $this->collectionType)
->where('hidden', false)
->get()
->groupBy(function ($species) {
return $species->taxon_id ?? $species->name;
})
->map(function ($group) {
return [
'taxon_id' => $group->first()->taxon_id,
'name' => $group->first()->name,
'amount' => $group->sum('amount'),
'collection' => $group->first()->collection,
];
})
->values();
}

private function getSiteReportIds(): array
{
return match (true) {
$this->entity instanceof Project => $this->entity->submittedSiteReportIds()->pluck('id')->toArray(),
$this->entity instanceof Site => $this->entity->submittedReportIds()->pluck('id')->toArray(),
$this->entity instanceof ProjectReport => $this->entity->task->siteReports()->whereNotIn('status', SiteReport::UNSUBMITTED_STATUSES)->pluck('id')->toArray(),
default => [],
};
}

private function getReportAmount(string $identifier): int
{
return (int) $this->siteReportTreeSpecies
->filter(function ($reportSpecies) use ($identifier) {
return ($reportSpecies['taxon_id'] ?? $reportSpecies['name']) === $identifier;
})
->sum('amount');
}

private function getNewSpecies(): Collection
{
$newSpecies = new Collection();

foreach ($this->siteReportTreeSpecies as $reportSpecies) {
$identifier = $reportSpecies['taxon_id'] ?? $reportSpecies['name'];

$existsInEntity = $this->entityTreeSpecies->contains(function ($species) use ($identifier) {
return ($species->taxon_id ?? $species->name) === $identifier;
});

if (! $existsInEntity) {
$species = new TreeSpecies([
'name' => $reportSpecies['name'],
'amount' => $reportSpecies['amount'],
'collection' => $reportSpecies['collection'],
'taxon_id' => $reportSpecies['taxon_id'],
]);

$species->report_amount = $reportSpecies['amount'];
$species->is_new_species = true;

$newSpecies->push($species);
}
}

return $newSpecies;
}
}
2 changes: 1 addition & 1 deletion app/Models/V2/Projects/Project.php
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ private function submittedSiteReports(): HasManyThrough
* @return HasManyThrough The query of site report IDs for all reports associated with sites that have been
* approved, and have a report status not in due or started (reports that have been submitted).
*/
private function submittedSiteReportIds(): HasManyThrough
public function submittedSiteReportIds(): HasManyThrough
{
return $this->submittedSiteReports()->select('v2_site_reports.id');
}
Expand Down
11 changes: 11 additions & 0 deletions app/Models/V2/Sites/Site.php
Original file line number Diff line number Diff line change
Expand Up @@ -471,4 +471,15 @@ public function getTotalHectaresRestoredSumAttribute(): float
{
return round($this->sitePolygons->where('status', 'approved')->sum('calc_area'));
}

public function submittedReports(): HasMany
{
return $this->reports()
->whereNotIn('status', SiteReport::UNSUBMITTED_STATUSES);
}

public function submittedReportIds(): HasMany
{
return $this->submittedReports()->select('id');
}
}
2 changes: 1 addition & 1 deletion app/Models/V2/TreeSpecies/TreeSpecies.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public static function createResourceCollection(EntityModel $entity): JsonResour
$query->where('collection', $filter['collection']);
}

return new TreeSpeciesCollection($query->paginate());
return new TreeSpeciesCollection($query->get());
}

public function scopeVisible($query): Builder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ parameters:
name: UUID
in: path
required: true
- type: string
name: filter[collection]
in: query
required: false
description: The collection to filter tree species by.
responses:
'200':
description: OK
Expand Down
5 changes: 5 additions & 0 deletions resources/docs/swagger-v2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44514,6 +44514,11 @@ paths:
name: UUID
in: path
required: true
- type: string
name: 'filter[collection]'
in: query
required: false
description: The collection to filter tree species by.
responses:
'200':
description: OK
Expand Down
Loading