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-849,848] feat: add swagger definitions and modify endpoints to create and uplo… #189

Closed
wants to merge 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ class TerrafundCreateGeometryController extends Controller
public function processGeometry(string $uuid)
{
$geometry = PolygonGeometry::where('uuid', $uuid)
->select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->first();
->select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->first();

$geojson = $geometry->geojson;

Expand All @@ -35,14 +35,14 @@ public function processGeometry(string $uuid)
public function storeGeometry(Request $request)
{
$request->validate([
'geometry' => 'required|json',
'geometry' => 'required|json',
]);

$geometry = json_decode($request->input('geometry'));
$geom = DB::raw("ST_GeomFromGeoJSON('" . json_encode($geometry) . "')");

$polygonGeometry = PolygonGeometry::create([
'geom' => $geom,
'geom' => $geom,
]);

return response()->json(['uuid' => $polygonGeometry->uuid], 200);
Expand Down Expand Up @@ -85,7 +85,7 @@ private function insertSinglePolygon(array $geometry, int $srid)
$areaHectares = $areaSqMeters / 10000;

$polygonGeometry = PolygonGeometry::create([
'geom' => $geom,
'geom' => $geom,
]);

return ['uuid' => $polygonGeometry->uuid, 'id' => $polygonGeometry->id, 'area' => $areaHectares];
Expand All @@ -96,7 +96,7 @@ private function insertSinglePolygon(array $geometry, int $srid)
}
}

public function insertGeojsonToDB(string $geojsonFilename)
public function insertGeojsonToDB(string $geojsonFilename, ?string $site_id = null)
{
$srid = 4326;
$geojsonData = Storage::get("public/geojson_files/{$geojsonFilename}");
Expand All @@ -106,6 +106,9 @@ public function insertGeojsonToDB(string $geojsonFilename)
}
$uuids = [];
foreach ($geojson['features'] as $feature) {
if ($site_id !== null) {
$feature['properties']['site_id'] = $site_id;
}
if ($feature['geometry']['type'] === 'Polygon') {
if (! $this->validatePolygonBounds($feature['geometry'])) {
return ['error' => 'Invalid polygon bounds'];
Expand All @@ -114,7 +117,7 @@ public function insertGeojsonToDB(string $geojsonFilename)
$uuids[] = $data['uuid'];
$returnSite = $this->insertSitePolygon($data['uuid'], $feature['properties'], $data['area']);
if ($returnSite) {
Log::info($returnSite) ;
Log::info($returnSite);
}
} elseif ($feature['geometry']['type'] === 'MultiPolygon') {
foreach ($feature['geometry']['coordinates'] as $polygon) {
Expand All @@ -126,7 +129,7 @@ public function insertGeojsonToDB(string $geojsonFilename)
$uuids[] = $data['uuid'];
$returnSite = $this->insertSitePolygon($data['uuid'], $feature['properties'], $data['area']);
if ($returnSite) {
Log::info($returnSite) ;
Log::info($returnSite);
}
}
}
Expand Down Expand Up @@ -228,7 +231,7 @@ private function insertSitePolygon(string $polygonUuid, array $properties, float
$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();

return null;
Expand Down Expand Up @@ -261,6 +264,7 @@ public function getGeometryProperties(string $geojsonFilename)
public function uploadKMLFile(Request $request)
{
if ($request->hasFile('file')) {
$site_id = $request->input('uuid');
$kmlfile = $request->file('file');
$directory = storage_path('app/public/kml_files');
if (! file_exists($directory)) {
Expand All @@ -278,7 +282,7 @@ public function uploadKMLFile(Request $request)

return response()->json(['error' => 'Failed to convert KML to GeoJSON', 'message' => $process->getErrorOutput()], 500);
}
$uuid = $this->insertGeojsonToDB($geojsonFilename);
$uuid = $this->insertGeojsonToDB($geojsonFilename, $site_id);
if (isset($uuid['error'])) {
return response()->json(['error' => 'Geometry not inserted into DB', 'message' => $uuid['error']], 500);
}
Expand Down Expand Up @@ -310,6 +314,7 @@ public function uploadShapefile(Request $request)
{
Log::debug('Upload Shape file data', ['request' => $request->all()]);
if ($request->hasFile('file')) {
$site_id = $request->input('uuid');
$file = $request->file('file');
if ($file->getClientOriginalExtension() !== 'zip') {
return response()->json(['error' => 'Only ZIP files are allowed'], 400);
Expand All @@ -335,7 +340,7 @@ public function uploadShapefile(Request $request)

return response()->json(['error' => 'Failed to convert Shapefile to GeoJSON', 'message' => $process->getErrorOutput()], 500);
}
$uuid = $this->insertGeojsonToDB($geojsonFilename);
$uuid = $this->insertGeojsonToDB($geojsonFilename, $site_id);
if (isset($uuid['error'])) {
return response()->json(['error' => 'Geometry not inserted into DB', 'message' => $uuid['error']], 500);
}
Expand Down Expand Up @@ -463,11 +468,11 @@ public function validatePolygonSize(Request $request)
$insertionSuccess = $this->insertCriteriaSite($uuid, $SIZE_CRITERIA_ID, $valid);

return response()->json([
'area_hectares' => $areaSqMeters / 10000, // Convert to hectares
'area_sqmeters' => $areaSqMeters,
'geometry_id' => $geometry->id,
'insertion_success' => $insertionSuccess,
'valid' => $valid,
'area_hectares' => $areaSqMeters / 10000, // Convert to hectares
'area_sqmeters' => $areaSqMeters,
'geometry_id' => $geometry->id,
'insertion_success' => $insertionSuccess,
'valid' => $valid,
], 200);
}

Expand Down Expand Up @@ -504,8 +509,8 @@ public function checkWithinCountry(Request $request)
}

$intersectionData = WorldCountryGeneralized::where('iso', $countryIso)
->selectRaw('world_countries_generalized.country AS country, ST_Area(ST_Intersection(world_countries_generalized.geometry, (SELECT geom FROM polygon_geometry WHERE uuid = ?))) AS area', [$polygonUuid])
->first();
->selectRaw('world_countries_generalized.country AS country, ST_Area(ST_Intersection(world_countries_generalized.geometry, (SELECT geom FROM polygon_geometry WHERE uuid = ?))) AS area', [$polygonUuid])
->first();

$intersectionArea = $intersectionData->area;
$countryName = $intersectionData->country;
Expand Down Expand Up @@ -577,9 +582,9 @@ public function getCriteriaData(Request $request)
$criteriaId = $criteria->criteria_id;
$valid = CriteriaSite::where(['polygon_id' => $uuid, 'criteria_id' => $criteriaId])->select('valid')->first()?->valid;
$criteriaList[] = [
'criteria_id' => $criteriaId,
'latest_created_at' => $criteria->latest_created_at,
'valid' => $valid,
'criteria_id' => $criteriaId,
'latest_created_at' => $criteria->latest_created_at,
'valid' => $valid,
];
}

Expand All @@ -589,14 +594,15 @@ public function getCriteriaData(Request $request)
public function uploadGeoJSONFile(Request $request)
{
if ($request->hasFile('file')) {
$site_id = $request->input('uuid');
$file = $request->file('file');
$directory = storage_path('app/public/geojson_files');
if (! file_exists($directory)) {
mkdir($directory, 0755, true);
}
$filename = uniqid('geojson_file_') . '.' . $file->getClientOriginalExtension();
$file->move($directory, $filename);
$uuid = $this->insertGeojsonToDB($filename);
$uuid = $this->insertGeojsonToDB($filename, $site_id);
if (is_array($uuid) && isset($uuid['error'])) {
return response()->json(['error' => 'Failed to insert GeoJSON data into the database', 'message' => $uuid['error']], 500);
}
Expand All @@ -611,24 +617,24 @@ public function validateOverlapping(Request $request)
{
$uuid = $request->input('uuid');
$sitePolygon = SitePolygon::where('poly_id', $uuid)
->first();
->first();

if (! $sitePolygon) {
return response()->json(['error' => 'Site polygon not found for the given polygon ID'], 200);
}

$projectId = $sitePolygon->project_id;
if(! $projectId) {
if (! $projectId) {
return response()->json(['error' => 'Project ID not found for the given polygon ID'], 200);
}
$relatedPolyIds = SitePolygon::where('project_id', $projectId)
->where('poly_id', '!=', $uuid)
->pluck('poly_id');
->where('poly_id', '!=', $uuid)
->pluck('poly_id');

$intersects = PolygonGeometry::whereIn('uuid', $relatedPolyIds)
->selectRaw('ST_Intersects(geom, (SELECT geom FROM polygon_geometry WHERE uuid = ?)) as intersects', [$uuid])
->get()
->pluck('intersects');
->selectRaw('ST_Intersects(geom, (SELECT geom FROM polygon_geometry WHERE uuid = ?)) as intersects', [$uuid])
->get()
->pluck('intersects');

$intersects = in_array(1, $intersects->toArray());
$valid = ! $intersects;
Expand All @@ -642,7 +648,7 @@ public function validateEstimatedArea(Request $request)
{
$uuid = $request->input('uuid');
$sitePolygon = SitePolygon::where('poly_id', $uuid)
->first();
->first();

if (! $sitePolygon) {
return response()->json(['error' => 'Site polygon not found for the given polygon ID'], 200);
Expand All @@ -651,10 +657,10 @@ 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();
->first();

if (! $project) {
return response()->json(['error' => 'Project not found for the given project ID', 'projectId' => $projectId], 200);
Expand All @@ -680,27 +686,27 @@ public function getPolygonsAsGeoJSON()
{
$limit = 2;
$polygons = PolygonGeometry::select(DB::raw('ST_AsGeoJSON(geom) AS geojson'))
->orderBy('created_at', 'desc')
->whereNotNull('geom')
->limit($limit)
->get();
->orderBy('created_at', 'desc')
->whereNotNull('geom')
->limit($limit)
->get();
$features = [];

foreach ($polygons as $polygon) {
$coordinates = json_decode($polygon->geojson)->coordinates;
$feature = [
'type' => 'Feature',
'geometry' => [
'type' => 'Polygon',
'coordinates' => $coordinates,
],
'properties' => [],
'type' => 'Feature',
'geometry' => [
'type' => 'Polygon',
'coordinates' => $coordinates,
],
'properties' => [],
];
$features[] = $feature;
}
$geojson = [
'type' => 'FeatureCollection',
'features' => $features,
'type' => 'FeatureCollection',
'features' => $features,
];

// Return the GeoJSON data
Expand All @@ -710,9 +716,9 @@ public function getPolygonsAsGeoJSON()
public function getAllCountryNames()
{
$countries = WorldCountryGeneralized::select('country')
->distinct()
->orderBy('country')
->pluck('country');
->distinct()
->orderBy('country')
->pluck('country');

return response()->json(['countries' => $countries]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function updateSitePolygon(string $uuid, Request $request)
'practice' => 'nullable|string',
'distr' => 'nullable|string',
'num_trees' => 'nullable|integer',
'est_area' => 'nullable|numeric',
'calc_area' => 'nullable|numeric',
'target_sys' => 'nullable|string',
]);

Expand Down Expand Up @@ -108,7 +108,7 @@ public function createSitePolygon(string $uuid, Request $request)
'practice' => $validatedData['practice'],
'distr' => $validatedData['distr'],
'num_trees' => $validatedData['num_trees'],
'est_area' => $areaHectares, // Assign the calculated area
'calc_area' => $areaHectares, // Assign the calculated area
'target_sys' => $validatedData['target_sys'],
]);
$sitePolygon->poly_id = $uuid;
Expand All @@ -121,4 +121,59 @@ public function createSitePolygon(string $uuid, Request $request)
return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
}
}

public function createSiteForPolygon(string $uuid, string $siteUuid, Request $request)
{
try {
if ($request->getContent() === '{}') {
$validatedData = [
'poly_name' => null,
'plantstart' => null,
'plantend' => null,
'practice' => null,
'distr' => null,
'num_trees' => null,
'target_sys' => null,
];
} else {
$validatedData = $request->validate([
'poly_name' => 'nullable|string',
'plantstart' => 'nullable|date',
'plantend' => 'nullable|date',
'practice' => 'nullable|string',
'distr' => 'nullable|string',
'num_trees' => 'nullable|integer',
'target_sys' => 'nullable|string',
]);
}
$polygonGeometry = PolygonGeometry::where('uuid', $uuid)->first();
if (! $polygonGeometry) {
return response()->json(['message' => 'No polygon geometry found for the given UUID.'], 404);
}
$areaSqDegrees = DB::selectOne('SELECT ST_Area(geom) AS area FROM polygon_geometry WHERE uuid = :uuid', ['uuid' => $uuid])->area;
$latitude = DB::selectOne('SELECT ST_Y(ST_Centroid(geom)) AS latitude FROM polygon_geometry WHERE uuid = :uuid', ['uuid' => $uuid])->latitude;
$areaSqMeters = $areaSqDegrees * pow(111320 * cos(deg2rad($latitude)), 2);
$areaHectares = $areaSqMeters / 10000;
$sitePolygon = new SitePolygon([
'poly_name' => $validatedData['poly_name'],
'plantstart' => $validatedData['plantstart'],
'plantend' => $validatedData['plantend'],
'practice' => $validatedData['practice'],
'distr' => $validatedData['distr'],
'num_trees' => $validatedData['num_trees'],
'calc_area' => $areaHectares,
'target_sys' => $validatedData['target_sys'],
'status' => 'Submitted',
'site_id' => $siteUuid,
]);
$sitePolygon->poly_id = $uuid;
$sitePolygon->uuid = Str::uuid();
$sitePolygon->save();

return response()->json(['message' => 'Site polygon created successfully', 'uuid' => $sitePolygon, 'area' => $areaHectares], 201);
} catch (\Exception $e) {
// Handle other exceptions
return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
}
}
}
8 changes: 2 additions & 6 deletions app/Models/V2/Sites/SitePolygon.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,18 @@ class SitePolygon extends Model
protected $table = 'site_polygon';

protected $fillable = [
'proj_name',
'org_name',
'poly_id',
'poly_name',
'site_id',
'site_name',
'project_id',
'poly_label',
'plantstart',
'plantend',
'practice',
'target_sys',
'distr',
'num_trees',
'est_area',
'country',
'calc_area',
'status',
];

public function polygonGeometry()
Expand Down
Loading
Loading