This commit is contained in:
2026-11-11 11:53:41 +02:00
parent 2209b83820
commit 1b8b9f414a
32 changed files with 36011 additions and 43 deletions
+47
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
@@ -12,6 +13,52 @@ final class InvestmentGeography
{
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
/** Public declared coverage; a territory join never multiplies the opportunity total.
*
* @return array{opportunities: int, provinces: int}
*/
public function opportunityStatistics(): array
{
$opportunities = Opportunity::published()->select(['id', 'primary_territory_id', 'province', 'geography_scope'])->toBase();
$references = $this->publicReferences()->select(['id', 'parent_id', 'name', 'location_type']);
$result = DB::selectOne('WITH RECURSIVE
published_opportunities AS ('.$opportunities->toSql().'),
public_references AS ('.$references->toSql().'),
declared_locations AS (
SELECT id AS opportunity_id, primary_territory_id AS location_id
FROM published_opportunities WHERE primary_territory_id IS NOT NULL
UNION
SELECT l.opportunity_id, l.geo_location_id FROM opportunity_locations l
JOIN published_opportunities o ON o.id=l.opportunity_id
),
territory_paths AS (
SELECT d.opportunity_id, d.location_id, g.id, g.parent_id, g.name, g.location_type,
ARRAY[g.id] AS visited, 1 AS depth
FROM declared_locations d JOIN public_references g ON g.id=d.location_id
UNION ALL
SELECT t.opportunity_id, t.location_id, g.id, g.parent_id, g.name, g.location_type,
t.visited||g.id, t.depth+1
FROM territory_paths t JOIN public_references g ON g.id=t.parent_id
WHERE t.depth<5 AND NOT g.id=ANY(t.visited)
),
covered_provinces AS (
SELECT t.name FROM territory_paths t WHERE t.location_type=\'province\'
AND EXISTS (SELECT 1 FROM territory_paths root
WHERE root.opportunity_id=t.opportunity_id AND root.location_id=t.location_id AND root.parent_id IS NULL)
UNION
SELECT g.name FROM public_references g JOIN published_opportunities o
ON lower(btrim(o.province))=lower(btrim(g.name))
WHERE g.location_type=\'province\' AND o.primary_territory_id IS NULL
AND COALESCE(o.geography_scope, \'unspecified\')<>\'national\'
AND NOT EXISTS (SELECT 1 FROM opportunity_locations l WHERE l.opportunity_id=o.id)
)
SELECT (SELECT count(DISTINCT id) FROM published_opportunities) AS opportunities,
(SELECT count(DISTINCT lower(btrim(name))) FROM covered_provinces) AS provinces',
[...$opportunities->getBindings(), ...$references->getBindings()]);
return ['opportunities' => (int) $result->opportunities, 'provinces' => (int) $result->provinces];
}
/** Resolve an old province-name search only when the public register has exactly one match.
* @param array<array-key, mixed> $filters
* @return array<array-key, mixed>