Skip to content
Open
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
33 changes: 33 additions & 0 deletions src/backend/app/Models/Cluster.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Support\Carbon;

/**
Expand All @@ -22,6 +23,7 @@
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Collection<int, City> $cities
* @property-read GeographicalInformation|null $location
* @property-read User|null $manager
* @property-read Collection<int, MiniGrid> $miniGrids
*/
Expand All @@ -31,6 +33,12 @@ class Cluster extends BaseModel implements ITargetAssignable {

public const RELATION_NAME = 'cluster';

/** @var array<int, string> */
protected $hidden = ['location'];

/** @var array<int, string> */
protected $appends = ['geo_json'];

/** @return BelongsTo<User, $this> */
public function manager(): BelongsTo {
return $this->belongsTo(User::class);
Expand All @@ -46,6 +54,31 @@ public function miniGrids(): HasMany {
return $this->hasMany(MiniGrid::class);
}

/** @return MorphOne<GeographicalInformation, $this> */
public function location(): MorphOne {
return $this->morphOne(GeographicalInformation::class, 'owner');
}

public function getGeoJsonAttribute(): mixed {
$location = $this->relationLoaded('location')
? $this->location
: $this->location()->first();

if ($location?->geo_json !== null) {
return $location->geo_json;
}

$legacyGeoJson = $this->getRawOriginal('geo_json');

if ($legacyGeoJson === null || $legacyGeoJson === '') {
return null;
}

return is_string($legacyGeoJson)
? json_decode($legacyGeoJson)
: $legacyGeoJson;
}

protected function casts(): array {
return [
'geo_json' => 'object',
Expand Down
7 changes: 7 additions & 0 deletions src/backend/app/Models/GeographicalInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* @property int $owner_id
* @property string $owner_type
* @property string $points
* @property object|null $geo_json
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read Model $owner
Expand All @@ -32,4 +33,10 @@ class GeographicalInformation extends BaseModel {
public function owner(): MorphTo {
return $this->morphTo();
}

protected function casts(): array {
return [
'geo_json' => 'object',
];
}
}
37 changes: 30 additions & 7 deletions src/backend/app/Services/ClusterService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use App\Services\Interfaces\IBaseService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

/**
* @implements IBaseService<Cluster>
Expand Down Expand Up @@ -35,15 +37,17 @@ public function getClusterWithComputedData(
}

public function getClusterCities(int $clusterId): ?Cluster {
return Cluster::query()->with('cities')->find($clusterId);
return Cluster::query()->with(['cities', 'location'])->find($clusterId);
}

public function getClusterMiniGrids(int $clusterId): ?Cluster {
return Cluster::query()->with('miniGrids')->find($clusterId);
return Cluster::query()->with(['miniGrids', 'location'])->find($clusterId);
}

public function getGeoLocationById(int $clusterId): mixed {
return $this->cluster->newQuery()->select('geo_json')->find($clusterId)->geo_json;
$cluster = $this->cluster->newQuery()->with('location')->findOrFail($clusterId);

return $cluster->geo_json;
}

/**
Expand All @@ -64,25 +68,43 @@ public function getDateRangeFromRequest(?string $startDate, ?string $endDate): a
}

public function getById(int $clusterId): Cluster {
return $this->cluster->newQuery()->with(['miniGrids.location', 'cities'])->find($clusterId);
return $this->cluster->newQuery()->with(['miniGrids.location', 'cities', 'location'])->find($clusterId);
}

/**
* @param array<string, mixed> $clusterData
*/
public function create(array $clusterData): Cluster {
return $this->cluster->newQuery()->create($clusterData);
return DB::connection('tenant')->transaction(function () use ($clusterData): Cluster {
$geoJson = $clusterData['geo_json'] ?? null;

// Keep legacy write only while clusters.geo_json exists.
if (! Schema::connection('tenant')->hasColumn('clusters', 'geo_json')) {
unset($clusterData['geo_json']);
}

$cluster = $this->cluster->newQuery()->create($clusterData);

if ($geoJson !== null) {
$cluster->location()->create([
'points' => '',
'geo_json' => $geoJson,
]);
}

return $cluster->fresh('location');
});
}

/**
* @return Collection<int, Cluster>|LengthAwarePaginator<int, Cluster>
*/
public function getAll(?int $limit = null): Collection|LengthAwarePaginator {
if ($limit !== null) {
return $this->cluster->newQuery()->with('miniGrids')->limit($limit)->get();
return $this->cluster->newQuery()->with(['miniGrids', 'location'])->limit($limit)->get();
}

return $this->cluster->newQuery()->with('miniGrids')->get();
return $this->cluster->newQuery()->with(['miniGrids', 'location'])->get();
}

/**
Expand All @@ -104,6 +126,7 @@ public function getAllForExport(): Collection {
'miniGrids',
'cities',
'manager',
'location',
])->get();
}
}
66 changes: 47 additions & 19 deletions src/backend/database/factories/ClusterFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Models\Cluster;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Schema;

/** @extends Factory<Cluster> */
class ClusterFactory extends Factory {
Expand All @@ -15,6 +16,19 @@ public function __construct(
$this->faker->addProvider(new \Faker\Provider\en_NG\Address($this->faker));
}

public function configure(): static {
return $this->afterCreating(function (Cluster $cluster): void {
if ($cluster->location()->exists()) {
return;
}

$cluster->location()->create([
'points' => '',
'geo_json' => $this->buildDefaultGeoJson($cluster->name),
]);
});
}

/**
* Define the model's default state.
*
Expand All @@ -24,27 +38,41 @@ public function definition(): array {
// @phpstan-ignore-next-line varTag.unresolvableType
/** @var \Faker\Generator&\Faker\Provider\en_NG\Address */
$faker = $this->faker;
$clusterName = 'Cluster '.$faker->county();
$geoJson = $this->buildDefaultGeoJson($clusterName);

return [
'name' => $clusterName,
// Kept for backward compatibility until tenant data migration removes the column.
...($this->shouldPersistLegacyGeoJsonOnCluster() ? ['geo_json' => $geoJson] : []),
];
}

/**
* @return array<string, mixed>
*/
private function buildDefaultGeoJson(string $clusterName): array {
return [
'name' => 'Cluster '.$faker->county(),
'geo_json' => json_decode('{
"type": "Feature",
"properties": {
"name": "Cluster '.$faker->county().'"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[34.09735878800838, -1.0021831137920607],
[34.08104951280351, -1.0037278294879668],
[34.08001945331692, -0.9961758791705448],
[34.079332746992485, -0.9831315606570004],
[34.08036280647911, -0.9745497443261169],
[34.09890387723834, -0.9889671831741885],
[34.09735878800838, -1.0021831137920607]
]
}
}'),
'type' => 'Feature',
'properties' => [
'name' => $clusterName,
],
'geometry' => [
'type' => 'Polygon',
'coordinates' => [[
[34.09735878800838, -1.0021831137920607],
[34.08104951280351, -1.0037278294879668],
[34.08001945331692, -0.9961758791705448],
[34.079332746992485, -0.9831315606570004],
[34.08036280647911, -0.9745497443261169],
[34.09890387723834, -0.9889671831741885],
[34.09735878800838, -1.0021831137920607],
]],
],
];
}

private function shouldPersistLegacyGeoJsonOnCluster(): bool {
return Schema::connection('tenant')->hasColumn('clusters', 'geo_json');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
public function up(): void {
$schema = Schema::connection('tenant');

if (! $schema->hasColumn('geographical_informations', 'geo_json')) {
$schema->table('geographical_informations', function (Blueprint $table): void {
$table->json('geo_json')->nullable()->after('points');
});
}

if (! $schema->hasColumn('clusters', 'geo_json')) {
return;
}

$clusters = DB::connection('tenant')
->table('clusters')
->select(['id', 'geo_json'])
->whereNotNull('geo_json')
->get();

foreach ($clusters as $cluster) {
$existingGeo = DB::connection('tenant')
->table('geographical_informations')
->where('owner_type', 'cluster')
->where('owner_id', $cluster->id)
->first();

if ($existingGeo) {
DB::connection('tenant')
->table('geographical_informations')
->where('id', $existingGeo->id)
->update([
'geo_json' => $cluster->geo_json,
'updated_at' => now(),
]);

continue;
}

DB::connection('tenant')
->table('geographical_informations')
->insert([
'owner_id' => $cluster->id,
'owner_type' => 'cluster',
'points' => '',
'geo_json' => $cluster->geo_json,
'created_at' => now(),
'updated_at' => now(),
]);
}

$schema->table('clusters', function (Blueprint $table): void {
$table->dropColumn('geo_json');
});
}

public function down(): void {
$schema = Schema::connection('tenant');

if (! $schema->hasColumn('clusters', 'geo_json')) {
$schema->table('clusters', function (Blueprint $table): void {
$table->json('geo_json')->nullable()->after('manager_id');
});
}

if (! $schema->hasColumn('geographical_informations', 'geo_json')) {
return;
}

$clusterGeo = DB::connection('tenant')
->table('geographical_informations')
->select(['owner_id', 'geo_json'])
->where('owner_type', 'cluster')
->whereNotNull('geo_json')
->get();

foreach ($clusterGeo as $geoInfo) {
DB::connection('tenant')
->table('clusters')
->where('id', $geoInfo->owner_id)
->update([
'geo_json' => $geoInfo->geo_json,
'updated_at' => now(),
]);
}

$schema->table('geographical_informations', function (Blueprint $table): void {
$table->dropColumn('geo_json');
});
}
};
Loading