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-692] add files for review #183

Closed
wants to merge 2 commits into from
Closed
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
114 changes: 114 additions & 0 deletions app/Helpers/GeometryHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?php

namespace App\Helpers;

use App\Models\V2\PolygonGeometry;
use App\Models\V2\Projects\Project;
use App\Models\V2\Sites\SitePolygon;
use Illuminate\Support\Facades\Log;

class GeometryHelper
{
public function centroidOfProject($projectUuid)
{
$sitePolygons = SitePolygon::where('project_id', $projectUuid)->get();

if ($sitePolygons->isEmpty()) {
return null; // Return null if no polygons are found for the given projectUuid
}

$polyIds = $sitePolygons->pluck('poly_id')->toArray();

$centroids = PolygonGeometry::selectRaw('ST_AsGeoJSON(ST_Centroid(geom)) AS centroid')
->whereIn('uuid', $polyIds)
->get();

if ($centroids->isEmpty()) {
return null; // Return null if no centroids are found
}

$centroidCount = $centroids->count();
$totalLatitude = 0;
$totalLongitude = 0;

foreach ($centroids as $centroid) {
$centroidData = json_decode($centroid->centroid, true);
$totalLatitude += $centroidData['coordinates'][1];
$totalLongitude += $centroidData['coordinates'][0];
}

$averageLatitude = $totalLatitude / $centroidCount;
$averageLongitude = $totalLongitude / $centroidCount;

$centroidOfCentroids = json_encode([
'type' => 'Point',
'coordinates' => [$averageLongitude, $averageLatitude],
]);

return $centroidOfCentroids;
}

public function updateProjectCentroid(string $projectUuid)
{
try {
$centroid = $this->centroidOfProject($projectUuid);

if ($centroid === null) {
Log::warning("Invalid centroid for projectUuid: $projectUuid");
}

$centroidArray = json_decode($centroid, true);

$latitude = $centroidArray['coordinates'][1];
$longitude = $centroidArray['coordinates'][0];


Project::where('uuid', $projectUuid)
->update([
'lat' => $latitude,
'long' => $longitude,
]);


Log::info("Centroid updated for projectUuid: $projectUuid");

return 'Centroids updated successfully!';
} catch (\Exception $e) {
Log::error("Error updating centroid for projectUuid: $projectUuid");

return response()->json([
'message' => 'Error updating centroid',
'error' => $e->getMessage(),
], 500);
}

}

public static function getPolygonsBbox($polygonsIds)
{
$envelopes = PolygonGeometry::whereIn('uuid', $polygonsIds)
->selectRaw('ST_ASGEOJSON(ST_Envelope(geom)) as envelope')
->get();

$maxX = $maxY = PHP_INT_MIN;
$minX = $minY = PHP_INT_MAX;

foreach ($envelopes as $envelope) {
$geojson = json_decode($envelope->envelope);
$coordinates = $geojson->coordinates[0];

foreach ($coordinates as $point) {
$x = $point[0];
$y = $point[1];
$maxX = max($maxX, $x);
$minX = min($minX, $x);
$maxY = max($maxY, $y);
$minY = min($minY, $y);
}
}

$bboxCoordinates = [$minX, $minY, $maxX, $maxY];

return $bboxCoordinates;
}
}
35 changes: 35 additions & 0 deletions app/Http/Controllers/V2/Sites/SitePolygonDataController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace App\Http\Controllers\V2\Sites;

use App\Helpers\GeometryHelper;
use App\Http\Controllers\Controller;
use App\Models\V2\Sites\SitePolygon;
use Illuminate\Support\Facades\Log;

class SitePolygonDataController extends Controller
{
public function getSitePolygonData($site)
{
$sitePolygons = SitePolygon::where('site_id', $site)->get();
Log::info(json_encode($sitePolygons));

return $sitePolygons;
}

public function getBboxOfCompleteSite($site)
{
try {
$sitePolygons = SitePolygon::where('site_id', $site)->get();
$polygonsIds = $sitePolygons->pluck('poly_id');

$bboxCoordinates = GeometryHelper::getPolygonsBbox($polygonsIds);

return response()->json(['bbox' => $bboxCoordinates]);
} catch (\Exception $e) {
Log::error($e->getMessage());

return response()->json(['error' => 'An error occurred while fetching the bounding box coordinates'], 404);
}
}
};
136 changes: 104 additions & 32 deletions app/Http/Controllers/V2/Terrafund/TerrafundCreateGeometryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Http\Controllers\V2\Terrafund;

use App\Helpers\GeometryHelper;
use App\Http\Controllers\Controller;
use App\Models\V2\PolygonGeometry;
use App\Models\V2\Projects\Project;
Expand Down Expand Up @@ -117,14 +118,16 @@ public function insertGeojsonToDB(string $geojsonFilename)
Log::info($returnSite) ;
}
} elseif ($feature['geometry']['type'] === 'MultiPolygon') {
$generalProperties = $feature['properties'];
Log::info("general properties multipolygon", $generalProperties);
foreach ($feature['geometry']['coordinates'] as $polygon) {
$singlePolygon = ['type' => 'Polygon', 'coordinates' => $polygon];
if (! $this->validatePolygonBounds($singlePolygon)) {
return ['error' => 'Invalid polygon bounds'];
}
$data = $this->insertSinglePolygon($singlePolygon, $srid);
$uuids[] = $data['uuid'];
$returnSite = $this->insertSitePolygon($data['uuid'], $feature['properties'], $data['area']);
$returnSite = $this->insertSitePolygon($data['uuid'], $generalProperties, $data['area']);
if ($returnSite) {
Log::info($returnSite) ;
}
Expand Down Expand Up @@ -198,6 +201,7 @@ private function validateData(array $properties, array $fields): bool
private function insertSitePolygon(string $polygonUuid, array $properties, float $area)
{
try {
Log::info('Inserting site polygon', ['properties' => $properties, 'polygonUuid' => $polygonUuid]);
$fieldsToValidate = ['poly_name', 'plantstart', 'plantend', 'practice', 'target_sys', 'distr', 'num_trees'];
$SCHEMA_CRITERIA_ID = 13;
$validSchema = true;
Expand All @@ -214,22 +218,23 @@ private function insertSitePolygon(string $polygonUuid, array $properties, float

$sitePolygon = new SitePolygon();
$sitePolygon->project_id = $properties['project_id'] ?? null;
$sitePolygon->proj_name = $properties['proj_name'] ?? null;
$sitePolygon->org_name = $properties['org_name'] ?? null;
$sitePolygon->country = $properties['country'] ?? null;
// $sitePolygon->country = $properties['country'] ?? null;
$sitePolygon->poly_id = $polygonUuid ?? null;
$sitePolygon->poly_name = $properties['poly_name'] ?? null;
$sitePolygon->site_id = $properties['site_id'] ?? null;
$sitePolygon->site_name = $properties['site_name'] ?? null;
$sitePolygon->poly_label = $properties['poly_label'] ?? null;
// $sitePolygon->poly_label = $properties['poly_label'] ?? null;
$sitePolygon->plantstart = ! empty($properties['plantstart']) ? $properties['plantstart'] : null;
$sitePolygon->plantend = ! empty($properties['plantend']) ? $properties['plantend'] : null;
$sitePolygon->practice = $properties['practice'] ?? null;
$sitePolygon->target_sys = $properties['target_sys'] ?? null;
$sitePolygon->distr = $properties['distr'] ?? null;
$sitePolygon->num_trees = $properties['num_trees'] ?? null;
$sitePolygon->est_area = $area ?? null;
$sitePolygon->calc_area = $area ?? null;
$sitePolygon->save();
if ($sitePolygon->project_id) {
$geometryHelper = new GeometryHelper();
$geometryHelper -> updateProjectCentroid($sitePolygon->project_id);
}

return null;
} catch (\Exception $e) {
Expand Down Expand Up @@ -651,7 +656,7 @@ public function validateEstimatedArea(Request $request)
$projectId = $sitePolygon->project_id;

$sumEstArea = SitePolygon::where('project_id', $projectId)
->sum('est_area');
->sum('calc_area');

$project = Project::where('uuid', $projectId)
->first();
Expand All @@ -676,35 +681,102 @@ public function validateEstimatedArea(Request $request)
return response()->json(['valid' => $valid, 'sum_area_project' => $sumEstArea, 'total_area_project' => $totalHectaresRestoredGoal, 'insertionSuccess' => $insertionSuccess], 200);
}

public function getPolygonsAsGeoJSON()
public function getPolygonAsGeoJSON(Request $request)
{
$limit = 2;
$polygons = PolygonGeometry::select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->orderBy('created_at', 'desc')
->whereNotNull('geom')
->limit($limit)
->get();
$features = [];

foreach ($polygons as $polygon) {
$coordinates = json_decode($polygon->geojson)->coordinates;
try {
$uuid = $request->query('uuid');

$polygonGeometry = PolygonGeometry::where('uuid', $uuid)
->select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->first();
if (! $polygonGeometry) {
return response()->json(['message' => 'No polygon geometry found for the given UUID.'], 404);
}

$sitePolygon = SitePolygon::where('poly_id', $uuid)->first();
if (! $sitePolygon) {
return response()->json(['message' => 'No site polygon found for the given UUID.'], 404);
}

$properties = [];
$fieldsToValidate = [
'poly_name',
'plantstart',
'plantend',
'practice',
'target_sys',
'distr',
'num_trees',
'uuid',
'site_id'
];
foreach ($fieldsToValidate as $field) {
$properties[$field] = $sitePolygon->$field;
}

$propertiesJson = json_encode($properties);

$feature = [
'type' => 'Feature',
'geometry' => [
'type' => 'Polygon',
'coordinates' => $coordinates,
],
'properties' => [],
'type' => 'Feature',
'geometry' => json_decode($polygonGeometry->geojson),
'properties' => json_decode($propertiesJson),
];

$featureCollection = [
'type' => 'FeatureCollection',
'features' => [$feature],
];
$features[] = $feature;

return response()->json($featureCollection);
} catch (\Exception $e) {
return response()->json(['message' => 'Failed to generate GeoJSON.', 'error' => $e->getMessage()], 500);
}
$geojson = [
'type' => 'FeatureCollection',
'features' => $features,
];
}

// Return the GeoJSON data
return response()->json($geojson);
public function getAllPolygonsAsGeoJSON(Request $request)
{
try {
$siteUuid = $request->query('uuid');
$polygonsUuids = SitePolygon::where('site_id', $siteUuid)->pluck('poly_id');
$features = [];
foreach ($polygonsUuids as $polygonUuid) {
$feature = [];
$polygonGeometry = PolygonGeometry::where('uuid', $polygonUuid)
->select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->first();
if (! $polygonGeometry) {
return response()->json(['message' => 'No polygon geometry found for the given UUID.'], 404);
}

$sitePolygon = SitePolygon::where('poly_id', $polygonUuid)->first();
if (! $sitePolygon) {
return response()->json(['message' => 'No site polygon found for the given UUID.'], 404);
}

$properties = [];
$fieldsToValidate = ['poly_name', 'plantstart', 'plantend', 'practice', 'target_sys', 'distr', 'num_trees'];
foreach ($fieldsToValidate as $field) {
$properties[$field] = $sitePolygon->$field;
}

$propertiesJson = json_encode($properties);

$feature = [
'type' => 'Feature',
'geometry' => json_decode($polygonGeometry->geojson),
'properties' => json_decode($propertiesJson),
];
$features[] = $feature;
}
$featureCollection = [
'type' => 'FeatureCollection',
'features' => $features,
];

return response()->json($featureCollection);
} catch (\Exception $e) {
return response()->json(['message' => 'Failed to generate GeoJSON.', 'error' => $e->getMessage()], 500);
}
}

public function getAllCountryNames()
Expand Down
Loading
Loading