Compare commits

...
100 changed files with 8484 additions and 271 deletions
@@ -0,0 +1,45 @@
<?php
namespace App\Console\Commands;
use App\Services\TerritorialCsvAudit;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Throwable;
class AuditTerritorialCsv extends Command
{
protected $signature = 'geo:audit-csv {path : CSV UTF-8 do contrato INE}';
protected $description = 'Arquivar e validar um CSV territorial sem alterar o cadastro';
public function handle(TerritorialCsvAudit $audit): int
{
$path = (string) $this->argument('path');
if (! is_file($path) || ! is_readable($path) || filesize($path) > 20 * 1024 * 1024) {
$this->error('CSV inacessível ou superior a 20 MiB.');
return self::FAILURE;
}
$directory = storage_path('app/private/geo-csv-audits/'.Str::uuid());
File::ensureDirectoryExists($directory, 0700);
try {
if (! copy($path, $directory.'/original.csv')) {
throw new \RuntimeException('Não foi possível arquivar o original.');
}
$codes = DB::table('geo_locations as p')->join('geo_locations as c', 'p.parent_id', '=', 'c.id')
->where('p.location_type', 'province')->where('c.location_type', 'country')->where('c.code', '508')
->whereNull('p.deleted_at')->whereNull('c.deleted_at')->pluck('p.code')->map(fn ($code) => (string) $code)->all();
$report = $audit->inspect($directory.'/original.csv', array_values($codes));
} catch (Throwable $exception) {
$report = ['status' => 'rejected', 'error' => $exception->getMessage()];
}
File::put($directory.'/report.json', json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
$this->info('Relatório privado: '.$directory.'/report.json');
$this->info('Nenhum território foi criado ou aprovado.');
return $report['status'] === 'rejected' ? self::FAILURE : self::SUCCESS;
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Http\Controllers;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake;
use App\Services\ExistingBusinessObjects;
use App\Services\ExistingBusinessVerification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Inertia\Inertia;
use Inertia\Response;
class ExistingBusinessController extends Controller
{
public function index(Request $request): Response|JsonResponse
{
$management = $request->is('management/*', 'api/v1/existing-business/review*');
$query = ExistingBusiness::query();
if ($management) {
Gate::authorize('reviewQueue', ExistingBusiness::class);
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', ['submitted', 'in_review', 'needs_information']);
} else {
$query->where('owner_user_id', $request->user()->id);
}
$props = ['records' => $query->orderByDesc('updated_at')->paginate(20)->through(fn ($row) => $this->record($row)),
'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES];
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props);
}
public function show(Request $request, string $id): Response|JsonResponse
{
$business = ExistingBusiness::findOrFail($id);
Gate::authorize('view', $business);
$props = ['record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
'modalities' => ExistingBusinessDrafts::MODALITIES,
'objectKinds' => ExistingBusinessObjects::KINDS,
'verificationChecks' => ExistingBusinessVerification::CHECKS,
'verifications' => app(ExistingBusinessVerification::class)->findings($business),
'objects' => ExistingBusinessObject::where('business_id', $id)->orderBy('created_at')->get()->map(fn ($object) => [
...$object->only(['id', 'kind', 'verification_status']), 'payload' => $object->payload]),
'history' => DB::table('existing_business_revisions')->where('business_id', $id)->orderByDesc('version_no')->limit(50)
->get(['version_no', 'action', 'created_at', 'reason'])->map(fn ($row) => ['version_no' => $row->version_no,
'action' => $row->action, 'created_at' => $row->created_at, 'note' => Crypt::decryptString($row->reason)])];
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/business', $props);
}
public function save(Request $request, ExistingBusinessDrafts $drafts, ?string $id = null): JsonResponse
{
$business = $drafts->save($request->user(), $request->all(), $id);
return response()->json($this->record($business), $id ? 200 : 201);
}
public function transition(Request $request, ExistingBusinessIntake $intake, string $id): JsonResponse
{
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'action' => ['required', 'string'],
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean']]);
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false));
return response()->json($this->record($business));
}
public function verify(Request $request, ExistingBusinessVerification $verification, string $id): JsonResponse
{
return response()->json($this->record($verification->save($request->user(), $id, $request->all())));
}
public function saveObject(Request $request, ExistingBusinessObjects $objects, string $id, ?string $object = null): JsonResponse
{
$saved = $objects->save($request->user(), $id, $request->all(), $object);
return response()->json(['id' => $saved->id, 'verification_status' => 'pending',
'version_no' => ExistingBusiness::findOrFail($id)->version_no], $object ? 200 : 201);
}
/** @return array<string,mixed> */
private function record(ExistingBusiness $business): array
{
return [...$business->only(['id', 'code', 'modality', 'status', 'classification', 'version_no']), 'payload' => $business->payload];
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class InvestmentCoordinatesController extends Controller
{
public function show(int $id): JsonResponse
{
Opportunity::findOrFail($id);
$point = DB::table('geo_locations as g')->join('geo_geometries as s', 's.geo_location_id', '=', 'g.id')
->where('g.source_system', 'investment-site-editor')->where('g.external_id', (string) $id)->whereNull('g.deleted_at')->whereNull('s.deleted_at')
->first(['s.version_no', 's.properties', DB::raw('ST_X(s.geom) as longitude'), DB::raw('ST_Y(s.geom) as latitude')]);
return response()->json(['version' => $point->version_no ?? 0, 'latitude' => $point?->latitude, 'longitude' => $point?->longitude,
'source_reference' => $point ? (json_decode($point->properties, true)['source_reference'] ?? '') : '']);
}
public function save(Request $request, int $id): JsonResponse
{
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'latitude' => ['required', 'numeric', 'between:-90,90'],
'longitude' => ['required', 'numeric', 'between:-180,180'], 'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'confirmed_site' => ['accepted']]);
$version = DB::transaction(function () use ($data, $id, $request) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$opportunity = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
$location = DB::table('geo_locations')->where('source_system', 'investment-site-editor')->where('external_id', (string) $id)->first();
abort_if($location && $location->deleted_at, 409, 'Local arquivado; requer reconciliação.');
abort_if($location && $location->data_classification !== 'public', 409, 'Local retirado de divulgação; requer revisão da classificação.');
$geometry = $location ? DB::table('geo_geometries')->where('geo_location_id', $location->id)->where('geometry_type', 'point')->first() : null;
abort_if($geometry && $geometry->deleted_at, 409, 'Geometria arquivada; requer reconciliação.');
abort_if($geometry && $geometry->data_classification !== 'public', 409, 'Geometria retirada de divulgação; requer revisão da classificação.');
abort_unless((int) ($geometry->version_no ?? 0) === $data['version'], 409, 'Coordenadas alteradas. Recarregue.');
$locationId = $location->id ?? (string) Str::uuid();
if (! $location) {
DB::table('geo_locations')->insert(['id' => $locationId, 'source_system' => 'investment-site-editor', 'external_id' => (string) $id,
'name' => $opportunity->title, 'location_type' => 'site', 'code' => 'SITE-OPP-'.$id, 'data_classification' => 'public', 'parent_id' => $opportunity->primary_territory_id]);
}
$version = $data['version'] + 1;
$geometryId = $geometry->id ?? (string) Str::uuid();
DB::statement("INSERT INTO geo_geometries(id,geo_location_id,geometry_type,geom,data_classification,version_no,properties)
VALUES(?,?,'point',ST_SetSRID(ST_MakePoint(?,?),4326),'public',?,?::jsonb)
ON CONFLICT(id) DO UPDATE SET geom=EXCLUDED.geom,version_no=EXCLUDED.version_no,properties=EXCLUDED.properties,updated_at=now()",
[$geometryId, $locationId, $data['longitude'], $data['latitude'], $version, json_encode(['source_reference' => $data['source_reference'], 'accuracy' => 'site_confirmed_by_editor'], JSON_THROW_ON_ERROR)]);
DB::table('opportunity_locations')->updateOrInsert(['opportunity_id' => $id, 'geo_location_id' => $locationId], []);
DB::table('audit_events')->insert(['source_system' => 'investment-coordinates', 'entity_type' => 'geo_geometries', 'entity_id' => $geometryId,
'actor_user_id' => $request->user()->id, 'action' => 'site_coordinates_saved',
'before_data' => $geometry ? json_encode(['version' => $geometry->version_no, 'geometry_hex' => $geometry->geom], JSON_THROW_ON_ERROR) : null,
'after_data' => json_encode(['opportunity_id' => $id, 'version' => $version, 'latitude' => $data['latitude'], 'longitude' => $data['longitude'], 'source_sha256' => hash('sha256', $data['source_reference'])], JSON_THROW_ON_ERROR)]);
return $version;
});
return response()->json(['version' => $version]);
}
}
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\InvestmentZones;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
@@ -24,6 +25,7 @@ class InvestmentDiscoveryController extends Controller
}
return Inertia::render('investment/catalogue', ['filters' => $filters, 'references' => $catalogue->references(),
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
'territorial' => $this->territorial($filters)]);
@@ -36,6 +38,15 @@ class InvestmentDiscoveryController extends Controller
private function territorial(array $filters): Collection
{
$query = InvestmentPortfolioController::visible();
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->where(function ($query) use ($ids) {
foreach (['project_id' => 'projects', 'cluster_id' => 'economic_clusters', 'corridor_id' => 'development_corridors'] as $foreign => $table) {
$query->orWhereIn($foreign, DB::table($table)->whereNull('deleted_at')->whereIn('primary_territory_id', $ids)->select('id'));
}
});
}
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
return $query->whereRaw('false')->get();
}
@@ -7,6 +7,7 @@ use App\Models\EconomicCluster;
use App\Models\InvestmentGap;
use App\Models\Project;
use App\Models\ValueChain;
use App\Services\InvestmentGeography;
use App\Services\PortalAudit;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -74,7 +75,19 @@ class InvestmentStructureController extends Controller
} else {
$rules['sector'] = ['required', 'string', 'max:200'];
}
PortalAudit::save($record, $request->validate($rules), $request->user()->id);
if (! $id) {
foreach (InvestmentGeography::FIELDS as $field => $type) {
$rules[$field] = ['nullable', 'uuid'];
}
}
$data = $request->validate($rules);
if (! $id && $request->has('province_id')) {
$path = app(InvestmentGeography::class)->selection($data);
$data = array_diff_key($data, InvestmentGeography::FIELDS);
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
$data['territory_version'] = $path === [] ? 0 : 1;
}
PortalAudit::save($record, $data, $request->user()->id);
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Registo guardado.');
}
@@ -0,0 +1,103 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentZones;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class InvestmentTerritoryController extends Controller
{
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
public function subjects(Request $request): JsonResponse
{
$data = $request->validate(['kind' => ['required', 'in:'.implode(',', array_keys(self::TABLES))], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$column = $data['kind'] === 'opportunities' ? 'title' : 'name';
$query = DB::table(self::TABLES[$data['kind']])->whereNull('deleted_at');
if (! empty($data['q'])) {
$query->whereRaw($column.' ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
}
return response()->json($query->orderBy($column)->orderBy('id')->paginate(50, ['id', $column.' as name']));
}
public function options(Request $request): JsonResponse
{
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type'])
->whereIn('data_classification', ['public', 'internal']);
if ($data['type'] !== 'province') {
$query->where('parent_id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000');
}
if (! empty($data['q'])) {
$query->whereRaw('name ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
}
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type']));
}
public function show(string $kind, string $id): JsonResponse
{
$table = self::TABLES[$kind] ?? abort(404);
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->first();
abort_unless($record !== null, 404);
$path = [];
$current = $record->primary_territory_id;
for ($i = 0; $current && $i < 5; $i++) {
$location = DB::table('geo_locations')->where('id', $current)->first(['id', 'name', 'parent_id', 'location_type', 'deleted_at']);
if (! $location) {
break;
}
$path[] = $location;
$current = $location->parent_id;
}
return response()->json(['version' => $record->territory_version, 'path' => $path]);
}
public function save(Request $request, string $kind, string $id): JsonResponse
{
$table = self::TABLES[$kind] ?? abort(404);
if ($kind === 'zones') {
abort_unless($request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
}
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'path' => ['present', 'array', 'max:4'], 'path.*' => ['required', 'uuid', 'distinct']]);
$version = DB::transaction(function () use ($request, $table, $id, $data) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($record !== null, 404);
abort_unless((int) $record->territory_version === $data['version'], 409, 'Localização alterada. Recarregue a ficha.');
$parent = null;
$names = [];
foreach (array_values($data['path']) as $index => $locationId) {
$location = DB::table('geo_locations')->where('id', $locationId)->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])->first();
if (! $location || $location->location_type !== ['province', 'district', 'admin_post', 'locality'][$index] || ($index > 0 && $location->parent_id !== $parent)) {
throw ValidationException::withMessages(['path' => 'Seleccione uma hierarquia territorial coerente e activa.']);
}
$parent = $locationId;
$names[] = $location->name;
}
$version = $data['version'] + 1;
$changes = ['primary_territory_id' => $parent, 'territory_version' => $version, 'updated_at' => now()];
if (in_array($table, ['opportunities', 'investment_zones'], true)) {
$changes['province'] = $names[0] ?? null;
$changes['district'] = $names[1] ?? null;
}
if ($table === 'investment_zones') {
app(InvestmentZones::class)->save($id, [...$changes, 'version_no' => $record->version_no], $request->user()->id);
} else {
DB::table($table)->where('id', $id)->update($changes);
}
DB::table('audit_events')->insert(['source_system' => 'investment-territory', 'entity_type' => $table,
'actor_user_id' => $request->user()->id, 'action' => 'primary_territory_saved',
'after_data' => json_encode(['record_id' => $id, 'territory_id' => $parent, 'version' => $version], JSON_THROW_ON_ERROR)]);
return $version;
});
return response()->json(['version' => $version]);
}
}
@@ -6,6 +6,7 @@ use App\Models\InvestmentDossier;
use App\Models\InvestmentZone;
use App\Models\Opportunity;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\InvestmentZoneAccess;
use App\Services\InvestmentZones;
use Illuminate\Http\JsonResponse;
@@ -49,13 +50,18 @@ class InvestmentZoneController extends Controller
public function index(Request $request, InvestmentZones $zones): Response|JsonResponse
{
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1']]);
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
$management = $request->is('management/*', 'api/v2/investment/admin/*');
$query = $management ? InvestmentZone::query() : $zones->visible();
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$query->whereIn('primary_territory_id', app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
}
$rows = $query->when($filters['category'] ?? null, fn ($q, $v) => $q->where('category', $v))
->when($filters['q'] ?? null, fn ($q, $v) => $q->where(fn ($q) => $q->where('name', 'ilike', '%'.$v.'%')->orWhere('code', 'ilike', '%'.$v.'%')))
->orderBy('name')->orderBy('id')->paginate(12, $management ? ['*'] : ['id', 'code', 'name', 'name_en', 'category', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'])->withQueryString();
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management];
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path];
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
}
@@ -70,6 +76,15 @@ class InvestmentZoneController extends Controller
'operator_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
'legal_source_id' => ['nullable', 'uuid', 'exists:investment_legal_sources,id']]);
if (! $id && $request->has('province_id')) {
$geo = $request->validate(['province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
$path = app(InvestmentGeography::class)->selection($geo);
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
$data['territory_version'] = $path === [] ? 0 : 1;
$data['province'] = $path[0]->name ?? null;
$data['district'] = $path[1]->name ?? null;
}
return response()->json($zones->save($id, $data, $request->user()->id), $id ? 200 : 201);
}
@@ -6,6 +6,7 @@ use App\Models\InterestRequest;
use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\InvestmentGeography;
use App\Services\InvestmentWorkspace;
use App\Services\PortalAudit;
use Illuminate\Http\JsonResponse;
@@ -177,7 +178,20 @@ class PortalManagementController extends Controller
'status' => ['required', Rule::in(['draft', 'published', 'archived'])],
'is_featured' => ['required', 'boolean'],
];
if ($resource === 'opportunities' && ! $id) {
foreach (InvestmentGeography::FIELDS as $field => $type) {
$rules[$field] = ['nullable', 'uuid'];
}
}
$data = $request->validate($rules);
if ($resource === 'opportunities' && ! $id && $request->has('province_id')) {
$path = app(InvestmentGeography::class)->selection($data);
$data = array_diff_key($data, InvestmentGeography::FIELDS);
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
$data['territory_version'] = $path === [] ? 0 : 1;
$data['province'] = $path[0]->name ?? null;
$data['district'] = $path[1]->name ?? null;
}
if ($resource === 'opportunities' && $data['status'] === 'published' && $record->exists
&& Schema::hasTable('education_investment_proposals')
&& DB::table('education_investment_proposals')->where('opportunity_id', $record->id)->exists()) {
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentGeography;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PublicGeographyController extends Controller
{
public function options(Request $request, InvestmentGeography $geography): JsonResponse
{
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$query = $geography->publicReferences()->where('location_type', $data['type']);
if ($data['type'] !== 'province') {
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']];
$parent = $geography->publicReferences()->where('id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000')->where('location_type', $parentType)->value('id');
$query->where('parent_id', $parent ?? '00000000-0000-0000-0000-000000000000');
}
if (! empty($data['q'])) {
$query->whereRaw('name ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
}
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type']));
}
}
@@ -0,0 +1,155 @@
<?php
namespace App\Http\Controllers;
use App\Services\TerritorialRegistry;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class TerritorialRegistryController extends Controller
{
public function sources(Request $request): JsonResponse
{
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
return response()->json(DB::table('geo_sources')->orderBy('id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
}
public function drafts(Request $request): JsonResponse
{
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
return response()->json(DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')->whereNull('g.deleted_at')
->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.source_id', 'p.status', 'p.valid_from', 'p.valid_to', 'p.editor_id', 'p.reviewer_id', 'p.publisher_id'])
->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
}
public function index(Request $request, TerritorialRegistry $registry, ?string $collection = null): JsonResponse
{
$data = $request->validate(['q' => ['nullable', 'string', 'max:150'], 'cursor' => ['nullable', 'string', 'max:512'],
'limit' => ['nullable', 'integer', 'between:1,100'], 'parent_id' => ['nullable', 'uuid'],
'country_id' => ['nullable', 'uuid'], 'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'],
'include_geometry' => ['nullable', 'in:0,false'], 'bbox' => ['prohibited'], 'near' => ['prohibited'], 'radius' => ['prohibited']]);
$types = ['countries' => 'country', 'provinces' => 'province', 'districts' => 'district', 'admin-posts' => 'admin_post', 'localities' => 'locality'];
$query = $registry->published()->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.valid_from', 'p.valid_to']);
if (isset($types[$collection])) {
$query->where('g.location_type', $types[$collection]);
}
if (! empty($data['q'])) {
$term = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $data['q']).'%';
$query->where(fn ($q) => $q->where('g.name', 'ilike', $term)->orWhere('g.code', 'ilike', $term)
->orWhereExists(fn ($n) => $n->selectRaw('1')->from('geo_names')->whereColumn('geo_location_id', 'g.id')->where('name', 'ilike', $term)));
}
foreach (['parent_id', 'country_id', 'province_id', 'district_id', 'admin_post_id'] as $key) {
if (! empty($data[$key])) {
if ($key === 'parent_id') {
$query->where('g.parent_id', $data[$key]);
} else {
$type = ['country_id' => 'country', 'province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post'][$key];
$query->whereRaw('EXISTS (WITH RECURSIVE a AS (SELECT id,parent_id,location_type,1 AS depth FROM geo_locations WHERE id=g.parent_id UNION ALL SELECT l.id,l.parent_id,l.location_type,a.depth+1 FROM geo_locations l JOIN a ON l.id=a.parent_id WHERE a.depth<5) SELECT 1 FROM a WHERE id=? AND location_type=?)', [$data[$key], $type]);
}
}
}
return response()->json($query->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
}
public function show(Request $request, TerritorialRegistry $registry, string $type, string $id): JsonResponse
{
abort_unless(array_key_exists($type, TerritorialRegistry::PARENTS), 404);
$row = $registry->published()->where('g.id', $id)->where('g.location_type', $type)
->first(['g.id', 'g.name', 'g.code', 'g.parent_id', 'g.location_type', 'g.version_no', 'p.valid_from', 'p.valid_to', 'p.capital_territory_id']);
abort_unless($row !== null, 404);
// An unapproved capital must not leak through a published province.
if ($row->capital_territory_id && ! $registry->published()->where('g.id', $row->capital_territory_id)->exists()) {
$row->capital_territory_id = null;
}
return response()->json(['territory' => $row, 'names' => DB::table('geo_names')->where('geo_location_id', $id)->get(['language', 'name', 'official'])]);
}
public function save(Request $request, TerritorialRegistry $registry, ?string $id = null): JsonResponse
{
$id = $registry->save($request->user(), $request->all(), $id);
return response()->json(['id' => $id, 'status' => 'draft', 'version_no' => DB::table('geo_locations')->where('id', $id)->value('version_no')]);
}
public function source(Request $request): JsonResponse
{
$data = $request->validate(['name' => ['required', 'string', 'max:255'], 'responsible_entity' => ['nullable', 'string', 'max:255'],
'reference' => ['required', 'string', 'min:10', 'max:2000'], 'license' => ['nullable', 'string', 'max:2000'],
'checksum' => ['required', 'regex:/^[0-9a-f]{64}$/'], 'source_version' => ['required', 'string', 'max:255'],
'collected_at' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'], 'original_crs' => ['nullable', 'string', 'max:255']]);
$id = (string) Str::uuid();
DB::transaction(function () use ($data, $id, $request) {
DB::select('SELECT pg_advisory_xact_lock(280926, hashtext(?))', [$data['checksum'].':'.$data['source_version']]);
abort_if(DB::table('geo_sources')->where('checksum', $data['checksum'])->where('source_version', $data['source_version'])->exists(), 422, 'Fonte e versão já registadas.');
DB::table('geo_sources')->insert([...$data, 'id' => $id, 'editor_id' => $request->user()->id, 'created_at' => now(), 'updated_at' => now()]);
});
return response()->json(['id' => $id, 'status' => 'pending'], 201);
}
public function transition(Request $request, TerritorialRegistry $registry, string $id): JsonResponse
{
$data = $request->validate(['action' => ['required', 'in:pending_review,approved,published,rejected,archived'],
'version_no' => ['required', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000']]);
return DB::transaction(function () use ($request, $registry, $id, $data) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$location = DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
$profile = DB::table('geo_territory_profiles')->where('geo_location_id', $id)->lockForUpdate()->first();
abort_unless($location && $profile, 404);
abort_unless($location->version_no === $data['version_no'], 409);
$from = ['pending_review' => ['draft', 'rejected'], 'approved' => ['pending_review'], 'published' => ['approved'],
'rejected' => ['pending_review'], 'archived' => ['draft', 'pending_review', 'approved', 'published', 'rejected']];
abort_unless(in_array($profile->status, $from[$data['action']], true), 409);
$actor = $request->user()->id;
$changes = ['status' => $data['action'], 'updated_at' => now()];
if ($data['action'] === 'pending_review') {
abort_unless($profile->editor_id === $actor, 403);
}
if (in_array($data['action'], ['approved', 'rejected'], true)) {
abort_if($profile->editor_id === $actor, 403, 'Revisão independente obrigatória.');
$changes['reviewer_id'] = $actor;
}
if ($data['action'] === 'published') {
abort_if(in_array($actor, [$profile->editor_id, $profile->reviewer_id], true), 403, 'Publicação exige terceiro interveniente.');
abort_unless(DB::table('geo_sources')->where('id', $profile->source_id)->where('status', 'approved')->exists(), 422, 'Fonte não aprovada.');
abort_if($profile->valid_from > today()->toDateString() || ($profile->valid_to && $profile->valid_to < today()->toDateString()), 422, 'Vigência inválida.');
abort_if($location->parent_id && ! $registry->published()->where('g.id', $location->parent_id)->exists(), 422, 'Ascendente não publicado.');
$changes['publisher_id'] = $actor;
}
DB::table('geo_territory_profiles')->where('geo_location_id', $id)->update($changes);
$version = $location->version_no + 1;
DB::table('geo_locations')->where('id', $id)->update(['version_no' => $version, 'data_classification' => $data['action'] === 'published' ? 'public' : 'internal']);
$registry->snapshot($id, $version, $request->user(), $data['reason']);
return response()->json(['id' => $id, 'status' => $data['action'], 'version_no' => $version]);
});
}
public function sourceTransition(Request $request, string $id): JsonResponse
{
$data = $request->validate(['action' => ['required', 'in:approved,revoked'], 'approval_reference' => ['required', 'string', 'min:10', 'max:2000']]);
return DB::transaction(function () use ($request, $id, $data) {
$source = DB::table('geo_sources')->where('id', $id)->lockForUpdate()->first();
abort_unless($source !== null, 404);
if ($data['action'] === 'approved') {
abort_unless($source->status === 'pending', 409);
abort_if($source->editor_id === $request->user()->id, 403);
abort_unless($source->responsible_entity && $source->license, 422, 'Entidade e licença em falta.');
}
DB::table('geo_sources')->where('id', $id)->update(['status' => $data['action'], 'reviewer_id' => $request->user()->id,
'approval_reference' => $data['approval_reference'], 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'territorial-registry', 'entity_type' => 'geo_sources', 'entity_id' => $id,
'actor_user_id' => $request->user()->id, 'action' => $data['action'], 'after_data' => json_encode(['status' => $data['action']], JSON_THROW_ON_ERROR)]);
return response()->json(['id' => $id, 'status' => $data['action']]);
});
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ExistingBusinessEnabled
{
/** @param Closure(Request): Response $next */
public function handle(Request $request, Closure $next): Response
{
abort_unless(config('existing-business.enabled'), 404);
return $next($request);
}
}
@@ -40,6 +40,7 @@ class HandleInertiaRequests extends Middleware
'name' => config('app.name'),
'educationEnabled' => (bool) config('education.enabled', false),
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
'flash' => ['success' => fn () => $request->session()->get('success')],
'auth' => [
'user' => $request->user(),
@@ -0,0 +1,69 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class TerritorialRequest
{
/** @param Closure(Request): Response $next */
public function handle(Request $request, Closure $next): Response
{
$correlation = (string) Str::uuid();
try {
abort_unless(config('territorial.enabled'), 404);
if ($request->isMethodSafe()) {
$response = $next($request);
} else {
abort_unless($request->user()->can('manage-portal') && $request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
$role = $request->is('*/transitions') ? match ($request->input('action')) {
'approved', 'rejected' => 'reviewers', 'published', 'archived', 'revoked' => 'publishers', default => 'editors',
} : 'editors';
abort_unless(in_array(strtolower($request->user()->email), config('territorial.'.$role, []), true), 403, 'Função editorial não atribuída.');
$key = $request->header('Idempotency-Key', '');
abort_unless(Str::isUuid($key), 422, 'Idempotency-Key UUID obrigatório.');
$scope = $request->method().':'.$request->path();
$actor = $request->user()->id;
$hash = hash('sha256', json_encode($request->all(), JSON_THROW_ON_ERROR));
$response = DB::transaction(function () use ($request, $next, $key, $scope, $actor, $hash) {
DB::select('SELECT pg_advisory_xact_lock(280926, hashtext(?))', [$actor.':'.$key.':'.$scope]);
$query = DB::table('geo_write_receipts')->where('actor_id', $actor)->where('idempotency_key', $key)->where('scope', $scope);
$existing = $query->first();
if ($existing) {
abort_unless(hash_equals($existing->request_hash, $hash), 409, 'Chave reutilizada com conteúdo diferente.');
return response(Crypt::decryptString($existing->response), $existing->http_status, ['Content-Type' => 'application/json']);
}
$result = $next($request);
if ($result->isSuccessful()) {
$body = $result->getContent();
if (! is_string($body)) {
throw new \RuntimeException('Expected JSON response body.');
}
DB::table('geo_write_receipts')->insert(['id' => (string) Str::uuid(), 'actor_id' => $actor, 'idempotency_key' => $key,
'scope' => $scope, 'request_hash' => $hash, 'response' => Crypt::encryptString($body), 'http_status' => $result->getStatusCode()]);
}
return $result;
});
}
} catch (ValidationException $exception) {
$response = response()->json(['type' => 'about:blank', 'title' => 'Dados inválidos', 'status' => 422, 'errors' => $exception->errors(), 'correlation_id' => $correlation], 422, ['Content-Type' => 'application/problem+json']);
} catch (HttpExceptionInterface $exception) {
$status = $exception->getStatusCode();
$response = response()->json(['type' => 'about:blank', 'title' => Response::$statusTexts[$status] ?? 'Request failed', 'status' => $status,
'detail' => $exception->getMessage(), 'correlation_id' => $correlation], $status, ['Content-Type' => 'application/problem+json']);
}
$response->headers->set('X-Correlation-ID', $correlation);
$response->headers->set('Cache-Control', 'private, no-store');
return $response;
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Models;
class ExistingBusiness extends DomainRecord
{
protected $hidden = ['payload'];
protected $casts = ['payload' => 'encrypted:array', 'version_no' => 'integer'];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class ExistingBusinessMandate extends Model
{
use HasUuids;
protected $guarded = ['id'];
protected $hidden = ['payload'];
protected $casts = ['payload' => 'encrypted:array', 'valid_from' => 'date', 'valid_until' => 'date'];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class ExistingBusinessObject extends Model
{
use HasUuids;
protected $guarded = ['id'];
protected $hidden = ['payload'];
protected $casts = ['payload' => 'encrypted:array'];
}
+2
View File
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
/** @property string|null $primary_territory_id */
class Opportunity extends Model
{
use SoftDeletes;
@@ -18,6 +19,7 @@ class Opportunity extends Model
'estimated_investment_currency', 'financing_modality',
'expected_impact', 'status', 'is_featured', 'published_at',
'last_validated_at',
'primary_territory_id', 'territory_version',
];
protected $casts = [
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Policies;
use App\Models\ExistingBusiness;
use App\Models\User;
class ExistingBusinessPolicy
{
public function create(User $user): bool
{
return $user->hasVerifiedEmail();
}
public function update(User $user, ExistingBusiness $business): bool
{
return $this->owns($user, $business) && in_array($business->status, ['draft', 'needs_information'], true);
}
public function view(User $user, ExistingBusiness $business): bool
{
return $this->owns($user, $business) || $this->review($user, $business);
}
public function delete(User $user, ExistingBusiness $business): bool
{
return $this->update($user, $business);
}
public function owns(User $user, ExistingBusiness $business): bool
{
return $user->hasVerifiedEmail() && $business->owner_user_id === $user->id && ! $business->trashed();
}
public function review(User $user, ExistingBusiness $business): bool
{
return ! $business->trashed() && $business->owner_user_id !== $user->id
&& in_array($business->status, ['submitted', 'in_review', 'needs_information'], true)
&& $this->reviewQueue($user);
}
public function reviewQueue(User $user): bool
{
return $user->can('manage-portal') && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Services;
use RuntimeException;
use SimpleXMLElement;
use ZipArchive;
/** Inspects an authorised local workbook without importing or transforming data. */
final class CartographyWorkbookAudit
{
/** @param array<string, mixed> $manifest
* @return array<string, mixed>
*/
public function inspect(string $path, array $manifest): array
{
if (! is_file($path) || filesize($path) > 20_000_000) {
throw new RuntimeException('Workbook missing or larger than 20 MB.');
}
$checksum = hash_file('sha256', $path);
if ($checksum === false) {
throw new RuntimeException('Unable to read workbook checksum.');
}
if (! isset($manifest['sha256']) || ! hash_equals(strtolower((string) $manifest['sha256']), $checksum)) {
throw new RuntimeException('Manifest checksum does not match the workbook.');
}
foreach (['inspection_authorization'] as $key) {
if (! is_string($manifest[$key] ?? null) || trim($manifest[$key]) === '') {
throw new RuntimeException('Missing manifest field: '.$key);
}
}
if (isset($manifest['classification']) && ! in_array($manifest['classification'], ['public', 'internal', 'confidential', 'restricted'], true)) {
throw new RuntimeException('Invalid classification.');
}
$zip = new ZipArchive;
if ($zip->open($path) !== true) {
throw new RuntimeException('Invalid XLSX container.');
}
try {
$bytes = 0;
if ($zip->numFiles > 1000) {
throw new RuntimeException('Too many archive entries.');
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->statIndex($i);
if ($entry === false) {
throw new RuntimeException('Unreadable archive entry.');
}
$bytes += $entry['size'];
if ($bytes > 50_000_000 || str_contains($entry['name'], '../')) {
throw new RuntimeException('Unsafe or oversized archive.');
}
}
$strings = [];
if ($zip->locateName('xl/sharedStrings.xml') !== false) {
foreach ($this->xml($zip, 'xl/sharedStrings.xml')->xpath('//*[local-name()="si"]') ?: [] as $item) {
$strings[] = implode('', array_map(fn ($t) => (string) $t, $item->xpath('.//*[local-name()="t"]') ?: []));
}
}
$relationships = [];
foreach ($this->xml($zip, 'xl/_rels/workbook.xml.rels')->children() as $rel) {
$target = (string) $rel['Target'];
if ((string) $rel['TargetMode'] !== 'External' && ! str_contains($target, '..')) {
$relationships[(string) $rel['Id']] = str_starts_with($target, '/') ? ltrim($target, '/') : 'xl/'.$target;
}
}
$sheets = [];
$rowCount = 0;
foreach ($this->xml($zip, 'xl/workbook.xml')->xpath('//*[local-name()="sheet"]') ?: [] as $sheet) {
$id = (string) $sheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
if (! isset($relationships[$id])) {
throw new RuntimeException('Unresolved worksheet relationship.');
}
$rows = [];
$seen = [];
foreach ($this->xml($zip, $relationships[$id])->xpath('//*[local-name()="sheetData"]/*[local-name()="row"]') ?: [] as $row) {
if (++$rowCount > 50000) {
throw new RuntimeException('Audit limit of 50000 rows exceeded.');
}
$values = [];
$issues = [];
foreach ($row->children() as $cell) {
$address = (string) $cell['r'];
$value = (string) $cell->v;
if ((string) $cell['t'] === 's') {
$value = $strings[(int) $value] ?? '';
} elseif ((string) $cell['t'] === 'inlineStr') {
$value = implode('', array_map(fn ($t) => (string) $t, $cell->xpath('.//*[local-name()="t"]') ?: []));
}
$values[preg_replace('/[0-9]+$/', '', $address)] = $value;
if ($value === '') {
$issues[] = ['field' => $address, 'code' => 'empty_cell'];
}
if (isset($cell->f)) {
$issues[] = ['field' => $address, 'code' => 'formula_not_evaluated'];
}
if ((string) $cell['t'] === 'e') {
$issues[] = ['field' => $address, 'code' => 'spreadsheet_error'];
}
}
$hash = hash('sha256', json_encode($values, JSON_THROW_ON_ERROR));
$duplicate = isset($seen[$hash]);
$seen[$hash] = true;
$issues[] = ['field' => '*', 'code' => 'semantic_mapping_and_institutional_validation_pending'];
if (empty($manifest['original_crs'])) {
$issues[] = ['field' => '*', 'code' => 'original_crs_unknown'];
}
$rows[] = ['row' => (int) $row['r'], 'status' => $duplicate ? 'duplicate' : 'pending', 'populated_columns' => array_keys($values), 'issues' => $issues];
}
$sheets[] = ['name' => (string) $sheet['name'], 'state' => (string) $sheet['state'] ?: 'visible', 'rows' => $rows];
}
return ['sha256' => $checksum, 'version' => $manifest['version'] ?? null, 'classification' => $manifest['classification'] ?? null,
'pending_metadata' => array_values(array_filter(['owner', 'version', 'received_at', 'classification', 'original_crs'], fn ($key) => empty($manifest[$key]))),
'original_crs' => $manifest['original_crs'] ?? null, 'publication_allowed' => false, 'transformations' => [],
'status' => 'quarantined', 'sheets' => $sheets, 'rows_inspected' => $rowCount,
'limitations' => ['No semantic header mapping, omitted-cell inference, coordinate validation or external reference resolution.', 'No source values, coordinates or formulas copied to the report.']];
} finally {
$zip->close();
}
}
private function xml(ZipArchive $zip, string $name): SimpleXMLElement
{
$content = $zip->getFromName($name);
if ($content === false || preg_match('/<!DOCTYPE|<!ENTITY/i', $content)) {
throw new RuntimeException('Missing or unsafe workbook XML.');
}
$previous = libxml_use_internal_errors(true);
try {
$xml = simplexml_load_string($content, SimpleXMLElement::class, LIBXML_NONET);
if ($xml === false) {
throw new RuntimeException('Malformed workbook XML.');
}
return $xml;
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previous);
}
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
final class ExistingBusinessDrafts
{
public const MODALITIES = ['company_sale', 'participation_sale', 'capital_increase', 'financial_investor', 'strategic_partner', 'buyer_search', 'position_assignment', 'franchise', 'asset_sale', 'asset_lease', 'business_unit_transfer', 'joint_venture', 'succession', 'recovery', 'expansion', 'internationalization', 'real_estate', 'agricultural_investment', 'land_right', 'mining_license', 'forestry_license'];
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?string $id = null): ExistingBusiness
{
$data = Validator::make($input, [
'modality' => ['required', 'in:'.implode(',', self::MODALITIES)],
'classification' => ['required', 'in:internal,confidential,restricted'],
'version_no' => [$id ? 'required' : 'prohibited', 'integer', 'min:1'],
'reason' => ['required', 'string', 'min:10', 'max:1000'],
'payload' => ['required', 'array:title,description,declared_reason,source_reference,valid_until'],
'payload.title' => ['required', 'string', 'max:200'],
'payload.description' => ['nullable', 'string', 'max:10000'],
'payload.declared_reason' => ['nullable', 'string', 'max:2000'],
'payload.source_reference' => ['nullable', 'string', 'max:2000'],
'payload.valid_until' => ['nullable', 'date_format:Y-m-d'],
])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
if ($id) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
Gate::forUser($actor)->authorize('update', $business);
abort_unless($business->version_no === $data['version_no'], 409, 'O rascunho foi alterado. Recarregue antes de gravar.');
$business->version_no++;
} else {
Gate::forUser($actor)->authorize('create', ExistingBusiness::class);
if (! $actor->exists || $actor->id < 1) {
abort(403, 'A conta deve estar registada.');
}
$business = new ExistingBusiness;
$business->code = 'MNE-'.Str::uuid();
$business->owner_user_id = $actor->id;
$business->version_no = 1;
$business->status = 'draft';
}
$business->fill(['modality' => $data['modality'], 'classification' => $data['classification'], 'payload' => $data['payload']]);
$business->save();
$this->snapshot($business, $actor, $id ? 'updated' : 'created', $data['reason']);
return $business;
});
}
public function archive(User $actor, string $id, int $version, string $reason): void
{
Validator::make(['reason' => $reason], ['reason' => ['required', 'string', 'min:10', 'max:1000']])->validate();
DB::transaction(function () use ($actor, $id, $version, $reason) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
Gate::forUser($actor)->authorize('delete', $business);
abort_unless($business->version_no === $version, 409);
$business->version_no++;
$business->save();
$business->delete();
$this->snapshot($business, $actor, 'archived', $reason);
});
}
/** @param array<string,mixed> $context */
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason, array $context = []): void
{
$snapshot = json_encode(['context' => $context, 'record' => $business->attributesToArray(), 'payload' => $business->payload,
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
], JSON_THROW_ON_ERROR);
DB::table('existing_business_revisions')->insert(['id' => (string) Str::uuid(), 'business_id' => $business->id,
'version_no' => $business->version_no, 'actor_id' => $actor->id, 'action' => $action,
'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString($snapshot), 'sha256' => hash('sha256', $snapshot)]);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
final class ExistingBusinessIntake
{
public function transition(User $actor, string $id, int $version, string $action, string $note, bool $consent = false): ExistingBusiness
{
Validator::make(compact('action', 'note'), [
'action' => ['required', 'in:submitted,in_review,needs_information,withdrawn'],
'note' => ['required', 'string', 'min:10', 'max:2000'],
])->validate();
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
Gate::forUser($actor)->authorize(in_array($action, ['submitted', 'withdrawn'], true) ? 'owns' : 'review', $business);
abort_unless($business->version_no === $version, 409, 'Versão desactualizada.');
$allowed = ['submitted' => ['draft', 'needs_information'], 'in_review' => ['submitted'],
'needs_information' => ['in_review'], 'withdrawn' => ['draft', 'submitted', 'in_review', 'needs_information']];
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
if ($action === 'submitted') {
Validator::make([...$business->payload, 'consent' => $consent], [
'description' => ['required', 'string', 'min:30'], 'source_reference' => ['required', 'string', 'min:10'],
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'consent' => ['accepted'],
])->validate();
}
$business->status = $action;
$business->version_no++;
$business->save();
DB::table('existing_business_reviews')->insert(['id' => (string) Str::uuid(), 'business_id' => $id, 'actor_id' => $actor->id,
'version_no' => $business->version_no, 'action' => $action,
'note' => Crypt::encryptString(json_encode(['note' => $note, 'review_consent' => $action === 'submitted' ? $consent : null], JSON_THROW_ON_ERROR))]);
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $action, $note);
return $business;
});
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
final class ExistingBusinessObjects
{
public const KINDS = ['company', 'participation', 'asset', 'property', 'unit', 'improvement', 'agricultural_investment', 'land_right', 'contract', 'license', 'authorization', 'encumbrance', 'valuation', 'capital_request'];
/** @return array<string,array<int,string>> */
public static function fields(): array
{
return [
'label' => ['required', 'string', 'max:200'],
'declared_holder' => ['nullable', 'string', 'max:500'],
'document_reference' => ['nullable', 'string', 'max:1000'],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'competent_entity' => ['nullable', 'string', 'max:500'],
'purpose' => ['nullable', 'string', 'max:2000'],
'location_description' => ['nullable', 'string', 'max:2000'],
'boundaries_description' => ['nullable', 'string', 'max:2000'],
'occupancy' => ['nullable', 'string', 'max:2000'],
'condition' => ['nullable', 'string', 'max:2000'],
'encumbrances' => ['nullable', 'string', 'max:4000'],
'restrictions' => ['nullable', 'string', 'max:4000'],
'required_authorizations' => ['nullable', 'string', 'max:4000'],
'transfer_condition' => ['nullable', 'string', 'max:4000'],
'contract_type' => ['nullable', 'in:purchase,sale,lease,operation,management,other'],
'valid_from' => ['nullable', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d'],
'area' => ['nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,4})?$/', 'numeric', 'gt:0'],
'area_unit' => ['nullable', 'required_with:area', 'in:m2,ha,km2'],
'amount' => ['nullable', 'string', 'regex:/^\d{1,15}(\.\d{1,2})?$/', 'numeric', 'min:0'],
'currency' => ['nullable', 'required_with:amount', 'regex:/^[A-Z]{3}$/'],
'value_kind' => ['nullable', 'required_with:amount', 'in:asking,indicative,appraised,proposed,negotiated,confirmed'],
'participation_percent' => ['nullable', 'numeric', 'between:0,100'],
];
}
/** @param array<string,mixed> $input */
public function save(User $actor, string $businessId, array $input, ?string $objectId = null): ExistingBusinessObject
{
$rules = self::fields();
if (! empty($input['payload']['valid_from'])) {
$rules['valid_until'][] = 'after_or_equal:valid_from';
}
$data = Validator::make($input, ['version_no' => ['required', 'integer', 'min:1'],
'kind' => ['required', 'in:'.implode(',', self::KINDS)], 'reason' => ['required', 'string', 'min:10', 'max:1000'],
'payload' => ['required', 'array:'.implode(',', array_keys($rules))],
])->validate();
// Cross-field rules operate on the payload itself, rather than sibling root fields.
Validator::make($data['payload'], $rules)->validate();
return DB::transaction(function () use ($actor, $businessId, $objectId, $data) {
$business = ExistingBusiness::whereKey($businessId)->lockForUpdate()->firstOrFail();
Gate::forUser($actor)->authorize('update', $business);
abort_unless($business->version_no === $data['version_no'], 409, 'Versão desactualizada.');
abort_if(! $objectId && ExistingBusinessObject::where('business_id', $businessId)->count() >= 100, 422, 'Máximo de 100 elementos por negócio.');
$object = $objectId ? ExistingBusinessObject::where('business_id', $businessId)->whereKey($objectId)->firstOrFail() : new ExistingBusinessObject;
if ($objectId) {
abort_unless($object->kind === $data['kind'], 422, 'Crie outro elemento para uma natureza diferente.');
}
$object->fill(['business_id' => $businessId, 'kind' => $data['kind'], 'classification' => 'restricted', 'verification_status' => 'pending', 'payload' => $data['payload']]);
$object->save();
$business->version_no++;
$business->save();
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $objectId ? 'object_updated' : 'object_added', $data['reason']);
return $object;
});
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
final class ExistingBusinessVerification
{
public const CHECKS = ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'];
private function contentVersion(string $id): int
{
return (int) DB::table('existing_business_revisions')->where('business_id', $id)
->whereIn('action', ['created', 'updated', 'object_added', 'object_updated'])->max('version_no');
}
/** @param array<string,mixed> $input */
public function save(User $actor, string $id, array $input): ExistingBusiness
{
$data = Validator::make($input, [
'version_no' => ['required', 'integer', 'min:1'],
'object_id' => ['nullable', 'uuid'],
'check' => ['required', 'in:'.implode(',', self::CHECKS)],
'outcome' => ['required', 'in:confirmed,rejected,inconclusive,revoked'],
'evidence_reference' => ['required', 'string', 'min:10', 'max:2000'],
'note' => ['required', 'string', 'min:10', 'max:2000'],
'valid_until' => ['required_if:outcome,confirmed', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
Gate::forUser($actor)->authorize('review', $business);
abort_unless($business->status === 'in_review' && $business->version_no === $data['version_no'], 409, 'Reabra a versão actual em revisão.');
if (! empty($data['object_id'])) {
ExistingBusinessObject::where('business_id', $id)->whereKey($data['object_id'])->firstOrFail();
}
$data['content_version'] = $this->contentVersion($id);
$business->version_no++;
$business->save();
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, 'verification', $data['note'], $data);
return $business;
});
}
/** Latest finding for each check/subject; complete evidence remains in immutable revisions.
* @return array<int,array<string,mixed>>
*/
public function findings(ExistingBusiness $business): array
{
$contentVersion = $this->contentVersion($business->id);
$findings = [];
foreach (DB::table('existing_business_revisions')->where('business_id', $business->id)
->where('action', 'verification')->orderByDesc('version_no')->cursor() as $revision) {
$data = json_decode(Crypt::decryptString($revision->snapshot), true, 512, JSON_THROW_ON_ERROR)['context'];
$key = ($data['object_id'] ?? 'business').':'.$data['check'];
if (isset($findings[$key])) {
continue;
}
$effective = $data['outcome'];
if ($data['content_version'] !== $contentVersion) {
$effective = 'stale';
} elseif (! empty($data['valid_until']) && $data['valid_until'] < today()->toDateString()) {
$effective = 'expired';
}
$findings[$key] = [...$data, 'effective_outcome' => $effective,
'version_no' => $revision->version_no, 'created_at' => $revision->created_at];
}
return array_values($findings);
}
}
+54 -8
View File
@@ -16,7 +16,9 @@ class InvestmentCatalogue
/** @return array<string,mixed> */
public function filters(Request $request): array
{
return $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
'opportunity_id' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'province' => ['nullable', 'string', 'max:100'], 'district' => ['nullable', 'string', 'max:100'],
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
@@ -28,6 +30,9 @@ class InvestmentCatalogue
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'],
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
app(InvestmentGeography::class)->selection($filters);
return $filters;
}
/**
@@ -37,6 +42,14 @@ class InvestmentCatalogue
public function query(array $filters): Builder
{
$query = Opportunity::published()->with('sector:id,name,slug');
if (! empty($filters['opportunity_id'])) {
$query->whereKey($filters['opportunity_id']);
}
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->whereIn('primary_territory_id', $ids);
}
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $filters['dimension'])->select('mapping.opportunity_id'));
@@ -147,6 +160,7 @@ class InvestmentCatalogue
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id)
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
$result['primary_territory_path'] = app(InvestmentGeography::class)->path(DB::table('opportunities')->where('id', $id)->value('primary_territory_id'));
return $result;
}
@@ -157,14 +171,46 @@ class InvestmentCatalogue
*/
public function map(array $filters): array
{
$ids = $this->query($filters)->reorder()->select('opportunities.id');
$points = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')->join('opportunities as o', 'o.id', '=', 'l.opportunity_id')
$records = $this->query($filters)->limit(1000)->get();
$total = $this->query($filters)->reorder()->count();
$ids = $records->pluck('id');
$points = DB::table('opportunities as o')->join('geo_locations as g', function ($join) {
$join->on('g.id', '=', 'o.primary_territory_id')->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_locations as l')->whereColumn('l.opportunity_id', 'o.id')->whereColumn('l.geo_location_id', 'g.id'));
})->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')
->whereIn('o.id', $ids)->where('g.data_classification', 'public')->where('shape.data_classification', 'public')
->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')->limit(1000)
->get(['o.id', 'o.title', 'o.slug', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')]);
->where('g.location_type', 'site')->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')
->whereRaw("NOT EXISTS (WITH RECURSIVE parents AS (
SELECT id,parent_id,deleted_at,data_classification,ARRAY[id] AS visited,false AS cycle FROM geo_locations WHERE id=g.id
UNION ALL SELECT p.id,p.parent_id,p.deleted_at,p.data_classification,a.visited||p.id,p.id=ANY(a.visited)
FROM geo_locations p JOIN parents a ON p.id=a.parent_id WHERE NOT a.cycle
) SELECT 1 FROM parents WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
->whereRaw('ST_IsValid(shape.geom) AND NOT ST_IsEmpty(shape.geom) AND ST_SRID(shape.geom)=4326')
->orderBy('o.id')->orderByRaw("CASE WHEN g.source_system='investment-site-editor' THEN 0 ELSE 1 END")->orderBy('g.id')->orderBy('shape.id')
->get(['o.id', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')])->unique('id')->keyBy('id');
$relations = [];
foreach (['clusters', 'corridors', 'projects'] as $relation) {
[$foreign, $table] = self::RELATIONS[$relation];
$relations[$relation] = DB::table('opportunity_'.$relation.' as l')->join($table.' as t', 't.id', '=', 'l.'.$foreign)
->whereIn('l.opportunity_id', $ids)->whereNull('t.deleted_at')
->whereIn('t.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign))
->get(['l.opportunity_id', 't.name'])->groupBy('opportunity_id');
}
$features = $missing = [];
foreach ($records as $record) {
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug];
foreach ($relations as $relation => $groups) {
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
}
if ($point = $points->get($record->id)) {
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties, 'location' => trim($properties['location'].' — '.$point->name)]];
} else {
$missing[] = [...$properties, 'reason' => 'missing_public_site_coordinates'];
}
}
return ['type' => 'FeatureCollection', 'limit' => 1000, 'features' => $points->map(fn ($p) => ['type' => 'Feature',
'geometry' => json_decode($p->geometry, true), 'properties' => ['id' => $p->id, 'title' => $p->title, 'location' => $p->name, 'url' => '/oportunidades/'.$p->slug]])->all()];
return ['type' => 'FeatureCollection', 'limit' => 1000, 'matched_count' => $total, 'truncated' => $total > $records->count(),
'georeferenced_count' => count($features), 'unlocated' => $missing, 'features' => $features,
'complete' => $total === count($features)];
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Services;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class InvestmentGeography
{
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
public function publicReferences(): Builder
{
return DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification', 'public')
->whereRaw("NOT EXISTS (WITH RECURSIVE ancestors AS (
SELECT id,parent_id,deleted_at,data_classification,ARRAY[id] AS visited,false AS cycle FROM geo_locations a WHERE a.id=geo_locations.id
UNION ALL SELECT a.id,a.parent_id,a.deleted_at,a.data_classification,p.visited||a.id,a.id=ANY(p.visited)
FROM geo_locations a JOIN ancestors p ON a.id=p.parent_id WHERE NOT p.cycle
) SELECT 1 FROM ancestors WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
->where(function ($query) {
$query->where(function ($workbook) {
$workbook->where('source_system', 'cartografia-workbook')
->where('external_id', 'like', '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:%');
})->orWhereIn('id', app(TerritorialRegistry::class)->published()->select('g.id'));
});
}
/** @param array<string,mixed> $input
* @return list<\stdClass>
*/
public function selection(array $input): array
{
$path = [];
$parent = null;
$gap = false;
foreach (self::FIELDS as $field => $type) {
if (empty($input[$field])) {
$gap = true;
continue;
}
$node = $this->publicReferences()->where('id', $input[$field])->where('location_type', $type)->first(['id', 'name', 'parent_id', 'location_type']);
if ($gap || ! $node || ($parent && $node->parent_id !== $parent)) {
throw ValidationException::withMessages([$field => 'Seleccione a localização dentro da hierarquia indicada.']);
}
$path[] = $node;
$parent = $node->id;
}
return $path;
}
/** @return list<string> */
public function descendants(string $id): array
{
$rows = DB::select('WITH RECURSIVE tree AS (
SELECT id, ARRAY[id] AS visited FROM geo_locations WHERE id=? AND deleted_at IS NULL
UNION ALL SELECT g.id, tree.visited||g.id FROM geo_locations g JOIN tree ON g.parent_id=tree.id
WHERE g.deleted_at IS NULL AND NOT g.id=ANY(tree.visited) AND cardinality(tree.visited)<5
) SELECT id FROM tree', [$id]);
return array_values($this->publicReferences()->whereIn('id', array_map(fn ($row) => $row->id, $rows))->pluck('id')->map(fn ($id) => (string) $id)->all());
}
/** @return list<\stdClass> */
public function path(?string $id): array
{
$path = [];
for ($i = 0; $id && $i < 5; $i++) {
$node = $this->publicReferences()->where('id', $id)->first(['id', 'name', 'parent_id', 'location_type']);
if (! $node) {
return [];
}
if ($node->location_type !== 'country') {
array_unshift($path, $node);
}
$id = $node->parent_id;
}
return $path;
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ class PortalAudit
$record->setRawAttributes($locked->getAttributes(), true);
}
// Exclude free text and personal data from the immutable event payload.
$fields = ['version_no', 'status', 'is_active', 'is_featured', 'sort_order', 'sector_id', 'maturity_level',
$fields = ['primary_territory_id', 'territory_version', 'version_no', 'status', 'is_active', 'is_featured', 'sort_order', 'sector_id', 'maturity_level',
'estimated_investment_amount', 'estimated_investment_currency', 'owner_user_id', 'assignee_user_id', 'due_at',
'cluster_id', 'project_id', 'corridor_id', 'dossier_id', 'interest_request_id', 'publication_status', 'editor_id', 'reviewer_id', 'role', 'stage', 'value_chain_id', 'from_value_chain_id', 'to_value_chain_id', 'link_type', 'deleted_at'];
$before = array_intersect_key($record->getAttributes(), array_flip($fields));
+133
View File
@@ -0,0 +1,133 @@
<?php
namespace App\Services;
use RuntimeException;
/** Offline structural validation. This never approves a source or writes territories. */
final class TerritorialCsvAudit
{
public const HEADERS = ['province_code', 'province_name', 'district_code', 'district_name', 'admin_post_code', 'admin_post_name', 'locality_code', 'locality_name', 'locality_type', 'latitude', 'longitude'];
/** @param list<string> $provinceCodes
* @return array<string,mixed>
*/
public function inspect(string $path, array $provinceCodes): array
{
if (! is_file($path) || ! is_readable($path) || filesize($path) > 20 * 1024 * 1024) {
throw new RuntimeException('CSV inacessível ou superior a 20 MiB.');
}
$bytes = file_get_contents($path);
if ($bytes === false || ! mb_check_encoding($bytes, 'UTF-8') || str_contains($bytes, "\0")) {
throw new RuntimeException('O CSV deve ser UTF-8 sem bytes nulos.');
}
// Parse the exact bytes hashed, avoiding a second read of a changing input.
$stream = fopen('php://temp', 'w+');
if ($stream === false) {
throw new RuntimeException('Não foi possível preparar a leitura.');
}
fwrite($stream, preg_replace('/^\xEF\xBB\xBF/', '', $bytes) ?? $bytes);
rewind($stream);
try {
if (fgetcsv($stream, null, ';', '"', '') !== self::HEADERS) {
throw new RuntimeException('Cabeçalho inválido: usar o contrato INE com separador ponto e vírgula.');
}
$errors = $seen = $names = $totals = [];
$duplicates = $count = 0;
while (($values = fgetcsv($stream, null, ';', '"', '')) !== false) {
$count++;
if ($count > 50000) {
throw new RuntimeException('O CSV excede 50.000 registos.');
}
$issues = [];
if (count($values) !== count(self::HEADERS)) {
$errors[] = ['record' => $count + 1, 'issues' => ['column_count']];
continue;
}
$row = array_combine(self::HEADERS, array_map(fn ($v) => trim((string) $v), $values));
foreach ($row as $field => $value) {
if (mb_strlen($value) > 255 || preg_match('/[\x00-\x1F\x7F]/', $value)) {
$issues[] = 'invalid_field:'.$field;
}
}
if (! preg_match('/^[0-9]{2}$/D', $row['province_code']) || ! in_array($row['province_code'], $provinceCodes, true)) {
$issues[] = 'unknown_province';
}
foreach (['province', 'district', 'admin_post', 'locality'] as $kind) {
$code = $row[$kind.'_code'];
$name = $row[$kind.'_name'];
if (($kind === 'province' || $kind === 'district' || $code !== '') && $name === '') {
$issues[] = 'missing_name:'.$kind;
}
if (($kind === 'province' || $kind === 'district' || $name !== '') && $code === '') {
$issues[] = 'missing_code:'.$kind;
}
if ($code === '') {
continue;
}
if (! preg_match('/^[0-9]+$/D', $code)) {
$issues[] = 'invalid_code:'.$kind;
}
$parent = match ($kind) {
'province' => 'MZ', 'district' => $row['province_code'],
'admin_post' => $row['district_code'], default => $row['admin_post_code'],
};
$identity = $kind.':'.$code;
$definition = [$parent, $name];
if ($kind === 'locality') {
$definition = [...$definition, $row['locality_type'], $row['latitude'], $row['longitude']];
}
if (isset($seen[$identity]) && $seen[$identity] !== $definition) {
$issues[] = 'conflicting_code:'.$kind;
}
$seen[$identity] ??= $definition;
$nameKey = $kind.':'.$parent.':'.mb_strtolower($name);
if (isset($names[$nameKey]) && $names[$nameKey] !== $code) {
$issues[] = 'ambiguous_name:'.$kind;
}
$names[$nameKey] ??= $code;
$totals[$row['province_code']][$kind][$code] = true;
}
if ($row['locality_code'] !== '' && $row['admin_post_code'] === '') {
$issues[] = 'locality_requires_reviewed_parent_exception';
}
if (($row['latitude'] === '') !== ($row['longitude'] === '')) {
$issues[] = 'incomplete_coordinates';
}
foreach (['latitude' => 90, 'longitude' => 180] as $field => $bound) {
if ($row[$field] !== '' && (! preg_match('/^-?[0-9]+(?:\.[0-9]+)?$/D', $row[$field]) || abs((float) $row[$field]) > $bound)) {
$issues[] = 'invalid_coordinate:'.$field;
}
}
if ($row['locality_code'] === '' && ($row['latitude'] !== '' || $row['longitude'] !== '' || $row['locality_type'] !== '')) {
$issues[] = 'locality_metadata_without_locality';
}
$fingerprint = hash('sha256', json_encode($row, JSON_THROW_ON_ERROR));
if (isset($seen['row:'.$fingerprint])) {
$duplicates++;
}
$seen['row:'.$fingerprint] = [];
if ($issues !== []) {
$errors[] = ['record' => $count + 1, 'issues' => array_values(array_unique($issues))];
}
}
if ($count === 0) {
$errors[] = ['record' => 1, 'issues' => ['empty_dataset']];
}
ksort($totals);
$counts = [];
foreach ($totals as $province => $kinds) {
$counts[$province] = array_map('count', $kinds);
}
return ['schema_version' => 1, 'sha256' => hash('sha256', $bytes), 'encoding' => 'UTF-8',
'delimiter' => ';', 'coordinate_crs' => 'EPSG:4326', 'records' => $count,
'duplicate_records' => $duplicates, 'rejected_records' => count($errors),
'status' => $errors === [] ? 'structurally_valid_requires_review' : 'rejected',
'candidate_counts_by_province' => $counts, 'errors' => $errors];
} finally {
fclose($stream);
}
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
final class TerritorialRegistry
{
public const PARENTS = ['country' => null, 'province' => 'country', 'district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'];
public function published(): Builder
{
// Every ancestor must remain public, in force and backed by an approved source.
return DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')
->whereNull('g.deleted_at')->where('g.data_classification', 'public')->where('p.status', 'published')
->whereRaw("NOT EXISTS (WITH RECURSIVE ancestry AS (
SELECT l.id,l.parent_id,l.deleted_at,l.data_classification,ARRAY[l.id] AS path,false AS cycle FROM geo_locations l WHERE l.id=g.id
UNION ALL SELECT l.id,l.parent_id,l.deleted_at,l.data_classification,a.path||l.id,l.id=ANY(a.path) FROM geo_locations l JOIN ancestry a ON l.id=a.parent_id WHERE NOT a.cycle
) SELECT 1 FROM ancestry a LEFT JOIN geo_territory_profiles ap ON ap.geo_location_id=a.id LEFT JOIN geo_sources s ON s.id=ap.source_id
WHERE a.cycle OR a.deleted_at IS NOT NULL OR a.data_classification<>'public' OR ap.status IS DISTINCT FROM 'published' OR s.status IS DISTINCT FROM 'approved'
OR ap.valid_from>CURRENT_DATE OR ap.valid_to<CURRENT_DATE)");
}
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?string $id = null): string
{
abort_unless($actor->can('manage-portal') && $actor->two_factor_confirmed_at && $actor->two_factor_secret, 403);
abort_unless(in_array(strtolower($actor->email), config('territorial.editors', []), true), 403);
$data = Validator::make($input, [
'name' => ['required', 'string', 'max:255'], 'code' => ['required', 'string', 'max:100'],
'location_type' => ['required', 'in:'.implode(',', array_keys(self::PARENTS))],
'parent_id' => ['nullable', 'uuid', 'exists:geo_locations,id'], 'source_id' => ['required', 'uuid', 'exists:geo_sources,id'],
'valid_from' => ['required', 'date_format:Y-m-d'], 'valid_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
'version_no' => [$id ? 'required' : 'prohibited', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000'],
])->validate();
return DB::transaction(function () use ($actor, $data, $id) {
// Serialise hierarchy changes to prevent concurrent parent cycles and duplicate paths.
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$current = $id ? DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first() : null;
if ($id) {
abort_unless($current && DB::table('geo_territory_profiles')->where('geo_location_id', $id)->exists(), 404);
abort_unless($current->version_no === $data['version_no'], 409);
abort_unless($current->location_type === $data['location_type'], 422, 'O tipo territorial é imutável.');
}
$parentType = self::PARENTS[$data['location_type']];
$parent = empty($data['parent_id']) ? null : DB::table('geo_locations')->where('id', $data['parent_id'])->whereNull('deleted_at')->first();
abort_unless($parentType ? $parent && $parent->location_type === $parentType : ! $parent, 422, 'Hierarquia territorial incoerente.');
$duplicate = DB::table('geo_locations')->where('location_type', $data['location_type'])->whereNull('deleted_at')->when($id, fn ($q) => $q->where('id', '<>', $id))
->where(fn ($q) => $q->where('code', $data['code'])->orWhere(fn ($q) => $q->where('parent_id', $data['parent_id'] ?? null)->whereRaw('lower(trim(name))=lower(trim(?))', [$data['name']])))->exists();
abort_if($duplicate, 422, 'Código ou nome no mesmo pai já existente.');
$id ??= (string) Str::uuid();
$version = $current ? $current->version_no + 1 : 1;
DB::table('geo_locations')->updateOrInsert(['id' => $id], ['name' => $data['name'], 'code' => $data['code'],
'location_type' => $data['location_type'], 'parent_id' => $data['parent_id'] ?? null,
'version_no' => $version, 'data_classification' => 'internal', 'updated_at' => now()]);
DB::table('geo_territory_profiles')->updateOrInsert(['geo_location_id' => $id], ['source_id' => $data['source_id'],
'valid_from' => $data['valid_from'], 'valid_to' => $data['valid_to'] ?? null, 'status' => 'draft',
'editor_id' => $actor->id, 'reviewer_id' => null, 'publisher_id' => null, 'updated_at' => now()]);
$this->snapshot($id, $version, $actor, $data['reason']);
return $id;
});
}
public function snapshot(string $id, int $version, User $actor, string $reason): void
{
$snapshot = json_encode(['location' => DB::table('geo_locations')->find($id),
'profile' => DB::table('geo_territory_profiles')->where('geo_location_id', $id)->first()], JSON_THROW_ON_ERROR);
DB::table('geo_territory_revisions')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $id,
'version_no' => $version, 'actor_id' => $actor->id, 'reason' => Crypt::encryptString($reason),
'snapshot' => Crypt::encryptString($snapshot), 'checksum' => hash('sha256', $snapshot)]);
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
return [
'enabled' => (bool) env('INVESTMOZ_MNE_ENABLED', false),
// Designations do not establish legal competence or an institutional mandate.
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_REVIEWERS', '')))))),
];
+8
View File
@@ -0,0 +1,8 @@
<?php
return [
'enabled' => (bool) env('INVESTMOZ_TERRITORIAL_ENABLED', false),
'editors' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_EDITORS', '')))))),
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_REVIEWERS', '')))))),
'publishers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_PUBLISHERS', '')))))),
];
@@ -0,0 +1,84 @@
<?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
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('PostgreSQL required.');
}
Schema::create('existing_businesses', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('code')->unique();
$t->string('source_system')->nullable();
$t->string('legacy_id')->nullable();
$t->unique(['source_system', 'legacy_id']);
$t->foreignId('owner_user_id')->constrained('users')->restrictOnDelete();
$t->foreignUuid('organization_id')->nullable()->constrained('organizations')->restrictOnDelete();
$t->foreignUuid('investment_item_id')->nullable()->unique()->constrained('investment_items')->restrictOnDelete();
$t->string('modality');
$t->string('status')->default('draft');
$t->string('classification')->default('confidential');
$t->unsignedInteger('version_no')->default(1);
$t->text('payload');
$t->timestampsTz();
$t->softDeletesTz();
});
// Phase 1 deliberately cannot publish. Future workflow must replace this constraint explicitly.
DB::statement("ALTER TABLE existing_businesses ADD CHECK(status='draft'), ADD CHECK(version_no>0), ADD CHECK(classification IN ('internal','confidential','restricted')), ADD CHECK((source_system IS NULL)=(legacy_id IS NULL)), ADD CHECK(modality IN ('company_sale','participation_sale','capital_increase','financial_investor','strategic_partner','buyer_search','position_assignment','franchise','asset_sale','asset_lease','business_unit_transfer','joint_venture','succession','recovery','expansion','internationalization','real_estate','agricultural_investment','land_right','mining_license','forestry_license'))");
Schema::create('existing_business_objects', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
$t->string('kind');
$t->string('classification')->default('restricted');
$t->string('verification_status')->default('pending');
$t->text('payload');
$t->timestampsTz();
});
DB::statement("ALTER TABLE existing_business_objects ADD CHECK(kind IN ('company','participation','asset','property','unit','improvement','agricultural_investment','land_right','contract','license','authorization','encumbrance','valuation','capital_request')), ADD CHECK(classification IN ('confidential','restricted')), ADD CHECK(verification_status='pending')");
Schema::create('existing_business_mandates', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
$t->foreignId('representative_user_id')->constrained('users')->restrictOnDelete();
$t->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
$t->date('valid_from');
$t->date('valid_until');
$t->string('verification_status')->default('pending');
$t->text('payload');
$t->timestampsTz();
});
DB::statement("ALTER TABLE existing_business_mandates ADD CHECK(valid_until>=valid_from), ADD CHECK(verification_status='pending')");
Schema::create('existing_business_revisions', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
$t->unsignedInteger('version_no');
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->string('action');
$t->text('reason');
$t->text('snapshot');
$t->char('sha256', 64);
$t->timestampTz('created_at')->useCurrent();
$t->unique(['business_id', 'version_no']);
});
DB::unprepared("CREATE OR REPLACE FUNCTION reject_business_revision_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Business revisions are immutable'; END $$; CREATE TRIGGER immutable_business_revision BEFORE UPDATE OR DELETE ON existing_business_revisions FOR EACH ROW EXECUTE FUNCTION reject_business_revision_change()");
}
public function down(): void
{
$tables = ['existing_business_revisions', 'existing_business_mandates', 'existing_business_objects', 'existing_businesses'];
foreach ($tables as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Business data exists; destructive rollback refused.');
}
}
foreach ($tables as $table) {
Schema::drop($table);
}
DB::statement('DROP FUNCTION reject_business_revision_change()');
}
};
@@ -0,0 +1,37 @@
<?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
{
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_status_check');
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_status_check CHECK(status IN ('draft','submitted','in_review','needs_information','withdrawn'))");
Schema::create('existing_business_reviews', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->unsignedInteger('version_no');
$t->string('action');
$t->text('note');
$t->timestampTz('created_at')->useCurrent();
$t->unique(['business_id', 'version_no']);
});
DB::statement("ALTER TABLE existing_business_reviews ADD CHECK(action IN ('submitted','in_review','needs_information','withdrawn'))");
DB::unprepared('CREATE TRIGGER immutable_business_review BEFORE UPDATE OR DELETE ON existing_business_reviews FOR EACH ROW EXECUTE FUNCTION reject_business_revision_change()');
}
public function down(): void
{
if (DB::table('existing_business_reviews')->exists() || DB::table('existing_businesses')->where('status', '<>', 'draft')->exists()) {
throw new RuntimeException('Intake evidence exists; destructive rollback refused.');
}
Schema::drop('existing_business_reviews');
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_status_check');
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_status_check CHECK(status='draft')");
}
};
@@ -0,0 +1,101 @@
<?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
{
DB::statement('ALTER TABLE geo_locations DROP CONSTRAINT imz_geo_locations_check_03');
DB::statement("ALTER TABLE geo_locations ADD CONSTRAINT imz_geo_locations_check_03 CHECK(location_type IN ('country','province','district','admin_post','locality','municipality','site'))");
Schema::create('geo_sources', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('name');
$t->string('responsible_entity')->nullable();
$t->text('reference');
$t->text('license')->nullable();
$t->char('checksum', 64);
$t->string('source_version');
$t->date('collected_at');
$t->string('original_crs')->nullable();
$t->string('status')->default('pending');
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
$t->text('approval_reference')->nullable();
$t->timestampsTz();
$t->unique(['checksum', 'source_version']);
});
DB::statement("ALTER TABLE geo_sources ADD CHECK(status IN ('pending','approved','revoked')), ADD CHECK(checksum ~ '^[0-9a-f]{64}$'), ADD CHECK(status<>'approved' OR (responsible_entity IS NOT NULL AND license IS NOT NULL))");
Schema::create('geo_territory_profiles', function (Blueprint $t) {
$t->foreignUuid('geo_location_id')->primary()->constrained('geo_locations')->restrictOnDelete();
$t->foreignUuid('source_id')->constrained('geo_sources')->restrictOnDelete();
$t->char('iso2', 2)->nullable()->unique();
$t->char('iso3', 3)->nullable()->unique();
$t->foreignUuid('capital_territory_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$t->date('valid_from');
$t->date('valid_to')->nullable();
$t->string('status')->default('draft');
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
$t->foreignId('publisher_id')->nullable()->constrained('users')->restrictOnDelete();
$t->timestampsTz();
});
DB::statement("ALTER TABLE geo_territory_profiles ADD CHECK(valid_to IS NULL OR valid_to>=valid_from), ADD CHECK(status IN ('draft','pending_review','approved','published','rejected','archived')), ADD CHECK(iso2 IS NULL OR iso2 ~ '^[A-Z]{2}$'), ADD CHECK(iso3 IS NULL OR iso3 ~ '^[A-Z]{3}$'), ADD CHECK(status NOT IN ('approved','published') OR (reviewer_id IS NOT NULL AND reviewer_id<>editor_id)), ADD CHECK(status<>'published' OR (publisher_id IS NOT NULL AND publisher_id<>editor_id AND publisher_id<>reviewer_id))");
Schema::create('geo_names', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
$t->string('language', 10);
$t->string('name');
$t->string('normalized_name');
$t->boolean('official')->default(false);
$t->timestampsTz();
$t->unique(['geo_location_id', 'language', 'normalized_name']);
});
DB::statement('CREATE UNIQUE INDEX geo_names_official_language_uq ON geo_names(geo_location_id,language) WHERE official');
Schema::create('geo_territory_revisions', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
$t->unsignedInteger('version_no');
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->text('reason');
$t->text('snapshot');
$t->char('checksum', 64);
$t->timestampTz('created_at')->useCurrent();
$t->unique(['geo_location_id', 'version_no']);
});
DB::unprepared("CREATE OR REPLACE FUNCTION reject_territory_revision_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Territory revisions are immutable'; END $$; CREATE TRIGGER immutable_territory_revision BEFORE UPDATE OR DELETE ON geo_territory_revisions FOR EACH ROW EXECUTE FUNCTION reject_territory_revision_change()");
Schema::create('geo_write_receipts', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->uuid('idempotency_key');
$t->string('scope');
$t->char('request_hash', 64);
$t->text('response');
$t->integer('http_status');
$t->timestampTz('created_at')->useCurrent();
$t->unique(['actor_id', 'idempotency_key', 'scope']);
});
}
public function down(): void
{
$tables = ['geo_write_receipts', 'geo_territory_revisions', 'geo_names', 'geo_territory_profiles', 'geo_sources'];
foreach ($tables as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Territory evidence exists; destructive rollback refused.');
}
}
if (DB::table('geo_locations')->whereIn('location_type', ['admin_post', 'locality'])->exists()) {
throw new RuntimeException('New territory types exist; rollback refused.');
}
foreach ($tables as $table) {
Schema::drop($table);
}
DB::statement('DROP FUNCTION reject_territory_revision_change()');
DB::statement('ALTER TABLE geo_locations DROP CONSTRAINT imz_geo_locations_check_03');
DB::statement("ALTER TABLE geo_locations ADD CONSTRAINT imz_geo_locations_check_03 CHECK(location_type IN ('country','province','district','municipality','site'))");
}
};
@@ -0,0 +1,38 @@
<?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
{
foreach (['opportunities', 'projects', 'economic_clusters', 'development_corridors', 'investment_zones'] as $table) {
Schema::table($table, function (Blueprint $t) {
$t->foreignUuid('primary_territory_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
$t->unsignedInteger('territory_version')->default(0);
});
}
}
public function down(): void
{
$tables = ['opportunities', 'projects', 'economic_clusters', 'development_corridors', 'investment_zones'];
foreach ($tables as $table) {
if (Schema::hasColumn($table, 'primary_territory_id') && DB::table($table)->whereNotNull('primary_territory_id')->exists()) {
throw new RuntimeException('Preserve territorial assignments before rollback.');
}
}
foreach ($tables as $table) {
if (Schema::hasColumn($table, 'primary_territory_id')) {
Schema::table($table, function (Blueprint $t) {
$t->dropConstrainedForeignId('primary_territory_id');
$t->dropColumn('territory_version');
});
}
}
}
};
+42
View File
@@ -0,0 +1,42 @@
# Revisão das entregas e omissões — 29/09/2026
As instruções de implementação e avanço entre fases estão autorizadas. Não é necessária nova autorização genérica. Este inventário distingue funcionalidades entregues de trabalho por terminar; não substitui a verificação integral de cada requisito dos anexos.
## Falhas confirmadas e corrigidas nesta revisão
1. O Excel foi inicialmente interpretado de forma errada: B:G são códigos, H é a designação do nível mais profundo da linha. Os dropdowns receberam códigos como nomes. Corrigida a transformação, preservando UUID; 1.920 nomes reparados, 69 referências sem definição inequívoca retiradas das opções e preservadas para auditoria. A contagem anterior de 1.990 não provava qualidade ou completude.
2. Os dropdowns só estavam na gestão. Acrescentados ao catálogo público, ao filtro de zonas e à criação de oportunidades, clusters/projectos e zonas. Removidos os inputs livres de província/distrito das fichas de edição de oportunidades e zonas; alterações de localização usam os identificadores.
3. As associações guardadas não eram usadas pela pesquisa pública. A pesquisa passa a usar o território seleccionado e os seus descendentes, com validação da hierarquia. A pesquisa da carteira considera a localização dos projectos/clusters/corredores ligados aos dossiers publicados.
4. As seis oportunidades existentes estavam sem relação territorial. Foram associadas às províncias por correspondência única de nome, normalizando apenas caixa, espaços exteriores e acentuação. Não se inferiram distritos a partir de descrições.
5. O envio do filtro pelo navegador falhava: `education=false` em texto não passava a validação booleana e `filters=[]` fazia a leitura de `.sort` devolver o método nativo JavaScript. Corrigidos serialização 0/1 e valor inicial da ordenação; teste real de selecção, submissão e recarregamento passou.
6. Alterar a localização de uma zona podia deixar a versão documental intacta. A alteração passa pelo serviço da zona, cria snapshot e devolve o registo a rascunho.
## Dados e disponibilidade actual
Referências com nomes efectivamente extraídos: **11 províncias, 148 distritos, 437 postos administrativos e 1.324 localidades**, além do país. Estes totais referem-se ao Excel recebido; não são declaração de cobertura administrativa actual do país. Dez linhas foram sinalizadas por conflitos/lacunas; 18.477 linhas de bairros/aldeias não são convertidas em localidades. As 69 referências anteriores sem definição inequívoca ficaram arquivadas, sem quebra de FK.
Disponível localmente em `/oportunidades`, `/zonas`, nas páginas de criação/edição aplicáveis e em `/management/territory-associations`. Filtro público expõe apenas ID/nome/tipo/pai das referências divulgadas, não os ficheiros originais. Publicação do vocabulário alfanumérico por instrução do responsável não equivale a publicação de limites geográficos homologados. Os dados confidenciais/restritos e ascendentes retirados não entram nas opções públicas.
Backup/restauro verificado antes desta correcção: `storage/app/private/zones-backup-20260929-005946/`, 113 tabelas. Relatórios e candidatos anteriores permanecem privados. A reparação não introduziu nova migration nem apagou referências fisicamente.
## Trabalho que continua por terminar
| Área | Lacuna confirmada nos relatórios/código | Trabalho necessário |
| --- | --- | --- |
| GIS completo | Limites geográficos versionados, transformação/validação de geometrias, endpoints resolve/near/bbox e cobertura espacial não entregues integralmente | Implementar serviços e contratos; carregar geometrias apenas quando fornecidas, sem inventar coordenadas |
| Integração territorial transversal | A nova associação é principal; os consumidores educativos, organizações e restantes formulários não usam ainda todos o mesmo selector; relações múltiplas legadas continuam separadas | Consolidar consumidores e testar cada jornada, incluindo históricos e remoção de referências |
| Importação territorial | CSV auditado, mas não existe ainda o workflow integral de batches/rejeições/aprovação/carga; PDF histórico tem colunas ambíguas | Terminar pipeline, excepções documentadas e reconciliação dos códigos; não tratar aprovação como reparação automática de dados contraditórios |
| IA | Base lexical/determinística; não há modelo generativo, embeddings, reranker ou benchmark generativo | Implementar RAG e avaliação com corpus autorizado; documentar recursos e fornecedor efectivamente usados |
| Mercado de Negócios | Preparação/submissão privada e objectos tipados; publicação, revisão completa, sala documental segura e integrações não concluídas | Implementar os estados/jornadas restantes, acesso documental, scanner, retenção e testes |
| ZEE/ZFI | Núcleo e filtros existentes; cadastro local de zonas continua vazio; modelo integral de actividades, benefícios, obrigações, lotes e indicadores não entregue | Completar domínio e importar conteúdos disponíveis com origem; não substituir dados ausentes por zonas fictícias |
| Educação | Há implementação parcial; metodologia, consumidores, integração e piloto não estão integralmente entregues | Confrontar decisões posteriores com o relatório histórico, executar lacunas técnicas e testar o fluxo completo |
| CRM/integrações | A integração externa real com SuiteCRM e a consolidação da outra máquina não foram executadas | Validar ligação quando disponível; a consolidação da outra máquina foi expressamente adiada pelo utilizador |
| Operação/QA | Testes automáticos e alguns percursos de navegador não cobrem todos os prompts; carga, acessibilidade assistiva e produção não demonstradas | Matriz de aceitação por jornada, testes com dados reais, ensaios operacionais e disponibilização no destino configurado |
Estas lacunas não são todas bloqueios de autorização. A maior parte corresponde a implementação que ficou por fazer. Dependências de dados, de ligações externas e de recursos de execução devem ser identificadas separadamente; não servem para suspender trabalho independente já autorizado.
## Evidência desta correcção
`tools/territory-public-browser.mjs` verifica o portal local sem escrever dados: 11 províncias com nomes, 17 opções de distrito para Zambezia, duas oportunidades correspondentes, filtro no URL preservado após recarregar, larguras 390/1.440 px sem overflow e zero erros JavaScript. A suite PHP cobre autorização, referências privadas, hierarquia, criação, associação, conflitos de versão e pesquisa. Os totais finais são registados no relatório GIS.
Não declarar os prompts integralmente concluídos enquanto a matriz acima contiver lacunas. A disponibilidade de uma tabela, de um endpoint ou de um teste isolado não equivale à entrega da jornada pedida pelo utilizador.
+127
View File
@@ -0,0 +1,127 @@
# Mercado de Negócios Existentes — Fase 0
Estado mais recente: [implementação e operação local do núcleo privado](implementation-status.md). A progressão entre fases foi posteriormente autorizada pelo utilizador; as paragens históricas abaixo não representam a autorização actual.
Actualização posterior: o utilizador solicitou continuação. Foi implementado e testado o [núcleo privado da Fase 1](phase-1.md). A presente página conserva o diagnóstico e a decisão histórica da Fase 0; não é o estado mais recente da implementação.
Data: 28/09/2026. Branch: `feature/existing-business-phase-0`.
## Execução e decisão
Fase executada: descoberta e enquadramento. Todas as etapas estão autorizadas para implementação, mas o prompt exige executar uma fase de cada vez e proíbe avançar automaticamente. Esta entrega não inicia a Fase 1.
**Recomendação: No-Go para o gate de prontidão da Fase 0.** A autorização de desenvolvimento do dono do produto está registada. Não foram fornecidas política de publicação aprovada, base legal validada, equipa nominal, carteira piloto com titulares confirmados ou evidência suficiente para homologar o ambiente. O diagnóstico técnico está entregue; a fase não está homologada como concluída. Não se inventaram essas aprovações.
## Diagnóstico confirmado
| Componente | Evidência no repositório | Aplicação ao mercado |
| --- | --- | --- |
| Stack | composer.lock: Laravel 13.30.1, Fortify 1.39.0, Inertia Laravel 3.3.3; instalados React 19.2.8, TypeScript 5.9.3, Vite 8.2.2 | Compatível; sem nova dependência |
| Runtime e BD | Inventário apenas de leitura: PHP 8.5.11, PostgreSQL 17.11, PostGIS 3.6.2 | Reutilizar; desenvolvimento local não comprova prontidão de produção |
| Identidade | users, organizations, memberships; Fortify e manage-portal | Identidade da conta não comprova titularidade nem representação; falta mandato por anúncio |
| Catálogo | InvestmentCatalogue, investment_items e mapeamento de oportunidades | Preservar IDs; não converter oportunidade em negócio sem revisão |
| Workspace | InvestmentWorkspace, InvestmentSubmissionController | Cifragem, snapshots, consentimento, mensagens e notificações reutilizáveis; sem workflow MNE |
| Documentos | documents, anexos privados, download autenticado com checksum | Não equivale a data room: faltam grants temporais, NDA validado, watermark e scanner comprovado |
| CRM interno | ConvertInterestToLead, CrmTask, leads, interest_requests | Conversão transaccional, consentimento e próxima acção; falta deduplicação negócio/modalidade/período |
| CRM externo | SuiteCrmClient, config/suitecrm.php, testes com doubles | Timeout 10s, ligação 3s, retries de leitura 2 e circuito configurados; nenhuma sincronização MNE real comprovada |
| Territórios | Clusters/corredores/projectos, zonas, PostGIS | Reutilizar relações; GIS transversal ainda incompleto, conforme ../gis/README.md |
| Notificações | investment_notifications, outbox_events/inbox_events | Notificações internas e infraestrutura; não presumir envio externo ou SLA contratado |
| Pagamentos/facturação | Nenhum módulo operacional identificado nas áreas inspeccionadas | Fora do piloto; sem taxas, comissões, impostos ou cobrança inventados |
| Jurídico | Fontes de zonas e documentos; não foi encontrado motor de elegibilidade MNE | Não reutilizar validação de ZEE como análise jurídica de venda/cessão |
Inventário agregado local em 28/09/2026: 103 tabelas, 38 migrations, 6 oportunidades, 6 investment_items, 16 projectos, 29 dossiers, 8 clusters, 6 corredores. Zero documentos, organizações, geometrias, localizações, zonas, pedidos de interesse e leads. Há 1 investidor; não foi lido o seu conteúdo. As 6 oportunidades não têm opportunity_profiles com source_reference; este indicador não prova ausência de todas as fontes possíveis. Nenhum destes registos foi reclassificado como negócio existente.
Não se encontrou cadastro dedicado de anúncios MNE, mandatos, titularidades, licenças transferíveis, data rooms, propostas MNE ou comissões. Pesquisa por nomes não substitui inventário semântico com os responsáveis. Não foram consultados segredos nem activados serviços externos.
## Conservar–Melhorar–Substituir–Descontinuar
| Decisão | Componente | Acção proposta |
| --- | --- | --- |
| Conservar | Laravel/React/PostGIS, identidade, documentos canónicos, outbox e IDs mestres | Adaptadores versionados; manter contratos existentes |
| Melhorar | Autorização | Função e atributo por anúncio, mandatário, revisor e aprovador; MFA privilegiado; segregação em dois níveis |
| Melhorar | Documentos e CRM | Quarentena/scanner, grants revogáveis, escopo por anúncio; idempotência e reconciliação MNE |
| Melhorar | Catálogo, pesquisa e GIS | Projecção pública mínima separada; indexar só atributos autorizados; testar reidentificação |
| Substituir, apenas no novo fluxo | Autodeclaração como prova de legitimidade | Evidência documental e revisão humana; preservar declarações históricas |
| Descontinuar | Nenhum componente existente nesta fase | Nenhuma remoção; retirar práticas de divulgação não autorizada apenas após análise de impacto |
## Jornada proposta
1. Anunciante cria rascunho privado e escolhe modalidade; identifica natureza do negócio/activo/direito sem anunciar transmissibilidade como facto.
2. Submete identidade, representação/mandato, documentos, fontes, consentimentos e autorização de publicação.
3. Triagem verifica completude e sinais de fraude; revisor examina evidências; pendências regressam ao anunciante. Titularidade declarada e documentalmente verificada são estados distintos.
4. Dois níveis de aprovação independentes avaliam a versão exacta; alterações relevantes invalidam aprovações. Publicação produz apenas resumo autorizado e localização indicativa.
5. Interessado pesquisa e manifesta interesse; CRM deduplica pela chave acordada, conserva origens e atribui responsável/próxima acção.
6. Pedido de acesso exige conflitos declarados, aprovação do proprietário e NDA apenas após validação jurídica; sala segregada e temporária.
7. Diligência especializada, propostas não vinculativas e negociação assistida; encerramento regista resultado sem formalizar transmissão.
8. Expiração/revogação/denúncia suspende divulgação e acessos afectados; revisão e arquivo preservam evidências segundo retenção aprovada.
Estados solicitados: rascunho, submetido, em triagem, em revisão, pendente de informação, validado, aprovado, publicado, suspenso, retirado, em negociação, concluído, arquivado. Grafo de transições, actores e invariantes serão definidos na Fase 1; ainda não existe máquina de estados MNE implementada.
## RACI proposto — atribuições nominais pendentes
| Actividade | Responsável pela execução (R) | Responsável final (A) | Consultados (C) | Informados (I) |
| --- | --- | --- | --- | --- |
| Escopo, piloto e política | Produto | Dono do Produto | Jurídico, Dados, Segurança | Operações |
| Modelo e contratos | Engenharia/Arquitectura | Arquitectura | Dados, CRM, Segurança | Produto |
| Legitimidade, direitos, NDA, KYC/AML aplicável | Jurídico/Conformidade | Responsável jurídico designado | Titular, entidade competente quando autorizada | Produto |
| Triagem e revisão documental | Operações/revisor | Gestor de validação | Jurídico, Dados | Anunciante |
| Aprovação/publicação | Aprovadores de níveis 1 e 2 | Responsável editorial designado | Jurídico, Segurança | CRM |
| Sala segura e incidentes | Segurança/Operações | Responsável de segurança | Jurídico, Dados | Produto |
| UAT e recuperação | QA/Operações | Dono do Produto | Arquitectura, Segurança | Suporte |
| Comissões/facturação futura | Finanças | Responsável financeiro | Jurídico, Auditoria | Produto |
Papéis propostos não concedem permissões. Ninguém foi nomeado por inferência. Autor da submissão não pode aprovar a própria publicação; os dois níveis exigem segregação a especificar e testar.
## Matriz jurídica e modalidades
Esta matriz é de **questões para validação**, não parecer ou afirmação de admissibilidade legal. Não foram inventadas leis, termos de uso ou autoridades competentes. Regra, fonte oficial, versão, entidade, parecer e validade ficam pendentes.
| Grupo de modalidades solicitadas | Objecto a distinguir | Verificação e documento necessário | Responsável proposto / estado |
| --- | --- | --- | --- |
| Venda 100%, parcial, aumento de capital, investidor financeiro, sócio estratégico, comprador | Empresa, participação, mandato e avaliação | Titularidade/representação, encargos, consentimentos e requisitos da operação | Jurídico + titular / pendente |
| Cessão de posição, franchising, joint venture | Contrato, licença de uso, posição contratual | Restrições, consentimentos de terceiros, validade e análise da cessão | Jurídico / pendente |
| Venda/arrendamento de activos, transferência de unidade, sucessão | Activo físico, unidade, contratos e obrigações | Cadeia documental, legitimidade, passivos e autorizações | Jurídico + diligência especializada / pendente |
| Recuperação, expansão, internacionalização | Pedido de capital e finalidade | Informação financeira rotulada, riscos e verificação independente | Revisor + assessor / pendente |
| Imobiliário, propriedades, benfeitorias, investimentos agrícolas | Imóvel/unidade, investimento, direito de uso/ocupação e contrato separados | Área/limites, ocupação, encargos, litígios, finalidade, prazo, autorizações e transmissibilidade | Jurídico fundiário + entidade competente por confirmar / pendente |
| Licenças mineiras/florestais e outras | Licença, titular declarado, entidade emissora e actividade | Fonte competente autorizada, validade, restrições, obrigações e possibilidade de transmissão | Jurídico sectorial + entidade por confirmar / pendente |
Termos de uso, base de tratamento, consentimento granular, retenção, conflitos de interesse, prevenção de fraude, denúncias, critérios AML/KYC quando aplicáveis e NDA: todos pendentes de aprovação especializada. Não recolher prova de fundos como obrigação geral nem presumir validade de assinatura electrónica. Política proposta: ausência de evidência bloqueia publicação/acesso; nenhum rótulo indica certificação da Tempo.
## Classificação e ameaças
| Dados | Classificação inicial proposta | Controlos e teste de aceitação |
| --- | --- | --- |
| Teaser aprovado, modalidade, sector, região indicativa, valor rotulado | Público apenas após autorização | Allowlist na API/índice/exportação; teste de reidentificação |
| Triagem, tarefas, estados, origens CRM | Interno | Menor privilégio; auditoria sem conteúdo reservado |
| Empresa, financeiros, contratos, clientes/fornecedores, propostas | Confidencial | Cifragem, escopo por anúncio, grants temporais; teste de acesso cruzado |
| Identidade, títulos/licenças integrais, coordenadas exactas, segredos e denúncias | Restrito por defeito até classificação aprovada | Sem índice público; URLs não públicas, revogação/expiração, logs minimizados |
Finalidade, base, dono, retenção, eliminação e divulgação precisam de decisão por categoria; nenhum prazo foi inventado. Cifragem existente depende da chave Laravel e não substitui gestão de chaves, mandatos ou política de retenção.
| Ameaça | Controlo planeado | Prova exigida |
| --- | --- | --- |
| Anunciante falso/mandato revogado | Verificação separada de conta, identidade, representação e mandato; revalidação | Publicação negada quando ausente/expirado/revogado |
| IDOR entre negócios ou data rooms | Autorização por utilizador, negócio, documento, versão e grant | Leitura/download/listagem cruzados negados |
| Auto-publicação e corrida de versões | Dupla aprovação, lock transaccional e versão esperada | Auto-aprovação negada; versão obsoleta 409 |
| Reidentificação no mapa/pesquisa | Projecção mínima e política GIS comum | Nenhuma coordenada restrita por filtros, cache ou exportação |
| Malware/ficheiro disfarçado | Quarentena, análise e validação de conteúdo | Nenhum download antes do resultado autorizado; falha do scanner bloqueia |
| Revogação com URL/cache persistente | Revalidar cada acesso, no-store, invalidação e TTL | URL partilhado/expirado não concede acesso |
| Duplicação/replay CRM e webhooks | Chave de idempotência, outbox/inbox, autenticação e reconciliação | Replay não duplica lead; falha externa recuperável |
| Fraude, discriminação ou matching opaco | Sinais explicáveis, fila humana, conflitos e denúncias | Sem contacto/recusa definitiva automática |
| Pipeline contabilizado como receita | Valores por natureza e eventos financeiros aprovados | Comissão/cobrança bloqueadas sem contrato/regra/evento |
## Backlog e escopo piloto proposto
Fase 1: modelo canónico, modalidades, activos/direitos separados, mandato, classificação, revisões, retenção e invariantes. Fase 2: submissão privada, dois níveis, documentos em quarentena, API versionada e OpenAPI. Fase 3: projecção pública, filtros, acessibilidade e mapas autorizados. Fase 4: interesse/CRM e matching revisto. Fase 5: acesso/NDA/sala segura/diligência. Fase 6: negociação; facturação só quando enquadrada. Fase 7: migração, piloto e operação.
Piloto proposto: ambiente isolado e fixtures exclusivamente sintéticas; primeiro rascunho privado de participação empresarial, sem divulgação, pagamento, NDA emitido ou integração externa real. Carteira real, quantidade, modalidades elegíveis e titulares dependem de validação. Não excluir do backlog as modalidades imobiliárias/fundiárias/licenças; ficam sujeitas às verificações específicas acima.
Prontidão: dono e equipa nomeados; política/base/termos aprovados; amostra piloto legitimada; matriz de acesso/retencão; backup/restauro; zero defeitos críticos nas jornadas; revisão humana de segurança; suporte e resposta a incidentes; reconciliação e rollback ensaiados. A autorização genérica de implementação não prova estes itens.
## Plano aplicado e ficheiros
Inspeccionados manifests/locks, migrations, configuração de CRM, serviços de catálogo/workspace/CRM, controllers de documentos, testes e inventário agregado em transacção READ ONLY. Criada branch própria, preservando alterações não commitadas anteriores de GIS e interface. Produzidos este diagnóstico, `traceability.csv` e `validation.md`. Nenhum ficheiro aplicacional removido ou alterado para o MNE.
Migrations/seeders: nenhum nesta fase de descoberta. Não alterados schema, dados de negócio, APIs, componentes ou integrações. Não se justifica gerar migrations sem modelo aprovado e depois chamar à descoberta uma implementação funcional. Rollback desta fase: reverter apenas o commit documental MNE; não usar reset/clean nem reverter alterações GIS/portal já existentes.
Proposta da fase seguinte: reconciliar entidades existentes e produzir modelo ER/dicionário/invariantes da Fase 1; caminhos, tabelas e endpoints novos serão propostas explícitas, não descritos como existentes. Não iniciada nesta entrega.
@@ -0,0 +1,27 @@
{
"date": "2026-09-29T06:39:38.960Z",
"scope": "Synthetic private create/save and responsive layout in isolated QA; institutional review covered by integration tests",
"observations": [
{
"scenario": "private_create_and_save",
"passed": true
},
{
"scenario": "private_submit_with_review_consent",
"passed": true
},
{
"width": 390,
"breadcrumb": true,
"supportVisible": true,
"overflow": false
},
{
"width": 1440,
"breadcrumb": true,
"supportVisible": true,
"overflow": false
}
],
"errors": []
}
@@ -0,0 +1,68 @@
# Estado actual — Mercado de Negócios Existentes
Actualização 29/09/2026: [revisão granular com evidência, validade e invalidação por alteração](verification-evidence.md) implementada na ficha privada. Suite: 173 testes / 1785 verificações aprovadas. Os limites e contagens abaixo descrevem a entrega anterior; o módulo integral continua incompleto.
28/09/2026. A instrução mais recente autoriza executar todas as fases e avançar automaticamente. Substitui a paragem entre fases do prompt inicial. Não presume evidências jurídicas, nomeação de revisores, publicação ou integração externa efectiva.
## Entrega utilizável localmente
- `/investidor/negocios`: lista própria, criação privada e formulário reservado.
- `/investidor/negocios/{uuid}`: edição, elementos separados, fonte/validade, submissão com consentimento de análise interna, histórico e retirada.
- `/management/negocios`: fila reservada aos gestores designados para revisão e com MFA confirmado; exclui os próprios negócios.
- O revisor inicia análise e pede informação; o proprietário consulta a nota, corrige e pode ressubmeter. Submissão não significa identidade, representação ou titularidade verificadas.
- O negócio fica bloqueado para edição enquanto submetido/em revisão. Todas as alterações exigem versão actual; revisões e decisões são transaccionais e imutáveis. A retirada remove imediatamente o acesso do revisor e a entrada da fila.
- Cada activo, imóvel, unidade, benfeitoria, investimento agrícola, direito, contrato, licença, autorização, encargo, participação, avaliação ou pedido de capital tem identificador próprio, natureza imutável e payload cifrado. Referências documentais são declarações, não ficheiros validados.
- Campos reservados incluem titular, entidade competente declarada, fonte, referência documental, finalidade, localização/limites descritivos, ocupação/conservação, encargos, restrições, autorizações e condição de transmissão. Não se inferem coordenadas nem direitos.
- Área exige unidade; montante exige moeda e natureza do valor. Datas indicadas em conjunto têm de ser coerentes. Nenhum montante é receita; todos os elementos permanecem `pending`.
- O serviço de objectos aplica autorização do agregado, controla versão e grava o snapshot completo cifrado. Edição cruzada por UUID é recusada. A lista/ficha só é entregue após verificação de acesso.
Não existe publicação neste incremento. A constraint da BD permite apenas `draft`, `submitted`, `in_review`, `needs_information`, `withdrawn`; `approved` e `published` são recusados. Não há endpoint público MNE nem documentos descarregáveis, contrato emitido, cobrança ou decisão de transmissibilidade.
## Matriz das fases e decisões
| Fase | Executado | Lacunas / decisão |
| --- | --- | --- |
| 0 — descoberta | Diagnóstico, ameaças, RACI, matriz jurídica, baseline | Política/base/equipa/piloto não homologados; No-Go institucional mantém-se |
| 1 — modelo | Negócio, objectos tipados separados, mandato pendente, classificação, versões, histórico, rollback | Relações documentais/territoriais detalhadas, titularidade comprovada, revisão de mandatos e retenção homologada pendentes; Go condicionado técnico |
| 2 — submissão/administração | UI e API de rascunho, submissão, consentimento, revisão independente, pedido de informação, retirada | Upload/scanner, verificações documentais, dois níveis de aprovação e publicação ainda não implementados; núcleo privado utilizável, fase parcial |
| 3 — catálogo público | Nenhuma ficha reservada enviada ao catálogo público | Projecção anonimizada, revisão de reidentificação, filtros e mapas MNE pendentes; No-Go para divulgação |
| 4 — CRM/matching | CRM existente preservado; nenhum lead MNE enviado | Deduplicação interessado/negócio/modalidade/período, matching revisto e integrações MNE pendentes |
| 5 — sala segura | Referências declarativas e cifragem privadas | NDA juridicamente aprovado, grants temporais, malware, watermark e diligência não implementados; sem sala segura anunciada |
| 6 — negociação/monetização | Valores reservados rotulados por natureza | Workflow negocial, contrato/regra financeira, facturação e reconciliação pendentes; nenhuma cobrança |
| 7 — piloto/operação | Backup/restauro, migrations locais, reconciliação, testes e build | Piloto real, UAT institucional, carga, recuperação MNE completa, PT/EN completo e decisão formal de produção pendentes |
Não se declara conclusão integral do prompt. Aprovação para desenvolver não torna disponíveis os documentos, mandatos ou regras que faltam. O próximo trabalho técnico é a evidência documental e a governação da validação, antes da publicação; não é necessário repetir autorização de desenvolvimento.
## Ficheiros e contratos
Novos: `ExistingBusinessController`, `ExistingBusinessEnabled`, `ExistingBusinessIntake`, `ExistingBusinessObjects`, `config/existing-business.php`, `routes/existing-business.php`, migration `2026_09_28_140000_existing_business_intake`, teste `ExistingBusinessIntakeTest`, React `businesses`, `business`, `business-types`, `business-objects`; ferramentas `existing-business-openapi.mjs`, `existing-business-browser.mjs` e `existing-business-reconcile.php`.
Adaptados: policy e snapshots MNE, shared props Inertia, navegação, web routes e testes de rollback em ordem inversa das dependências. Nenhum ficheiro removido.
[OpenAPI](openapi.json): oito operações API v1 privadas de listagem, criação, consulta, edição, transição e objectos. Contrato preserva as APIs anteriores. Sessão, email verificado, CSRF/origin Laravel, limite de 30 pedidos/minuto e `Cache-Control: private, no-store`; nomes de cookie dependem do ambiente. Não existe bearer token inventado. Erros de validação 422, autorização 403, versão/estado 409; módulo desactivado 404. Contrato de eventos externos e correlation_id transversal ainda por implementar; não fingir integração completa.
## Activação e reconciliação local
Backup antes das migrations: `storage/app/private/zones-backup-20260928-151000/`, SHA-256 `f7b56bfcf76d1937ba6a1e58142e8a85c25c69c2d1d21418703c9ed54f70c851`. Restauro isolado verificado e 103 tabelas reconciliadas. Configuração anterior guardada privadamente no mesmo directório; contém segredos e não deve ser publicada.
Migrations 130000 e 140000 aplicadas localmente. Reconciliação posterior com `php tools/existing-business-reconcile.php <manifesto-privado>`: só migrations mudou de 38 para 40; 5 tabelas MNE novas, todas vazias. Total 108 tabelas. Nenhum anúncio ou documento real importado. Fixtures do navegador residem apenas em `portal_services_test`, nunca na base da aplicação.
`INVESTMOZ_MNE_ENABLED=true` activado apenas na `.env` local; configuração de origem mantém default false. `INVESTMOZ_MNE_REVIEWERS` é uma lista de emails de gestores previamente autorizados e com MFA. Nenhum revisor foi nomeado automaticamente (contagem local: zero). O proprietário pode preparar/submeter; a fila exige designação administrativa explícita, que não prova competência jurídica.
## Validação
Resultado final após integrar os objectos: **157 testes / 1647 verificações aprovadas**, 47369 ms. Build final: 2363 módulos, 16,29 s. Navegador repetido sobre o build final: quatro observações aprovadas, zero erros JavaScript. Ajuste posterior de limites/representação decimal verificado novamente nos testes focados.
- Suite antes de acrescentar objectos: 156 testes / 1633 verificações aprovadas.
- Testes focados após objectos: 9 testes / 67 verificações aprovadas; isolamento entre negócios, natureza imutável, valores/moeda, cifragem e snapshot incluídos.
- Áreas e montantes usam strings decimais (sem conversão para float); máximo de 100 elementos por negócio para limitar tamanho de histórico/respostas.
- PHPStan, TypeScript, lint e Pint aprovados nos ficheiros verificados.
- Build inicial das páginas: 2362 módulos, 8,46 s. Validação final após objectos registada abaixo.
- Navegador QA em 390 e 1440 px: criar/gravar/submeter com consentimento, breadcrumbs, apoio fixo, ausência de overflow e zero erros JavaScript. [Evidência](browser-validation.json). Não é UAT institucional, pentest ou certificação WCAG.
- `tools/existing-business-browser.mjs` usa exclusivamente servidor QA local na porta 18027 e Edge de teste em 9224. Conta sintética preparada na base isolada; não executar contra produção. O teste nunca publica negócios.
## Suspensão e rollback
Para suspender acesso: `INVESTMOZ_MNE_ENABLED=false` e `php artisan config:clear`; conservar dados e evidências. Novas tabelas vazias permitem down de 140000 antes de 130000. Os testes confirmam recusa de rollback destrutivo quando há negócios ou decisões. Não usar CASCADE, DROP EXTENSION ou `migrate:fresh` na aplicação. Preferir correcção progressiva quando existam dados; qualquer restauro substitutivo exige plano de reconciliação para alterações posteriores ao backup.
Riscos residuais: mandatos ainda declarativos, ausência de scanner e fluxo documental, revisão editorial/jurídica não implementada, objectos com metadados tipados mas conteúdo declarativo, ausência de duas aprovações e política final de retenção. Estes limites impedem abertura pública, sala segura e transacções; não impedem a preparação privada identificada como pendente.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,60 @@
# Fase 1 — núcleo privado do modelo canónico
28/09/2026. Continuação expressamente solicitada após a Fase 0. Estado: **implementação parcial; Go condicionado para revisão técnica, No-Go para publicação/piloto real**. Não se declara concluído todo o modelo solicitado. Fase 2 não iniciada.
## Plano aplicado e modelo
Migration aditiva `2026_09_28_130000_existing_business_foundation.php`, três modelos, `ExistingBusinessPolicy`, serviço `ExistingBusinessDrafts` e testes de integração. Reutiliza users, organizations, investment_items e documents, sem converter os registos existentes. Nenhuma API, ecrã, integração ou contrato anterior foi modificado. O serviço é interno; não há rota para submissão pública nesta fase.
```mermaid
erDiagram
users ||--o{ existing_businesses : owns
organizations o|--o{ existing_businesses : identifies
investment_items o|--o| existing_businesses : maps
existing_businesses ||--o{ existing_business_objects : describes
existing_businesses ||--o{ existing_business_mandates : receives
documents ||--o{ existing_business_mandates : evidences
users ||--o{ existing_business_mandates : represents
existing_businesses ||--o{ existing_business_revisions : versions
```
## Dicionário implementado
| Tabela | Campos e invariantes |
| --- | --- |
| existing_businesses | UUID, code único permanente, source_system/legacy_id conjuntamente nulos ou presentes e únicos, owner_user_id obrigatório, organization_id opcional, investment_item_id opcional e único, modality, status exclusivamente draft, classification internal/confidential/restricted, version_no positivo, payload cifrado, timestamps e deleted_at |
| existing_business_objects | UUID, business_id, kind distinguindo company/participation/asset/property/unit/improvement/agricultural_investment/land_right/contract/license/authorization/encumbrance/valuation/capital_request, classification confidential/restricted, verification_status exclusivamente pending, payload cifrado, timestamps |
| existing_business_mandates | UUID, business_id, representative_user_id, document_id, valid_from/valid_until coerentes, verification_status exclusivamente pending, payload cifrado, timestamps. Documento anexado não comprova legitimidade. Nenhum acesso é concedido pelo mandato pendente. |
| existing_business_revisions | UUID, business_id/version_no únicos, actor_id, action, reason cifrada, snapshot cifrado, SHA-256 do snapshot e created_at. Trigger rejeita UPDATE/DELETE. |
Modalidades implementadas como vocabulário técnico, sem declarar admissibilidade: venda de empresa/participação, aumento de capital, investidor financeiro, parceiro estratégico, comprador, cessão, franchise, venda/arrendamento de activo, unidade, joint venture, sucessão, recuperação, expansão, internacionalização, imobiliário, investimento agrícola, direito fundiário e licenças mineira/florestal. As modalidades não fazem aprovação jurídica automática.
Payload do rascunho aceita apenas title, description, declared_reason, source_reference e valid_until. Todos permanecem privados e declarativos; podem estar incompletos. Não aceita identidade empresarial, mandato, valor, direito ou status arbitrários para os apresentar como verificados. Os modelos de objecto e mandato são suportes de persistência sem endpoints ou workflows ainda. Não os expor directamente antes de implementar validação por tipo e autorização por agregado.
## Autorização, histórico e confidencialidade
Conta com email verificado pode criar rascunho. Só o proprietário verificado pode ler/alterar/arquivar pelo policy. Gestor genérico não ganha acesso aos dados reservados. Os privilégios de revisão, MFA e segregação em dois níveis serão introduzidos explicitamente no workflow; ainda não há papel privilegiado MNE.
O serviço bloqueia a linha, compara versão, grava alteração e revisão na mesma transacção. Motivo é obrigatório e cifrado. Arquivo usa soft delete e incrementa versão. Payload não participa na serialização normal do modelo. Nenhum log transporta o conteúdo. A constraint de status permite apenas draft: não há caminho de publicação até uma migration futura acompanhada do workflow aprovado.
Limite: serviços/models não substituem privilégios de administração da BD. O histórico implementado cobre alterações de rascunho feitas pelo serviço; objectos e mandatos ainda precisam dos seus próprios serviços e snapshots antes de disponibilizar edição. SHA-256 verifica integridade de conteúdo; não é assinatura jurídica.
## Retenção e lacunas
Sem prazos inventados nem purga automática. Soft delete conserva evidências; duração, base legal, eliminação, litígio e gestão de chaves continuam pendentes da política. A não eliminação automática é uma precaução técnica temporária, não uma política de retenção homologada.
Faltam normalização detalhada de participações/valores/moedas, titularidade e cadeias documentais, emissor, área/unidades, contratos, ónus/restrições, transmissibilidade, relações territoriais, autorização editorial, consentimentos por finalidade, diligência, propostas e encerramento. Os payloads de objectos não são substituto final dessas entidades. Política/base legal, equipa nominal e carteira piloto continuam pendentes.
## Testes e reversão
Suite completa após integração: **153 testes, 1597 verificações aprovadas (34741 ms)**. PHPStan e Pint aprovados. A primeira execução completa identificou a nova dependência do catálogo no teste de rollback das zonas; o teste foi actualizado para remover/recriar a migration MNE na ordem correcta. Não se usou CASCADE. Resultado final sem falhas.
Base isolada `portal_services_test` em localhost:55441, APP_ENV=testing. `php vendor/bin/phpunit tests/Feature/ExistingBusinessFoundationTest.php --do-not-cache-result`: **5 testes, 17 verificações aprovadas**. Verifica cifragem e ocultação, proprietário versus outro gestor, email não verificado, versões desactualizadas, soft delete, histórico imutável, bloqueio de publicação e down/up vazio seguido de recusa de down com dados.
Migration executada apenas pelos testes na base isolada; não aplicada à base local da aplicação. Nenhum seeder ou dado real inserido. `down()` verifica as quatro tabelas antes de alterar qualquer uma, recusa dados, remove por dependência e não usa CASCADE nem DROP EXTENSION. Em ambiente com dados, manter o módulo inacessível e corrigir progressivamente; qualquer restauro exige backup verificado e reconciliação.
## Rastreabilidade deste incremento
RF-MNE-001: negócio/proprietário/modalidades/modelo/policy/testes implementados parcialmente; legitimidade não comprovada. RF-MNE-002/003: distinção tipológica de objectos e estado pending, sem validação jurídica. RF-MNE-004: cifragem, versão, histórico e publicação bloqueada; dupla aprovação ainda não implementada. RF-MNE-007: referência documental de mandato, sem sala segura. RF-MNE-009: rollback vazio testado e protecção contra perda de dados; migração de anúncios reais não executada.
Próximo incremento da própria Fase 1: contratos tipados e normalização dos objectos/valores, associação de fontes e governação por agregado, sem abrir publicação. Fase 2 só após modelo e invariantes completos.
@@ -0,0 +1,10 @@
rf_local,modalidade,objecto,regra_juridica,entidade,migration,modelo,servico,api,ecra,validacao,teste_planeado,fase,responsavel,estado
RF-MNE-001,todas,negocio e mandato,pendente,pendente,proposta fase 1,proposta fase 1,proposta fase 2,proposta fase 2,submissao privada,identidade e representacao,mandato ausente impede publicacao,1-2,Juridico e Engenharia,nao implementado
RF-MNE-002,imobiliario e agricola,imovel benfeitoria direito e contrato,pendente,pendente,proposta fase 1,entidades separadas,proposta fase 2,proposta fase 2,revisao especializada,titularidade validade encargos e transmissibilidade,direito nao analisado impede publicacao,1-2,Juridico especializado,nao implementado
RF-MNE-003,mineira e florestal,licenca e autorizacao,pendente,pendente,proposta fase 1,entidades separadas,proposta fase 2,proposta fase 2,revisao especializada,fonte competente autorizada,licenca expirada impede publicacao,1-2,Juridico sectorial,nao implementado
RF-MNE-004,todas,anuncio publico,politica pendente,aprovadores por nomear,proposta fase 1,versoes e aprovacoes,workflow proposto,versao a definir,catalogo e administracao,dois niveis e classificacao,auto-publicacao e versao obsoleta negadas,2-3,Produto e Seguranca,nao implementado
RF-MNE-005,todas,localizacao e ficha,divulgacao pendente,pendente,reutilizar GIS com adaptacao,projeccao publica,politica comum proposta,contrato a definir,lista mapa e comparacao,precisao autorizada,nao reidentificacao por combinacao,3,Dados e Seguranca,base parcial
RF-MNE-006,todas,interesse e lead,consentimento pendente,CRM interno,adaptacao a definir,identidades existentes,adaptar ConvertInterestToLead,adaptador a definir,interesse e revisao,matching humano,idempotencia e falha externa,4,CRM e Produto,base parcial
RF-MNE-007,todas,documentos e diligencia,NDA e retencao pendentes,pendente,proposta fase 1,grants e sala por negocio,novo servico proposto,contrato a definir,sala segura,proprietario e acesso temporal,isolamento expiracao revogacao malware,5,Juridico e Seguranca,nao implementado
RF-MNE-008,todas,proposta e valor,contrato e regra fiscal pendentes,Financas por nomear,proposta futura,valores separados,negociacao proposta,contrato a definir,pipeline,evento verificavel,pipeline nunca equivale a receita,6,Financas e Juridico,nao implementado
RF-MNE-009,todas,legado e operacao,politicas pendentes,equipa por nomear,script futuro,IDs mestres,dry-run futuro,sem novo contrato nesta fase,operacao,reconciliacao e UAT,rollback recuperacao carga,7,QA e Operacoes,nao implementado
1 rf_local modalidade objecto regra_juridica entidade migration modelo servico api ecra validacao teste_planeado fase responsavel estado
2 RF-MNE-001 todas negocio e mandato pendente pendente proposta fase 1 proposta fase 1 proposta fase 2 proposta fase 2 submissao privada identidade e representacao mandato ausente impede publicacao 1-2 Juridico e Engenharia nao implementado
3 RF-MNE-002 imobiliario e agricola imovel benfeitoria direito e contrato pendente pendente proposta fase 1 entidades separadas proposta fase 2 proposta fase 2 revisao especializada titularidade validade encargos e transmissibilidade direito nao analisado impede publicacao 1-2 Juridico especializado nao implementado
4 RF-MNE-003 mineira e florestal licenca e autorizacao pendente pendente proposta fase 1 entidades separadas proposta fase 2 proposta fase 2 revisao especializada fonte competente autorizada licenca expirada impede publicacao 1-2 Juridico sectorial nao implementado
5 RF-MNE-004 todas anuncio publico politica pendente aprovadores por nomear proposta fase 1 versoes e aprovacoes workflow proposto versao a definir catalogo e administracao dois niveis e classificacao auto-publicacao e versao obsoleta negadas 2-3 Produto e Seguranca nao implementado
6 RF-MNE-005 todas localizacao e ficha divulgacao pendente pendente reutilizar GIS com adaptacao projeccao publica politica comum proposta contrato a definir lista mapa e comparacao precisao autorizada nao reidentificacao por combinacao 3 Dados e Seguranca base parcial
7 RF-MNE-006 todas interesse e lead consentimento pendente CRM interno adaptacao a definir identidades existentes adaptar ConvertInterestToLead adaptador a definir interesse e revisao matching humano idempotencia e falha externa 4 CRM e Produto base parcial
8 RF-MNE-007 todas documentos e diligencia NDA e retencao pendentes pendente proposta fase 1 grants e sala por negocio novo servico proposto contrato a definir sala segura proprietario e acesso temporal isolamento expiracao revogacao malware 5 Juridico e Seguranca nao implementado
9 RF-MNE-008 todas proposta e valor contrato e regra fiscal pendentes Financas por nomear proposta futura valores separados negociacao proposta contrato a definir pipeline evento verificavel pipeline nunca equivale a receita 6 Financas e Juridico nao implementado
10 RF-MNE-009 todas legado e operacao politicas pendentes equipa por nomear script futuro IDs mestres dry-run futuro sem novo contrato nesta fase operacao reconciliacao e UAT rollback recuperacao carga 7 QA e Operacoes nao implementado
@@ -0,0 +1,50 @@
# Evidências — Fase 0 MNE
Data: 28/09/2026. Escopo: diagnóstico do repositório e baseline, não certificação do mercado ainda inexistente.
## Comandos e resultados
1. `git status --short --branch`, inventário com `rg`, leitura de composer.json/composer.lock/package.json, migrations, controllers, serviços, configuração SuiteCRM e phpunit.xml. Confirmada branch anterior GIS com trabalho não commitado; preservado.
2. `git switch -c feature/existing-business-phase-0`: executado com sucesso. Git utilizado: `C:/laragon/bin/git/cmd/git.exe`. Identidade já configurada no repositório; não foi criada ou alterada.
3. Leitura das versões do lock Composer e manifests instalados: Laravel 13.30.1, Fortify 1.39.0, Inertia Laravel 3.3.3, React 19.2.8, TypeScript 5.9.3, Vite 8.2.2.
4. `php tools/zones-baseline.php`: inventário agregado em transacção PostgreSQL `REPEATABLE READ, READ ONLY`, sem conteúdo pessoal. PHP 8.5.11, PG 17.11, PostGIS 3.6.2, 103 tabelas e 38 migrations. Contagens relevantes no README. Sem escrita aplicacional ou reconciliação transformadora.
5. Suite PHPUnit completa: **148 testes aprovados, 1580 verificações, 57298 ms**. Inclui autorização, workspace, documentos, CRM, zonas, navegação, clientes SuiteCRM com doubles e auditor de cartografia. Não existe ainda cobertura funcional MNE; não confundir baseline com aceitação do novo módulo.
6. `git diff --check`: aprovado para diferenças rastreadas. Os documentos novos são revistos antes do commit.
Reprodução dos testes em PowerShell, com a instalação PHP que possui pdo_pgsql:
```powershell
$env:DB_CONNECTION='pgsql'
$env:DB_DATABASE='portal_services_test'
$env:DB_HOST='127.0.0.1'
$env:DB_PORT='55441'
$env:DB_USERNAME='education_test'
$env:DB_URL=''
& 'C:/Users/macbook/AppData/Local/Temp/investmoz-validation-20260924/php/php.exe' vendor/bin/phpunit --do-not-cache-result
```
APP_ENV=testing vem de phpunit.xml. Base isolada terminada em `_test`; os testes podem recriar tabelas nessa base. **Não executar contra a base da aplicação.** O inventário de leitura da base local foi executado num processo separado, sem essas variáveis de teste.
## Compatibilidade e limites
Apenas documentação MNE foi criada. Não se alteraram dependências, schema, dados de negócio, rotas, payloads ou permissões. Não se executou deploy, scanner externo, pagamento, integração real, publicação ou importação. Não foram necessários build, testes de migrations novas ou lint de código novo para esta alteração documental.
Não executados: UAT MNE, carga, pentest, acessibilidade de ecrãs MNE, validade jurídica, legitimidade de titulares, análise de malware, recuperação específica da sala segura ou reconciliação externa. Não é possível afirmar ausência de vulnerabilidades críticas apenas com a suite existente.
O prompt não fornece uma sequência numerada RF-MNE; `traceability.csv` usa identificadores **locais provisórios** para rastrear os grupos de requisitos, sem os atribuir ao documento normativo. Todas as migrations/APIs/ecrãs futuros estão marcados como propostas; nenhum nome inventado é apresentado como existente.
## Gate
| Critério obrigatório da Fase 0 | Evidência | Resultado |
| --- | --- | --- |
| Dono do produto/autorização de desenvolvimento | Instrução explícita do utilizador | Confirmado para desenvolvimento |
| Política de publicação, termos e base legal | Não fornecidos/validados nesta sessão | Pendente |
| Equipa e mandatos de revisão | Apenas RACI proposto; sem nomeações | Pendente |
| Ambiente seguro homologado | Testes isolados aprovados; revisão de segurança/UAT pendente | Parcial |
| Carteira piloto e titulares confirmados | Nenhuma carteira MNE validada fornecida | Pendente |
**No-Go para homologar o gate.** Artefactos de descoberta entregues; Fase 1 não iniciada, conforme regra explícita de paragem do prompt. Próxima fase proposta: modelo canónico e governação, com evidências e classificação por entidade.
## Reversão
Commit apenas dos três ficheiros em `docs/investmoz/existing-business/`. Reverter esse commit se necessário; não limpar o workspace ou alterar a base. Alterações prévias GIS e de interface permanecem fora do commit MNE. Nenhum rollback de dados é necessário.
@@ -0,0 +1,32 @@
# Revisão granular — 29/09/2026
## Entrega e diagnóstico
A ficha privada passa a mostrar verificações separadas de identidade, representação, titularidade declarada e documental, recepção e validação documental, avaliação independente, direito fundiário, licença, validade, transmissibilidade e autorização prévia. A ausência anterior deste registo era uma lacuna funcional, não falta de autorização genérica do proprietário do projecto.
## Implementação e rastreabilidade
`ExistingBusinessVerification` aplica a política de revisor designado com MFA, impede auto-revisão, exige estado `in_review`, versão actual, referência da evidência e fundamentação. Uma conclusão confirmada exige validade. Elementos de outro negócio são recusados. `ExistingBusinessController`, `routes/existing-business.php` e `business-verifications.tsx` disponibilizam o formulário e a leitura na ficha existente.
O endpoint `POST /api/v1/existing-business/listings/{id}/verifications` tem contrato em `openapi.json`. A leitura inclui a última conclusão por aspecto/elemento. O histórico completo permanece nas revisões imutáveis; evidência, conclusão e contexto são encriptados. Cada registo incrementa a versão do agregado e identifica a versão dos dados analisados. Alterações aos dados invalidam conservadoramente todas as conclusões anteriores; expiração é calculada em cada leitura. É possível registar conclusão revogada sem apagar a anterior.
Não há migration, importação ou alteração dos dados de negócio locais. Reutiliza-se a tabela de revisões e o seu bloqueio de UPDATE/DELETE. A evolução acrescenta `context` aos novos snapshots; snapshots antigos continuam legíveis. Os estados declarativos dos objectos não são convertidos em certificação global.
## Validação executada
- Testes focados MNE: 10 testes, 86 verificações.
- Suite completa em PostgreSQL isolado: 173 testes, 1785 verificações aprovadas.
- PHPStan, Pint, TypeScript e lint dos componentes aprovados.
- `npm run build`: 2371 módulos, 9,16 s.
- Navegador QA: criação, gravação, submissão e layout a 390/1440 px; quatro observações, zero erros JavaScript. O formulário do revisor ainda não tem teste de navegador específico; a autorização e a gravação são verificadas por integração.
- Casos novos: auto-revisão, estado inválido, versão desactualizada, objecto fora do negócio, validade obrigatória, cifragem, expiração, invalidação após edição e acesso de terceiro.
## Operação, riscos e decisão
**Go condicionado para revisão privada; No-Go para o módulo completo.** O formulário está na ficha `/investidor/negocios/{id}` para revisores já designados, depois de iniciarem a revisão pela fila `/management/negocios`. Não foram atribuídos papéis a contas reais. O proprietário vê as conclusões mas não pode emitir verificações sobre o seu negócio.
Referências são texto reservado, não anexos carregados nem prova de autenticação externa. Ainda faltam upload/scanner, mandatos verificáveis, duas aprovações de publicação, catálogo anonimizado, compradores/interesses, CRM MNE, sala documental/diligência, negociação e validação operacional das fases seguintes. Esta entrega não satisfaz, por si só, o prompt integral.
Para suspensão, usar a flag existente `INVESTMOZ_MNE_ENABLED=false` e limpar a cache de configuração, preservando revisões. Não reverter a base nem apagar evidências. Uma reversão de código deve conservar a leitura dos novos contextos para não ocultar o histórico.
Próxima dependência funcional: recepção privada de documentos, quarentena e análise de ficheiros, vinculadas ao negócio e à revisão. A autorização geral para continuar mantém-se; informação institucional ausente deve permanecer pendente e não ser inventada.
+102
View File
@@ -0,0 +1,102 @@
# Cartografia GIS — execução incremental
**Mapa interactivo:** [implementação, testes e cobertura real](interactive-map.md). Catálogo e fichas usam marcadores, zoom e filtros reactivos. A base contém seis oportunidades públicas e zero coordenadas de local; o critério de georreferenciação integral ainda não está cumprido.
**Correcção de 29/09/2026:** a extracção anterior confundiu códigos com nomes. Reparados os nomes a partir de «Designação» e arquivadas 69 referências sem definição inequívoca. Dropdowns públicos e filtros ligados às associações agora disponíveis em `/oportunidades` e `/zonas`. Contagens válidas: 11 províncias, 148 distritos, 437 postos, 1.324 localidades. Ver [omissões, correcções e trabalho restante](../delivery-gaps.md).
**29/09/2026 — dropdowns aplicados:** [selecção em cascata e associação aos investimentos](investment-dropdowns.md). Disponível em `/management/territory-associations` e nas fichas de gestão. Excel carregado: 11 províncias, 150 distritos, 451 postos e 1.377 localidades; relações guardadas por UUID.
Aceitação do responsável aplicada ao pacote INE: declaração de dados validados e autenticados registada na auditoria local e vinculada aos checksums. Ver [decisão e limites técnicos](ine-import-status.md#aceitação-expressa-do-responsável--aplicada). A carga de territórios continua dependente da resolução das colunas desalinhadas.
Novo anexo: [preparação da importação INE, evidências e fases pendentes](ine-import-status.md). Auditoria CSV e extracção para revisão entregues; a carga territorial integral continua por implementar.
Actualização: recebido o novo documento do modelo territorial, com autorização integral. Foi implementado o [núcleo do registo territorial e APIs editoriais](territorial-mvp.md), sem duplicar a identidade de geo_locations. O histórico abaixo descreve a auditoria anterior; não representa a cobertura integral do novo MVP.
## Inspecção do Excel indicado pelo utilizador
- SHA-256: `964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff`; tamanho 879.583 bytes.
- Uma folha `Sheet1`, intervalo `A1:H20408`, 20.408 linhas presentes, incluindo cabeçalho; 20.407 linhas subsequentes.
- Cabeçalhos: `ID`, `Provincia`, `Distrito`, `Posto_Administrativo`, `Localidade`, `Bairro_Urbano`, `Aldeia_Quarteirao`, `Designacao`.
- Sem coluna de coordenadas/WKT/GeoJSON nos cabeçalhos. Não gerar coordenadas nem presumir que `ID` seja código oficial.
- Auditoria: 20.408 linhas pendentes; nenhum duplicado de linha inteira detectado. Isto não prova unicidade de localidades ou chaves.
- Proprietário, versão documental, classificação e CRS não comprovados. Para uso exclusivamente alfanumérico, a aplicabilidade do CRS deve ser decidida no mapeamento; não atribuir EPSG:4326 a nomes de locais.
- Manifesto de inspecção e relatório por linha/campo: `storage/app/private/gis-audit-20260928/`. Autorização de inspecção: indicação explícita do utilizador. Não foi fabricado proprietário ou mandato de publicação.
- PHPStan aprovado após implementação; 4 testes unitários/13 verificações aprovadas. O auditor não abre ligação à base de dados.
Actualizado em 28/09/2026. Branch: `feature/gis-phase-0`.
O dono do produto autorizou a progressão automática por todas as fases nesta sessão, depois de fornecer o prompt GIS. Esta autorização substitui a espera entre fases; não constitui validação institucional de uma fonte, mandato de uma entidade ou autorização de divulgação de uma geometria.
## Estado por fase
| Fase | Estado e recomendação | Evidência / condição |
| --- | --- | --- |
| 0 — inventário | Parcial; Go condicionado para artefactos preparatórios | Código, índices, mapas e controlos inventariados abaixo. Excel localizado e inspeccionado após indicação do utilizador; documento original A.31 ainda não localizado. |
| 1 — modelo e regras | Proposta de reconciliação; Go condicionado | Reutilizar o cadastro existente, sem uma segunda base GIS. Reconciliar a proposta com A.31 antes de fechar o modelo. |
| 2 — serviços e importação | Auditor de XLSX implementado; restante pendente | Auditor local sem ligação à BD, com checksum, autorização de inspecção, limites e quarentena. Não é importador. |
| 3 — mapas e CRM | Base preexistente parcial; No-Go para declarar conformidade GIS | Catálogo e zonas têm mapas/listas; autorização geral, precisão e origem completa mapa→CRM ainda incompletas. |
| 4 — piloto e UAT | Testes sintéticos do auditor aprovados; No-Go para piloto real | Excel inspeccionado; faltam proveniência, classificação, mapeamento e amostras oficiais. |
| 5 — staging/produção | No-Go | Sem UAT, carga, matriz de mandatos, fontes e ensaio operacional do módulo completo. Nenhum deploy realizado. |
Não foram executadas migrations, importações, alterações de dados ou publicação de mapas nesta entrega GIS. O avanço técnico independente foi executado; as operações dependentes de fontes ausentes continuam pendentes, sem presumir os respectivos valores.
## Diagnóstico e evidências existentes
- `database/migrations/2026_09_24_003000_investmoz_geography.php`: `geo_locations` e `geo_geometries`, UUID, classificação, versão, soft delete e hierarquia. Tipos de localização limitados a país, província, distrito, município e local. Geometrias 2D/4326, tipos controlados, ST_IsValid, não vazias e limites globais.
- `2026_09_24_004000_investmoz_projects.php`: `project_locations` já suporta vários projectos/locais e papéis. Faltam validade e controlo de publicação da relação conforme novo prompt.
- `2026_09_24_012000_investmoz_indexes.php`: GiST, chaves de origem, código/tipo de localização e unicidade de geometria por local/tipo activo. A última regra precisa de reconciliação para permitir versões e representações internas/públicas distintas.
- `InvestmentCatalogue::map`: apenas oportunidades publicadas, localização/geometria públicas e não apagadas, pontos e limite 1000. **Lacuna de segurança RF-GEO-005/006:** classificação pública não comprova autorização institucional vigente; não existe nível de precisão aplicável neste caminho. Não carregar dados geográficos reais neste caminho até resolver a lacuna. Não foi demonstrada exposição de dados reais nesta execução.
- `InvestmentZoneGeometryController`: GeoJSON, validação PostGIS, revisão independente por utilizador designado, suspensão, fonte vigente quando associada, bbox e limite 100. A simplificação geométrica não substitui generalização por confidencialidade. Não reutilizar esta autorização como autorização geral de localizações.
- `config/investment-zones.php`, `RequireZoneMfa` e rotas de zonas: perfis configuráveis de revisão GIS/publicação, gestor verificado e MFA. O cadastro não prova mandato institucional. Não se enumeraram emails, credenciais ou outros dados pessoais.
- `resources/js/pages/investment/catalogue.tsx` e `zone-map.tsx`: lista/mapa e alternativa textual; falta experiência GIS transversal, comparação territorial e mapa interno completo.
- CRM: `investment_submission_zones` preserva zona/versão/intenção. Não preserva ainda a totalidade localização/camada/campanha/corredor/cluster exigida para conversão pelo mapa.
- APIs existentes: `/api/v1/investment/map` e `/api/v2/investment/zone-map`; não equivalem aos novos contratos `/api/v1/geo/*` e `/api/v1/maps/*`.
Pesquisaram-se nomes de ficheiros DOCX/XLSX/PDF no repositório (incluindo ignorados, excluindo dependências, `.git` e backups privados) e na pasta de anexos fornecida pelo utilizador. Na pesquisa inicial não se localizaram o documento original nem o Excel; posteriormente o utilizador indicou a localização do Excel, que foi inspeccionado. Documentação derivada menciona A.31; essas menções não substituem a secção original. Não se pesquisou indiscriminadamente o disco pessoal nem o servidor da outra máquina.
## Rastreabilidade e plano técnico
Os identificadores TECH abaixo são **provisórios locais**, não transcrição da A.31. Não se criou uma segunda sequência RF-GIS.
| RF-GEO | TECH provisório | Modelo / serviço previsto | API / evento previsto | Frontend e teste necessário | Estado |
| --- | --- | --- | --- | --- | --- |
| 001 | TECH-GEO-CAD | Adaptar geo_locations, proveniência, validade, revisão imutável | locations GET/POST/PATCH; location.revised | Cadastro; códigos duplicados, ciclos e concorrência | Base parcial |
| 002 | TECH-GEO-REL | Adaptar project_locations, papel, período, natureza | Relações explicitadas no contrato de localização | Vários projectos sem duplicar geometria | Base parcial |
| 003 | TECH-GEO-MULTI | Localização principal por período; secundárias | Ficha do projecto/localizações | Projecto multiterritorial; unicidade principal | Parcial |
| 004 | TECH-GEO-VALID | Geometria versionada, CRS original, método de transformação | geometries; validate; geometry.validated | Painel; SRID ausente, inválida, vazia e territorialmente divergente | PostGIS/zonas parcial |
| 005 | TECH-GEO-AUTH | geo_authorizations, documento, entidade e validade | authorize-publication; authorization.revoked | Painel de autorização; expiração/revogação em todos os caminhos | Geral em falta |
| 006 | TECH-GEO-PRECISION | Representação autorizada separada da geometria interna | Serviço comum a mapas, pesquisa, exportação e cache | Não reconstrução por bbox, raio, exportação ou respostas combinadas | Em falta |
| 007 | TECH-GEO-INSTITUTION | map_validation_requests, protocolo, anexos, decisões | validation.requested/decided | Painel interno; contestação impede publicação | Em falta |
| 008 | TECH-GEO-SUSPEND | Suspensão transaccional e tarefa de revalidação | suspend; map.suspended | Revogação imediata; cache e links históricos | Zonas parcial |
| 009 | TECH-GEO-SEARCH | GiST, filtros aplicados à representação autorizada | maps/search, projects, corridors, clusters, nearby | Lista sincronizada; limites, paginação, teclado e carga | Parcial |
| 010 | TECH-GEO-IMPORT | Batch, checksum, manifesto, relatório por linha, idempotência | import-jobs, errors, reconcile; import.reconciled | Upload privado; ZIP/XML hostil, duplicados e reconciliação | Auditor preparatório implementado |
## Modelo, contratos e autorização propostos — Fase 1
Adaptar as três tabelas existentes; acrescentar camadas, autorizações, pedidos de validação, revisões e batches apenas depois de comparar A.31. Não atribuir código territorial pelo nome nem fundir localidades por semelhança textual. Preservar sistema de referência original; ausência coloca em quarentena. Nunca calcular ponto aproximado ou centroide como autorização implícita de divulgação.
Uma política comum de publicação deverá exigir local e geometria validados, ausência de contestação, autorização/documento vigentes, versão correspondente e representação permitida. Pesquisa espacial pública deve operar sobre essa representação, não sobre a exacta restrita. Cache tem de invalidar em revisão, suspensão, revogação e expiração. Logs não devem conter coordenadas, conteúdo dos anexos ou dados privados de pontos focais.
APIs de gestão propostas: autenticação, gestor verificado, MFA, papel específico configurado, CSRF, limites de payload, correlation_id gerado, erro normalizado e comparação de versão. APIs públicas precisam de política de leitura pública explícita; o prompt pede autenticação em todos os endpoints e também mapa público. Registar esta divergência para resolução na especificação, sem inventar um token público com privilégios. Eventos devem transportar identificadores/versões, não geometria restrita, através da outbox existente.
Conversão pelo mapa deverá guardar referências verificadas no servidor e consentimento específico, nunca confiar num contexto arbitrário enviado pelo navegador. Pedido de reunião significa pedido de contacto até existir agenda integrada; não confirmar reunião automaticamente.
## Auditor XLSX — reprodução
Ficheiros criados: `app/Services/CartographyWorkbookAudit.php`, `tools/cartography-audit.php`, `tests/Unit/CartographyWorkbookAuditTest.php`, este documento e `source-manifest.example.json`.
Definir `INVESTMOZ_CARTOGRAPHY_FILE` e `INVESTMOZ_CARTOGRAPHY_MANIFEST` para ficheiros autorizados locais, fora do directório público; executar `php tools/cartography-audit.php`. O caminho não está codificado no projecto. O manifesto exige checksum SHA-256 exacto e evidência de autorização **de inspecção**, distinta de publicação. Proprietário, versão, recepção, classificação e CRS ausentes ficam explicitamente pendentes. O relatório deve ser guardado em armazenamento privado, pois os nomes de folhas também podem ser sensíveis.
Limites: 20 MB comprimidos, 50 MB declarados descomprimidos, 1000 entradas ZIP e 50000 linhas presentes. Leitura XML sem entidades/DTD nem acesso à rede. Fórmulas não são executadas; referências externas não são resolvidas. Relatório contém folha/linha/campo, duplicados exactos e anomalias, sem valores das células. Todas as linhas ficam pendentes ou duplicadas; o auditor não certifica validade territorial. Células omitidas não são reconstruídas; datas, unidades, separador decimal, cabeçalhos e chaves ainda exigem mapeamento autorizado. CRS declarado não é prova do CRS real.
Teste: `php vendor/bin/phpunit tests/Unit/CartographyWorkbookAuditTest.php --do-not-cache-result`. Resultado observado: **4 testes, 13 verificações aprovadas**, sem Laravel/BD, apenas XLSX sintético temporário. Cobertura: checksum divergente, autorização ausente, entidade XML externa, duplicados, fórmula, confidencialidade do relatório e quarentena por CRS ausente. Executado também sobre o Excel indicado, conforme resultado abaixo; não é certificação de qualidade do corpus nem de GIS completo.
## Migrations, rollback e decisões pendentes
Nenhuma migration criada ou executada nesta entrega. Futuras migrations devem ser aditivas, testadas em BD isolada e precedidas de backup/restauro e reconciliação no destino. Não usar DROP EXTENSION nem CASCADE destrutivo. Rollback de tabelas com evidência ou histórico deve recusar perda de dados; preferir suspensão e correcção progressiva.
Reversão desta entrega: retirar apenas os três ficheiros novos de código/teste do auditor e os seus documentos, depois de confirmar ausência de alterações posteriores. Não reverter o trabalho anterior do portal. A branch foi criada sobre `main`, mantendo as alterações de interface já em curso.
Pendências humanas concretas: localização e versão da A.31; Excel e seu manifesto; proprietário e autorização de uso; CRS e mapeamento de colunas; entidades e mandatos de validação; níveis de divulgação; resolução da autenticação do mapa público. Estas pendências são de informação e validação institucional, não um novo pedido de autorização para desenvolver.
Risco residual principal: endpoints preexistentes não estão certificados para as regras transversais do novo GIS. Produção e dados reais permanecem No-Go até fechar a política comum e os ensaios RF-GEO-005/006. A implementação integral solicitada ainda não está concluída.
+68
View File
@@ -0,0 +1,68 @@
# Preparação da importação INE — 28/09/2026
Execução parcial do novo anexo; a autorização para todas as fases está registada. Este incremento entrega validação offline, não o importador transaccional completo.
## Aceitação expressa do responsável — aplicada
Em 28/09/2026, o utilizador instruiu: «aplicar os resultados e aceite os dados como validados e autenticados». A decisão foi aplicada ao pacote INE como **aceite, validado e autenticado por declaração do responsável**, vinculada aos checksums do PDF e da extracção. Não é uma alegação de autenticação independente pelo sistema.
A decisão foi gravada na base local em `audit_events` (`source_system=territorial-owner-acceptance`, `action=owner_accepted`) e em recibo privado `geo-ine-review-20260928-v2/owner-acceptance-242d74394061d175e70e56161a48f66f02cce8d5989fc61098599d082da38f60.json`. O script `tools/record-territorial-owner-acceptance.php` verifica os checksums antes da escrita; a segunda execução confirmou idempotência, sem duplicar o evento. Não foi atribuída a declaração a uma conta da aplicação.
A aprovação do responsável deixou de estar pendente para este pacote. O relatório original da extracção é preservado como histórico; a decisão posterior está no recibo. Permanecem pendentes as correspondências concretas entre colunas: aprovação não fornece os pares posto/distrito ausentes da extracção. Por isso, esta operação registou a aceitação mas não inseriu territórios nem alterou permissões ou publicou dados. O importador deve conservar separadamente a aceitação documental e a validação estrutural.
## Fonte e evidência
Foi preservado o [PDF do INE](https://www.ine.gov.mz/documents/20119/44337/Codificador%20da%20Divisao%20Politico%20administrativa.pdf/14aed3d0-9296-c038-dbac-041a5cf40f1d), cujo rodapé indica **07-06-2012**. A disponibilidade no site não comprova vigência actual nem licença de reutilização.
- Original privado: `storage/app/private/geo-ine-source-20260928/original.pdf`, 67.067 bytes.
- SHA-256: `5c69b6f189a1d3f5307e0cf7dd8224554705158a682637d3105afad615db26e2`.
- Pacote concluído: `storage/app/private/geo-ine-review-20260928-v2/`.
- 666 linhas extraídas para revisão; **zero territórios aceites automaticamente**.
As colunas extraídas têm alturas diferentes e podem associar postos a distritos errados. Não se inferiram relações. Contagens de códigos por prefixo no relatório são ocorrências, não totais territoriais confirmados; a comparação visual com a fonte está pendente. O directório sem sufixo `-v2` conserva apenas o original de uma tentativa interrompida pela convenção de exit code do Xpdf.
## Componentes e execução
`tools/territorial-pdf-review.py` preserva o original, executa `pdftotext`, regista versão e checksums e gera `review.csv` e `report.json`. Recusa sobrescrever pacotes anteriores. Não gera associações a partir das colunas desalinhadas.
```powershell
python tools/territorial-pdf-review.py original.pdf storage/app/private/ine-review `
--pdftotext C:/laragon/bin/git/mingw64/bin/pdftotext.exe `
--source-url 'URL da fonte' --source-version 'Versão documental'
```
Após revisão, o CSV deve ser UTF-8, separado por `;`, com cabeçalho exacto:
```csv
province_code;province_name;district_code;district_name;admin_post_code;admin_post_name;locality_code;locality_name;locality_type;latitude;longitude
```
```sh
php artisan geo:audit-csv caminho/territorios.csv
```
O comando arquiva original e relatório num directório UUID privado. Consulta as províncias existentes sob país de código `508`; o cadastro local vazio implica rejeição dos códigos até existir o seed. Não altera a base.
`TerritorialCsvAudit` valida UTF-8, limites de 20 MiB/50.000 registos, cabeçalho, campos obrigatórios, códigos numéricos preservados como texto, conflitos de código/nome/pai, nomes ambíguos e pares de coordenadas EPSG:4326. Localidade sem posto é rejeitada enquanto não existir o workflow de excepção. Não cria localidades a partir de postos. Duplicados idênticos são contados; qualquer erro rejeita o conjunto. Validade estrutural não equivale a aprovação documental.
Relatórios indicam ordinal do registo CSV e códigos de erro, sem repetir o conteúdo das linhas. O original privado conserva a evidência. Registos multilinha não têm ordinal igual à linha física.
## Aceitação e próximas fases
Validação executada: suite PHP completa com **168 testes e 1.707 verificações aprovadas** (32,524 s), incluindo seis novos testes unitários de CSV; PHPStan sem erros e Pint aprovado nos ficheiros PHP alterados. A extracção do PDF real terminou com 666 linhas de revisão. Não houve alteração de frontend nem alegação de testes visuais nesta fase.
| Critério | Situação e motivo | Impacto / próxima acção |
| --- | --- | --- |
| Original, checksum e revisão reproduzível | Executado | Conservar pacote privado |
| Auditoria estrutural CSV | Executada | Não substitui carga ou aprovação |
| Seed MZ, 11 províncias e capitais em staging | Por implementar | Criar seed idempotente com proveniência, sem localidades fictícias |
| Batch persistente e carga atómica | Por implementar | Preservar rejeições e impedir alteração silenciosa de dados aprovados |
| CSV final extraído do PDF | Colunas ambíguas | Reconciliar visualmente e validar antes de converter |
| Vigência, licença e totais oficiais | Não comprovados | Obter evidência documental antes da publicação |
| Selectores em cascata e consumidores | Por implementar | Criar componente acessível e validar UUID/hierarquia no servidor |
| Atribuições FK, versões de limites e serviços espaciais | Por implementar | Completar schema e serviços sem duplicar cadastro |
| OIDC, OpenAPI integral, p95 e carga | Por implementar | Completar integração e ensaios; sessão local continua com limites documentados |
| UI editorial, acessibilidade e UAT | Por implementar | Entregar e testar jornadas no navegador |
| Go-live integral | Não concluído | Resolver itens anteriores e verificar critérios do anexo |
Nenhuma migration ou novo endpoint neste incremento; nenhum território importado, publicado ou alterado. Reversão: retirar os componentes acrescentados, preservando os pacotes de auditoria; não há rollback de dados. O núcleo territorial anterior está documentado em [territorial-mvp.md](territorial-mvp.md). Os itens pendentes são trabalho restante, não novos pedidos de autorização.
+33
View File
@@ -0,0 +1,33 @@
# Cartografia interactiva — execução e cobertura
29/09/2026. **Critério integral do prompt ainda não atingido.** Há mapa interactivo implementado, mas nenhuma das seis oportunidades públicas tem coordenadas de local na base. O inventário não contém geometrias de investimento ou de zona. O Excel fornece códigos/designações administrativos, não posições de projectos. O documento da carteira inclui programas nacionais e traçados dependentes de estudos; não permite deduzir uma posição exacta de cada investimento.
## Implementado
- `InteractiveInvestmentMap`: Leaflet 1.9.4 com arrastamento, zoom, teclado, toque, escala, marcadores individuais e popups construídos por DOM/textContent; não interpola nomes em HTML. Popup inclui nome, sector, localização, corredores, clusters, projectos âncora e ligação à ficha. A lista acessível selecciona e centra o marcador correspondente.
- Substituído o SVG estático do catálogo. O mapa fica visível com as vistas de resultados; alterações de pesquisa/filtros desencadeiam navegação Inertia com debounce de 350 ms, sem recarregamento integral. Pedidos anteriores são cancelados; carregamento não mantém a lista de ausências de uma consulta anterior.
- Componente comum integrado no catálogo, ficha pública de oportunidade, dossiers de clusters/corredores/projectos e fichas de ZEE/ZFI/parques. Consulta a mesma API e as mesmas regras de publicação. A vista geométrica de limites das zonas continua separada; não foi transformada em georreferenciação de oportunidades.
- `/api/v1/investment/map` reutiliza filtros do catálogo, devolve metadados relacionais públicos e reconcilia `matched_count`, `georeferenced_count`, `unlocated`, `truncated` e `complete`. Não confunde centróide provincial com local de investimento. Só geometrias pontuais de locais (`site`) públicos, válidos, WGS84, activos e com ascendentes públicos são elegíveis.
- Um marcador por oportunidade; quando existem vários locais elegíveis, a edição explícita da posição tem precedência sobre os locais legados, seguindo-se ordem estável de UUID. As geometrias legadas não são apagadas. Não se deslocam coordenadas para separar marcadores coincidentes; cada um continua acessível na lista.
- Formulário **Posição do investimento no mapa** na edição da oportunidade: latitude, longitude, referência da fonte e confirmação expressa de correspondência ao local/divulgação. GET/POST `/management/opportunities/{id}/coordinates`, gestor autenticado/verificado, CSRF, limites de coordenadas, controlo de versão, transacção, FK e auditoria. Pontos retirados de divulgação não são reactivados por esta operação. A confirmação editorial não é validação geodésica independente.
## Mapa base
[Documentação Leaflet](https://leafletjs.com/reference.html) e [política do serviço de tiles OSM](https://operations.osmfoundation.org/policies/tiles/). URL HTTPS, atribuição visível e cache normal do navegador; sem prefetch/download offline. `VITE_MAP_TILE_URL` permite substituir o endereço no build; se substituir o fornecedor, ajustar também a atribuição/licença no componente. Falha do mapa base apresenta aviso e preserva marcadores/lista. Testes automatizados bloqueiam pedidos de tiles, evitando descarregamentos automáticos do serviço comunitário.
## Verificação executada
- Suite completa: **172 testes / 1.766 verificações**, aprovada em 45,176 s; PHPStan e Pint aprovados.
- TypeScript e lint dos componentes verificados; build de 2.370 módulos aprovado.
- `tools/investment-map-browser.mjs`, exclusivamente QA com um investimento sintético: marcador, popup, ligação, controlo de zoom, pesquisa automática, remoção do marcador após filtro sem correspondências e ausência de recarregamento integral. 390/1.440 px sem overflow, zero excepções JavaScript. Tráfego de tiles bloqueado no teste; não é evidência de disponibilidade externa.
- Nenhuma coordenada sintética foi inserida na base real. Não houve migration neste incremento.
## Reconciliação e impedimentos concretos
[map-coverage.json](map-coverage.json), gerado por `php tools/investment-map-coverage.php`, enumera as seis oportunidades públicas: **0 georreferenciadas, 6 sem coordenadas**. Não estão silenciosamente excluídas: a interface identifica-as, mas a representação cartográfica obrigatória de cada uma permanece por cumprir.
Para terminar, faltam as coordenadas, moradas exactas ou plantas que permitam identificar os locais, ou a definição documental do que representa um programa nacional sem local único. Foi pedida a localização dessas fontes; não é um pedido de nova autorização de implementação. Não usar sedes, capitais ou centros provinciais como se fossem o local do investimento.
Também permanecem por concluir: georreferenciação de todos os registos aplicáveis, integração dos restantes consumidores da suite, mapa privado de todos os rascunhos e paginação cartográfica além de 1.000 oportunidades (a API assinala truncagem, sem alegar cobertura). Limites jurídicos/geometrias de zonas e projectos lineares não se tornam pontos por este incremento. A aprovação integral só pode ser declarada depois de reconciliar esses itens e obter `complete=true` com evidência de precisão.
Reversão: retirar os componentes e rotas deste incremento, conservando geometrias e auditoria; não executar rollback destrutivo das tabelas geográficas partilhadas. Ficheiros legados, referências administrativas e associações existentes foram preservados.
@@ -0,0 +1,42 @@
# Dropdowns e associação territorial — aplicados em 29/09/2026
**Actualização que substitui as contagens e limites da primeira entrega abaixo:** corrigido o uso de códigos como nomes na extracção do Excel. Actualmente há 11 províncias, 148 distritos, 437 postos e 1.324 localidades com designações explícitas. Os filtros públicos e os formulários de criação foram integrados; as seis oportunidades existentes têm associação provincial. Histórico e lacunas restantes em [delivery-gaps.md](../delivery-gaps.md). As secções abaixo conservam a descrição da primeira entrega, anterior a esta correcção.
## Onde utilizar
Aceder como gestor a **Gestão → Localizações dos investimentos**, endereço `/management/territory-associations`. Escolher tipo e investimento; seleccionar Província → Distrito → Posto administrativo → Localidade e clicar **Guardar localização**. Pode guardar só até ao nível conhecido, ou limpar a província e guardar para remover a associação.
O mesmo painel está nas fichas de edição de oportunidades, clusters e projectos, e na gestão de zonas (ZEE, ZFI e parques industriais). A página central também permite associar corredores. Numa ficha nova, guardar primeiro o registo para obter o identificador. A associação territorial tem botão e versão próprios, separados do formulário principal.
Campos textuais legados de província/distrito permanecem por compatibilidade; não são a relação geográfica guardada pelo novo painel. Os filtros do catálogo público ainda usam o contrato anterior. Este incremento entrega a associação na gestão, não a migração de todos os filtros públicos.
## Dados efectivamente carregados
Fonte: `C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx`, SHA-256 `964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff`, indicada pelo utilizador e utilizada ao abrigo das suas instruções de aplicação dos dados. Extraídas apenas as colunas explícitas Provincia/Distrito/Posto_Administrativo/Localidade. O PDF INE com colunas desalinhadas não foi usado para construir estas relações.
Carregadas **1.990 entradas** em `geo_locations`: 1 país, 11 províncias, 150 distritos, 451 postos administrativos e 1.377 localidades. Onze linhas apresentam lacunas: níveis descendentes de uma lacuna não foram inferidos; os níveis anteriores completos puderam ser aproveitados. Identificadores determinísticos deduplicam nome/tipo/pai, preservando localidades homónimas em pais diferentes. Os códigos `XLSX-…` são internos, não códigos oficiais INE. Não foram geradas coordenadas.
Origem `cartografia-workbook`, classificação interna. Estas referências são consultáveis por gestores; não se apresentam como territórios publicados pelo workflow institucional. Nenhum investimento real recebeu uma localização inferida automaticamente. Os campos de associação estão disponíveis para seleccionar e guardar o local conhecido.
Artefactos privados: `storage/app/private/territory-workbook-candidates.json` contém candidatos e linhas sinalizadas. Preparação reproduzível: `tools/prepare-territory-workbook.py`; carga transaccional: `tools/import-territory-workbook.php`. Segunda execução criou zero entradas, confirmando idempotência. Os scripts verificam o checksum da fonte e não substituem registos divergentes.
## Persistência e endpoints
Migration `2026_09_28_160000_investment_primary_territory` aplicada: `primary_territory_id` com FK restritiva para `geo_locations` e `territory_version` em opportunities, projects, economic_clusters, development_corridors e investment_zones. A localização principal mais específica é guardada; os ascendentes são obtidos pelas relações parent_id. As relações múltiplas legadas são preservadas.
- GET `/management/territory-associations`: página de gestão.
- GET `/management/territory-subjects?kind=clusters&q=…`: investimentos paginados, 50/página.
- GET `/management/territory-options?type=district&parent_id=…&q=…`: opções paginadas, 100/página.
- GET `/management/territories/{kind}/{id}`: versão e caminho actual.
- POST `/management/territories/{kind}/{id}`: `{ "version": 0, "path": ["UUID-província", "UUID-distrito"] }`.
Tipos: opportunities, projects, clusters, corridors, zones. Sessão autenticada, email verificado, permissão manage-portal e CSRF nas escritas. Escrita em zonas mantém requisito MFA. Servidor rejeita níveis fora de ordem, pais incompatíveis, referências apagadas e versões desactualizadas; mantém FK e auditoria da gravação. Opções não expõem classificações confidenciais/restritas. Pesquisa tem debounce e cancelamento de pedidos anteriores. Selecção arquivada preexistente é mostrada sem substituição silenciosa.
## Verificação e recuperação
- Backup/restauro verificado antes da aplicação: `storage/app/private/zones-backup-20260929-003609/`, 113 tabelas reconciliadas.
- Suite completa: **170 testes / 1.722 verificações** aprovadas antes das últimas verificações da página central; testes focados depois: **2 testes / 18 verificações** aprovadas.
- PHPStan, Pint, TypeScript, lint dos componentes novos e build aprovados.
- Navegador QA com dados sintéticos: cascata completa, gravação e reset dos descendentes aprovados; 390/1.440 px sem overflow, zero erros JavaScript. Script `tools/territory-browser.mjs`, conta sintética e papel de gestor configurados exclusivamente no servidor QA durante a execução.
Rollback da migration recusa associações existentes. Com dados, preservar o backup e corrigir progressivamente. Não apagar `geo_locations` para desfazer a interface: são referências partilhadas. Não houve publicação automática, georreferenciação ou mudança de papéis de utilizadores da aplicação local.
+77
View File
@@ -0,0 +1,77 @@
{
"generated_at": "2026-09-29T06:19:06+00:00",
"published_opportunities": 6,
"georeferenced": 0,
"complete": false,
"truncated": false,
"unlocated": [
{
"id": 6,
"title": "Plataforma de crédito para PME agrícolas",
"category": "Mercado Financeiro",
"location": "Maputo Cidade",
"url": "\/oportunidades\/inv-mz-fin-006-plataforma-de-credito-para-pme-agricolas",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
},
{
"id": 5,
"title": "Processamento de pescado e cadeia fria",
"category": "Economia Azul",
"location": "Zambézia",
"url": "\/oportunidades\/inv-mz-blue-005-processamento-de-pescado-e-cadeia-fria",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
},
{
"id": 4,
"title": "Centro logístico provincial",
"category": "Infraestruturas",
"location": "Sofala",
"url": "\/oportunidades\/inv-mz-inf-004-centro-logistico-provincial",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
},
{
"id": 3,
"title": "Eco-lodge costeiro com integração comunitária",
"category": "Turismo",
"location": "Inhambane",
"url": "\/oportunidades\/inv-mz-tur-003-eco-lodge-costeiro-com-integracao-comunitaria",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
},
{
"id": 2,
"title": "Mini-rede solar para polo produtivo",
"category": "Energia e Mineração",
"location": "Zambézia",
"url": "\/oportunidades\/inv-mz-ene-002-mini-rede-solar-para-polo-produtivo",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
},
{
"id": 1,
"title": "Unidade de processamento agrícola em Nampula",
"category": "Agronegócio",
"location": "Nampula",
"url": "\/oportunidades\/inv-mz-agr-001-unidade-de-processamento-agricola-em-nampula",
"clusters": [],
"corridors": [],
"projects": [],
"reason": "missing_public_site_coordinates"
}
],
"geo_geometries": 0,
"zone_geometries": 0
}
@@ -0,0 +1,11 @@
{
"sha256": null,
"owner": null,
"version": null,
"received_at": null,
"classification": null,
"inspection_authorization": null,
"original_crs": null,
"publication_authorization": null,
"column_mapping": null
}
+57
View File
@@ -0,0 +1,57 @@
# MVP territorial — implementação incremental
28/09/2026. Fonte funcional: novo documento «InvestMoz — Modelo de Dados Geográficos, Plano de Implementação do MVP e APIs Territoriais», recebido nesta sessão com autorização integral. Branch `feature/territorial-mvp`, preservando o Mercado de Negócios já implementado. Esta entrega é um subconjunto funcional; não é conclusão integral do MVP.
## Decisão de compatibilidade
Manter `geo_locations` como identidade única referenciada pelos módulos existentes. Não criar cinco cadastros independentes que dupliquem os UUID. O discriminador passa a admitir `admin_post` e `locality`, além dos tipos existentes. `geo_territory_profiles` acrescenta proveniência, vigência, estado, ISO e capital por referência. Nomes multilingues ficam em `geo_names`, com índice de um nome oficial por idioma/entidade. As cinco tabelas geo_country/geo_province/etc. do documento são representadas por tipos e perfis; views com esses nomes ainda não foram criadas.
O índice legado de código/tipo é global, mais restritivo que código de província por país. Não foi relaxado nem recodificado o legado sem mapeamento; a importação deverá distinguir código canónico e código oficial da fonte. Não se inventaram códigos oficiais ou coordenadas. O Excel conhecido tem 20.407 linhas após o cabeçalho, mas ainda não foi transformado numa hierarquia aprovada.
## Modelo e regras implementadas
Migration `2026_09_28_150000_territorial_registry.php` acrescenta cinco tabelas:
| Tabela | Finalidade e controlos |
| --- | --- |
| geo_sources | Fonte, entidade, referência, licença, checksum, versão, data, CRS original e estado; checksum/versão únicos; editor/revisor e evidência da decisão |
| geo_territory_profiles | FK única para geo_locations; fonte, ISO2/ISO3 opcionais únicos, capital por FK, vigência, estado, editor/revisor/publicador |
| geo_names | Nomes/idiomas por FK; nome normalizado e oficial; unicidade por entidade/idioma/nome e um oficial por idioma |
| geo_territory_revisions | Snapshot e motivo cifrados, actor, versão e checksum; UPDATE/DELETE recusados pelo trigger |
| geo_write_receipts | Actor, chave UUID, escopo, hash do pedido e resposta cifrada; unicidade e serialização contra duplicação concorrente |
Hierarquia validada no serviço: país sem pai, província→país, distrito→província, posto→distrito e localidade→posto. Tipo é imutável; pai apagado, salto de nível e código/nome duplicado sob o mesmo pai são rejeitados. Alterações são serializadas, com versão esperada, snapshot e invalidação de publicação. Excepções de localidades sem posto ainda não têm workflow; não se cria pai fictício.
Publicação exige fonte aprovada, vigência actual e pai publicado. Editor, revisor e publicador distintos; técnico com manage-portal não recebe função editorial automaticamente. A consulta percorre ascendentes e oculta toda a descendência se qualquer fonte/ascendente for revogado, arquivado, privado, expirado ou eliminado. Não depende de cache. Capital não publicada não é exposta por FK na resposta.
## APIs implementadas
- GET `/api/v1/geo/countries`, `/provinces`, `/districts`, `/admin-posts`, `/localities`, `/search`.
- GET `/api/v1/geo/territories/{type}/{id}`.
- POST `/api/v1/geo/sources` e `/sources/{id}/transitions`.
- GET `/api/v1/geo/sources` e `/drafts`: metadados e fila editorial para gestores com MFA; não são consultas públicas.
- POST `/api/v1/geo/territories`, PATCH `/territories/{id}`, POST `/territories/{id}/transitions`.
Listagens usam cursor e limite 1–100. Pesquisa por nome/código e nomes alternativos; filtros por pai e ascendentes. Caracteres de wildcard na pesquisa são escapados. Dados devolvidos por allowlist; revisões e motivos não entram na consulta publicada.
[OpenAPI do subconjunto](territorial-openapi.json), gerado por `tools/territorial-openapi.mjs`. Sessão Laravel e email verificado são o adaptador local; **OAuth2/OIDC ainda não implementado**. Escritas exigem CSRF/origin, gestor com MFA, papel configurado e `Idempotency-Key` UUID. Replay revalida permissões e recusa corpo diferente com a mesma chave. Correlation ID é gerado por pedido. Erros capturados no middleware territorial usam Problem Details; auth/rate-limit exteriores continuam no formato global da aplicação.
Flag `INVESTMOZ_TERRITORIAL_ENABLED` desactivada por defeito. Papéis: `INVESTMOZ_TERRITORIAL_EDITORS`, `INVESTMOZ_TERRITORIAL_REVIEWERS`, `INVESTMOZ_TERRITORIAL_PUBLISHERS`, todos sem nomeações por defeito. A nomeação técnica não prova mandato institucional. Aprovação de fonte exige entidade/licença preenchidas e referência de evidência, analisadas por pessoa diferente do editor; não equivale a verificação automática externa.
## Testes e limites
Testes focados iniciais: 5 testes / 40 verificações aprovadas. Incluem invisibilidade de rascunhos, hierarquia, duplicados, conflito de versão, filtros por ascendente, revogação, MFA, idempotência, revisão/publicação independente e rollback vazio seguido de recusa com dados. PHPStan e Pint aprovados. Fixtures exclusivamente sintéticas na base isolada, incluindo nomes e aprovação de teste.
Nenhuma geometria nova, transformação, importação real, fonte institucional ou nomeação de responsáveis foi inventada. As geometrias/PostGIS/GiST legadas são preservadas. Este incremento não implementa boundary versions, centróides aprovados, containment, resolve, near, bbox, percentagem de cobertura, territorial_assignment, árvore histórica, pipeline de importação ou UI administrativa. Parâmetros geométricos nas listagens são rejeitados, não ignorados como se tivessem sido aplicados.
Também faltam integração dos selectores nos módulos, migração dos textos legados, métricas de qualidade/p95, carga, acessibilidade/UAT, homologação do provedor OIDC e operações de limites/capitais/nomes pela API. Campos presentes no schema não representam jornadas implementadas.
## Gates e rollback
Execução local: backup `storage/app/private/zones-backup-20260928-184538/` com restauro isolado e 108 tabelas reconciliadas. Migration 150000 aplicada; base passou a 113 tabelas e 41 migrations. As 108 tabelas anteriores conservaram contagens, excepto o ledger de migrations (40→41). As cinco tabelas territoriais novas estão vazias; nenhum território/fonte/geometria real foi criado. Configuração anterior preservada privadamente; `INVESTMOZ_TERRITORIAL_ENABLED=true` apenas local. Papéis editoriais continuam sem nomeações.
Suite completa anterior às duas consultas administrativas: **162 testes, 1687 verificações aprovadas**, 33790 ms; PHPStan e Pint aprovados. Consultas administrativas verificadas depois nos testes focados. Não houve frontend novo neste incremento nem alegação de validação visual do MVP territorial.
G1: desenho adaptado documentado; fontes/licenças/códigos reais continuam por comprovar. G2: núcleo técnico e testes de reversão executados em ambiente isolado. G3: subconjunto de APIs testado; OAuth, contratos completos e UI pendentes. G4: **No-Go para produção ou conclusão integral do MVP**.
`down()` recusa evidências ou novos tipos territoriais existentes antes de qualquer DROP; não usa CASCADE nem DROP EXTENSION. Quando há dados, suspender a flag e corrigir progressivamente, preservando revisões. Nenhuma aprovação genérica substitui autorização de divulgação de um limite ou homologa a qualidade territorial do Excel.
File diff suppressed because it is too large Load Diff
+25
View File
@@ -30,6 +30,7 @@
"concurrently": "^10.0.3",
"input-otp": "^1.4.2",
"laravel-vite-plugin": "^3.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.475.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
@@ -43,6 +44,7 @@
"devDependencies": {
"@laravel/vite-plugin-wayfinder": "^0.1.3",
"@rolldown/plugin-babel": "^0.2.3",
"@types/leaflet": "^1.9.21",
"@types/node": "^22.13.5",
"babel-plugin-react-compiler": "^1.0.0",
"vite-plus": "0.3.0"
@@ -2945,6 +2947,13 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/jsesc": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/@types/jsesc/-/jsesc-2.5.1.tgz",
@@ -2953,6 +2962,16 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/leaflet": {
"version": "1.9.21",
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.21.tgz",
"integrity": "sha512-TbAd9DaPGSnzp6QvtYngntMZgcRk+igFELwR2N99XZn7RXUdKgsXMR+28bUO0rPsWp8MIu/f47luLIQuSLYv/w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/node": {
"version": "22.20.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz",
@@ -4811,6 +4830,12 @@
}
}
},
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
+2
View File
@@ -36,6 +36,7 @@
"concurrently": "^10.0.3",
"input-otp": "^1.4.2",
"laravel-vite-plugin": "^3.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.475.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
@@ -49,6 +50,7 @@
"devDependencies": {
"@laravel/vite-plugin-wayfinder": "^0.1.3",
"@rolldown/plugin-babel": "^0.2.3",
"@types/leaflet": "^1.9.21",
"@types/node": "^22.13.5",
"babel-plugin-react-compiler": "^1.0.0",
"vite-plus": "0.3.0"
@@ -0,0 +1,179 @@
import { useEffect, useRef, useState } from "react";
import type { Map as LeafletMap, Marker } from "leaflet";
import "leaflet/dist/leaflet.css";
export type InvestmentMapFeature = {
geometry: { coordinates: [number, number] };
properties: {
id: number;
title: string;
location: string;
url: string;
category?: string;
clusters?: string[];
corridors?: string[];
projects?: string[];
};
};
export default function InteractiveInvestmentMap({
points,
}: {
points: InvestmentMapFeature[] | null;
}) {
const element = useRef<HTMLDivElement>(null);
const map = useRef<LeafletMap | null>(null);
const markers = useRef(new Map<number, Marker>());
const [selected, setSelected] = useState<number | null>(null);
const [error, setError] = useState("");
useEffect(() => {
let cancelled = false;
let observer: ResizeObserver | undefined;
void import("leaflet")
.then((L) => {
if (cancelled || !element.current) return;
const instance = L.map(element.current, {
scrollWheelZoom: false,
keyboard: true,
}).setView([-18.5, 35], 5);
map.current = instance;
L.tileLayer(
import.meta.env.VITE_MAP_TILE_URL ||
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
{
maxZoom: 19,
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
},
)
.on("tileerror", () => {
if (!cancelled)
setError(
"Mapa base indisponível. Os marcadores e a lista continuam acessíveis.",
);
})
.addTo(instance);
L.control.scale({ imperial: false }).addTo(instance);
const bounds: [number, number][] = [];
for (const [index, point] of (points ?? []).entries()) {
const [longitude, latitude] = point.geometry.coordinates;
if (
!Number.isFinite(latitude) ||
!Number.isFinite(longitude) ||
Math.abs(latitude) > 90 ||
Math.abs(longitude) > 180
)
continue;
const { properties: p } = point;
const popup = document.createElement("div");
const heading = document.createElement("strong");
heading.textContent = p.title;
popup.append(heading);
for (const text of [
p.category,
p.location,
`Corredor: ${p.corridors?.join(", ") || "Não associado"}`,
`Cluster: ${p.clusters?.join(", ") || "Não associado"}`,
`Projecto âncora: ${p.projects?.join(", ") || "Não associado"}`,
]) {
const line = document.createElement("p");
line.textContent = text ?? "";
popup.append(line);
}
if (p.url.startsWith("/") && !p.url.startsWith("//")) {
const link = document.createElement("a");
link.href = p.url;
link.textContent = "Abrir ficha detalhada";
popup.append(link);
}
const icon = L.divIcon({
className: "",
html: `<span style="display:grid;place-items:center;width:32px;height:32px;border-radius:50%;background:#065f46;color:white;border:2px solid white;font-weight:bold">${index + 1}</span>`,
iconSize: [32, 32],
iconAnchor: [16, 16],
});
const marker = L.marker([latitude, longitude], {
icon,
title: p.title,
alt: p.title,
keyboard: true,
})
.bindPopup(popup)
.on("click", () => setSelected(p.id))
.addTo(instance);
markers.current.set(p.id, marker);
bounds.push([latitude, longitude]);
}
if (bounds.length) instance.fitBounds(bounds, { padding: [40, 40], maxZoom: 14 });
observer = new ResizeObserver(() => instance.invalidateSize());
observer.observe(element.current);
})
.catch(() => {
if (!cancelled) setError("Não foi possível iniciar o mapa.");
});
return () => {
cancelled = true;
observer?.disconnect();
map.current?.remove();
map.current = null;
markers.current.clear();
};
}, [points]);
return (
<section
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
aria-label="Mapa interactivo dos investimentos"
>
<h2 className="text-xl font-bold">Mapa dos investimentos</h2>
<p>
Arraste para navegar; use +/− para ampliar. Pode seleccionar um investimento na
lista para o localizar.
</p>
{error && <p role="status">{error}</p>}
<div
ref={element}
className="relative z-0 h-[460px] w-full rounded"
aria-label="Mapa; navegação por setas e teclas mais e menos"
/>
{points === null ? (
<p role="status">A carregar localizações…</p>
) : (
<p role="status">{points.length} investimentos com coordenadas disponíveis.</p>
)}
<ul className="grid gap-2 md:grid-cols-2">
{(points ?? []).map((p) => (
<li
key={p.properties.id}
className={
selected === p.properties.id
? "rounded border-2 border-emerald-700 p-3"
: "rounded border p-3"
}
>
<button
type="button"
className="text-left font-bold underline"
aria-pressed={selected === p.properties.id}
onClick={() => {
const marker = markers.current.get(p.properties.id);
if (marker) {
map.current?.setView(marker.getLatLng(), 14);
marker.openPopup();
setSelected(p.properties.id);
}
}}
>
{p.properties.title}
</button>
<p>
{p.properties.category} · {p.properties.location}
</p>
<a className="underline" href={p.properties.url}>
Abrir ficha
</a>
</li>
))}
</ul>
</section>
);
}
@@ -0,0 +1,106 @@
import { useEffect, useState } from "react";
import { api } from "@/pages/investment/shared";
export default function InvestmentCoordinates({ id }: { id: number | string }) {
const [data, setData] = useState({
version: 0,
latitude: "",
longitude: "",
source_reference: "",
});
const [ready, setReady] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
useEffect(() => {
let active = true;
api(`/management/opportunities/${id}/coordinates`)
.then((result) => {
if (active) {
setData({
...result,
latitude: String(result.latitude ?? ""),
longitude: String(result.longitude ?? ""),
});
setReady(true);
}
})
.catch((e) => {
if (active) setMessage(e.message);
});
return () => {
active = false;
};
}, [id]);
return (
<form
className="my-6 space-y-3 rounded border p-4"
onSubmit={async (event) => {
event.preventDefault();
setBusy(true);
try {
const result = await api(`/management/opportunities/${id}/coordinates`, {
...data,
confirmed_site: confirmed,
});
setData((previous) => ({ ...previous, version: result.version }));
setMessage(
"Coordenadas guardadas. O marcador acompanha a publicação da oportunidade.",
);
} catch (e) {
setMessage(e instanceof Error ? e.message : "Falha ao guardar.");
} finally {
setBusy(false);
}
}}
>
<h2 className="text-lg font-bold">Posição do investimento no mapa</h2>
<p>Registe a posição do local em WGS84 e a referência que a confirma.</p>
<div className="grid gap-3 md:grid-cols-2">
{(["latitude", "longitude"] as const).map((field) => (
<label key={field}>
{field === "latitude" ? "Latitude" : "Longitude"}
<input
className="w-full rounded border p-2"
type="number"
step="any"
min={field === "latitude" ? -90 : -180}
max={field === "latitude" ? 90 : 180}
required
value={data[field]}
onChange={(e) => setData({ ...data, [field]: e.target.value })}
/>
</label>
))}
</div>
<label className="block">
Fonte das coordenadas
<input
className="w-full rounded border p-2"
required
minLength={10}
maxLength={2000}
value={data.source_reference}
onChange={(e) => setData({ ...data, source_reference: e.target.value })}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
required
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
/>
Confirmo que esta posição corresponde ao local do investimento e pode ser divulgada
quando a ficha estiver publicada.
</label>
<button
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
disabled={!ready || busy}
>
Guardar coordenadas
</button>
{message && <p role="status">{message}</p>}
</form>
);
}
@@ -0,0 +1,56 @@
import { useEffect, useState } from "react";
import InteractiveInvestmentMap, { type InvestmentMapFeature } from "./interactive-investment-map";
export default function InvestmentMapPanel({
filters,
}: {
filters: Record<string, string | number>;
}) {
const key = JSON.stringify(filters);
const [points, setPoints] = useState<InvestmentMapFeature[] | null>(null);
const [missing, setMissing] = useState<{ id: number; title: string; url: string }[]>([]);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
setPoints(null);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
})
.then(async (response) => {
if (!response.ok) throw new Error("Mapa indisponível.");
return response.json();
})
.then((data) => {
if (controller.signal.aborted) return;
setPoints(data.features);
setMissing(data.unlocated ?? []);
setError(data.truncated ? "Cobertura limitada: refine os filtros." : "");
})
.catch((e) => {
if (!controller.signal.aborted) setError(e.message);
});
return () => controller.abort();
}, [key]);
return (
<section className="space-y-3">
{error && <p role="alert">{error}</p>}
<InteractiveInvestmentMap points={points} />
{missing.length > 0 && (
<div>
<p>{missing.length} investimentos aguardam coordenadas do local:</p>
<ul>
{missing.map((record) => (
<li key={record.id}>
<a href={record.url} className="underline">
{record.title}
</a>
</li>
))}
</ul>
</div>
)}
</section>
);
}
@@ -0,0 +1,230 @@
import { useEffect, useId, useState } from "react";
import { api } from "@/pages/investment/shared";
export type TerritoryOption = {
id: string;
name: string;
parent_id: string | null;
location_type: string;
deleted_at?: string | null;
};
type Option = TerritoryOption;
const levels = ["province", "district", "admin_post", "locality"];
const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"];
const control = "w-full rounded border bg-background p-2 text-foreground";
export function TerritoryFields({
initial = [],
onChange,
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
}) {
const [path, setPath] = useState(initial);
return (
<div className="grid gap-4 md:col-span-full md:grid-cols-2">
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
(field, index) => (
<div key={`${field}-${path[index - 1]?.id ?? ""}`}>
<input type="hidden" name={field} value={path[index]?.id ?? ""} />
<TerritoryLevel
index={index}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) => {
const next = [...path.slice(0, index), ...(value ? [value] : [])];
setPath(next);
onChange?.(next);
}}
/>
</div>
),
)}
</div>
);
}
export function TerritoryLevel({
index,
parent,
selected,
onChange,
endpoint = "/management/territory-options",
}: {
index: number;
parent: string;
selected?: Option;
onChange: (value?: Option) => void;
endpoint?: string;
}) {
const id = useId();
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
const [options, setOptions] = useState<Option[]>([]);
const [more, setMore] = useState(false);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const enabled = index === 0 || Boolean(parent);
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
const timer = setTimeout(async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams({
type: levels[index],
parent_id: parent,
q,
page: String(page),
});
const response = await fetch(`${endpoint}?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!response.ok) throw new Error("Não foi possível carregar as localizações.");
const data = await response.json();
setOptions(data.data);
setMore(Boolean(data.next_page_url));
} catch (e) {
if (!controller.signal.aborted)
setError(e instanceof Error ? e.message : "Erro de ligação.");
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}, 250);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [index, parent, q, page, enabled, endpoint]);
return (
<div className="space-y-2">
<label htmlFor={id} className="font-medium">
{labels[index]}
</label>
<input
className={control}
aria-label={`Pesquisar ${labels[index]}`}
disabled={!enabled}
value={q}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
}}
placeholder="Pesquisar por nome"
/>
<select
id={id}
className={control}
disabled={!enabled || loading}
value={selected?.id ?? ""}
onChange={(e) => onChange(options.find((o) => o.id === e.target.value))}
>
<option value="">{enabled ? "Seleccione" : "Seleccione o nível anterior"}</option>
{selected && !options.some((o) => o.id === selected.id) && (
<option value={selected.id}>
{selected.name}
{selected.deleted_at ? " (arquivada)" : " (selecção actual)"}
</option>
)}
{options.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
{loading && <p role="status">A carregar…</p>}
{error && <p role="alert">{error}</p>}
{enabled && !loading && !error && options.length === 0 && (
<p className="text-sm">Sem opções para esta pesquisa.</p>
)}
<div className="flex gap-3 text-sm">
{page > 1 && (
<button type="button" onClick={() => setPage(page - 1)}>
Anterior
</button>
)}
{more && (
<button type="button" onClick={() => setPage(page + 1)}>
Mais opções
</button>
)}
</div>
</div>
);
}
export default function InvestmentTerritory({ kind, id }: { kind: string; id: string | number }) {
const [path, setPath] = useState<Option[]>([]);
const [version, setVersion] = useState<number | null>(null);
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
api(`/management/territories/${kind}/${id}`)
.then((data) => {
if (!active) return;
setPath(
levels.flatMap((level) =>
data.path.filter((o: Option) => o.location_type === level),
),
);
setVersion(data.version);
})
.catch((e) => {
if (active) setMessage(e.message);
});
return () => {
active = false;
};
}, [kind, id]);
return (
<section
className="my-6 space-y-4 rounded border p-4"
aria-label="Localização do investimento"
>
<h2 className="text-lg font-semibold">Localização do investimento</h2>
<p>Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes.</p>
<div className="grid gap-4 md:grid-cols-2">
{levels.map((level, index) => (
<TerritoryLevel
key={`${level}-${path[index - 1]?.id ?? ""}`}
index={index}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
onChange={(value) => {
setPath([...path.slice(0, index), ...(value ? [value] : [])]);
setMessage("");
}}
/>
))}
</div>
<button
type="button"
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
disabled={version === null || busy}
onClick={async () => {
setBusy(true);
setMessage("");
try {
const data = await api(`/management/territories/${kind}/${id}`, {
version,
path: path.map((o) => o.id),
});
setVersion(data.version);
setMessage("Localização associada e guardada.");
} catch (e) {
setMessage(e instanceof Error ? e.message : "Erro ao guardar.");
} finally {
setBusy(false);
}
}}
>
Guardar localização
</button>
{message && <p role="status">{message}</p>}
</section>
);
}
+12 -1
View File
@@ -17,6 +17,8 @@ export const portalLinks = [
["/apoio", "Apoio ao Investidor"],
] as const;
const names: Record<string, string> = {
"/investidor/negocios": "Os meus negócios",
"/management/negocios": "Revisão de negócios",
...Object.fromEntries(portalLinks),
"/parcerias": "Bolsa de Parcerias",
"/simulador-fiscal": "Simulador Fiscal",
@@ -47,13 +49,16 @@ export default function PortalNavigation({ children }: { children: ReactNode })
.filter((p) => p !== "/" && path.startsWith(`${p}/`))
.sort((a, b) => b.length - a.length)[0];
const pageProps = props as {
record?: { title?: string };
record?: { title?: string; name?: string };
zone?: { name?: string };
sector?: { name?: string };
initialOpportunity?: { title?: string };
};
const title =
names[path] ??
pageProps.record?.title ??
pageProps.record?.name ??
pageProps.zone?.name ??
pageProps.sector?.name ??
pageProps.initialOpportunity?.title ??
(path.includes("/edit")
@@ -109,6 +114,7 @@ export default function PortalNavigation({ children }: { children: ReactNode })
}
export function PortalMenu() {
const { existingBusinessEnabled } = usePage<{ existingBusinessEnabled?: boolean }>().props;
const [expanded, setExpanded] = useState(false);
const menuId = useId();
return (
@@ -139,6 +145,11 @@ export function PortalMenu() {
{label}
</Link>
))}
{existingBusinessEnabled && (
<Link href="/investidor/negocios" className="underline">
Os meus negócios
</Link>
)}
<Link href="/parcerias" className="underline">
Bolsa de Parcerias
</Link>
+9
View File
@@ -0,0 +1,9 @@
/** Estados de preparação usados pelo cadastro de oportunidades (níveis 1–6). */
export const MATURITY_LEVELS = [
"Ideia identificada",
"Pré-estudo disponível",
"Estudo de viabilidade em curso",
"Projecto estruturado",
"Pronto para investimento",
"Em negociação ou implementação",
] as const;
+1 -8
View File
@@ -1,6 +1,7 @@
import { createContext, useContext, useRef, useState } from "react";
import { router } from "@inertiajs/react";
import { PortalMenu } from "@/layouts/portal-navigation";
import { MATURITY_LEVELS } from "@/lib/investment-maturity";
import type { Dispatch, FormEvent, ReactNode, SetStateAction } from "react";
import type { LucideIcon } from "lucide-react";
import { usePortalQuery } from "@/hooks/use-portal-query";
@@ -94,14 +95,6 @@ const PROVINCES = [
"Niassa",
];
const MATURITY_LEVELS = [
"Ideia identificada",
"Pré-estudo disponível",
"Estudo de viabilidade em curso",
"Projecto estruturado",
"Pronto para investimento",
"Em negociação ou implementação",
];
/* ------------------------------------------------------------------ */
/* Componentes */
@@ -0,0 +1,286 @@
import { router } from "@inertiajs/react";
import { useState } from "react";
import { Field, input, button, card, api } from "./shared";
export type BusinessObject = {
id: string;
kind: string;
verification_status: string;
payload: Record<string, string>;
};
const kinds: Record<string, string> = {
company: "Empresa",
participation: "Participação",
asset: "Activo físico",
property: "Imóvel/propriedade",
unit: "Unidade imobiliária",
improvement: "Benfeitoria",
agricultural_investment: "Investimento agrícola",
land_right: "Direito fundiário",
contract: "Contrato",
license: "Licença",
authorization: "Autorização",
encumbrance: "Ónus ou encargo",
valuation: "Avaliação declarada",
capital_request: "Pedido de capital",
};
const fields: Record<string, string> = {
label: "Designação reservada",
declared_holder: "Titular declarado",
document_reference: "Referência documental",
source_reference: "Fonte da informação",
competent_entity: "Entidade emissora/competente declarada",
purpose: "Finalidade autorizada declarada",
location_description: "Localização reservada",
boundaries_description: "Limites declarados",
occupancy: "Ocupação/utilização",
condition: "Conservação/operação",
encumbrances: "Ónus, garantias ou litígios declarados",
restrictions: "Restrições declaradas",
required_authorizations: "Autorizações necessárias declaradas",
transfer_condition: "Condição de cessão/transmissão declarada",
valid_from: "Início de validade",
valid_until: "Fim de validade",
area: "Área (decimal com ponto)",
participation_percent: "Participação (%)",
amount: "Valor (decimal com ponto)",
currency: "Moeda (código de três letras)",
};
export default function BusinessObjects({
businessId,
version,
editable,
objects,
objectKinds,
}: {
businessId: string;
version: number;
editable: boolean;
objects: BusinessObject[];
objectKinds: string[];
}) {
const [kind, setKind] = useState(objectKinds[0]);
const [objectId, setObjectId] = useState<string | null>(null);
const [payload, setPayload] = useState<Record<string, string>>({});
const [reason, setReason] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<section className={`${card} space-y-4`}>
<h2 className="text-xl font-bold">Activos, contratos e direitos declarados</h2>
<p>
Registe separadamente cada elemento. Todos ficam pendentes de verificação; a
declaração não confirma titularidade, validade ou transmissibilidade. Não use este
formulário para anexar ficheiros.
</p>
{!objects.length && <p>Nenhum elemento registado.</p>}
{objects.map((o) => (
<article key={o.id} className="rounded border p-4">
<h3 className="font-bold">
{kinds[o.kind]} · {o.payload.label}
</h3>
<p>Pendente de verificação</p>
<dl>
{Object.entries(o.payload)
.filter(([key, value]) => key !== "label" && value)
.map(([key, value]) => (
<div key={key}>
<dt className="font-semibold">
{fields[key] ??
(
{
area_unit: "Unidade da área",
value_kind: "Natureza do valor",
contract_type: "Tipo de contrato",
} as Record<string, string>
)[key] ??
key}
</dt>
<dd className="break-words">
{key === "value_kind"
? ((
{
asking: "Pedido",
indicative: "Indicativo",
appraised: "Avaliado — declaração pendente",
proposed: "Proposto",
negotiated: "Negociado — declaração pendente",
confirmed: "Confirmado — declaração pendente",
} as Record<string, string>
)[value] ?? value)
: value}
</dd>
</div>
))}
</dl>
{editable && (
<button
type="button"
className={button}
onClick={() => {
setObjectId(o.id);
setKind(o.kind);
setPayload(o.payload);
setReason("");
}}
>
Editar elemento
</button>
)}
</article>
))}
{editable && (
<form
className="space-y-4"
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
setError("");
try {
await api(
`/api/v1/existing-business/listings/${businessId}/objects${objectId ? `/${objectId}` : ""}`,
{
...(objectId ? { _method: "PUT" } : {}),
kind,
payload,
reason,
version_no: version,
},
);
router.reload();
} catch (err) {
setError(
err instanceof Error
? err.message
: "Não foi possível guardar o elemento.",
);
} finally {
setBusy(false);
}
}}
>
<h3 className="font-bold">
{objectId ? "Editar elemento reservado" : "Acrescentar elemento reservado"}
</h3>
<Field label="Natureza">
<select
className={input}
value={kind}
disabled={!!objectId || busy}
onChange={(e) => setKind(e.target.value)}
>
{objectKinds.map((k) => (
<option key={k} value={k}>
{kinds[k]}
</option>
))}
</select>
</Field>
<div className="grid gap-4 md:grid-cols-2">
{Object.entries(fields).map(([key, label]) => (
<Field key={key} label={label}>
<input
className={input}
type={key.startsWith("valid_") ? "date" : "text"}
value={payload[key] ?? ""}
maxLength={key === "label" ? 200 : 2000}
required={key === "label" || key === "source_reference"}
onChange={(e) =>
setPayload({ ...payload, [key]: e.target.value })
}
/>
</Field>
))}
<Field label="Unidade da área">
<select
className={input}
value={payload.area_unit ?? ""}
onChange={(e) =>
setPayload({ ...payload, area_unit: e.target.value })
}
>
<option value="">Não indicada</option>
{["m2", "ha", "km2"].map((x) => (
<option key={x}>{x}</option>
))}
</select>
</Field>
<Field label="Natureza do valor">
<select
className={input}
value={payload.value_kind ?? ""}
onChange={(e) =>
setPayload({ ...payload, value_kind: e.target.value })
}
>
<option value="">Não indicada</option>
{Object.entries({
asking: "Pedido",
indicative: "Indicativo",
appraised: "Avaliado (declaração por verificar)",
proposed: "Proposto",
negotiated: "Negociado (declaração por verificar)",
confirmed: "Confirmado (declaração por verificar)",
}).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</Field>
<Field label="Tipo de contrato">
<select
className={input}
value={payload.contract_type ?? ""}
onChange={(e) =>
setPayload({ ...payload, contract_type: e.target.value })
}
>
<option value="">Não indicado</option>
{Object.entries({
purchase: "Compra",
sale: "Venda",
lease: "Arrendamento",
operation: "Exploração",
management: "Gestão",
other: "Outro",
}).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</Field>
</div>
<Field label="Motivo do registo ou alteração">
<textarea
className={input}
value={reason}
minLength={10}
maxLength={1000}
required
onChange={(e) => setReason(e.target.value)}
/>
</Field>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>
{busy ? "A guardar…" : "Guardar elemento reservado"}
</button>
{objectId && (
<button
type="button"
className="ml-4 underline"
onClick={() => {
setObjectId(null);
setPayload({});
setReason("");
}}
>
Cancelar edição
</button>
)}
</form>
)}
</section>
);
}
@@ -0,0 +1,45 @@
export type Business = {
id: string;
code: string;
modality: string;
status: string;
classification: string;
version_no: number;
payload: {
title: string;
description?: string;
declared_reason?: string;
source_reference?: string;
valid_until?: string;
};
};
export const businessStates: Record<string, string> = {
draft: "Rascunho",
submitted: "Submetido",
in_review: "Em revisão",
needs_information: "Pendente de informação",
withdrawn: "Retirado",
};
export const businessModalities: Record<string, string> = {
company_sale: "Venda da empresa",
participation_sale: "Venda de participação",
capital_increase: "Aumento de capital",
financial_investor: "Investidor financeiro",
strategic_partner: "Sócio estratégico",
buyer_search: "Procura de comprador",
position_assignment: "Cessão de posição",
franchise: "Franchising",
asset_sale: "Venda de activos",
asset_lease: "Arrendamento de activos",
business_unit_transfer: "Transferência de unidade de negócio",
joint_venture: "Joint venture",
succession: "Sucessão empresarial",
recovery: "Recuperação",
expansion: "Expansão",
internationalization: "Internacionalização",
real_estate: "Imobiliário",
agricultural_investment: "Investimento agrícola",
land_right: "Direito fundiário",
mining_license: "Licença mineira",
forestry_license: "Licença florestal",
};
@@ -0,0 +1,176 @@
import { router } from "@inertiajs/react";
import { useState } from "react";
import { api, button, card, Field, input } from "./shared";
import type { BusinessObject } from "./business-objects";
const labels: Record<string, string> = {
identity: "Identidade",
representation: "Representação",
declared_ownership: "Titularidade declarada",
documentary_ownership: "Titularidade documental",
document_received: "Documento recebido",
document_validated: "Documento validado",
independent_valuation: "Avaliação independente",
land_right_documented: "Direito fundiário documentado",
license_confirmed: "Licença confirmada",
validity: "Validade",
legal_transfer: "Transmissibilidade jurídica",
prior_authorization: "Autorização prévia",
confirmed: "Confirmado pelo revisor",
rejected: "Não confirmado",
inconclusive: "Inconclusivo",
revoked: "Revogado",
stale: "Rever após alteração dos dados",
expired: "Expirado",
};
export type BusinessVerification = {
check: string;
object_id?: string | null;
outcome: string;
effective_outcome: string;
evidence_reference: string;
note: string;
valid_until?: string | null;
version_no: number;
};
export default function BusinessVerifications({
id,
version,
editable,
checks,
findings,
objects,
}: {
id: string;
version: number;
editable: boolean;
checks: string[];
findings: BusinessVerification[];
objects: BusinessObject[];
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [outcome, setOutcome] = useState("inconclusive");
return (
<section className={`${card} space-y-4`}>
<h2 className="text-xl font-bold">Verificações e evidências</h2>
<p>
Cada conclusão corresponde apenas ao aspecto e à versão analisados. Não constitui
certificação global, autorização de publicação ou garantia de transmissão.
Alterações aos dados exigem nova revisão.
</p>
{findings.length === 0 && <p>Ainda não existem verificações registadas.</p>}
<ul className="space-y-4">
{findings.map((finding) => (
<li key={finding.version_no} className="break-words">
<strong>
{labels[finding.check]} · {labels[finding.effective_outcome]}
</strong>
<p>
{objects.find((object) => object.id === finding.object_id)?.payload
.label ?? "Negócio"}{" "}
· versão {finding.version_no}
</p>
<p>Evidência: {finding.evidence_reference}</p>
<p>{finding.note}</p>
{finding.valid_until && <p>Válido até {finding.valid_until}</p>}
</li>
))}
</ul>
{editable && (
<form
className="space-y-4"
onSubmit={async (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.currentTarget));
setBusy(true);
setError("");
try {
await api(`/api/v1/existing-business/listings/${id}/verifications`, {
...data,
version_no: version,
});
router.reload();
} catch (failure) {
setError(
failure instanceof Error
? failure.message
: "Não foi possível registar a verificação.",
);
} finally {
setBusy(false);
}
}}
>
<fieldset disabled={busy} className="space-y-4">
<Field label="Elemento analisado">
<select className={input} name="object_id">
<option value="">Negócio</option>
{objects.map((object) => (
<option key={object.id} value={object.id}>
{object.payload.label}
</option>
))}
</select>
</Field>
<Field label="Aspecto verificado">
<select className={input} name="check">
{checks.map((check) => (
<option key={check} value={check}>
{labels[check]}
</option>
))}
</select>
</Field>
<Field label="Conclusão">
<select
className={input}
name="outcome"
value={outcome}
onChange={(event) => setOutcome(event.target.value)}
>
{["inconclusive", "confirmed", "rejected", "revoked"].map(
(value) => (
<option key={value} value={value}>
{labels[value]}
</option>
),
)}
</select>
</Field>
<Field label="Referência da evidência consultada">
<textarea
className={input}
name="evidence_reference"
required
minLength={10}
maxLength={2000}
/>
</Field>
<Field label="Fundamentação e limites da conclusão">
<textarea
className={input}
name="note"
required
minLength={10}
maxLength={2000}
/>
</Field>
<Field label="Validade da conclusão">
<input
className={input}
type="date"
name="valid_until"
required={outcome === "confirmed"}
/>
</Field>
<button className={button} disabled={busy}>
Registar verificação
</button>
</fieldset>
{error && <p role="alert">{error}</p>}
</form>
)}
</section>
);
}
+252
View File
@@ -0,0 +1,252 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
import { businessModalities, businessStates } from "./business-types";
import type { Business } from "./business-types";
import BusinessObjects from "./business-objects";
import type { BusinessObject } from "./business-objects";
import BusinessVerifications from "./business-verifications";
import type { BusinessVerification } from "./business-verifications";
type Props = {
record: Business;
canEdit: boolean;
owner: boolean;
canReview: boolean;
modalities: string[];
objects: BusinessObject[];
objectKinds: string[];
verificationChecks: string[];
verifications: BusinessVerification[];
history: { version_no: number; action: string; created_at: string; note: string }[];
};
export default function BusinessPage(props: Props) {
return <Editor key={`${props.record.id}:${props.record.version_no}`} {...props} />;
}
function Editor({
record,
canEdit,
owner,
canReview,
modalities,
history,
objects,
objectKinds,
verificationChecks,
verifications,
}: Props) {
const [payload, setPayload] = useState(record.payload);
const [modality, setModality] = useState(record.modality);
const [note, setNote] = useState("");
const [consent, setConsent] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const dirty =
JSON.stringify(payload) !== JSON.stringify(record.payload) || modality !== record.modality;
const run = async (action?: string) => {
setBusy(true);
setError("");
try {
await api(
`/api/v1/existing-business/listings/${record.id}${action ? "/transitions" : ""}`,
action
? { action, version_no: record.version_no, note, review_consent: consent }
: {
_method: "PUT",
modality,
classification: record.classification,
payload,
reason: note,
version_no: record.version_no,
},
);
router.reload();
} catch (err) {
setError(
err instanceof Error
? err.message
: "Não foi possível guardar. Recarregue se a versão mudou.",
);
} finally {
setBusy(false);
}
};
return (
<Frame title={record.payload.title}>
<Link
className="underline"
href={owner ? "/investidor/negocios" : "/management/negocios"}
>
Voltar à lista
</Link>
<p>
{businessStates[record.status]} · versão {record.version_no} · informação reservada
</p>
<p>
Informação declarada, pendente de validação. Não constitui anúncio público,
certificação, avaliação ou autorização de transmissão.
</p>
<form
className={`${card} space-y-4`}
onSubmit={(e) => {
e.preventDefault();
void run();
}}
>
<fieldset disabled={!canEdit || busy} className="space-y-4">
<Field label="Modalidade">
<select
className={input}
value={modality}
onChange={(e) => setModality(e.target.value)}
>
{modalities.map((m) => (
<option value={m} key={m}>
{businessModalities[m] ?? m}
</option>
))}
</select>
</Field>
{(
[
["title", "Título privado"],
["description", "Descrição reservada"],
["declared_reason", "Motivo declarado"],
["source_reference", "Referência da fonte"],
["valid_until", "Validade declarada"],
] as const
).map(([key, label]) => (
<Field key={key} label={label}>
{key === "description" ? (
<textarea
className={input}
rows={5}
maxLength={10000}
value={payload[key] ?? ""}
onChange={(e) =>
setPayload({ ...payload, [key]: e.target.value })
}
/>
) : (
<input
className={input}
type={key === "valid_until" ? "date" : "text"}
maxLength={key === "title" ? 200 : 2000}
value={payload[key] ?? ""}
onChange={(e) =>
setPayload({ ...payload, [key]: e.target.value })
}
/>
)}
</Field>
))}
</fieldset>
<Field label="Motivo da alteração ou nota para a revisão">
<textarea
className={input}
value={note}
onChange={(e) => setNote(e.target.value)}
minLength={10}
maxLength={1000}
required
/>
</Field>
{error && <p role="alert">{error}</p>}
{canEdit && (
<button className={button} disabled={busy || note.trim().length < 10}>
Guardar rascunho
</button>
)}
{dirty && <p role="status">Guarde as alterações antes de mudar de estado.</p>}
</form>
{owner && canEdit && (
<label className="flex gap-3">
<input
type="checkbox"
checked={consent}
onChange={(e) => setConsent(e.target.checked)}
/>
Autorizo a análise interna desta submissão pelos revisores designados. Esta
autorização não permite publicação.
</label>
)}
<div className="flex flex-wrap gap-3">
{owner && canEdit && (
<button
className={button}
disabled={busy || dirty || !consent || note.trim().length < 10}
onClick={() => void run("submitted")}
>
Submeter para análise
</button>
)}
{canReview && record.status === "submitted" && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run("in_review")}
>
Iniciar revisão
</button>
)}
{canReview && record.status === "in_review" && (
<button
className={button}
disabled={busy || note.trim().length < 10}
onClick={() => void run("needs_information")}
>
Pedir informação
</button>
)}
{owner && record.status !== "withdrawn" && (
<button
className={button}
disabled={busy || dirty || note.trim().length < 10}
onClick={() => void run("withdrawn")}
>
Retirar submissão
</button>
)}
</div>
<BusinessObjects
businessId={record.id}
version={record.version_no}
editable={canEdit && !dirty && !busy}
objects={objects}
objectKinds={objectKinds}
/>
<BusinessVerifications
id={record.id}
version={record.version_no}
editable={canReview && record.status === "in_review" && !busy}
checks={verificationChecks}
findings={verifications}
objects={objects}
/>
<section className={card}>
<h2 className="text-xl font-bold">Histórico</h2>
<ol>
{history.map((h) => (
<li key={h.version_no}>
Versão {h.version_no} ·{" "}
{businessStates[h.action] ??
(
{
created: "Criado",
updated: "Alterado",
archived: "Arquivado",
object_added: "Elemento declarado acrescentado",
object_updated: "Elemento declarado alterado",
verification: "Verificação registada",
} as Record<string, string>
)[h.action] ??
h.action}{" "}
· {new Date(h.created_at).toLocaleString("pt-MZ")}
<p>{h.note}</p>
</li>
))}
</ol>
</section>
</Frame>
);
}
@@ -0,0 +1,99 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
import { businessModalities, businessStates } from "./business-types";
import type { Business } from "./business-types";
export default function Businesses({
records,
management,
modalities,
}: {
records: { data: Business[]; prev_page_url: string | null; next_page_url: string | null };
management: boolean;
modalities: string[];
}) {
const [title, setTitle] = useState("");
const [modality, setModality] = useState(modalities[0]);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<Frame title={management ? "Revisão de negócios" : "Os meus negócios"}>
<p>
Área privada de preparação e revisão. A submissão não confirma titularidade,
validade ou transmissibilidade do negócio, activo ou direito.
</p>
{!management && (
<form
className={`${card} space-y-4`}
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
setError("");
try {
const result = await api("/api/v1/existing-business/listings", {
modality,
classification: "confidential",
reason: "Criação de rascunho pelo proprietário",
payload: { title },
});
router.visit(`/investidor/negocios/${result.id}`);
} catch (err) {
setError(
err instanceof Error
? err.message
: "Não foi possível criar o rascunho.",
);
} finally {
setBusy(false);
}
}}
>
<h2 className="text-xl font-bold">Preparar negócio</h2>
<Field label="Título privado">
<input
className={input}
value={title}
onChange={(e) => setTitle(e.target.value)}
required
maxLength={200}
/>
</Field>
<Field label="Modalidade">
<select
className={input}
value={modality}
onChange={(e) => setModality(e.target.value)}
>
{modalities.map((m) => (
<option key={m} value={m}>
{businessModalities[m] ?? m}
</option>
))}
</select>
</Field>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>
{busy ? "A criar…" : "Criar rascunho privado"}
</button>
</form>
)}
{!records.data.length && <p role="status">Não existem negócios nesta lista.</p>}
{records.data.map((r) => (
<article className={card} key={r.id}>
<Link className="font-bold underline" href={`/investidor/negocios/${r.id}`}>
{r.payload.title}
</Link>
<p>
{businessModalities[r.modality]} · {businessStates[r.status]} · versão{" "}
{r.version_no}
</p>
</article>
))}
<nav aria-label="Paginação dos negócios" className="flex gap-4">
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
</nav>
</Frame>
);
}
+131 -109
View File
@@ -1,5 +1,8 @@
import { Link, router, useForm, usePage } from "@inertiajs/react";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import Map from "@/components/interactive-investment-map";
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
import { MATURITY_LEVELS } from "@/lib/investment-maturity";
import { Frame, Field, input, button, card, money, api, groupLabels } from "./shared";
import type { Opportunity, References } from "./shared";
@@ -13,6 +16,7 @@ export default function Catalogue({
results,
favourites,
territorial,
territorySelection,
}: {
filters: Record<string, string | string[] | boolean>;
references: References;
@@ -23,6 +27,7 @@ export default function Catalogue({
next_page_url: string | null;
};
favourites: number[];
territorySelection: TerritoryOption[];
territorial: {
id: string;
title: string;
@@ -40,6 +45,10 @@ export default function Catalogue({
sector: String(filters.sector ?? ""),
province: String(filters.province ?? ""),
district: String(filters.district ?? ""),
province_id: String(filters.province_id ?? ""),
district_id: String(filters.district_id ?? ""),
admin_post_id: String(filters.admin_post_id ?? ""),
locality_id: String(filters.locality_id ?? ""),
cluster_id: String(filters.cluster_id ?? ""),
zee_id: String(filters.zee_id ?? ""),
zfi_id: String(filters.zfi_id ?? ""),
@@ -53,19 +62,49 @@ export default function Catalogue({
currency: String(filters.currency ?? ""),
maturity_level: String(filters.maturity_level ?? ""),
before: String(filters.before ?? ""),
sort: String(filters.sort ?? "recent"),
sort: typeof filters.sort === "string" ? filters.sort : "recent",
facets: (Array.isArray(filters.facets) ? filters.facets : []).map(Number),
});
const view = String(filters.view ?? "grid");
const [territoryPath, setTerritoryPath] = useState(territorySelection);
const [saved, setSaved] = useState(favourites);
const [selected, setSelected] = useState<number[]>([]);
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
const [points, setPoints] = useState<Feature[] | null>(null);
const [unlocated, setUnlocated] = useState<
{ id: number; title: string; location: string; url: string }[]
>([]);
const [truncated, setTruncated] = useState(false);
const [error, setError] = useState("");
const [suggestions, setSuggestions] = useState<{ title: string; slug: string }[]>([]);
const filterKey = JSON.stringify(filters);
const draftFilterKey = JSON.stringify(form.data);
const lastRequest = useRef(draftFilterKey);
useEffect(() => {
if (draftFilterKey === lastRequest.current) return;
let cancel: (() => void) | undefined;
const timer = setTimeout(() => {
const data = JSON.parse(draftFilterKey);
lastRequest.current = draftFilterKey;
router.get(
"/oportunidades",
{ ...data, education: data.education ? 1 : 0 },
{
preserveState: true,
preserveScroll: true,
replace: true,
onCancelToken: (token) => {
cancel = () => token.cancel();
},
},
);
}, 350);
return () => {
clearTimeout(timer);
cancel?.();
};
}, [draftFilterKey]);
useEffect(() => {
if (view !== "map" && view !== "combined") return;
let active = true;
const values = JSON.parse(filterKey) as Record<string, string | string[] | boolean>;
const params = new URLSearchParams();
@@ -75,10 +114,16 @@ export default function Catalogue({
params.set(key, String(value === true ? 1 : value === false ? 0 : value));
}
setPoints(null);
setUnlocated([]);
setTruncated(false);
setError("");
api(`/api/v1/investment/map?${params}`)
.then((data) => {
if (active) setPoints(data.features);
if (active) {
setPoints(data.features);
setUnlocated(data.unlocated ?? []);
setTruncated(Boolean(data.truncated));
}
})
.catch(() => {
if (active)
@@ -166,6 +211,7 @@ export default function Catalogue({
setPoints(null);
setComparison([]);
setSelected([]);
form.transform((data) => ({ ...data, education: data.education ? 1 : 0 }));
form.get("/oportunidades", { preserveState: true });
}}
>
@@ -218,39 +264,30 @@ export default function Catalogue({
</select>
</Field>
))}
{(["clusters", "corridors", "projects", "locations"] as const).map(
(group, i) => {
const key = (
[
"cluster_id",
"corridor_id",
"project_id",
"geo_location_id",
] as const
)[i];
return (
<Field
key={group}
label={
["Cluster", "Corredor", "Projecto âncora", "Localização"][i]
}
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
const key = (
["cluster_id", "corridor_id", "project_id", "geo_location_id"] as const
)[i];
return (
<Field
key={group}
label={["Cluster", "Corredor", "Projecto âncora", "Localização"][i]}
>
<select
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
>
<select
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
>
<option value="">Todos</option>
{references[group].map((r) => (
<option value={r.id} key={r.id}>
{r.name}
</option>
))}
</select>
</Field>
);
},
)}
<option value="">Todos</option>
{references[group].map((r) => (
<option value={r.id} key={r.id}>
{r.name}
</option>
))}
</select>
</Field>
);
})}
<Field label="Sector">
<select
className={input}
@@ -265,16 +302,34 @@ export default function Catalogue({
))}
</select>
</Field>
{(["province", "district"] as const).map((key) => (
<Field key={key} label={key === "province" ? "Província" : "Distrito"}>
<input
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
maxLength={100}
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
(key, index) => (
<TerritoryLevel
key={`${key}-${territoryPath[index - 1]?.id ?? ""}`}
index={index}
parent={territoryPath[index - 1]?.id ?? ""}
selected={territoryPath[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) => {
const path = [
...territoryPath.slice(0, index),
...(value ? [value] : []),
];
setTerritoryPath(path);
form.setData((data) => ({
...data,
province: "",
district: "",
geo_location_id: "",
province_id: path[0]?.id ?? "",
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
}));
}}
/>
</Field>
))}
),
)}
<Field label="Estado de preparação">
<select
className={input}
@@ -282,9 +337,9 @@ export default function Catalogue({
onChange={(e) => form.setData("maturity_level", e.target.value)}
>
<option value="">Todos os níveis</option>
{[1, 2, 3, 4, 5, 6].map((n) => (
<option key={n} value={n}>
Maturidade {n}
{MATURITY_LEVELS.map((label, index) => (
<option key={index + 1} value={index + 1}>
{label}
</option>
))}
</select>
@@ -434,7 +489,34 @@ export default function Catalogue({
</Link>
</div>
{error && <p role="alert">{error}</p>}
{(view === "map" || view === "combined") && !error && <Map points={points} />}
{!error && <Map points={points} />}
{truncated && (
<p role="alert">
O mapa atingiu o limite de 1.000 registos; refine os filtros. A cobertura não
está completa.
</p>
)}
{unlocated.length > 0 && (
<section className={card} aria-label="Investimentos a georreferenciar">
<h2 className="text-xl font-bold">
{unlocated.length} investimentos sem coordenadas de local confirmadas
</h2>
<p>
Continuam nos resultados. Seleccionar uma província não determina a posição
exacta do investimento.
</p>
<ul>
{unlocated.map((record) => (
<li key={record.id}>
<Link href={record.url} className="underline">
{record.title}
</Link>{" "}
— {record.location || "Localização por completar"}
</li>
))}
</ul>
</section>
)}
{(view !== "map" || error || points?.length === 0) && (
<div
className={
@@ -583,63 +665,3 @@ export default function Catalogue({
</Frame>
);
}
function Map({ points }: { points: Feature[] | null }) {
if (points === null) return <p role="status">A carregar localizações…</p>;
if (!points.length)
return (
<p className={card}>
Sem coordenadas públicas associadas aos resultados. Não são atribuídas localizações
aproximadas.
</p>
);
const xs = points.map((p) => p.geometry.coordinates[0]),
ys = points.map((p) => p.geometry.coordinates[1]);
const minX = Math.min(...xs) - 0.1,
maxX = Math.max(...xs) + 0.1,
minY = Math.min(...ys) - 0.1,
maxY = Math.max(...ys) + 0.1;
return (
<section className={card}>
<h2 className="text-xl font-bold">Localizações georreferenciadas</h2>
<p>
Coordenadas WGS84 publicadas, sem mapa base externo. Até 1.000 pontos; a lista
acessível apresenta os mesmos dados.
</p>
<svg
viewBox="0 0 900 400"
role="img"
aria-label="Distribuição das localizações por longitude e latitude"
className="my-4 w-full rounded bg-sky-50"
>
<path d="M30 10 V370 H880" fill="none" stroke="#475569" />
{points.map((p, i) => (
<a
key={`${p.properties.id}-${i}`}
href={p.properties.url}
aria-label={`${p.properties.title}, ${p.properties.location}`}
>
<circle
cx={45 + ((p.geometry.coordinates[0] - minX) / (maxX - minX)) * 810}
cy={350 - ((p.geometry.coordinates[1] - minY) / (maxY - minY)) * 310}
r="8"
fill="#065f46"
>
<title>{p.properties.title}</title>
</circle>
</a>
))}
</svg>
<ul className="space-y-2">
{points.map((p, i) => (
<li key={i}>
<Link className="underline" href={p.properties.url}>
{p.properties.title}
</Link>{" "}
— {p.properties.location}; longitude {p.geometry.coordinates[0]}, latitude{" "}
{p.geometry.coordinates[1]}
</li>
))}
</ul>
</section>
);
}
+5
View File
@@ -1,5 +1,6 @@
import { Link, router, usePage } from "@inertiajs/react";
import { useState } from "react";
import InvestmentMapPanel from "@/components/investment-map-panel";
import { Frame, card, button, money, groupLabels } from "./shared";
import type { Opportunity, Context } from "./shared";
export default function Detail({
@@ -19,6 +20,10 @@ export default function Detail({
{r.reference} · {r.sector?.name} · {r.province} {r.district}
</p>
<p className="text-xl">{r.summary}</p>
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
<p>Localização: {c.primary_territory_path.map((node) => node.name).join(" → ")}</p>
)}
<div className="flex flex-wrap gap-4">
{auth.user ? (
<button
+1
View File
@@ -40,6 +40,7 @@ export type Opportunity = {
status: string;
};
export type Context = {
primary_territory_path?: { id: string; name: string; location_type: string }[];
zones?: {
id: string;
name: string;
+14 -4
View File
@@ -1,4 +1,6 @@
import { Link, router, useForm } from "@inertiajs/react";
import InvestmentTerritory from "@/components/investment-territory";
import InvestmentMapPanel from "@/components/investment-map-panel";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
import ZoneRelations from "./zone-relations";
@@ -91,8 +93,6 @@ function Editor({
name_en: z.name_en ?? "",
description: z.description ?? "",
description_en: z.description_en ?? "",
province: z.province ?? "",
district: z.district ?? "",
operator_id: z.operator_id ?? "",
legal_source_id: z.legal_source_id ?? "",
});
@@ -153,8 +153,6 @@ function Editor({
["code", "Código"],
["name", "Nome PT"],
["name_en", "Nome EN"],
["province", "Província"],
["district", "Distrito"],
] as const
).map(([key, label]) => (
<Field key={key} label={label}>
@@ -484,6 +482,18 @@ function Editor({
</section>
</>
)}
{management && <InvestmentTerritory kind="zones" id={z.id} />}
{!management && ["zee", "zfi", "industrial_park"].includes(z.category) && (
<InvestmentMapPanel
filters={{
[z.category === "zee"
? "zee_id"
: z.category === "zfi"
? "zfi_id"
: "park_id"]: z.id,
}}
/>
)}
</Frame>
);
}
+5
View File
@@ -1,5 +1,6 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
import { Frame, Field, input, button, card, api } from "./shared";
type Zone = {
@@ -17,6 +18,7 @@ export default function Zones({
records,
filters,
management,
territorySelection = [],
}: {
records: {
data: Zone[];
@@ -26,6 +28,7 @@ export default function Zones({
};
filters: { q?: string; category?: string };
management: boolean;
territorySelection?: TerritoryOption[];
}) {
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
@@ -56,6 +59,7 @@ export default function Zones({
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
<TerritoryFields initial={territorySelection} />
<button className={button}>Pesquisar</button>
</form>
<p role="status">{records.total} registos disponíveis</p>
@@ -115,6 +119,7 @@ export default function Zones({
}}
>
<h2 className="text-xl font-bold">Criar rascunho</h2>
<TerritoryFields />
<Field label="Código">
<input name="code" className={input} required maxLength={80} />
</Field>
+41 -2
View File
@@ -1,4 +1,8 @@
import { Link, useForm } from "@inertiajs/react";
import InvestmentTerritory from "@/components/investment-territory";
import InvestmentCoordinates from "@/components/investment-coordinates";
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
import { useState } from "react";
import { Management, Field, button, control, states } from "./shared";
type Values = Record<string, string | boolean>;
@@ -9,8 +13,6 @@ const opportunityFields = {
slug: "Slug (endereço)",
summary: "Resumo",
description: "Descrição",
province: "Província",
district: "Distrito",
promoter_name: "Promotor",
promoter_type: "Tipo de promotor",
estimated_investment_amount: "Investimento estimado",
@@ -66,6 +68,7 @@ export default function Editor({
initial.is_featured = Boolean(record?.is_featured ?? false);
}
const form = useForm<Values>(initial);
const [creationPath, setCreationPath] = useState<TerritoryOption[]>([]);
return (
<Management
title={`${record ? "Editar" : "Criar"} ${isSector ? "sector" : "oportunidade"}`}
@@ -84,6 +87,40 @@ export default function Editor({
}}
>
<fieldset disabled={form.processing} className="space-y-5">
{!isSector && !record && (
<div className="grid gap-4 md:grid-cols-2">
{(
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${creationPath[index - 1]?.id ?? ""}`}
index={index}
parent={creationPath[index - 1]?.id ?? ""}
selected={creationPath[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) => {
const path = [
...creationPath.slice(0, index),
...(value ? [value] : []),
];
setCreationPath(path);
form.setData((data) => ({
...data,
province_id: path[0]?.id ?? "",
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
}));
}}
/>
))}
</div>
)}
{Object.entries(fields).map(([key, label]) => (
<Field key={key} label={label} error={form.errors[key]}>
{[
@@ -177,6 +214,8 @@ export default function Editor({
</div>
</fieldset>
</form>
{!isSector && record && <InvestmentTerritory kind="opportunities" id={record.id} />}
{!isSector && record && <InvestmentCoordinates id={record.id} />}
</Management>
);
}
+3
View File
@@ -41,6 +41,9 @@ export function Management({ title, children }: { title: string; children: React
<Link href="/management/crm/investors">Investidores</Link>
<Link href="/management/projects">Projectos</Link>
<Link href="/management/clusters">Clusters</Link>
<Link href="/management/territory-associations">
Localizações dos investimentos
</Link>
<Link href="/management/investment/zones">ZEE, ZFI e parques</Link>
{educationEnabled && (
<Link href="/management/education">Competências e formação</Link>
@@ -0,0 +1,108 @@
import { useEffect, useState } from "react";
import InvestmentTerritory from "@/components/investment-territory";
import { Management, Field, control } from "./shared";
export default function TerritoryAssociations() {
const [kind, setKind] = useState("projects");
const [id, setId] = useState("");
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
const [rows, setRows] = useState<{ id: string; name: string }[]>([]);
const [more, setMore] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
const timer = setTimeout(async () => {
try {
const params = new URLSearchParams({ kind, q, page: String(page) });
const response = await fetch(`/management/territory-subjects?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!response.ok) throw new Error("Não foi possível carregar os investimentos.");
const data = await response.json();
setRows(data.data);
setMore(Boolean(data.next_page_url));
setError("");
} catch (e) {
if (!controller.signal.aborted)
setError(e instanceof Error ? e.message : "Erro de ligação.");
}
}, 250);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [kind, q, page]);
return (
<Management title="Localizações dos investimentos">
<Field label="Tipo de investimento">
<select
className={control}
value={kind}
onChange={(e) => {
setKind(e.target.value);
setId("");
setRows([]);
setQ("");
setPage(1);
}}
>
<option value="projects">Projectos / projectos âncora</option>
<option value="clusters">Clusters</option>
<option value="corridors">Corredores</option>
<option value="zones">ZEE / ZFI / parques industriais</option>
<option value="opportunities">Oportunidades</option>
</select>
</Field>
<Field label="Pesquisar investimento">
<input
className={control}
value={q}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
setId("");
}}
/>
</Field>
<Field label="Investimento">
<select className={control} value={id} onChange={(e) => setId(e.target.value)}>
<option value="">Seleccione</option>
{rows.map((row) => (
<option value={row.id} key={row.id}>
{row.name}
</option>
))}
</select>
</Field>
{error && <p role="alert">{error}</p>}
{!error && rows.length === 0 && <p>Sem registos para esta pesquisa.</p>}
<div className="flex gap-4">
{page > 1 && (
<button
type="button"
onClick={() => {
setId("");
setPage(page - 1);
}}
>
Anterior
</button>
)}
{more && (
<button
type="button"
onClick={() => {
setId("");
setPage(page + 1);
}}
>
Mais investimentos
</button>
)}
</div>
{id && <InvestmentTerritory key={`${kind}-${id}`} kind={kind} id={id} />}
</Management>
);
}
+12
View File
@@ -1,4 +1,5 @@
import { Link, useForm, router } from "@inertiajs/react";
import InvestmentMapPanel from "@/components/investment-map-panel";
import { Management } from "../management/shared";
import { Layout, Field, control, button, labels, kind } from "./shared";
import type { Dossier } from "./shared";
@@ -47,6 +48,17 @@ function Editor({
{kind(record)} · {record.content.code}
</p>
<p className="text-sm">Fonte: {record.source}</p>
{!management && (record.cluster_id || record.corridor_id || record.project_id) && (
<InvestmentMapPanel
filters={
record.cluster_id
? { cluster_id: record.cluster_id }
: record.corridor_id
? { corridor_id: record.corridor_id }
: { project_id: record.project_id! }
}
/>
)}
{zones.length > 0 && (
<section>
<h2 className="text-xl font-bold">ZEE, ZFI e parques relacionados</h2>
+84 -135
View File
@@ -1,15 +1,16 @@
import { Link, useForm } from '@inertiajs/react';
import { Management, Field, button, control } from '../management/shared';
import { titles, statuses, stages, roles } from './types';
import type { Structure, StructureRecord, Chain } from './types';
import ValueNetwork from './value-network';
import type { ChainLink, Gap } from './value-network';
import { Link, useForm } from "@inertiajs/react";
import InvestmentTerritory, { TerritoryFields } from "@/components/investment-territory";
import { Management, Field, button, control } from "../management/shared";
import { titles, statuses, stages, roles } from "./types";
import type { Structure, StructureRecord, Chain } from "./types";
import ValueNetwork from "./value-network";
import type { ChainLink, Gap } from "./value-network";
function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
const form = useForm({
code: chain?.code ?? '',
name: chain?.name ?? '',
stage: chain?.stage ?? 'input',
code: chain?.code ?? "",
name: chain?.name ?? "",
stage: chain?.stage ?? "input",
});
return (
<form
@@ -17,8 +18,7 @@ function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
onSubmit={(e) => {
e.preventDefault();
const url = `/management/clusters/${clusterId}/chains`;
if (chain)
form.put(`${url}/${chain.id}`, { preserveScroll: true });
if (chain) form.put(`${url}/${chain.id}`, { preserveScroll: true });
else
form.post(url, {
preserveScroll: true,
@@ -26,28 +26,26 @@ function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
});
}}
>
<h3 className="font-semibold">
{chain ? chain.name : 'Nova etapa'}
</h3>
<h3 className="font-semibold">{chain ? chain.name : "Nova etapa"}</h3>
<Field label="Código da etapa" error={form.errors.code}>
<input
className={control}
value={form.data.code}
onChange={(e) => form.setData('code', e.target.value)}
onChange={(e) => form.setData("code", e.target.value)}
/>
</Field>
<Field label="Nome da etapa" error={form.errors.name}>
<input
className={control}
value={form.data.name}
onChange={(e) => form.setData('name', e.target.value)}
onChange={(e) => form.setData("name", e.target.value)}
/>
</Field>
<Field label="Fase da cadeia" error={form.errors.stage}>
<select
className={control}
value={form.data.stage}
onChange={(e) => form.setData('stage', e.target.value)}
onChange={(e) => form.setData("stage", e.target.value)}
>
{Object.entries(stages).map(([value, label]) => (
<option key={value} value={value}>
@@ -85,36 +83,47 @@ export default function Editor({
role: string;
}[];
}) {
const isProject = structure === 'projects';
const isProject = structure === "projects";
const form = useForm({
code: record?.code ?? '',
name: record?.name ?? '',
status: record?.status ?? (isProject ? 'draft' : 'planned'),
sector: record?.sector ?? '',
description: record?.description ?? '',
budget_amount: record?.budget_amount ?? '',
budget_currency: record?.budget_currency ?? '',
start_date: record?.start_date?.slice(0, 10) ?? '',
end_date: record?.end_date?.slice(0, 10) ?? '',
code: record?.code ?? "",
name: record?.name ?? "",
status: record?.status ?? (isProject ? "draft" : "planned"),
sector: record?.sector ?? "",
description: record?.description ?? "",
budget_amount: record?.budget_amount ?? "",
budget_currency: record?.budget_currency ?? "",
start_date: record?.start_date?.slice(0, 10) ?? "",
end_date: record?.end_date?.slice(0, 10) ?? "",
province_id: "",
district_id: "",
admin_post_id: "",
locality_id: "",
});
const association = useForm({ project_id: '', role: 'complementary' });
const association = useForm({ project_id: "", role: "complementary" });
return (
<Management
title={`${record ? 'Editar' : 'Criar'} ${isProject ? 'projecto' : 'cluster'}`}
>
<Management title={`${record ? "Editar" : "Criar"} ${isProject ? "projecto" : "cluster"}`}>
<Link className="underline" href={`/management/${structure}`}>
Voltar a {titles[structure].toLowerCase()}
</Link>
<p>
Registo interno de gestão. O estado activo não publica este
conteúdo no portal.
</p>
<p>Registo interno de gestão. O estado activo não publica este conteúdo no portal.</p>
{!record && (
<TerritoryFields
onChange={(path) =>
form.setData((data) => ({
...data,
province_id: path[0]?.id ?? "",
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
}))
}
/>
)}
<form
className="max-w-3xl space-y-4"
onSubmit={(e) => {
e.preventDefault();
if (record)
form.put(`/management/${structure}/${record.id}`);
if (record) form.put(`/management/${structure}/${record.id}`);
else form.post(`/management/${structure}`);
}}
>
@@ -122,29 +131,27 @@ export default function Editor({
<input
className={control}
value={form.data.code}
onChange={(e) => form.setData('code', e.target.value)}
onChange={(e) => form.setData("code", e.target.value)}
/>
</Field>
<Field label="Nome" error={form.errors.name}>
<input
className={control}
value={form.data.name}
onChange={(e) => form.setData('name', e.target.value)}
onChange={(e) => form.setData("name", e.target.value)}
/>
</Field>
<Field label="Estado" error={form.errors.status}>
<select
className={control}
value={form.data.status}
onChange={(e) => form.setData('status', e.target.value)}
onChange={(e) => form.setData("status", e.target.value)}
>
{Object.entries(statuses[structure]).map(
([value, label]) => (
<option key={value} value={value}>
{label}
</option>
),
)}
{Object.entries(statuses[structure]).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</Field>
{!isProject && (
@@ -152,25 +159,18 @@ export default function Editor({
<input
className={control}
value={form.data.sector}
onChange={(e) =>
form.setData('sector', e.target.value)
}
onChange={(e) => form.setData("sector", e.target.value)}
/>
</Field>
)}
{isProject && (
<>
<Field
label="Descrição"
error={form.errors.description}
>
<Field label="Descrição" error={form.errors.description}>
<textarea
className={control}
rows={5}
value={form.data.description}
onChange={(e) =>
form.setData('description', e.target.value)
}
onChange={(e) => form.setData("description", e.target.value)}
/>
</Field>
<Field
@@ -181,12 +181,7 @@ export default function Editor({
inputMode="decimal"
className={control}
value={form.data.budget_amount}
onChange={(e) =>
form.setData(
'budget_amount',
e.target.value,
)
}
onChange={(e) => form.setData("budget_amount", e.target.value)}
/>
</Field>
<Field
@@ -198,37 +193,24 @@ export default function Editor({
className={control}
value={form.data.budget_currency}
onChange={(e) =>
form.setData(
'budget_currency',
e.target.value.toUpperCase(),
)
form.setData("budget_currency", e.target.value.toUpperCase())
}
/>
</Field>
<Field
label="Data de início"
error={form.errors.start_date}
>
<Field label="Data de início" error={form.errors.start_date}>
<input
type="date"
className={control}
value={form.data.start_date}
onChange={(e) =>
form.setData('start_date', e.target.value)
}
onChange={(e) => form.setData("start_date", e.target.value)}
/>
</Field>
<Field
label="Data de conclusão"
error={form.errors.end_date}
>
<Field label="Data de conclusão" error={form.errors.end_date}>
<input
type="date"
className={control}
value={form.data.end_date}
onChange={(e) =>
form.setData('end_date', e.target.value)
}
onChange={(e) => form.setData("end_date", e.target.value)}
/>
</Field>
</>
@@ -240,9 +222,7 @@ export default function Editor({
{!isProject && record && (
<>
<section className="max-w-3xl space-y-4">
<h2 className="text-xl font-semibold">
Projectos associados
</h2>
<h2 className="text-xl font-semibold">Projectos associados</h2>
{memberships.map((member) => (
<p key={member.id}>
<Link
@@ -250,93 +230,61 @@ export default function Editor({
href={`/management/projects/${member.project_id}/edit`}
>
{member.name}
</Link>{' '}
</Link>{" "}
· {roles[member.role]}
</p>
))}
{!memberships.length && (
<p>Ainda não existem projectos associados.</p>
)}
{!memberships.length && <p>Ainda não existem projectos associados.</p>}
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
association.post(
`/management/clusters/${record.id}/projects`,
{ preserveScroll: true },
);
association.post(`/management/clusters/${record.id}/projects`, {
preserveScroll: true,
});
}}
>
<Field
label="Projecto"
error={association.errors.project_id}
>
<Field label="Projecto" error={association.errors.project_id}>
<select
className={control}
value={association.data.project_id}
onChange={(e) =>
association.setData(
'project_id',
e.target.value,
)
association.setData("project_id", e.target.value)
}
>
<option value="">Seleccione</option>
{projects.map((project) => (
<option
key={project.id}
value={project.id}
>
<option key={project.id} value={project.id}>
{project.code} — {project.name}
</option>
))}
</select>
</Field>
<Field
label="Papel no cluster"
error={association.errors.role}
>
<Field label="Papel no cluster" error={association.errors.role}>
<select
className={control}
value={association.data.role}
onChange={(e) =>
association.setData(
'role',
e.target.value,
)
}
onChange={(e) => association.setData("role", e.target.value)}
>
{Object.entries(roles).map(
([value, label]) => (
<option key={value} value={value}>
{label}
</option>
),
)}
{Object.entries(roles).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</Field>
<button
className={button}
disabled={association.processing}
>
<button className={button} disabled={association.processing}>
Guardar associação
</button>
<p className="text-sm">
Seleccionar um projecto já associado permite
actualizar o seu papel.
Seleccionar um projecto já associado permite actualizar o seu papel.
</p>
</form>
</section>
<section className="max-w-3xl space-y-4">
<h2 className="text-xl font-semibold">
Etapas da cadeia de valor
</h2>
<h2 className="text-xl font-semibold">Etapas da cadeia de valor</h2>
{chains.map((chain) => (
<ChainForm
key={chain.id}
clusterId={record.id}
chain={chain}
/>
<ChainForm key={chain.id} clusterId={record.id} chain={chain} />
))}
<ChainForm clusterId={record.id} />
</section>
@@ -348,6 +296,7 @@ export default function Editor({
/>
</>
)}
{record && <InvestmentTerritory kind={structure} id={record.id} />}
</Management>
);
}
+23
View File
@@ -0,0 +1,23 @@
<?php
use App\Http\Controllers\ExistingBusinessController;
use App\Http\Middleware\ExistingBusinessEnabled;
use App\Http\Middleware\PrivateInvestmentResponse;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth', 'verified', PrivateInvestmentResponse::class, 'throttle:30,1', ExistingBusinessEnabled::class])->group(function () {
Route::get('/investidor/negocios', [ExistingBusinessController::class, 'index']);
Route::get('/management/negocios', [ExistingBusinessController::class, 'index']);
Route::get('/investidor/negocios/{id}', [ExistingBusinessController::class, 'show'])->whereUuid('id');
Route::prefix('api/v1/existing-business')->group(function () {
Route::get('/reviews', [ExistingBusinessController::class, 'index']);
Route::get('/listings', [ExistingBusinessController::class, 'index']);
Route::post('/listings', [ExistingBusinessController::class, 'save']);
Route::get('/listings/{id}', [ExistingBusinessController::class, 'show'])->whereUuid('id');
Route::put('/listings/{id}', [ExistingBusinessController::class, 'save'])->whereUuid('id');
Route::post('/listings/{id}/transitions', [ExistingBusinessController::class, 'transition'])->whereUuid('id');
Route::post('/listings/{id}/verifications', [ExistingBusinessController::class, 'verify'])->whereUuid('id');
Route::post('/listings/{id}/objects', [ExistingBusinessController::class, 'saveObject'])->whereUuid('id');
Route::put('/listings/{id}/objects/{object}', [ExistingBusinessController::class, 'saveObject'])->whereUuid(['id', 'object']);
});
});
+22
View File
@@ -0,0 +1,22 @@
<?php
use App\Http\Controllers\TerritorialRegistryController;
use App\Http\Middleware\PrivateInvestmentResponse;
use App\Http\Middleware\RequireZoneMfa;
use App\Http\Middleware\TerritorialRequest;
use Illuminate\Support\Facades\Route;
Route::prefix('api/v1/geo')->middleware(['auth', 'verified', PrivateInvestmentResponse::class, 'throttle:api', TerritorialRequest::class])->group(function () {
Route::get('/search', [TerritorialRegistryController::class, 'index']);
Route::get('/{collection}', [TerritorialRegistryController::class, 'index'])->whereIn('collection', ['countries', 'provinces', 'districts', 'admin-posts', 'localities']);
Route::get('/territories/{type}/{id}', [TerritorialRegistryController::class, 'show'])->whereUuid('id');
Route::middleware(['can:manage-portal', RequireZoneMfa::class])->group(function () {
Route::get('/sources', [TerritorialRegistryController::class, 'sources']);
Route::get('/drafts', [TerritorialRegistryController::class, 'drafts']);
Route::post('/sources', [TerritorialRegistryController::class, 'source']);
Route::post('/territories', [TerritorialRegistryController::class, 'save']);
Route::patch('/territories/{id}', [TerritorialRegistryController::class, 'save'])->whereUuid('id');
Route::post('/territories/{id}/transitions', [TerritorialRegistryController::class, 'transition'])->whereUuid('id');
Route::post('/sources/{id}/transitions', [TerritorialRegistryController::class, 'sourceTransition'])->whereUuid('id');
});
});
+15
View File
@@ -1,5 +1,8 @@
<?php
require __DIR__.'/existing-business.php';
require __DIR__.'/territorial-registry.php';
require __DIR__.'/investment-zones.php';
use App\Http\Controllers\AiController;
@@ -8,12 +11,15 @@ use App\Http\Controllers\CrmController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\EducationController;
use App\Http\Controllers\EducationInvestmentController;
use App\Http\Controllers\InvestmentCoordinatesController;
use App\Http\Controllers\InvestmentDiscoveryController;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Http\Controllers\InvestmentStructureController;
use App\Http\Controllers\InvestmentTerritoryController;
use App\Http\Controllers\InvestorWorkspaceController;
use App\Http\Controllers\PortalManagementController;
use App\Http\Controllers\PortalServicesController;
use App\Http\Controllers\PublicGeographyController;
use App\Http\Controllers\PublicPortalController;
use App\Http\Middleware\AiEnabled;
use App\Http\Middleware\EducationEnabled;
@@ -77,7 +83,16 @@ Route::middleware(['auth', 'verified', 'can:manage-portal', AiEnabled::class])->
}
});
Route::get('/api/v1/investment/territory-options', [PublicGeographyController::class, 'options'])->middleware('throttle:api');
Route::middleware(['auth', 'verified', 'can:manage-portal'])->prefix('management')->name('management.')->group(function () {
Route::get('opportunities/{id}/coordinates', [InvestmentCoordinatesController::class, 'show'])->whereNumber('id');
Route::post('opportunities/{id}/coordinates', [InvestmentCoordinatesController::class, 'save'])->whereNumber('id');
Route::get('territory-options', [InvestmentTerritoryController::class, 'options'])->middleware('throttle:api');
Route::get('territory-subjects', [InvestmentTerritoryController::class, 'subjects'])->middleware('throttle:api');
Route::get('territory-associations', fn () => Inertia::render('management/territory-associations'));
Route::get('territories/{kind}/{id}', [InvestmentTerritoryController::class, 'show']);
Route::post('territories/{kind}/{id}', [InvestmentTerritoryController::class, 'save']);
$controller = PortalManagementController::class;
Route::prefix('education')->name('education.')->middleware(EducationEnabled::class)->group(function () {
Route::get('/', [EducationController::class, 'index'])->name('index');
@@ -0,0 +1,100 @@
<?php
namespace Tests\Feature;
use App\Models\ExistingBusiness;
use App\Models\User;
use App\Services\ExistingBusinessDrafts;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
class ExistingBusinessFoundationTest extends TestCase
{
use RefreshDatabase;
/** @return array<string,mixed> */
private function draft(): array
{
return ['modality' => 'company_sale', 'classification' => 'confidential', 'reason' => 'Synthetic draft created', 'payload' => ['title' => 'Private synthetic business']];
}
public function test_draft_is_encrypted_and_history_is_versioned_with_stale_writes_rejected(): void
{
$owner = User::factory()->create();
$service = app(ExistingBusinessDrafts::class);
$business = $service->save($owner, $this->draft());
$this->assertSame('draft', $business->status);
$this->assertArrayNotHasKey('payload', $business->toArray());
$raw = DB::table('existing_businesses')->where('id', $business->id)->value('payload');
$this->assertStringNotContainsString('Private synthetic', $raw);
$this->assertStringContainsString('Private synthetic', Crypt::decryptString($raw));
$service->save($owner, [...$this->draft(), 'version_no' => 1], $business->id);
$this->assertDatabaseCount('existing_business_revisions', 2);
try {
$service->save($owner, [...$this->draft(), 'version_no' => 1], $business->id);
$this->fail('Stale update accepted');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertDatabaseCount('existing_business_revisions', 2);
$service->archive($owner, $business->id, 2, 'Synthetic archive reason');
$this->assertNull(ExistingBusiness::find($business->id));
$this->assertSame(3, ExistingBusiness::withTrashed()->findOrFail($business->id)->version_no);
$this->assertDatabaseCount('existing_business_revisions', 3);
}
public function test_other_user_including_manager_cannot_edit_reserved_business(): void
{
$service = app(ExistingBusinessDrafts::class);
$business = $service->save(User::factory()->create(), $this->draft());
$other = User::factory()->create();
config(['portal.managers' => [$other->email]]);
$this->expectException(AuthorizationException::class);
$service->save($other, [...$this->draft(), 'version_no' => 1], $business->id);
}
public function test_unverified_account_cannot_create_business(): void
{
$this->expectException(AuthorizationException::class);
app(ExistingBusinessDrafts::class)->save(User::factory()->unverified()->create(), $this->draft());
}
public function test_database_prevents_publication_and_history_changes(): void
{
$business = app(ExistingBusinessDrafts::class)->save(User::factory()->create(), $this->draft());
foreach (['publish', 'history'] as $operation) {
DB::statement('SAVEPOINT business_constraint');
try {
if ($operation === 'publish') {
DB::table('existing_businesses')->where('id', $business->id)->update(['status' => 'published']);
} else {
DB::table('existing_business_revisions')->where('business_id', $business->id)->delete();
}
$this->fail('Database invariant was not enforced');
} catch (QueryException) {
DB::statement('ROLLBACK TO SAVEPOINT business_constraint');
$this->assertTrue(true);
}
}
$this->assertDatabaseCount('existing_business_revisions', 1);
}
public function test_empty_rollback_is_reversible_and_populated_rollback_is_refused(): void
{
$migration = require database_path('migrations/2026_09_28_130000_existing_business_foundation.php');
$intake = require database_path('migrations/2026_09_28_140000_existing_business_intake.php');
$intake->down();
$migration->down();
$migration->up();
$intake->up();
app(ExistingBusinessDrafts::class)->save(User::factory()->create(), $this->draft());
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('destructive rollback refused');
$migration->down();
}
}
@@ -0,0 +1,144 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class ExistingBusinessIntakeTest extends TestCase
{
use RefreshDatabase;
private string $base = '/api/v1/existing-business/listings';
protected function setUp(): void
{
parent::setUp();
config(['existing-business.enabled' => true]);
}
private function reviewer(): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
config(['portal.managers' => [$user->email], 'existing-business.reviewers' => [$user->email]]);
return $user;
}
/** @return array<string,mixed> */
private function draft(): array
{
return ['modality' => 'participation_sale', 'classification' => 'restricted', 'reason' => 'Synthetic initial draft',
'payload' => ['title' => 'Private synthetic business', 'description' => 'Synthetic reserved description for the internal review only.',
'source_reference' => 'Synthetic source reference', 'valid_until' => today()->addMonth()->toDateString()]];
}
public function test_private_intake_review_information_and_withdrawal_preserve_isolation(): void
{
$owner = User::factory()->create();
$reviewer = $this->reviewer();
$this->actingAs($owner);
$id = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$url = $this->base.'/'.$id;
$this->getJson($url)->assertOk()->assertHeader('Cache-Control', 'no-store, private');
$this->actingAs($reviewer)->getJson($url)->assertForbidden();
$this->actingAs($owner)->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested'])->assertUnprocessable();
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested', 'review_consent' => true])->assertOk()->assertJsonPath('version_no', 2);
$this->putJson($url, [...$this->draft(), 'version_no' => 2])->assertForbidden();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Attempted self review'])->assertForbidden();
$this->actingAs($reviewer)->getJson('/api/v1/existing-business/reviews')->assertOk()->assertJsonPath('records.total', 1);
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertConflict();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk()->assertJsonPath('version_no', 3);
$this->postJson($url.'/transitions', ['version_no' => 3, 'action' => 'needs_information', 'note' => 'Please clarify synthetic source'])->assertOk();
$this->actingAs($owner)->getJson($url)->assertOk()->assertJsonPath('history.0.note', 'Please clarify synthetic source');
$this->postJson($url, [...$this->draft(), '_method' => 'PUT', 'version_no' => 4])->assertOk()->assertJsonPath('version_no', 5);
$this->postJson($url.'/transitions', ['version_no' => 5, 'action' => 'withdrawn', 'note' => 'Synthetic withdrawal requested'])->assertOk();
$this->actingAs($reviewer)->getJson($url)->assertForbidden();
$this->getJson('/api/v1/existing-business/reviews')->assertJsonPath('records.total', 0);
$this->assertDatabaseCount('existing_business_reviews', 4);
$this->assertDatabaseCount('existing_business_revisions', 6);
$this->assertStringNotContainsString('Please clarify', DB::table('existing_business_reviews')->where('action', 'needs_information')->value('note'));
}
public function test_granular_verification_requires_independent_review_and_invalidates_after_changes(): void
{
$owner = User::factory()->create();
$reviewer = $this->reviewer();
$this->actingAs($owner);
$id = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$url = $this->base.'/'.$id;
$finding = ['version_no' => 3, 'check' => 'identity', 'outcome' => 'confirmed',
'evidence_reference' => 'Synthetic identity evidence', 'note' => 'Synthetic independent review',
'valid_until' => today()->addDay()->toDateString()];
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested', 'review_consent' => true])->assertOk();
$this->postJson($url.'/verifications', $finding)->assertForbidden();
$this->actingAs($reviewer)->postJson($url.'/verifications', [...$finding, 'version_no' => 2])->assertConflict();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk();
$this->postJson($url.'/verifications', [...$finding, 'valid_until' => null])->assertUnprocessable();
$this->postJson($url.'/verifications', [...$finding, 'object_id' => '00000000-0000-4000-8000-000000000001'])->assertNotFound();
$this->postJson($url.'/verifications', $finding)->assertOk()->assertJsonPath('version_no', 4);
$this->postJson($url.'/verifications', $finding)->assertConflict();
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'confirmed');
$raw = DB::table('existing_business_revisions')->where('business_id', $id)->where('action', 'verification')->value('snapshot');
$this->assertStringNotContainsString('Synthetic identity evidence', $raw);
$this->travel(2)->days();
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'expired');
$this->travelBack();
$this->postJson($url.'/transitions', ['version_no' => 4, 'action' => 'needs_information', 'note' => 'Synthetic clarification requested'])->assertOk();
$this->actingAs($owner)->putJson($url, [...$this->draft(), 'version_no' => 5])->assertOk();
$this->getJson($url)->assertJsonPath('verifications.0.effective_outcome', 'stale');
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
}
public function test_flag_mfa_and_current_designation_are_required(): void
{
$this->getJson($this->base)->assertUnauthorized();
$reviewer = $this->reviewer();
$this->actingAs($reviewer)->getJson('/api/v1/existing-business/reviews')->assertOk();
config(['existing-business.reviewers' => []]);
$this->getJson('/api/v1/existing-business/reviews')->assertForbidden();
config(['existing-business.reviewers' => [$reviewer->email]]);
$reviewer->forceFill(['two_factor_confirmed_at' => null])->save();
$this->getJson('/api/v1/existing-business/reviews')->assertForbidden();
config(['existing-business.enabled' => false]);
$this->getJson($this->base)->assertNotFound();
}
public function test_arbitrary_states_and_incomplete_or_expired_submission_are_rejected(): void
{
$this->actingAs(User::factory()->create());
$draft = $this->draft();
$draft['payload']['valid_until'] = today()->subDay()->toDateString();
$id = $this->postJson($this->base, $draft)->assertCreated()->json('id');
foreach (['published', 'approved', 'submitted'] as $action) {
$this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 1, 'action' => $action, 'note' => 'Synthetic invalid transition', 'review_consent' => true])->assertUnprocessable();
}
$this->assertDatabaseCount('existing_business_reviews', 0);
}
public function test_reserved_objects_are_scoped_versioned_and_never_verified_by_declaration(): void
{
$this->actingAs(User::factory()->create());
$first = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$second = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$object = ['kind' => 'license', 'version_no' => 1, 'reason' => 'Synthetic license declaration',
'payload' => ['label' => 'Private synthetic license', 'source_reference' => 'Synthetic source only',
'declared_holder' => 'Synthetic holder', 'valid_from' => '2026-01-01', 'valid_until' => '2027-01-01',
'amount' => '1200.25', 'currency' => 'MZN', 'value_kind' => 'asking']];
$id = $this->postJson($this->base.'/'.$first.'/objects', $object)->assertCreated()->assertJsonPath('verification_status', 'pending')->assertJsonPath('version_no', 2)->json('id');
$this->postJson($this->base.'/'.$first.'/objects', $object)->assertConflict();
$this->putJson($this->base.'/'.$second.'/objects/'.$id, $object)->assertNotFound();
$this->putJson($this->base.'/'.$first.'/objects/'.$id, [...$object, 'version_no' => 2, 'kind' => 'asset'])->assertUnprocessable();
$object['payload']['currency'] = null;
$this->putJson($this->base.'/'.$first.'/objects/'.$id, [...$object, 'version_no' => 2])->assertUnprocessable();
$this->getJson($this->base.'/'.$first)->assertOk()->assertJsonPath('objects.0.payload.amount', '1200.25');
$this->assertStringNotContainsString('Synthetic holder', DB::table('existing_business_objects')->where('id', $id)->value('payload'));
$snapshot = Crypt::decryptString(DB::table('existing_business_revisions')->where('business_id', $first)->where('version_no', 2)->value('snapshot'));
$this->assertStringContainsString('Synthetic holder', $snapshot);
$this->actingAs(User::factory()->create())->getJson($this->base.'/'.$first)->assertForbidden();
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\InvestmentCatalogue;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class InvestmentTerritoryTest extends TestCase
{
use RefreshDatabase;
public function test_confirmed_coordinates_create_a_marker_without_hiding_missing_records(): void
{
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$sector = Sector::create(['name' => 'Synthetic map', 'slug' => 'synthetic-map', 'is_active' => true]);
$record = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'MAP-COORD', 'slug' => 'map-coord', 'title' => 'Synthetic marker', 'status' => 'published', 'published_at' => now()->subMinute()]);
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('matched_count', 1)->assertJsonPath('complete', false)->assertJsonCount(1, 'unlocated');
$this->actingAs($manager);
$url = '/management/opportunities/'.$record->id.'/coordinates';
$payload = ['version' => 0, 'latitude' => -25.9, 'longitude' => 32.5, 'source_reference' => 'Synthetic coordinates for automated tests only', 'confirmed_site' => true];
$this->postJson($url, [...$payload, 'latitude' => 91])->assertUnprocessable();
$this->postJson($url, [...$payload, 'confirmed_site' => false])->assertUnprocessable();
$this->postJson($url, $payload)->assertOk()->assertJsonPath('version', 1);
$this->postJson($url, $payload)->assertConflict();
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('complete', true)->assertJsonPath('features.0.properties.id', $record->id)->assertJsonPath('features.0.geometry.coordinates.0', 32.5);
$record->update(['status' => 'draft']);
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonCount(0, 'features')->assertJsonCount(0, 'unlocated');
}
public function test_public_cascade_filters_saved_locations_and_hides_unapproved_references(): void
{
$country = $this->location('country');
$province = $this->location('province', $country);
$district = $this->location('district', $province);
$other = $this->location('province', $country);
$private = $this->location('province', $country);
foreach ([$country, $province, $district, $other] as $id) {
DB::table('geo_locations')->where('id', $id)->update(['source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id, 'data_classification' => 'public']);
}
$sector = Sector::create(['name' => 'Synthetic', 'slug' => 'synthetic', 'is_active' => true]);
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'SYNTHETIC-PUBLIC', 'slug' => 'synthetic-public', 'title' => 'Synthetic', 'status' => 'published', 'published_at' => now()->subMinute(), 'primary_territory_id' => $district]);
$this->getJson('/api/v1/investment/territory-options?type=province')->assertOk()->assertJsonCount(2, 'data');
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$province)->assertOk()->assertJsonPath('data.0.id', $district);
$service = app(InvestmentCatalogue::class);
$this->assertSame([$opportunity->id], $service->query(['province_id' => $province])->pluck('id')->all());
$this->assertSame([], $service->query(['province_id' => $other])->pluck('id')->all());
$this->getJson('/oportunidades?province_id='.$other.'&district_id='.$district)->assertUnprocessable();
$this->getJson('/oportunidades?province_id='.$private)->assertUnprocessable();
$this->get('/oportunidades?province_id='.$province)->assertOk();
$this->assertCount(2, $service->context($opportunity->id)['primary_territory_path']);
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAs($manager)->post('/management/opportunities', ['sector_id' => $sector->id, 'reference' => 'SYNTHETIC-CREATE', 'slug' => 'synthetic-create', 'title' => 'Synthetic create',
'status' => 'draft', 'is_featured' => false, 'estimated_investment_currency' => 'USD', 'province_id' => $province, 'district_id' => $district])->assertRedirect();
$this->assertDatabaseHas('opportunities', ['reference' => 'SYNTHETIC-CREATE', 'primary_territory_id' => $district, 'territory_version' => 1]);
$this->post('/management/clusters', ['code' => 'GEO-CREATE', 'name' => 'Synthetic cluster', 'sector' => 'Synthetic', 'status' => 'planned', 'province_id' => $province, 'district_id' => $district])->assertRedirect();
$this->assertDatabaseHas('economic_clusters', ['code' => 'GEO-CREATE', 'primary_territory_id' => $district]);
$manager->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
$zone = $this->postJson('/api/v2/investment/admin/zones', ['code' => 'GEO-ZEE', 'name' => 'Synthetic ZEE', 'category' => 'zee', 'province_id' => $province, 'district_id' => $district])->assertCreated()->json('id');
$this->assertDatabaseHas('investment_zones', ['id' => $zone, 'primary_territory_id' => $district]);
$this->getJson('/api/v2/investment/admin/zones?province_id='.$province)->assertOk()->assertJsonPath('records.total', 1);
$this->getJson('/api/v2/investment/admin/zones?province_id='.$other)->assertOk()->assertJsonPath('records.total', 0);
$this->postJson('/management/territories/zones/'.$zone, ['version' => 1, 'path' => [$province]])->assertOk();
$this->assertDatabaseHas('investment_zones', ['id' => $zone, 'primary_territory_id' => $province, 'version_no' => 2, 'publication_status' => 'draft']);
$this->assertSame(2, DB::table('investment_zone_revisions')->where('zone_id', $zone)->count());
DB::table('geo_locations')->where('id', $province)->update(['data_classification' => 'internal']);
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$province)->assertOk()->assertJsonCount(0, 'data');
}
public function test_cascade_assignment_persists_and_rejects_mismatched_parent_and_stale_write(): void
{
$user = User::factory()->create();
config(['portal.managers' => [$user->email]]);
$this->actingAs($user);
$province = $this->location('province');
$other = $this->location('province');
$district = $this->location('district', $province);
$cluster = (string) Str::uuid();
DB::table('economic_clusters')->insert(['id' => $cluster, 'code' => 'SYNTHETIC', 'name' => 'Synthetic cluster', 'sector' => 'Synthetic', 'status' => 'planned']);
$this->getJson('/management/territory-subjects?kind=clusters&q=Synthetic')->assertOk()->assertJsonPath('data.0.id', $cluster);
$this->get('/management/territory-associations')->assertOk();
$this->getJson('/management/territory-options?type=district&parent_id='.$province)->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $district);
$this->getJson('/management/territory-options?type=district&parent_id='.$other)->assertOk()->assertJsonCount(0, 'data');
$url = '/management/territories/clusters/'.$cluster;
$this->postJson($url, ['version' => 0, 'path' => [$other, $district]])->assertUnprocessable();
$this->postJson($url, ['version' => 0, 'path' => [$province, $district]])->assertOk()->assertJsonPath('version', 1);
$this->getJson($url)->assertOk()->assertJsonPath('path.0.id', $district);
$this->assertDatabaseHas('economic_clusters', ['id' => $cluster, 'primary_territory_id' => $district]);
$this->postJson($url, ['version' => 0, 'path' => []])->assertConflict();
$this->postJson($url, ['version' => 1, 'path' => []])->assertOk();
$this->assertDatabaseHas('economic_clusters', ['id' => $cluster, 'primary_territory_id' => null]);
}
public function test_non_managers_cannot_read_internal_options(): void
{
config(['portal.managers' => []]);
$this->actingAs(User::factory()->create())->getJson('/management/territory-options?type=province')->assertForbidden();
}
private function location(string $type, ?string $parent = null): string
{
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Synthetic '.$id, 'location_type' => $type, 'parent_id' => $parent]);
return $id;
}
}
+6
View File
@@ -66,12 +66,18 @@ class InvestmentZoneTest extends TestCase
$migration = require database_path('migrations/2026_09_28_100000_investment_zone_foundation.php');
$originMigration = require database_path('migrations/2026_09_28_120000_investment_submission_zones.php');
$geometryMigration = require database_path('migrations/2026_09_28_110000_zone_geometry_review.php');
$businessMigration = require database_path('migrations/2026_09_28_130000_existing_business_foundation.php');
$intakeMigration = require database_path('migrations/2026_09_28_140000_existing_business_intake.php');
$intakeMigration->down();
$businessMigration->down();
$originMigration->down();
$geometryMigration->down();
$migration->down();
$migration->up();
$geometryMigration->up();
$originMigration->up();
$businessMigration->up();
$intakeMigration->up();
$this->assertTrue(Schema::hasTable('investment_zone_links'));
$this->actingAs($this->manager())->postJson('/api/v2/investment/admin/zones', ['code' => 'QA', 'name' => 'Synthetic', 'category' => 'pending'])->assertCreated();
try {
+145
View File
@@ -0,0 +1,145 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class TerritorialRegistryTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
config(['territorial.enabled' => true]);
}
private function create(string $url, array $data)
{
return $this->postJson($url, $data, ['Idempotency-Key' => (string) Str::uuid()]);
}
private function patchTerritory(string $url, array $data)
{
return $this->patchJson($url, $data, ['Idempotency-Key' => (string) Str::uuid()]);
}
public function test_writes_require_idempotency_and_replays_recheck_current_permissions(): void
{
$user = $this->editor();
$this->actingAs($user);
$source = $this->source();
$this->postJson('/api/v1/geo/territories', $this->territory($source))->assertUnprocessable()->assertHeader('Content-Type', 'application/problem+json');
$key = ['Idempotency-Key' => (string) Str::uuid()];
$first = $this->postJson('/api/v1/geo/territories', $this->territory($source), $key)->assertOk()->json('id');
$this->postJson('/api/v1/geo/territories', $this->territory($source), $key)->assertOk()->assertJsonPath('id', $first);
$this->postJson('/api/v1/geo/territories', [...$this->territory($source), 'name' => 'Changed'], $key)->assertConflict();
config(['portal.managers' => []]);
$this->postJson('/api/v1/geo/territories', $this->territory($source), $key)->assertForbidden();
$this->assertDatabaseCount('geo_locations', 1);
}
private function editor(): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
config(['portal.managers' => [$user->email]]);
config(['territorial.editors' => [$user->email]]);
return $user;
}
private function source(): string
{
return $this->create('/api/v1/geo/sources', ['name' => 'Synthetic source', 'reference' => 'Synthetic reference only',
'checksum' => str_repeat('a', 64), 'source_version' => 'test', 'collected_at' => today()->toDateString()])->assertCreated()->json('id');
}
/** @return array<string,mixed> */
private function territory(string $source, string $type = 'country', ?string $parent = null): array
{
return ['name' => 'Synthetic '.$type, 'code' => 'TEST-'.$type, 'location_type' => $type, 'parent_id' => $parent,
'source_id' => $source, 'valid_from' => today()->toDateString(), 'reason' => 'Synthetic territorial record'];
}
public function test_drafts_are_private_and_hierarchy_duplicates_and_stale_versions_are_rejected(): void
{
$this->actingAs($this->editor());
$source = $this->source();
$country = $this->create('/api/v1/geo/territories', $this->territory($source))->assertOk()->json('id');
$this->getJson('/api/v1/geo/sources')->assertOk()->assertJsonPath('data.0.id', $source);
$this->getJson('/api/v1/geo/drafts')->assertOk()->assertJsonPath('data.0.id', $country);
$this->create('/api/v1/geo/territories', $this->territory($source))->assertUnprocessable();
$this->create('/api/v1/geo/territories', $this->territory($source, 'district', $country))->assertUnprocessable();
$province = $this->create('/api/v1/geo/territories', $this->territory($source, 'province', $country))->assertOk()->json('id');
$this->getJson('/api/v1/geo/provinces')->assertOk()->assertJsonCount(0, 'data');
$this->patchTerritory('/api/v1/geo/territories/'.$province, [...$this->territory($source, 'province', $country), 'version_no' => 1])->assertOk()->assertJsonPath('version_no', 2);
$this->patchTerritory('/api/v1/geo/territories/'.$province, [...$this->territory($source, 'province', $country), 'version_no' => 1])->assertConflict();
$this->assertDatabaseCount('geo_territory_revisions', 3);
}
public function test_revoking_ancestor_source_hides_descendants_and_filters_are_scoped(): void
{
$this->actingAs($this->editor());
$source = $this->source();
$country = $this->create('/api/v1/geo/territories', $this->territory($source))->json('id');
$province = $this->create('/api/v1/geo/territories', $this->territory($source, 'province', $country))->json('id');
// Synthetic published fixture only; no production approval is inferred from this test.
$reviewer = User::factory()->create();
$publisher = User::factory()->create();
DB::table('geo_sources')->where('id', $source)->update(['status' => 'approved', 'responsible_entity' => 'Synthetic entity', 'license' => 'Synthetic licence']);
DB::table('geo_territory_profiles')->update(['status' => 'published', 'reviewer_id' => $reviewer->id, 'publisher_id' => $publisher->id]);
DB::table('geo_locations')->update(['data_classification' => 'public']);
$this->getJson('/api/v1/geo/provinces?country_id='.$country.'&limit=1')->assertOk()->assertJsonPath('data.0.id', $province);
$this->getJson('/api/v1/geo/provinces?country_id='.Str::uuid())->assertJsonCount(0, 'data');
DB::table('geo_territory_profiles')->where('geo_location_id', $country)->update(['status' => 'archived']);
$this->getJson('/api/v1/geo/provinces')->assertJsonCount(0, 'data');
$this->getJson('/api/v1/geo/territories/province/'.$province)->assertNotFound();
}
public function test_authentication_mfa_and_empty_rollback(): void
{
$this->getJson('/api/v1/geo/countries')->assertUnauthorized();
$user = User::factory()->create();
config(['portal.managers' => [$user->email]]);
$this->actingAs($user)->create('/api/v1/geo/sources', [])->assertForbidden();
$migration = require database_path('migrations/2026_09_28_150000_territorial_registry.php');
$migration->down();
$migration->up();
$this->actingAs($this->editor());
$this->source();
$this->expectException(\RuntimeException::class);
$migration->down();
}
public function test_editor_reviewer_publisher_workflow_and_source_revocation(): void
{
$editor = $this->editor();
$reviewer = $this->editor();
$publisher = $this->editor();
config(['portal.managers' => [$editor->email, $reviewer->email, $publisher->email],
'territorial.editors' => [$editor->email], 'territorial.reviewers' => [$reviewer->email, $editor->email],
'territorial.publishers' => [$publisher->email, $editor->email]]);
$this->actingAs($editor);
$source = $this->create('/api/v1/geo/sources', ['name' => 'Synthetic complete source', 'reference' => 'Synthetic source reference',
'checksum' => str_repeat('b', 64), 'source_version' => 'test', 'collected_at' => today()->toDateString(),
'responsible_entity' => 'Synthetic entity', 'license' => 'Synthetic test permission'])->json('id');
$id = $this->create('/api/v1/geo/territories', $this->territory($source))->json('id');
$url = '/api/v1/geo/territories/'.$id.'/transitions';
$this->create($url, ['version_no' => 1, 'action' => 'pending_review', 'reason' => 'Synthetic review requested'])->assertOk();
$this->create($url, ['version_no' => 2, 'action' => 'approved', 'reason' => 'Synthetic self review attempt'])->assertForbidden();
$this->actingAs($reviewer);
$this->create('/api/v1/geo/sources/'.$source.'/transitions', ['action' => 'approved', 'approval_reference' => 'Synthetic source review evidence'])->assertOk();
$this->create($url, ['version_no' => 2, 'action' => 'approved', 'reason' => 'Synthetic independent review'])->assertOk();
$this->actingAs($editor)->create($url, ['version_no' => 3, 'action' => 'published', 'reason' => 'Synthetic self publication attempt'])->assertForbidden();
$this->actingAs($publisher)->create($url, ['version_no' => 3, 'action' => 'published', 'reason' => 'Synthetic independent publication'])->assertOk();
$this->getJson('/api/v1/geo/countries')->assertJsonPath('data.0.id', $id);
$this->create('/api/v1/geo/sources/'.$source.'/transitions', ['action' => 'revoked', 'approval_reference' => 'Synthetic source revoked'])->assertOk();
$this->getJson('/api/v1/geo/countries')->assertJsonCount(0, 'data');
}
}
@@ -0,0 +1,75 @@
<?php
namespace Tests\Unit;
use App\Services\CartographyWorkbookAudit;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use ZipArchive;
class CartographyWorkbookAuditTest extends TestCase
{
private string $path;
protected function setUp(): void
{
parent::setUp();
$this->path = tempnam(sys_get_temp_dir(), 'gis-test-');
$zip = new ZipArchive;
$zip->open($this->path, ZipArchive::OVERWRITE);
$zip->addFromString('xl/workbook.xml', '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Synthetic" sheetId="1" r:id="rId1"/></sheets></workbook>');
$zip->addFromString('xl/_rels/workbook.xml.rels', '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>');
$zip->addFromString('xl/worksheets/sheet1.xml', '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Private synthetic label</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>Private synthetic label</t></is></c></row><row r="3"><c r="B3"><f>1+1</f><v>2</v></c><c r="C3"/></row></sheetData></worksheet>');
$zip->close();
}
protected function tearDown(): void
{
unlink($this->path);
parent::tearDown();
}
/** @return array<string, string> */
private function manifest(): array
{
return ['sha256' => hash_file('sha256', $this->path), 'owner' => 'Synthetic owner', 'version' => 'test-1',
'received_at' => '2026-09-28', 'classification' => 'internal', 'inspection_authorization' => 'Synthetic test only'];
}
public function test_audit_quarantines_unknown_crs_and_reports_duplicates_without_copying_source_values(): void
{
$report = (new CartographyWorkbookAudit)->inspect($this->path, $this->manifest());
$this->assertSame(3, $report['rows_inspected']);
$this->assertSame('quarantined', $report['status']);
$this->assertFalse($report['publication_allowed']);
$this->assertSame([], $report['transformations']);
$this->assertSame('duplicate', $report['sheets'][0]['rows'][1]['status']);
$this->assertStringNotContainsString('Private synthetic label', json_encode($report));
$this->assertStringContainsString('formula_not_evaluated', json_encode($report));
$this->assertStringContainsString('original_crs_unknown', json_encode($report));
}
public function test_checksum_mismatch_is_rejected(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('checksum');
(new CartographyWorkbookAudit)->inspect($this->path, [...$this->manifest(), 'sha256' => str_repeat('0', 64)]);
}
public function test_inspection_requires_authorization_evidence(): void
{
$this->expectException(RuntimeException::class);
(new CartographyWorkbookAudit)->inspect($this->path, [...$this->manifest(), 'inspection_authorization' => '']);
}
public function test_xml_entities_are_rejected(): void
{
$zip = new ZipArchive;
$zip->open($this->path);
$zip->addFromString('xl/workbook.xml', '<!DOCTYPE workbook [<!ENTITY x SYSTEM "file:///secret">]><workbook>&x;</workbook>');
$zip->close();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('unsafe');
(new CartographyWorkbookAudit)->inspect($this->path, $this->manifest());
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace Tests\Unit;
use App\Services\TerritorialCsvAudit;
use PHPUnit\Framework\TestCase;
use RuntimeException;
class TerritorialCsvAuditTest extends TestCase
{
private string $path;
protected function setUp(): void
{
$this->path = tempnam(sys_get_temp_dir(), 'geo-csv-');
}
protected function tearDown(): void
{
unlink($this->path);
}
private function inspect(string $rows): array
{
file_put_contents($this->path, implode(';', TerritorialCsvAudit::HEADERS)."\n".$rows);
return (new TerritorialCsvAudit)->inspect($this->path, ['01']);
}
public function test_preserves_leading_zero_codes_and_counts_identical_duplicates(): void
{
$row = '01;Synthetic;0101;District;010101;Post;01010101;Locality;village;-12.5;35.1';
$report = $this->inspect($row."\n".$row);
$this->assertSame('structurally_valid_requires_review', $report['status']);
$this->assertSame(1, $report['duplicate_records']);
$this->assertSame(1, $report['candidate_counts_by_province']['01']['locality']);
$this->assertSame(hash_file('sha256', $this->path), $report['sha256']);
}
public function test_conflicting_names_and_coordinates_cancel_whole_dataset(): void
{
$report = $this->inspect("01;Synthetic;0101;First;010101;Post;01010101;Locality;village;0;0\n01;Synthetic;0101;Other;010101;Post;01010101;Locality;village;1;0");
$this->assertSame('rejected', $report['status']);
$this->assertContains('conflicting_code:district', $report['errors'][0]['issues']);
$this->assertContains('conflicting_code:locality', $report['errors'][0]['issues']);
}
public function test_no_inferred_parent_or_coordinates_and_unknown_province_are_rejected(): void
{
$report = $this->inspect('02;Synthetic;0201;District;;;02010101;Locality;village;91;');
$this->assertSame('rejected', $report['status']);
foreach (['unknown_province', 'locality_requires_reviewed_parent_exception', 'incomplete_coordinates', 'invalid_coordinate:latitude'] as $issue) {
$this->assertContains($issue, $report['errors'][0]['issues']);
}
}
public function test_district_only_rows_do_not_create_localities(): void
{
$report = $this->inspect('01;Synthetic;0101;District;;;;;;;');
$this->assertSame('structurally_valid_requires_review', $report['status']);
$this->assertArrayNotHasKey('locality', $report['candidate_counts_by_province']['01']);
}
public function test_empty_csv_is_rejected(): void
{
$this->assertSame('rejected', $this->inspect('')['status']);
}
public function test_wrong_delimiter_is_not_silently_interpreted(): void
{
file_put_contents($this->path, implode(',', TerritorialCsvAudit::HEADERS));
$this->expectException(RuntimeException::class);
(new TerritorialCsvAudit)->inspect($this->path, ['01']);
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
use App\Services\CartographyWorkbookAudit;
// Explicit paths only; no Laravel boot, database connection, import or publication.
require __DIR__.'/../vendor/autoload.php';
try {
$manifestPath = getenv('INVESTMOZ_CARTOGRAPHY_MANIFEST');
$workbookPath = getenv('INVESTMOZ_CARTOGRAPHY_FILE');
if (! $manifestPath || ! $workbookPath || ! is_file($manifestPath) || filesize($manifestPath) > 100000) {
throw new RuntimeException('Set INVESTMOZ_CARTOGRAPHY_FILE and INVESTMOZ_CARTOGRAPHY_MANIFEST to authorised local files.');
}
$manifest = json_decode(file_get_contents($manifestPath), true, 32, JSON_THROW_ON_ERROR);
$report = (new CartographyWorkbookAudit)->inspect($workbookPath, $manifest);
echo json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
} catch (Throwable $exception) {
fwrite(STDERR, 'Audit failed: '.$exception->getMessage().PHP_EOL);
exit(1);
}
+71
View File
@@ -0,0 +1,71 @@
// Isolated QA only. Synthetic account is prepared separately, never against the application DB.
import fs from 'node:fs';
const base = 'http://127.0.0.1:18027';
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).json();
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise(resolve => ws.addEventListener('open', resolve, { once: true }));
let seq = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => {
const m = JSON.parse(event.data);
if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails.text);
if (m.id) { const p = pending.get(m.id); pending.delete(m.id); m.error ? p.reject(m.error) : p.resolve(m.result); }
};
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++seq; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => {
const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
if (r.exceptionDetails) throw Error('Browser expression failed');
return r.result?.value;
};
const wait = async expression => { for (let n = 0; n < 100; n++) { if (await evaluate(expression)) return; await new Promise(r => setTimeout(r, 100)); } throw Error('Browser condition timed out: ' + expression); };
const fill = async (selector, value) => {
await evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`);
await send('Input.insertText', { text: value });
};
const observations = [];
try {
await send('Page.enable'); await send('Runtime.enable');
await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 900, deviceScaleFactor: 1, mobile: true });
await send('Page.navigate', { url: base + '/login' });
await wait(`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`);
if (await evaluate(`location.pathname==='/login'`)) {
await fill('input[type="email"]', 'mne-browser@example.test');
await fill('input[type="password"]', 'SyntheticMneOnly-2026!');
await evaluate(`document.querySelector('button[type="submit"]').click()`);
await wait(`!location.pathname.startsWith('/login')`);
}
await send('Page.navigate', { url: base + '/investidor/negocios' });
await wait(`!!document.querySelector('h1') && document.body.innerText.includes('Preparar neg')`);
await fill('main form input', 'Synthetic browser business');
await evaluate(`document.querySelector('main form button').click()`);
await wait(`location.pathname.startsWith('/investidor/negocios/') && !!document.querySelector('textarea')`);
await fill('fieldset textarea', 'Synthetic private description for review of a browser-only business.');
await fill('fieldset input[maxlength="2000"]', 'Synthetic declared reason');
await fill('fieldset input[maxlength="2000"]:last-of-type', 'Synthetic source evidence');
// Find source input by its wrapping label; field labels are accessible label elements.
await evaluate(`(()=>{const labels=[...document.querySelectorAll('label')];const field=labels.find(l=>l.textContent.includes('Referência da fonte'))?.querySelector('input'); if(field) field.focus();})()`);
await send('Input.insertText', { text: 'Synthetic source evidence' });
await evaluate(`(()=>{const el=document.querySelector('input[type="date"]'); const setter=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; setter.call(el,'2027-12-31');el.dispatchEvent(new Event('input',{bubbles:true}));el.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await fill('main form > label textarea', 'Synthetic save for browser QA');
await evaluate(`document.querySelector('main form button').click()`);
await wait(`document.body.innerText.includes('versão 2')`);
observations.push({ scenario: 'private_create_and_save', passed: true });
await fill('main form > label textarea', 'Synthetic submission for browser QA');
await evaluate(`document.querySelector('input[type="checkbox"]').click()`);
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent==='Submeter para análise').click()`);
await wait(`document.body.innerText.includes('versão 3') && document.body.innerText.includes('Submetido')`);
observations.push({ scenario: 'private_submit_with_review_consent', passed: true });
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 });
const result = await evaluate(`(()=>{const a=[...document.querySelectorAll('a')].find(a=>getComputedStyle(a).position==='fixed'&&a.href.endsWith('/apoio'));const b=a?.getBoundingClientRect();return {width:innerWidth,breadcrumb:!!document.querySelector('nav[aria-label="Caminho de navegação"]'),supportVisible:!!b&&b.bottom<=innerHeight&&b.left>=0,overflow:document.documentElement.scrollWidth>innerWidth+1};})()`);
if (!result.breadcrumb || !result.supportVisible || result.overflow) throw Error('Layout failure');
observations.push(result);
}
if (errors.length) throw Error('JavaScript errors observed');
fs.writeFileSync('docs/investmoz/existing-business/browser-validation.json', JSON.stringify({ date: new Date().toISOString(), scope: 'Synthetic private create/save and responsive layout in isolated QA; institutional review covered by integration tests', observations, errors }, null, 2) + '\n');
console.log(JSON.stringify({ passed: observations.length, javascript_errors: errors.length }));
} catch (error) {
console.log(await evaluate(`({path:location.pathname,title:document.title,body:document.body.innerText.slice(0,1200)})`));
throw error;
} finally { await send('Page.close'); ws.close(); }
+51
View File
@@ -0,0 +1,51 @@
import fs from 'node:fs';
const ref = name => ({ $ref: `#/components/schemas/${name}` });
const id = { name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' } };
const responses = schema => Object.fromEntries(['200', '401', '403', '404', '409', '422', '429'].map(status => [status, {
description: { '200': 'Private response; Cache-Control private, no-store', '401': 'Authentication required', '403': 'Account, ownership or current reviewer/MFA policy rejected', '404': 'Module disabled or resource unavailable', '409': 'Stale version or invalid transition', '422': 'Validation error', '429': 'Rate limited' }[status],
...(status === '200' ? { content: { 'application/json': { schema } } } : {}),
}]));
const operation = (summary, response, body, parameters = []) => ({ summary, parameters, security: [{ session: [] }], responses: responses(response), ...(body ? { requestBody: { required: true, content: { 'application/json': { schema: body } } }, description: 'Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients.' } : {}) });
const text = { type: 'string' };
const payload = { type: 'object', additionalProperties: false, required: ['title'], properties: { title: { type: 'string', maxLength: 200 }, description: { type: ['string', 'null'], maxLength: 10000 }, declared_reason: { type: ['string', 'null'], maxLength: 2000 }, source_reference: { type: ['string', 'null'], maxLength: 2000 }, valid_until: { type: ['string', 'null'], format: 'date' } } };
const input = { type: 'object', required: ['modality', 'classification', 'reason', 'payload'], properties: { modality: text, classification: { enum: ['internal', 'confidential', 'restricted'] }, reason: { type: 'string', minLength: 10, maxLength: 1000 }, payload } };
const document = {
openapi: '3.1.0', info: { title: 'InvestMoz — private existing-business intake', version: '1.0.0', description: 'Internal preparation and review only. No publication, certification, legal transfer, NDA, payment or external CRM operation.' },
servers: [{ url: '/api/v1/existing-business' }],
paths: {
'/listings': {
get: operation('List own active records, 20 per page', { type: 'object', required: ['records', 'management', 'modalities'], properties: { records: { type: 'object', properties: { data: { type: 'array', items: ref('Business') }, total: { type: 'integer' } } }, management: { type: 'boolean' }, modalities: { type: 'array', items: text } } }, null, [{ name: 'page', in: 'query', schema: { type: 'integer', minimum: 1 } }]),
post: operation('Create private draft', ref('Business'), input),
},
'/reviews': { get: operation('List submitted records for designated reviewers with MFA; excludes own records', { type: 'object', properties: { records: { type: 'object', properties: { data: { type: 'array', items: ref('Business') } } }, management: { type: 'boolean' } } }) },
'/listings/{id}': {
get: operation('Read own record or currently reviewable submission', { type: 'object', properties: { record: ref('Business'), canEdit: { type: 'boolean' }, owner: { type: 'boolean' }, canReview: { type: 'boolean' }, history: { type: 'array', items: { type: 'object', properties: { version_no: { type: 'integer' }, action: text, created_at: text, note: text } } } } }, null, [id]),
put: operation('Update owned draft or request for information; optimistic version required', ref('Business'), { ...input, required: [...input.required, 'version_no'], properties: { ...input.properties, version_no: { type: 'integer', minimum: 1 } } }, [id]),
},
'/listings/{id}/transitions': { post: operation('Submit, begin review, request information or withdraw', ref('Business'), { type: 'object', required: ['version_no', 'action', 'note'], properties: { version_no: { type: 'integer', minimum: 1 }, action: { enum: ['submitted', 'in_review', 'needs_information', 'withdrawn'] }, note: { type: 'string', minLength: 10, maxLength: 2000 }, review_consent: { type: 'boolean', description: 'Must be true for submission. Stored in encrypted review evidence. Does not authorize publication.' } } }, [id]) },
},
components: { securitySchemes: { session: { type: 'apiKey', in: 'cookie', name: 'session_cookie', description: 'Actual Laravel cookie name comes from deployment configuration; no bearer token support.' } }, schemas: { Business: { type: 'object', required: ['id', 'code', 'modality', 'status', 'classification', 'version_no', 'payload'], properties: { id: { type: 'string', format: 'uuid' }, code: text, modality: text, status: { enum: ['draft', 'submitted', 'in_review', 'needs_information', 'withdrawn'] }, classification: { enum: ['internal', 'confidential', 'restricted'] }, version_no: { type: 'integer', minimum: 1 }, payload } } } },
};
document.paths['/listings'].post.responses['201'] = document.paths['/listings'].post.responses['200'];
delete document.paths['/listings'].post.responses['200'];
const objectPayload = { type: 'object', additionalProperties: false, required: ['label', 'source_reference'], properties: Object.fromEntries(['label','declared_holder','document_reference','source_reference','competent_entity','purpose','location_description','boundaries_description','occupancy','condition','encumbrances','restrictions','required_authorizations','transfer_condition','contract_type','valid_from','valid_until','area','area_unit','amount','currency','value_kind','participation_percent'].map(key => [key, { type: ['string','null'] }])) };
const objectInput = { type: 'object', required: ['kind','version_no','reason','payload'], properties: { kind: { enum: ['company','participation','asset','property','unit','improvement','agricultural_investment','land_right','contract','license','authorization','encumbrance','valuation','capital_request'] }, version_no: { type: 'integer', minimum: 1 }, reason: { type: 'string', minLength: 10, maxLength: 1000 }, payload: objectPayload } };
const objectResponse = { type: 'object', properties: { id: { type: 'string', format: 'uuid' }, version_no: { type: 'integer' }, verification_status: { const: 'pending' } } };
document.paths['/listings/{id}/objects'] = { post: operation('Declare a separate restricted object; increments aggregate version without granting verification', objectResponse, objectInput, [id]) };
document.paths['/listings/{id}/objects'].post.responses['201'] = document.paths['/listings/{id}/objects'].post.responses['200'];
delete document.paths['/listings/{id}/objects'].post.responses['200'];
document.paths['/listings/{id}/objects/{object}'] = { put: operation('Update scoped object with immutable kind; amount requires currency and value kind; area requires unit', objectResponse, objectInput, [id, { ...id, name: 'object' }]) };
const verification = { type: 'object', required: ['version_no', 'check', 'outcome', 'evidence_reference', 'note'], properties: {
version_no: { type: 'integer', minimum: 1 }, object_id: { type: ['string', 'null'], format: 'uuid' },
check: { enum: ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'] },
outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked'] },
evidence_reference: { type: 'string', minLength: 10, maxLength: 2000 }, note: { type: 'string', minLength: 10, maxLength: 2000 },
valid_until: { type: ['string', 'null'], format: 'date', description: 'Required for confirmed findings; must be today or later.' },
} };
document.paths['/listings/{id}/verifications'] = { post: operation('Record independent finding while in_review; immutable encrypted evidence, optimistic version and scoped object. Does not publish or certify the business.', ref('Business'), verification, [id]) };
document.paths['/listings/{id}'].get.responses['200'].content['application/json'].schema.properties.verifications = {
type: 'array', items: { ...verification, properties: { ...verification.properties, effective_outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked', 'stale', 'expired'] }, content_version: { type: 'integer' }, created_at: text } },
};
document.info.version = '1.1.0';
fs.writeFileSync('docs/investmoz/existing-business/openapi.json', JSON.stringify(document, null, 2) + '\n');
console.log('OpenAPI written: 9 operations, private session API.');
+35
View File
@@ -0,0 +1,35 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Local PostgreSQL only.');
}
$manifest = $argv[1] ?? '';
if (! is_file($manifest)) {
throw new RuntimeException('Provide the private backup manifest path.');
}
$before = json_decode(file_get_contents($manifest), true, 512, JSON_THROW_ON_ERROR)['row_counts'];
$result = DB::transaction(function () use ($before): array {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
$changes = [];
foreach ($before as $table => $count) {
$after = DB::table($table)->count();
if ($after !== $count) {
$changes[$table] = ['before' => $count, 'after' => $after];
}
}
$new = [];
foreach (['existing_businesses', 'existing_business_objects', 'existing_business_mandates', 'existing_business_revisions', 'existing_business_reviews'] as $table) {
$new[$table] = DB::table($table)->count();
}
return ['previous_tables' => count($before), 'changes' => $changes, 'new_tables' => $new,
'private_module_enabled' => (bool) config('existing-business.enabled'),
'designated_reviewer_count' => count(config('existing-business.reviewers', []))];
});
echo json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
+46
View File
@@ -0,0 +1,46 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local', 'testing') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Local/testing PostgreSQL required.');
}
$path = storage_path('app/private/territory-workbook-candidates.json');
$data = json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
$expected = '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff';
if ($data['checksum'] !== $expected || hash_file('sha256', 'C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx') !== $expected) {
throw new RuntimeException('Authorised source checksum mismatch.');
}
$created = DB::transaction(function () use ($data, $expected) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$created = 0;
foreach ($data['nodes'] as $node) {
$existing = DB::table('geo_locations')->where('id', $node['id'])->first();
if ($existing) {
foreach (['name', 'parent_id', 'location_type', 'code'] as $field) {
if ($node[$field] !== $existing->$field) {
throw new RuntimeException('Existing territory differs: '.$node['id']);
}
}
continue;
}
if ($node['parent_id'] && ! DB::table('geo_locations')->where('id', $node['parent_id'])->exists()) {
throw new RuntimeException('Missing parent.');
}
DB::table('geo_locations')->insert([...$node, 'source_system' => 'cartografia-workbook', 'external_id' => $expected.':'.$node['id'], 'data_classification' => 'internal']);
$created++;
}
if ($created) {
DB::table('audit_events')->insert(['source_system' => 'cartografia-workbook', 'entity_type' => 'geo_locations', 'action' => 'owner_authorised_reference_import',
'after_data' => json_encode(['checksum' => $expected, 'created' => $created, 'rejected_rows' => $data['rejected_rows'],
'approval_basis' => 'workspace_user_instructions', 'codes' => 'internal_identifiers_not_official_ine', 'classification' => 'internal'], JSON_THROW_ON_ERROR)]);
}
return $created;
});
echo json_encode(['created' => $created, 'rejected_rows' => count($data['rejected_rows']), 'scope' => 'internal_management_dropdowns'], JSON_THROW_ON_ERROR).PHP_EOL;
+29
View File
@@ -0,0 +1,29 @@
// Synthetic QA only; tile traffic is blocked to avoid automated OSM downloads.
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).json();
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise(resolve => ws.addEventListener('open', resolve, { once: true }));
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => { const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (response.exceptionDetails) throw Error(JSON.stringify(response.exceptionDetails)); return response.result?.value; };
const wait = async expression => { for (let i = 0; i < 150; i++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 100)); } throw Error('Timed out: '+expression); };
try {
await send('Runtime.enable'); await send('Page.enable'); await send('Network.enable');
await send('Network.setBlockedURLs', { urls: ['*://tile.openstreetmap.org/*'] });
await send('Page.navigate', { url: 'http://127.0.0.1:18027/oportunidades' });
await wait(`document.querySelectorAll('.leaflet-marker-icon').length===1`);
await evaluate(`document.querySelector('.leaflet-marker-icon').click()`);
await wait(`document.querySelector('.leaflet-popup-content')?.textContent.includes('Synthetic map marker')`);
if (!await evaluate(`document.querySelector('.leaflet-popup-content a')?.getAttribute('href')==='/oportunidades/synthetic-map-browser'`)) throw Error('Missing detail link');
await evaluate(`document.querySelector('.leaflet-control-zoom-in').click()`);
const layouts = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); layouts.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
await evaluate(`window.__mapSentinel=1;document.querySelector('main form input').focus()`);
await send('Input.insertText', { text: 'NoMatchingSyntheticInvestment' });
await wait(`location.search.includes('NoMatchingSyntheticInvestment') && document.querySelectorAll('.leaflet-marker-icon').length===0`);
if (!await evaluate(`window.__mapSentinel===1`)) throw Error('Full page reload detected');
if (errors.length || layouts.some(l=>!l.noOverflow)) throw Error('Browser validation failed');
console.log(JSON.stringify({ marker: true, popup: true, detail_link: true, zoom_control: true, automatic_filter: true, no_full_reload: true, layouts, javascript_errors: errors.length, tiles_blocked_for_test: true }));
} finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
+22
View File
@@ -0,0 +1,22 @@
<?php
use App\Services\InvestmentCatalogue;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local', 'testing') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Local/testing PostgreSQL required.');
}
$report = DB::transaction(function () {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
$map = app(InvestmentCatalogue::class)->map([]);
return ['generated_at' => date(DATE_ATOM), 'published_opportunities' => $map['matched_count'],
'georeferenced' => $map['georeferenced_count'], 'complete' => $map['complete'], 'truncated' => $map['truncated'],
'unlocated' => $map['unlocated'], 'geo_geometries' => DB::table('geo_geometries')->whereNull('deleted_at')->count(),
'zone_geometries' => DB::table('investment_zone_geometries')->count()];
});
echo json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
+69
View File
@@ -0,0 +1,69 @@
"""B:G contain codes. Designacao names only the deepest populated level."""
import hashlib
import json
from pathlib import Path
import uuid
import xml.etree.ElementTree as ET
import zipfile
source = Path('C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx')
checksum = hashlib.sha256(source.read_bytes()).hexdigest()
if checksum != '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff':
raise ValueError('Authorised workbook changed')
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
country = str(uuid.uuid5(uuid.NAMESPACE_URL, 'investmoz:workbook:MZ'))
nodes = {(): dict(id=country, parent_id=None, name='Moçambique', location_type='country', code='508')}
definitions = {}
conflicts = set()
rejected = []
ignored = 0
with zipfile.ZipFile(source) as archive:
strings = [''.join(si.itertext()) for si in ET.fromstring(archive.read('xl/sharedStrings.xml')).findall('s:si', ns)]
sheet = ET.fromstring(archive.read('xl/worksheets/sheet1.xml'))
for row in sheet.findall('s:sheetData/s:row', ns)[1:]:
cells = {}
invalid = False
for cell in row:
column = ''.join(c for c in cell.attrib['r'] if c.isalpha())
value = cell.findtext('s:v', '', ns)
if cell.attrib.get('t') == 's':
value = strings[int(value)]
elif cell.attrib.get('t') == 'inlineStr':
value = ''.join(cell.find('s:is', ns).itertext())
if cell.find('s:f', ns) is not None or cell.attrib.get('t') == 'e':
invalid = True
cells[column] = ' '.join(value.split())
if cells.get('F') or cells.get('G'):
ignored += 1
continue
segments = [cells.get(column, '') for column in 'BCDE']
while segments and not segments[-1]:
segments.pop()
if invalid or not segments or '' in segments or not cells.get('H'):
rejected.append({'row': row.attrib['r'], 'reason': 'missing_code_path_or_designation'})
continue
key = tuple(segments)
name = cells['H']
if key in conflicts:
rejected.append({'row': row.attrib['r'], 'reason': 'conflicting_designation'})
continue
if key in definitions and definitions[key]['name'] != name:
rejected.extend([{'row': definitions[key]['row'], 'reason': 'conflicting_designation'}, {'row': row.attrib['r'], 'reason': 'conflicting_designation'}])
conflicts.add(key)
del definitions[key]
continue
definitions[key] = {'name': name, 'row': row.attrib['r']}
for key, definition in sorted(definitions.items(), key=lambda item: (len(item[0]), item[0])):
if key[:-1] not in nodes:
rejected.append({'row': definition['row'], 'reason': 'missing_parent_definition'})
continue
parent = nodes[key[:-1]]['id']
kind = ['province', 'district', 'admin_post', 'locality'][len(key)-1]
identifier = str(uuid.uuid5(uuid.NAMESPACE_URL, parent + ':' + kind + ':' + key[-1].casefold()))
nodes[key] = dict(id=identifier, parent_id=parent, name=definition['name'], location_type=kind, code='XLSX-' + identifier)
output = Path('storage/app/private/territory-workbook-candidates.json')
previous = output.with_name('territory-workbook-candidates-before-designation-fix.json')
if output.exists() and not previous.exists():
previous.write_bytes(output.read_bytes())
output.write_text(json.dumps(dict(checksum=checksum, mapping_version=2, nodes=list(nodes.values()), rejected_rows=rejected, ignored_sub_locality_rows=ignored), ensure_ascii=False), encoding='utf-8')
print(json.dumps(dict(counts={kind: sum(n['location_type'] == kind for n in nodes.values()) for kind in ['country','province','district','admin_post','locality']}, rejected_rows=len(rejected), ignored_sub_locality_rows=ignored)))
+67
View File
@@ -0,0 +1,67 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Local PostgreSQL only.');
}
$checksum = '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff';
if (hash_file('sha256', 'C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx') !== $checksum) {
throw new RuntimeException('Source changed.');
}
$data = json_decode(file_get_contents(storage_path('app/private/territory-workbook-candidates.json')), true, 512, JSON_THROW_ON_ERROR);
$result = DB::transaction(function () use ($data, $checksum) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$ids = [];
foreach ($data['nodes'] as $node) {
$record = DB::table('geo_locations')->where('id', $node['id'])->where('source_system', 'cartografia-workbook')->where('external_id', $checksum.':'.$node['id'])->whereNull('deleted_at')->first();
if (! $record || ! in_array($record->data_classification, ['internal', 'public'], true)) {
throw new RuntimeException('Reference unavailable or reclassified.');
}
foreach (['name', 'parent_id', 'location_type', 'code'] as $field) {
if ($node[$field] !== $record->$field) {
throw new RuntimeException('Reference changed since import.');
}
}
$ids[] = $node['id'];
}
$published = DB::table('geo_locations')->whereIn('id', $ids)->where('data_classification', 'internal')->update(['data_classification' => 'public']);
$matched = $unmatched = [];
foreach (['opportunities', 'investment_zones'] as $table) {
foreach (DB::table($table)->whereNull('deleted_at')->whereNull('primary_territory_id')->whereNotNull('province')->get() as $record) {
$normalise = fn ($value) => mb_strtolower(Str::ascii(trim((string) $value)));
$province = DB::table('geo_locations')->whereIn('id', $ids)->where('location_type', 'province')->get()->filter(fn ($node) => $normalise($node->name) === $normalise($record->province))->values();
if ($province->count() !== 1) {
$unmatched[] = ['table' => $table, 'id' => $record->id, 'reason' => 'province_not_unique'];
continue;
}
$location = $province->first();
if (trim((string) $record->district) !== '') {
$district = DB::table('geo_locations')->whereIn('id', $ids)->where('location_type', 'district')->where('parent_id', $location->id)->get()->filter(fn ($node) => $normalise($node->name) === $normalise($record->district))->values();
if ($district->count() !== 1) {
$unmatched[] = ['table' => $table, 'id' => $record->id, 'reason' => 'district_not_unique'];
continue;
}
$location = $district->first();
}
DB::table($table)->where('id', $record->id)->update(['primary_territory_id' => $location->id, 'territory_version' => $record->territory_version + 1]);
$matched[] = ['table' => $table, 'id' => $record->id, 'territory_id' => $location->id];
}
}
$result = ['published_reference_names' => $published, 'matched' => $matched, 'unmatched' => $unmatched,
'basis' => 'owner_authorised_public_dropdowns', 'checksum' => $checksum, 'official_territory_publication' => false];
if ($published || $matched !== []) {
DB::table('audit_events')->insert(['source_system' => 'territory-reference-publication', 'entity_type' => 'geo_locations', 'action' => 'reference_names_enabled', 'after_data' => json_encode($result, JSON_THROW_ON_ERROR)]);
}
return $result;
});
file_put_contents(storage_path('app/private/territory-publication-'.date('Ymd-His').'.json'), json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['reference_names_enabled' => $result['published_reference_names'], 'exact_associations' => count($result['matched']), 'unmatched' => count($result['unmatched'])], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,73 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('This recorded instruction applies to the local PostgreSQL installation only.');
}
// Specific owner instruction received in this workspace; never impersonate an application user.
$directory = storage_path('app/private/geo-ine-review-20260928-v2');
$expected = [
'original.pdf' => '5c69b6f189a1d3f5307e0cf7dd8224554705158a682637d3105afad615db26e2',
'layout.txt' => '783a7886ed5a27b8f9d0063a787928e9a4b09723c28a260c019c2de215a670a3',
];
foreach ($expected as $file => $hash) {
if (! is_file($directory.'/'.$file) || hash_file('sha256', $directory.'/'.$file) !== $hash) {
throw new RuntimeException('Source differs from the reviewed package: '.$file);
}
}
$receipt = [
'schema_version' => 1,
'decision_date' => '2026-09-28',
'decision' => 'accepted_by_owner',
'validation' => 'declared_validated_by_owner',
'authenticity' => 'declared_authenticated_by_owner',
'approval_basis' => 'explicit_workspace_user_instruction',
'instruction' => 'aplicar os resultados e aceite os dados como validados e autenticados',
'source_checksums' => $expected,
'scope' => 'INE PDF and extraction package geo-ine-review-20260928-v2',
'independent_authentication_performed' => false,
'technical_mapping_status' => 'unresolved_column_alignment',
'territories_imported_by_this_decision' => 0,
];
$json = json_encode($receipt, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
$hash = hash('sha256', $json);
$path = $directory.'/owner-acceptance-'.$hash.'.json';
if (is_file($path)) {
if (file_get_contents($path) !== $json) {
throw new RuntimeException('Existing acceptance receipt differs.');
}
} else {
// Exclusive creation preserves any existing evidence.
$stream = fopen($path, 'x');
if ($stream === false) {
throw new RuntimeException('Could not create acceptance receipt.');
}
try {
if (fwrite($stream, $json) !== strlen($json)) {
throw new RuntimeException('Incomplete acceptance receipt.');
}
} finally {
fclose($stream);
}
}
$created = DB::transaction(function () use ($receipt, $hash): bool {
DB::select('SELECT pg_advisory_xact_lock(280926, 150001)');
if (DB::table('audit_events')->where('source_system', 'territorial-owner-acceptance')->where('external_id', $hash)->exists()) {
return false;
}
DB::table('audit_events')->insert([
'source_system' => 'territorial-owner-acceptance', 'external_id' => $hash,
'entity_type' => 'territorial_source_package', 'action' => 'owner_accepted',
'after_data' => json_encode($receipt, JSON_THROW_ON_ERROR),
]);
return true;
});
echo json_encode(['status' => 'accepted_by_owner', 'audit_created' => $created,
'receipt' => $path, 'territories_imported' => 0], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
+58
View File
@@ -0,0 +1,58 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('local') || DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('Local PostgreSQL only.');
}
$root = storage_path('app/private/');
$before = json_decode(file_get_contents($root.'territory-workbook-candidates-before-designation-fix.json'), true, 512, JSON_THROW_ON_ERROR);
$after = json_decode(file_get_contents($root.'territory-workbook-candidates.json'), true, 512, JSON_THROW_ON_ERROR);
if (($after['mapping_version'] ?? 0) !== 2 || $before['checksum'] !== $after['checksum'] || hash_file('sha256', 'C:/Mac/Home/Documents/eBAU/cartografia_moz.xlsx') !== $after['checksum']) {
throw new RuntimeException('Source or mapping mismatch.');
}
$old = array_column($before['nodes'], null, 'id');
$new = array_column($after['nodes'], null, 'id');
$result = DB::transaction(function () use ($old, $new, $after) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$renamed = $quarantined = 0;
foreach ($old as $id => $prior) {
$record = DB::table('geo_locations')->where('id', $id)->where('source_system', 'cartografia-workbook')->where('external_id', $after['checksum'].':'.$id)->lockForUpdate()->first();
if (! $record || $record->parent_id !== $prior['parent_id'] || $record->code !== $prior['code'] || $record->location_type !== $prior['location_type']) {
throw new RuntimeException('Existing reference changed: '.$id);
}
$desired = $new[$id] ?? null;
if (! $desired) {
if ($record->deleted_at === null) {
DB::table('geo_locations')->where('id', $id)->update(['data_classification' => 'internal', 'deleted_at' => now(), 'version_no' => $record->version_no + 1]);
$quarantined++;
}
continue;
}
if ($record->name === $desired['name']) {
continue;
}
if ($record->name !== $prior['name'] || $record->deleted_at !== null) {
throw new RuntimeException('Manual edit must not be overwritten: '.$id);
}
DB::table('geo_locations')->where('id', $id)->update(['name' => $desired['name'], 'version_no' => $record->version_no + 1]);
$renamed++;
}
foreach ($new as $id => $node) {
if (! isset($old[$id])) {
throw new RuntimeException('Unexpected identity change: '.$id);
}
}
$result = ['renamed' => $renamed, 'quarantined' => $quarantined, 'mapping_version' => 2, 'checksum' => $after['checksum']];
if ($renamed || $quarantined) {
DB::table('audit_events')->insert(['source_system' => 'cartografia-workbook', 'entity_type' => 'geo_locations', 'action' => 'designation_mapping_corrected', 'after_data' => json_encode($result, JSON_THROW_ON_ERROR)]);
}
return $result;
});
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+22
View File
@@ -0,0 +1,22 @@
import fs from 'node:fs';
const id = { name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' } };
const string = { type: 'string' };
const schema = properties => ({ type: 'object', properties });
const paths = {};
const operation = (summary, parameters = [], body = null) => ({ summary, security: [{ laravelSession: [] }], parameters: [...parameters, ...(body ? [{ name: 'Idempotency-Key', in: 'header', required: true, schema: { type: 'string', format: 'uuid' } }] : [])],
...(body ? { requestBody: { required: true, content: { 'application/json': { schema: body } } } } : {}),
responses: Object.fromEntries([200, ...(summary.startsWith('Create source') ? [201] : []), 401, 403, 404, 409, 422, 429].map(code => [code, { description: code < 300 ? 'JSON result with X-Correlation-ID; private, no-store' : 'Request rejected; validation and workflow errors use Problem Details within territorial middleware' }])) });
for (const collection of ['countries','provinces','districts','admin-posts','localities','search']) paths['/'+collection] = { get: operation('Read currently published territories: '+collection,
['q','cursor','parent_id','country_id','province_id','district_id','admin_post_id'].map(name => ({ name, in: 'query', schema: string })).concat([{ name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1, maximum: 100 } }])) };
paths['/territories/{type}/{id}'] = { get: operation('Read published territory and translated names', [id, { name: 'type', in: 'path', required: true, schema: { enum: ['country','province','district','admin_post','locality'] } }]) };
const territory = schema({ name: string, code: string, location_type: { enum: ['country','province','district','admin_post','locality'] }, parent_id: { type: ['string','null'], format: 'uuid' }, source_id: { type: 'string', format: 'uuid' }, valid_from: { type: 'string', format: 'date' }, valid_to: { type: ['string','null'], format: 'date' }, reason: { type: 'string', minLength: 10, maxLength: 1000 } });
territory.required = ['name','code','location_type','source_id','valid_from','reason'];
paths['/territories'] = { post: operation('Create private territorial draft; designated editor with MFA', [], territory) };
paths['/territories/{id}'] = { patch: operation('Replace draft attributes and invalidate editorial approvals', [id], { ...territory, required: [...territory.required,'version_no'], properties: { ...territory.properties, version_no: { type: 'integer', minimum: 1 } } }) };
paths['/territories/{id}/transitions'] = { post: operation('Submit, review, publish, reject or archive; independent actors required', [id], { ...schema({ action: { enum: ['pending_review','approved','published','rejected','archived'] }, version_no: { type: 'integer', minimum: 1 }, reason: { type: 'string', minLength: 10 } }), required: ['action','version_no','reason'] }) };
paths['/sources'] = { post: operation('Create source in pending state', [], { ...schema({ name: string, responsible_entity: string, reference: string, license: string, checksum: { type: 'string', pattern: '^[0-9a-f]{64}$' }, source_version: string, collected_at: { type: 'string', format: 'date' }, original_crs: string }), required: ['name','reference','checksum','source_version','collected_at'] }) };
paths['/sources/{id}/transitions'] = { post: operation('Independent source approval or revocation with evidence reference', [id], { ...schema({ action: { enum: ['approved','revoked'] }, approval_reference: { type: 'string', minLength: 10 } }), required: ['action','approval_reference'] }) };
paths['/sources'].get = operation('Management-only source metadata and decision evidence, MFA required');
paths['/drafts'] = { get: operation('Management-only territorial editorial records, MFA required') };
fs.writeFileSync('docs/investmoz/gis/territorial-openapi.json', JSON.stringify({ openapi: '3.1.0', info: { title: 'InvestMoz territorial registry — implemented subset', version: '0.1.0', description: 'Local session adapter. OAuth/OIDC, geometric queries, assignments, imports, hierarchy endpoint and administrative UI remain unimplemented. Response schemas require expansion before external certification.' }, servers: [{ url: '/api/v1/geo' }], paths, components: { securitySchemes: { laravelSession: { type: 'apiKey', in: 'cookie', name: 'deployment_session_cookie', description: 'Actual name configured by Laravel; write requests also require Laravel CSRF/origin protection. This is not OAuth/OIDC.' } } } }, null, 2)+'\n');
console.log('Territorial OpenAPI: '+Object.keys(paths).length+' paths');
+79
View File
@@ -0,0 +1,79 @@
"""Preserve an INE PDF and prepare a review package; never guess table joins.
The 2012 INE PDF contains independently wrapped columns. A line-based merge
would associate valid codes with the wrong district. This tool deliberately
exports the extracted lines for review instead of manufacturing such joins.
"""
import argparse
import csv
import hashlib
import json
from pathlib import Path
import re
import subprocess
def prepare(source, destination, executable, source_url, source_version):
source = Path(source).resolve(strict=True)
destination = Path(destination).resolve()
original = source.read_bytes()
if len(original) > 20 * 1024 * 1024 or not original.startswith(b"%PDF-"):
raise ValueError("Expected a PDF of at most 20 MiB")
# Never overwrite an earlier review or its preserved original.
destination.mkdir(parents=True, exist_ok=False)
(destination / "original.pdf").write_bytes(original)
version = subprocess.run([executable, "-v"], capture_output=True, timeout=10, check=False)
# Xpdf 4.00 exits 99 after printing its version; Poppler exits zero.
if version.returncode not in (0, 99) or b"pdftotext version" not in version.stdout + version.stderr:
raise RuntimeError("Could not identify the pdftotext executable")
subprocess.run(
[executable, "-enc", "UTF-8", "-layout", str(destination / "original.pdf"), str(destination / "layout.txt")],
capture_output=True, timeout=60, check=True,
)
extracted = (destination / "layout.txt").read_text(encoding="utf-8")
counts = {}
records = 0
with (destination / "review.csv").open("w", encoding="utf-8", newline="") as stream:
writer = csv.writer(stream, delimiter=";")
writer.writerow(["page", "line", "extracted_text", "issue"])
for page, contents in enumerate(extracted.split("\f"), 1):
for line, text in enumerate(contents.splitlines(), 1):
if not text.strip():
continue
records += 1
# Preserve text exactly. A code occurrence is not a joined territory.
code = re.match(r"^\s*([0-9]{6})\s", text)
if code:
prefix = code.group(1)[:2]
counts[prefix] = counts.get(prefix, 0) + 1
writer.writerow([page, line, text, "manual_column_alignment_required"])
report = {
"schema_version": 1,
"source_url": source_url,
"source_version_declared": source_version,
"sha256": hashlib.sha256(original).hexdigest(),
"extraction_sha256": hashlib.sha256((destination / "layout.txt").read_bytes()).hexdigest(),
"extractor": (version.stdout + version.stderr).decode("utf-8", errors="replace").strip(),
"status": "requires_steward_review",
"license_status": "unverified",
"nonempty_extracted_lines": records,
"lines_requiring_review": records,
"automatically_accepted_territories": 0,
"observed_admin_post_code_lines_by_prefix": dict(sorted(counts.items())),
"source_totals_comparison": "pending_independent_visual_review",
"notice": "Code occurrences are not validated totals. No administrative relation or locality was inferred."
}
(destination / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source")
parser.add_argument("destination")
parser.add_argument("--pdftotext", required=True)
parser.add_argument("--source-url", required=True)
parser.add_argument("--source-version", required=True)
args = parser.parse_args()
report = prepare(args.source, args.destination, args.pdftotext, args.source_url, args.source_version)
print(json.dumps({"status": report["status"], "sha256": report["sha256"], "review_lines": report["lines_requiring_review"]}))
+39
View File
@@ -0,0 +1,39 @@
// Synthetic QA server only; never writes to the application database.
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).json();
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise(resolve => ws.addEventListener('open', resolve, { once: true }));
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => { const result = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (result.exceptionDetails) throw Error(JSON.stringify(result.exceptionDetails)); return result.result?.value; };
const wait = async expression => { for (let n = 0; n < 100; n++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 100)); } throw Error('Timed out: ' + expression); };
const select = async (index, value) => evaluate(`(()=>{const element=document.querySelectorAll('select')[${index}];Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(element,${JSON.stringify(value)});element.dispatchEvent(new Event('change',{bubbles:true}));})()`);
try {
await send('Runtime.enable'); await send('Page.enable');
await send('Page.navigate', { url: 'http://127.0.0.1:18027/login' });
await wait(`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`);
if (await evaluate(`location.pathname==='/login'`)) {
for (const [selector, text] of [['input[type="email"]', 'mne-browser@example.test'], ['input[type="password"]', 'SyntheticMneOnly-2026!']]) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`); await send('Input.insertText', { text }); }
await evaluate(`document.querySelector('button[type="submit"]').click()`); await wait(`!location.pathname.startsWith('/login')`);
}
await send('Page.navigate', { url: 'http://127.0.0.1:18027/management/territory-associations' });
await wait(`document.querySelectorAll('select').length===2`);
await select(0, 'clusters');
await wait(`document.querySelectorAll('select')[1].options.length>1`);
await select(1, '20000000-0000-4000-8000-000000000001');
await wait(`document.querySelectorAll('select').length===6`);
for (let level = 0; level < 4; level++) {
await wait(`!document.querySelectorAll('select')[${level+2}].disabled && document.querySelectorAll('select')[${level+2}].options.length>1`);
await select(level+2, `10000000-0000-4000-8000-${String(level+2).padStart(12, '0')}`);
}
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent==='Guardar localização').click()`);
await wait(`document.body.innerText.includes('Localização associada e guardada.')`);
await select(2, '');
await wait(`[...document.querySelectorAll('section[aria-label="Localização do investimento"] select')].slice(1).every(s=>s.value===''&&s.disabled)`);
const widths = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); widths.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
if (errors.length || widths.some(w => !w.noOverflow)) throw Error('Browser validation failed');
console.log(JSON.stringify({ cascade: true, save: true, reset_descendants: true, widths, javascript_errors: errors.length }));
} finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
+36
View File
@@ -0,0 +1,36 @@
// Read-only checks against the local public portal and real reference names.
const base = 'http://127.0.0.1:8000';
const provinces = await (await fetch(`${base}/api/v1/investment/territory-options?type=province`)).json();
if (provinces.data.length !== 11 || provinces.data.some(p => /^\d+$/.test(p.name))) throw Error('Province designations invalid');
const province = provinces.data.find(p => p.name === 'Zambezia');
if (!province) throw Error('Expected source designation missing');
const result = await (await fetch(`${base}/api/v1/investment/search?province_id=${province.id}`)).json();
if (result.total < 1) throw Error('Existing opportunities not linked to province');
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).json();
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise(resolve => ws.addEventListener('open', resolve, { once: true }));
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Network.requestWillBeSent' && message.params.request.url.includes('/oportunidades?')) console.log(message.params.request.url); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => { const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (response.exceptionDetails) throw Error(JSON.stringify(response.exceptionDetails)); return response.result?.value; };
const wait = async expression => { for (let i = 0; i < 100; i++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 150)); } throw Error('Timed out: '+expression); };
const element = label => `document.getElementById([...document.querySelectorAll('label')].find(l=>l.textContent===${JSON.stringify(label)})?.htmlFor)`;
try {
await send('Runtime.enable'); await send('Page.enable'); await send('Network.enable');
await send('Page.navigate', { url: `${base}/oportunidades` });
await wait(`${element('Província')}?.options.length===12`);
await evaluate(`(()=>{const e=${element('Província')};Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(e,${JSON.stringify(province.id)});e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await wait(`${element('Distrito')}?.options.length>1`);
const districtNames = await evaluate(`[...${element('Distrito')}.options].slice(1).map(o=>o.textContent)`);
if (districtNames.some(n => /^\d+$/.test(n))) throw Error('District designations invalid');
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent.trim()==='Aplicar filtros').click()`);
await wait(`location.search.includes('province_id=') && ${element('Província')}?.value===${JSON.stringify(province.id)}`);
await send('Page.reload');
await wait(`${element('Província')}?.value===${JSON.stringify(province.id)} && ${element('Distrito')}?.options.length>1`);
const layouts = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); layouts.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
if (errors.length || layouts.some(l=>!l.noOverflow)) throw Error('Browser check failed');
console.log(JSON.stringify({ named_provinces: 11, named_district_options: districtNames.length, matching_opportunities: result.total, persisted_url_filter: true, layouts, javascript_errors: errors.length }));
} catch (error) { console.log(JSON.stringify(await evaluate(`({url:location.href,alerts:[...document.querySelectorAll('[role="alert"]')].map(e=>e.textContent),selected:[...document.querySelectorAll('select')].map(e=>e.value)})`))); throw error; } finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }