Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
276d833a4b | ||
|
|
5d45541a11 | ||
|
|
066707ece6 | ||
|
|
c1f4a71963 | ||
|
|
cf2ddf21a1 | ||
|
|
3fd5128c62 | ||
|
|
cdf8fcfba4 |
@@ -61,8 +61,15 @@ class InvestmentPortfolioController extends Controller
|
||||
{
|
||||
$management = $request->routeIs('management.portfolio*');
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'kind' => ['nullable', 'in:corridor,cluster,project'],
|
||||
'sector' => ['nullable', 'string', 'max:500'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
|
||||
$query = $management ? InvestmentDossier::query() : self::visible();
|
||||
$sectorOptions = ($management ? InvestmentDossier::query() : self::visible())
|
||||
->whereNotNull('content->sector')->get()->pluck('content.sector')
|
||||
->filter(fn ($sector) => is_string($sector) && trim($sector) !== '')->unique()->sort()->values();
|
||||
if (! empty($filters['sector'])) {
|
||||
$query->where('content->sector', $filters['sector']);
|
||||
}
|
||||
if (! empty($filters['kind'])) {
|
||||
$query->whereNotNull($filters['kind'].'_id');
|
||||
}
|
||||
@@ -76,7 +83,7 @@ class InvestmentPortfolioController extends Controller
|
||||
}
|
||||
|
||||
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(),
|
||||
'management' => $management, 'filters' => $filters, 'territorySelection' => $territorySelection]);
|
||||
'management' => $management, 'filters' => $filters, 'sectors' => $sectorOptions, 'territorySelection' => $territorySelection]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id): Response
|
||||
@@ -137,6 +144,13 @@ class InvestmentPortfolioController extends Controller
|
||||
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
|
||||
}
|
||||
|
||||
public function resumeInterest(Request $request, string $id): RedirectResponse
|
||||
{
|
||||
self::visible()->findOrFail($id);
|
||||
$data = $request->validate(['catalogue_query' => ['nullable', 'string', 'max:4000']]);
|
||||
return redirect('/carteira/'.$id.'?'.http_build_query([...$data, 'prepare_interest' => '1']));
|
||||
}
|
||||
|
||||
public function save(Request $request, InvestmentDossier $dossier): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'title' => ['required', 'string', 'max:255'], 'source' => ['required', 'string', 'max:2000'],
|
||||
|
||||
@@ -19,12 +19,21 @@ class InvestmentTerritoryController extends Controller
|
||||
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
||||
$profile = $request->is('minhas-oportunidades/*');
|
||||
$management = $request->is('management/*') || $profile;
|
||||
$actor = $request->user();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
// The general consumers use this same endpoint while authenticated.
|
||||
// Reuse the read access already granted by the private cadastral routes.
|
||||
$profileAccess = $actor && $actor->hasVerifiedEmail()
|
||||
&& ($access->grants($actor) !== [] || $access->superuser($actor));
|
||||
$internal = $profileAccess || ($actor?->hasVerifiedEmail() && $actor->can('manage-portal'));
|
||||
if ($management) {
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($profile ? ($access->grants($request->user()) !== [] || $access->superuser($request->user())) : $request->user()?->can('manage-portal'), 403);
|
||||
abort_unless($profile ? $profileAccess : $internal, 403);
|
||||
}
|
||||
|
||||
return response()->json(app(TerritoryGeometry::class)->context($data['territory_id'], $management));
|
||||
return response()->json([
|
||||
...app(TerritoryGeometry::class)->context($data['territory_id'], $internal),
|
||||
'geometry_scope' => $internal ? 'authorized_internal' : 'public',
|
||||
])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
|
||||
|
||||
@@ -103,12 +103,17 @@ final class InvestorContextController extends Controller
|
||||
if ($kept && ($kept['territory']['key'] ?? null) !== ($entry['territory']['key'] ?? null)) $differences[] = ['title'=>$entry['opportunity']['title'],'saved'=>$kept['territory']['title']??'Por definir','requested'=>$entry['territory']['title']??'Por definir'];
|
||||
}
|
||||
$complements = isset($draft['complements']) ? app(\App\Services\InvestmentComplements::class)->resolve($draft['complements'], $data['context']['complements'] ?? []) : ($data['context']['complements'] ?? []);
|
||||
$entryTerritory = null;
|
||||
if (($source['kind'] ?? null) === 'portfolio') {
|
||||
$path = app(InvestmentGeography::class)->selection($r->validate(['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid']));
|
||||
if ($path) $entryTerritory = $context->reference('territory:'.$path[array_key_last($path)]->id);
|
||||
}
|
||||
foreach ($this->entryComplements($r) as $entry) {
|
||||
$tag = 'complement:'.hash('sha256', $entry['key'].'@'.($selectionKey ?? ''));
|
||||
$entrySources[] = $tag;
|
||||
if (!in_array($tag, $draft['entry_sources'] ?? [], true)) $complements = collect([...$complements, $entry])->unique('key')->values()->all();
|
||||
}
|
||||
return Inertia::render('investor-path/context', ['entryComplements' => $complements, 'entryLocationDifferences'=>$differences,'entrySources'=>$entrySources,'draft' => $draft, 'requestedChoices' => $choices, 'initial' => $data, 'options' => $context->options(), 'source' => $source, 'territorySelection' => isset($data['context']['selection']['territory']) ? app(InvestmentGeography::class)->path($data['context']['selection']['territory']['id']) : []]);
|
||||
return Inertia::render('investor-path/context', ['entryTerritory' => $entryTerritory, 'entryComplements' => $complements, 'entryLocationDifferences'=>$differences,'entrySources'=>$entrySources,'draft' => $draft, 'requestedChoices' => $choices, 'initial' => $data, 'options' => $context->options(), 'source' => $source, 'territorySelection' => isset($data['context']['selection']['territory']) ? app(InvestmentGeography::class)->path($data['context']['selection']['territory']['id']) : ($entryTerritory ? app(InvestmentGeography::class)->path($entryTerritory['id']) : [])]);
|
||||
}
|
||||
|
||||
public function preview(Request $r, string $id, InvestorContext $context)
|
||||
@@ -125,9 +130,16 @@ final class InvestorContextController extends Controller
|
||||
{
|
||||
$d = $r->validate(['source' => 'nullable|string|max:100', 'step' => ['nullable', 'regex:/^S(0[1-9]|1[0-9])$/']]);
|
||||
$ref = isset($d['source']) ? $context->reference($d['source']) : null;
|
||||
$submissionId = $r->validate(['submission' => 'nullable|uuid'])['submission'] ?? null;
|
||||
$entrySubmission = null;
|
||||
if ($submissionId) {
|
||||
$submission = \App\Models\InvestmentSubmission::where('id', $submissionId)->where('user_id', $r->user()->id)->where('status', 'draft')->firstOrFail();
|
||||
abort_unless(($ref['kind'] ?? null) === 'portfolio' && $submission->dossier_id === $ref['id'], 422, 'Conserve a ficha de origem da manifestação.');
|
||||
$entrySubmission = ['id' => $submission->id, 'version' => $submission->version];
|
||||
}
|
||||
|
||||
$choices = $this->entryChoices($r, $context);
|
||||
return Inertia::render('investor-path/context-start', ['entryComplements' => $this->entryComplements($r), 'entryQuery' => $r->only(['complement_origin', 'complement_code', 'complement_target', 'complement_territory', 'from_dossier', 'province_id', 'district_id', 'admin_post_id', 'locality_id']), 'opportunityChoices' => $choices, 'contexts' => $path->contexts($r->user()), 'source' => $ref, 'step' => $d['step'] ?? null]);
|
||||
return Inertia::render('investor-path/context-start', ['entrySubmission' => $entrySubmission, 'entryComplements' => $this->entryComplements($r), 'entryQuery' => $r->only(['complement_origin', 'complement_code', 'complement_target', 'complement_territory', 'from_dossier', 'province_id', 'district_id', 'admin_post_id', 'locality_id']), 'opportunityChoices' => $choices, 'contexts' => $path->contexts($r->user()), 'source' => $ref, 'step' => $d['step'] ?? null]);
|
||||
}
|
||||
|
||||
public function installation(Request $r, InvestorContextInstallation $install)
|
||||
|
||||
@@ -14,12 +14,13 @@ final class EnsureScopedPortalAdministration
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
abort_unless($actor, 403);
|
||||
abort_unless($actor !== null, 403);
|
||||
$scope = app(ScopedPortalAdministration::class);
|
||||
$path = $request->path();
|
||||
$interests = $request->is('management/interests', 'management/interests/*', 'api/v1/investment/admin/interests/*');
|
||||
// Fiscal maintenance reuses authorised administration; unrelated gates remain unchanged.
|
||||
$catalogue = $request->is('management/territory-geometry-import', 'management/territory-geometry-import/*',
|
||||
$geometryRead = $request->isMethod('GET') && $path === 'management/territory-geometries';
|
||||
$catalogue = $geometryRead || $request->is('management/territory-geometry-import', 'management/territory-geometry-import/*',
|
||||
'management/economic-references/lot-01', 'management/economic-references/lot-01/*',
|
||||
'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*',
|
||||
'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*',
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Public read projection authorized by Tempo; source rows and originals stay private. */
|
||||
class ApprovedAdministrativeBoundaries
|
||||
{
|
||||
public const HASH = '06ab905fcf9b19115c3521bf81de03f37873880f7765f229b9e1f79d99df7adc';
|
||||
|
||||
/** @var array<string,array<string,string>>|null */
|
||||
private ?array $items = null;
|
||||
|
||||
/** @return array<string,array<string,string>> */
|
||||
public function snapshots(): array
|
||||
{
|
||||
if ($this->items !== null) {
|
||||
return $this->items;
|
||||
}
|
||||
$contents = file_get_contents(base_path('docs/investmoz/unification/approved-administrative-boundaries-20261024.json'));
|
||||
if ($contents === false || ! hash_equals(self::HASH, hash('sha256', str_replace("\r\n", "\n", $contents)))) {
|
||||
throw new RuntimeException('Approved administrative boundary manifest changed.');
|
||||
}
|
||||
$manifest = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($manifest['items']) !== 408) {
|
||||
throw new RuntimeException('Exact 408-boundary scope required.');
|
||||
}
|
||||
$this->items = array_column($manifest['items'], null, 'id');
|
||||
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
public function allows(string $id, string $territoryId, string $geometryHash, string $propertiesHash): bool
|
||||
{
|
||||
$item = $this->snapshots()[$id] ?? null;
|
||||
|
||||
return $item !== null && $item['territory_id'] === $territoryId
|
||||
&& hash_equals($item['geometry_sha256'], $geometryHash)
|
||||
&& hash_equals($item['properties_sha256'], $propertiesHash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/** Exact replay of the 28 accepted links into the transported project identities. */
|
||||
final class ApprovedAnchorTerritories
|
||||
{
|
||||
public const HASH = 'd2893d0a638d630435aca1890f79a8094dc58eb65bbdd65a470bb685fa075190';
|
||||
|
||||
/** @return array{manifest_sha256:string,projects:list<array<string,mixed>>,links:list<array<string,mixed>>} */
|
||||
public function plan(): array
|
||||
{
|
||||
$file = base_path('docs/investmoz/unification/approved-anchor-territories-20261023.json');
|
||||
$contents = is_file($file) ? file_get_contents($file) : false;
|
||||
if ($contents !== false) {
|
||||
$contents = str_replace("\r\n", "\n", $contents);
|
||||
}
|
||||
if ($contents === false || ! hash_equals(self::HASH, hash('sha256', $contents))) {
|
||||
throw new RuntimeException('Reviewed territorial manifest changed.');
|
||||
}
|
||||
$manifest = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($manifest['items']) !== 28) {
|
||||
throw new RuntimeException('Exact 28-link scope required.');
|
||||
}
|
||||
$projects = [];
|
||||
$links = [];
|
||||
foreach ($manifest['items'] as $item) {
|
||||
$project = DB::table('projects')->where('id', $item['project_id'])->whereNull('deleted_at')->first();
|
||||
$dossier = DB::table('investment_dossiers')->where('id', $item['dossier_id'])->whereNull('deleted_at')->first();
|
||||
if (! $project || $project->code !== $item['code'] || ! $dossier || $dossier->project_id !== $project->id
|
||||
|| ! hash_equals($item['content_sha256'], hash('sha256', $dossier->content))
|
||||
|| ! hash_equals($item['source_sha256'], hash('sha256', $dossier->source))) {
|
||||
throw new RuntimeException('Project identity or documentary source changed: '.$item['code']);
|
||||
}
|
||||
$original = $item['original_relation'];
|
||||
$geo = DB::table('geo_locations')->where('id', $original['geo_location_id'])->whereNull('deleted_at')->first();
|
||||
foreach (['location_type', 'source_code', 'parent_id', 'data_classification'] as $field) {
|
||||
if (! $geo || $item['territory'][$field] !== $geo->$field) {
|
||||
throw new RuntimeException('Territory identity changed: '.$original['geo_location_id']);
|
||||
}
|
||||
}
|
||||
$metadata = $projects[$project->id]['after_metadata'] ?? json_decode($project->metadata, true, 512, JSON_THROW_ON_ERROR);
|
||||
$key = $geo->id.':'.$original['role'];
|
||||
$evidence = $item['evidence'];
|
||||
// Preserve the original dossier id in evidence and explicitly map the destination.
|
||||
$evidence['transported_dossier_id'] = $dossier->id;
|
||||
if (isset($metadata['documented_location_sources'][$key]) && $metadata['documented_location_sources'][$key] != $evidence) {
|
||||
throw new RuntimeException('Existing territorial evidence differs; no overwrite: '.$item['code']);
|
||||
}
|
||||
$projects[$project->id] ??= ['id' => $project->id, 'code' => $project->code, 'before_version' => (int) $project->version_no, 'before_metadata' => json_decode($project->metadata, true, 512, JSON_THROW_ON_ERROR)];
|
||||
$metadata['documented_location_sources'][$key] = $evidence;
|
||||
$projects[$project->id]['after_metadata'] = $metadata;
|
||||
$existing = DB::table('project_locations')->where('project_id', $project->id)->where('geo_location_id', $geo->id)->where('role', $original['role'])->first();
|
||||
if ($existing && ($existing->deleted_at || $existing->data_classification !== 'public')) {
|
||||
throw new RuntimeException('Archived or restricted territorial relation must not be revived.');
|
||||
}
|
||||
$identity = DB::table('project_locations')->where('id', $original['id'])->first();
|
||||
if ($identity && (! $existing || $identity->id !== $existing->id)) {
|
||||
throw new RuntimeException('Historical relation identity is already occupied.');
|
||||
}
|
||||
$links[] = ['code' => $item['code'], 'already_present' => (bool) $existing, 'row' => [...$original, 'project_id' => $project->id]];
|
||||
}
|
||||
|
||||
return ['manifest_sha256' => self::HASH, 'projects' => array_values($projects), 'links' => $links];
|
||||
}
|
||||
|
||||
/** Caller supplies an authenticated, backed-up transaction; no source publication changes.
|
||||
* @param array{manifest_sha256:string,projects:list<array<string,mixed>>,links:list<array<string,mixed>>} $plan
|
||||
* @return array<string,int>
|
||||
*/
|
||||
public function apply(array $plan): array
|
||||
{
|
||||
if (DB::transactionLevel() < 1 || $this->plan() !== $plan) {
|
||||
throw new RuntimeException('Reviewed transaction and unchanged preview required.');
|
||||
}
|
||||
$inserted = 0;
|
||||
$updated = 0;
|
||||
foreach ($plan['projects'] as $project) {
|
||||
if ($project['before_metadata'] == $project['after_metadata']) {
|
||||
continue;
|
||||
}
|
||||
$count = DB::table('projects')->where('id', $project['id'])->where('version_no', $project['before_version'])->update([
|
||||
'metadata' => json_encode($project['after_metadata'], JSON_THROW_ON_ERROR), 'version_no' => $project['before_version'] + 1, 'updated_at' => now(),
|
||||
]);
|
||||
if ($count !== 1) {
|
||||
throw new RuntimeException('Concurrent project change.');
|
||||
}
|
||||
DB::table('audit_events')->insert(['source_system' => 'approved-anchor-territories-recovery-v1', 'external_id' => self::HASH.':'.$project['id'], 'entity_type' => 'projects', 'entity_id' => $project['id'], 'action' => 'accepted_territories_restored',
|
||||
'data_classification' => 'public', 'before_data' => json_encode(['version_no' => $project['before_version'], 'metadata' => $project['before_metadata']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['version_no' => $project['before_version'] + 1, 'manifest_sha256' => self::HASH, 'metadata' => $project['after_metadata'], 'new_approval' => false], JSON_THROW_ON_ERROR)]);
|
||||
$updated++;
|
||||
}
|
||||
foreach ($plan['links'] as $link) {
|
||||
if ($link['already_present']) {
|
||||
continue;
|
||||
}
|
||||
DB::table('project_locations')->insert($link['row']);
|
||||
$inserted++;
|
||||
}
|
||||
|
||||
return ['relations_restored' => $inserted, 'projects_updated' => $updated, 'new_dossiers' => 0, 'publication_changes' => 0];
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,7 @@ final class InvestorContext
|
||||
|
||||
public function dependencyHash(array $selection): string
|
||||
{
|
||||
unset($selection['portfolio'], $selection['selection']['portfolio']);
|
||||
if (isset($selection['opportunity_choices'])) $selection['opportunity_choices'] = array_map(fn($choice)=>Arr::except($choice,['portfolio_origins']),$selection['opportunity_choices']);
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($selection), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
@@ -168,6 +169,18 @@ final class InvestorContext
|
||||
if ($o->primary_territory_id) {
|
||||
$fields = [...$fields, ...$this->territoryFields($o->primary_territory_id)];
|
||||
}
|
||||
} elseif ($kind === 'portfolio') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$dossier = \App\Http\Controllers\InvestmentPortfolioController::visible()->findOrFail($id);
|
||||
$title = $dossier->title;
|
||||
$href = '/carteira/'.$id;
|
||||
// Documentary coverage is not the investor's chosen implantation.
|
||||
$version = DB::table('investment_dossiers')->where('id', $id)->value('version_no');
|
||||
$fields = ['project_title' => $title, 'project_summary' => $dossier->content['description'] ?? $dossier->content['focus'] ?? ''];
|
||||
$state = 'documented_origin';
|
||||
$zoneAnalysis = ['source' => $dossier->source, 'documented_sector' => $dossier->content['sector'] ?? null,
|
||||
'documented_location' => $dossier->content['location'] ?? $dossier->content['region'] ?? null,
|
||||
'geography' => app(InvestmentRelations::class)->dossier($dossier), 'available_opportunity' => false];
|
||||
} elseif ($kind === 'business') {
|
||||
abort_unless(config('existing-business.enabled') && Str::isUuid($id), 404);
|
||||
$o = ExistingBusiness::published()->with('sector')->findOrFail($id);
|
||||
@@ -354,7 +367,7 @@ final class InvestorContext
|
||||
'opportunity_choices.*.park' => 'sometimes|nullable|string|max:100',
|
||||
'opportunity_choices.*.source' => 'required|string|distinct|max:100', 'opportunity_choices.*.territory' => 'nullable|string|max:100',
|
||||
'opportunity_choices.*.location_reason' => 'nullable|string|max:2000', 'opportunity_choices.*.confirm_location_change' => 'sometimes|boolean',
|
||||
'version' => 'required|integer|min:1', 'selection' => 'present|array:opportunity,sector,territory,park',
|
||||
'version' => 'required|integer|min:1', 'selection' => 'present|array:portfolio,opportunity,sector,territory,park',
|
||||
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:project_title,project_summary,currency,expected_start_date,investor_origin,person_type,entity_stage,tax_residency_country,fiscal_residency_country,project_type,maturity_stage,'.implode(',', PrivateInvestmentPreparation::FIELDS), 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
|
||||
'declarations.currency' => 'nullable|regex:/^[A-Z]{3}$/', 'declarations.expected_start_date' => 'nullable|date_format:Y-m-d', 'declarations.investor_origin' => 'nullable|in:national,foreign,mixed', 'declarations.person_type' => 'nullable|in:singular,collective,sole_trader,consortium', 'declarations.entity_stage' => 'nullable|in:existing,being_formed', 'declarations.tax_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.fiscal_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.project_type' => 'nullable|string|max:100', 'declarations.maturity_stage' => 'nullable|string|max:100',
|
||||
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
|
||||
@@ -432,7 +445,7 @@ final class InvestorContext
|
||||
}
|
||||
$proposed = [];
|
||||
$origins = [];
|
||||
foreach (['opportunity', 'sector', 'park', 'territory'] as $slot) {
|
||||
foreach (['portfolio', 'opportunity', 'sector', 'park', 'territory'] as $slot) {
|
||||
if (in_array($slot, ['park', 'territory'], true) && array_intersect(array_keys($selection[$slot]['fields'] ?? []), array_keys(InvestmentGeography::FIELDS))) {
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'] as $key) {
|
||||
unset($proposed[$key],$origins[$key]);
|
||||
@@ -484,7 +497,7 @@ final class InvestorContext
|
||||
$replaced[] = ['field' => $key, 'before' => $old['fields'][$key] ?? null, 'after' => $fields[$key] ?? null];
|
||||
}
|
||||
}
|
||||
foreach (['opportunity', 'sector', 'territory', 'park'] as $slot) {
|
||||
foreach (['portfolio', 'opportunity', 'sector', 'territory', 'park'] as $slot) {
|
||||
if (($old['selection'][$slot] ?? null) !== ($selection[$slot] ?? null)) {
|
||||
$changed[] = $slot;
|
||||
}
|
||||
@@ -657,6 +670,7 @@ final class InvestorContext
|
||||
$sim['context_applicability_snapshot'] = json_encode([
|
||||
'version' => 1, 'context_revision' => $ctx['revision'],
|
||||
'consumer_opportunity' => $ctx['consumer_opportunity']['opportunity']['key'] ?? null,
|
||||
'portfolio_origin' => $ctx['selection']['portfolio'] ?? null,
|
||||
'zone' => $zone ? Arr::only($zone, ['id', 'title', 'href', 'version', 'sha256', 'fields', 'analysis']) : null,
|
||||
'provenance' => $ctx['provenance'],
|
||||
'opportunity_choices' => $ctx['opportunity_choices'] ?? [],
|
||||
|
||||
@@ -14,16 +14,31 @@ final class TerritoryGeometry
|
||||
abort_unless($geography->references($management)->where('id', $id)->exists(), 404);
|
||||
$path = $geography->path($id, $management);
|
||||
$ids = array_map(fn ($node) => $node->id, $path);
|
||||
$approved = app(ApprovedAdministrativeBoundaries::class);
|
||||
$rows = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id')
|
||||
->whereIn('g.geo_location_id', $ids)->whereNull('g.deleted_at')->whereNull('l.deleted_at')
|
||||
->whereIn('g.data_classification', $management ? ['internal', 'public'] : ['public'])
|
||||
->where(function ($query) use ($management, $approved) {
|
||||
$query->where('g.data_classification', 'public');
|
||||
$query->orWhere(function ($internal) use ($management, $approved) {
|
||||
$internal->where('g.data_classification', 'internal');
|
||||
if (! $management) {
|
||||
$internal->whereIn('g.id', array_keys($approved->snapshots()));
|
||||
}
|
||||
});
|
||||
})
|
||||
->whereRaw("g.properties->>'purpose' = 'administrative_boundary'")
|
||||
->whereIn('g.geometry_type', ['polygon', 'multipolygon'])
|
||||
->whereRaw('ST_IsValid(g.geom) AND NOT ST_IsEmpty(g.geom) AND ST_SRID(g.geom)=4326')
|
||||
->orderBy('g.geo_location_id')->orderBy('g.id')->limit(101)
|
||||
->get(['g.id', 'g.geo_location_id', 'l.name', 'l.location_type', 'g.properties', 'g.data_classification',
|
||||
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry')]);
|
||||
$areas = $rows->take(100)->map(function ($row) use ($id) {
|
||||
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry'),
|
||||
DB::raw("encode(sha256(ST_AsEWKB(g.geom)),'hex') as geometry_sha256"),
|
||||
DB::raw("encode(sha256(convert_to(g.properties::text,'UTF8')),'hex') as properties_sha256")]);
|
||||
if (! $management) {
|
||||
$rows = $rows->filter(fn ($row) => $row->data_classification === 'public'
|
||||
|| $approved->allows($row->id, $row->geo_location_id, $row->geometry_sha256, $row->properties_sha256))->values();
|
||||
}
|
||||
$areas = $rows->take(100)->map(function ($row) use ($id, $management) {
|
||||
$source = json_decode($row->properties, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return ['id' => $row->id, 'territory_id' => $row->geo_location_id, 'location_type' => $row->location_type,
|
||||
@@ -31,7 +46,7 @@ final class TerritoryGeometry
|
||||
'title' => 'Limite administrativo: '.$row->name, 'purpose' => 'administrative_boundary',
|
||||
'source_reference' => $source['authority'] ?? null, 'source_date' => $source['source_version'] ?? null,
|
||||
'source_url' => $source['source_url'] ?? null, 'source_sha256' => $source['source_sha256'] ?? null,
|
||||
'data_classification' => $row->data_classification, 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
|
||||
'data_classification' => $management ? $row->data_classification : 'public', 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
|
||||
})->all();
|
||||
|
||||
return ['territory_id' => $id, 'territory_registered' => true,
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
{
|
||||
"status": "installed_in_homologation_territories_recovered_delta_verified",
|
||||
"date": "2026-10-23",
|
||||
"base": "8036b9b0",
|
||||
"accepted_delivery_receipt": "cdf8fcfb",
|
||||
"active_comparison": {
|
||||
"database": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432,
|
||||
"role": "teste_investidor_app"
|
||||
},
|
||||
"read_only": "on",
|
||||
"published_fiches": 29,
|
||||
"cluster_relations": 13,
|
||||
"project_locations": 0,
|
||||
"RLS": [
|
||||
{
|
||||
"relname": "projects",
|
||||
"relrowsecurity": false,
|
||||
"relforcerowsecurity": false
|
||||
},
|
||||
{
|
||||
"relname": "project_locations",
|
||||
"relrowsecurity": false,
|
||||
"relforcerowsecurity": false
|
||||
},
|
||||
{
|
||||
"relname": "cluster_projects",
|
||||
"relrowsecurity": false,
|
||||
"relforcerowsecurity": false
|
||||
},
|
||||
{
|
||||
"relname": "investment_dossiers",
|
||||
"relrowsecurity": false,
|
||||
"relforcerowsecurity": false
|
||||
},
|
||||
{
|
||||
"relname": "opportunity_projects",
|
||||
"relrowsecurity": false,
|
||||
"relforcerowsecurity": false
|
||||
}
|
||||
],
|
||||
"missing_accepted_locations": 28,
|
||||
"source_inventory": "inventory-20261007-172113.json",
|
||||
"cause_scope": "Transported project identities omit accepted territorial rows and citation metadata; visibility recovery only restored publication status. Exact event/time not established."
|
||||
},
|
||||
"qa_recovery": {
|
||||
"mode": "applied",
|
||||
"database": "simulator_fiscal_delta_20261021_test",
|
||||
"port": 55441,
|
||||
"qa": true,
|
||||
"manifest_sha256": "dc3ae2014da51005d95780e2e4ae87e55e000e66e0765f0671c6e44a958026a0",
|
||||
"preview_sha256": "601a8603cf39f51a22cef9195e238a21c1552cb3303672b78ec52826c6342b57",
|
||||
"relations": 28,
|
||||
"projects": 13,
|
||||
"relations_restored": 28,
|
||||
"projects_updated": 13,
|
||||
"new_dossiers": 0,
|
||||
"publication_changes": 0
|
||||
},
|
||||
"tests": {
|
||||
"php": {
|
||||
"tests": 4,
|
||||
"assertions": 116,
|
||||
"passed": 4
|
||||
},
|
||||
"frontend": {
|
||||
"tests": 2,
|
||||
"passed": 2
|
||||
},
|
||||
"typescript": "passed",
|
||||
"build": "passed",
|
||||
"phpstan_new_recovery_service": "passed, zero errors"
|
||||
},
|
||||
"backup": {
|
||||
"stage": "/var/backups/investmoz-anchor-integration-20261023/backup",
|
||||
"target": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432
|
||||
},
|
||||
"tables": 174,
|
||||
"files_verified": 369,
|
||||
"dump_sha256": "207ff14c6af7c4b2dd280def898945cb58314e01930b51c50d502e95cbe6ac68",
|
||||
"files_sha256": "8cd85ab7d5a772452111e4fe7feab48f7fc694ee3f0fbd264f50096254835fe2",
|
||||
"restore_verified": false
|
||||
},
|
||||
"isolated_restore": {
|
||||
"restore_verified": true,
|
||||
"tables_verified": 174,
|
||||
"container_network": "none",
|
||||
"database": "anchor_restore_20261023",
|
||||
"port": 55441,
|
||||
"source_dump_sha256": "207ff14c6af7c4b2dd280def898945cb58314e01930b51c50d502e95cbe6ac68",
|
||||
"active_database_writes": 0
|
||||
},
|
||||
"preserved_closures": [
|
||||
"6b544548",
|
||||
"d8224ba8",
|
||||
"55136b44",
|
||||
"8036b9b0"
|
||||
],
|
||||
"not_repeated": [
|
||||
"native saved PDF",
|
||||
"Word",
|
||||
"ZIP",
|
||||
"accepted portfolio via opportunity branch",
|
||||
"accepted complements and four consumers"
|
||||
],
|
||||
"deferred": [
|
||||
"statistics",
|
||||
"AI"
|
||||
],
|
||||
"pending": [],
|
||||
"screenshots": [
|
||||
"outputs/anchor-integration-20261023/qa-sector-location.png",
|
||||
"outputs/anchor-integration-20261023/qa-anchor-fiche.png",
|
||||
"outputs/anchor-integration-20261023/qa-anchor-dossier.png",
|
||||
"outputs/anchor-integration-20261023/qa-anchor-simulator.png",
|
||||
"outputs/anchor-integration-20261023/homologation-sector-location.png",
|
||||
"outputs/anchor-integration-20261023/homologation-anchor-fiche.png"
|
||||
],
|
||||
"visual_QA": {
|
||||
"anchor_code": "A06",
|
||||
"anchor_fiche": "57a4ee7a-4c07-4e26-b8f5-e07726e41512",
|
||||
"case_id": "3fd1bac6-80cf-48c8-97f3-eb4bb3398a17",
|
||||
"simulation_draft_id": "bbc9ae3d-8c0e-45d2-b93f-9eaa85bab4d4",
|
||||
"sector": "Agronegócio",
|
||||
"province": "Sofala",
|
||||
"offer_invented": false,
|
||||
"deliberate_title_preserved": true,
|
||||
"source_link_visible_in_dossier_and_simulator": true,
|
||||
"manifestation": "HTTP directed proof, including ownership, same-source identity and versioned binding; browser native confirmation cancelled after control timeout; no formal submission"
|
||||
},
|
||||
"served_commit": "cf2ddf21a1457f4852fe6aa10069ec3b854f1567",
|
||||
"functional_commits": [
|
||||
"3fd5128c",
|
||||
"cf2ddf21"
|
||||
],
|
||||
"installation": {
|
||||
"service": "ExecMainStatus=0\nActiveState=inactive\nSubState=dead\n",
|
||||
"installed": {
|
||||
"status": "installed",
|
||||
"commit": "cf2ddf21a1457f4852fe6aa10069ec3b854f1567",
|
||||
"release": "/var/www/investmoz-homologacao/releases/cf2ddf21a1457f4852fe6aa10069ec3b854f1567-7749f82e",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/3fd5128c62296bc5c85dcd19f1458a7949de5784-803cd41e",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0
|
||||
},
|
||||
"latest_report": {
|
||||
"status": "installed",
|
||||
"commit": "cf2ddf21a1457f4852fe6aa10069ec3b854f1567",
|
||||
"release": "/var/www/investmoz-homologacao/releases/cf2ddf21a1457f4852fe6aa10069ec3b854f1567-7749f82e",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/3fd5128c62296bc5c85dcd19f1458a7949de5784-803cd41e",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"cf2ddf21a1457f4852fe6aa10069ec3b854f1567"
|
||||
],
|
||||
"finished_at": "2026-10-23T17:21:57.897758+00:00"
|
||||
},
|
||||
"log_file": "1792776037181186915.log",
|
||||
"summaries": [
|
||||
"OK (1 test, 3106 assertions)",
|
||||
"built in 24.44s",
|
||||
"OK (57 tests, 309 assertions)",
|
||||
"# tests 216",
|
||||
"# pass 216",
|
||||
"# fail 0"
|
||||
],
|
||||
"log_bytes": 92267
|
||||
},
|
||||
"recovery_preview": {
|
||||
"mode": "preview",
|
||||
"database": "teste_investidor",
|
||||
"port": 5432,
|
||||
"qa": false,
|
||||
"manifest_sha256": "d2893d0a638d630435aca1890f79a8094dc58eb65bbdd65a470bb685fa075190",
|
||||
"preview_sha256": "f59e324222ea480d176f1e8e6ae164efa184904c8244873d3fcf6af8497e0dac",
|
||||
"relations": 28,
|
||||
"projects": 13
|
||||
},
|
||||
"recovery_applied": {
|
||||
"mode": "applied",
|
||||
"database": "teste_investidor",
|
||||
"port": 5432,
|
||||
"qa": false,
|
||||
"manifest_sha256": "d2893d0a638d630435aca1890f79a8094dc58eb65bbdd65a470bb685fa075190",
|
||||
"preview_sha256": "f59e324222ea480d176f1e8e6ae164efa184904c8244873d3fcf6af8497e0dac",
|
||||
"relations": 28,
|
||||
"projects": 13,
|
||||
"relations_restored": 28,
|
||||
"projects_updated": 13,
|
||||
"new_dossiers": 0,
|
||||
"publication_changes": 0
|
||||
},
|
||||
"installed_delta": {
|
||||
"published_fiches": 29,
|
||||
"territorial_links": 28,
|
||||
"affected_projects": 13,
|
||||
"cluster_relations": 13,
|
||||
"dossier_rows_unchanged": true,
|
||||
"clusters_corridors_opportunity_relations_unchanged": true,
|
||||
"historical_territorial_link_identities_preserved": true,
|
||||
"only_project_metadata_version_timestamp_changed": true,
|
||||
"functional_file_hashes_match_Git": {
|
||||
"app/Http/Controllers/InvestmentPortfolioController.php": true,
|
||||
"app/Http/Controllers/InvestorContextController.php": true,
|
||||
"app/Services/ApprovedAnchorTerritories.php": true,
|
||||
"app/Services/InvestorContext.php": true,
|
||||
"resources/js/lib/investor-context.ts": true,
|
||||
"resources/js/lib/project-dossier-report.ts": true,
|
||||
"resources/js/lib/search-territory.ts": true,
|
||||
"resources/js/pages/investment/submission.tsx": true,
|
||||
"resources/js/pages/investor-path/context-start.tsx": true,
|
||||
"resources/js/pages/investor-path/context.tsx": true,
|
||||
"resources/js/pages/investor-path/show.tsx": true,
|
||||
"resources/js/pages/portfolio/index.tsx": true,
|
||||
"resources/js/pages/portfolio/show.tsx": true,
|
||||
"routes/web.php": true,
|
||||
"tools/restore-approved-anchor-territories.php": true
|
||||
},
|
||||
"pipeline_summaries": [
|
||||
"OK (1 test, 3106 assertions)",
|
||||
"built in 24.44s",
|
||||
"OK (57 tests, 309 assertions)",
|
||||
"# tests 216",
|
||||
"# pass 216",
|
||||
"# fail 0"
|
||||
],
|
||||
"table_preservation": {
|
||||
"tables": 174,
|
||||
"changed_tables": {
|
||||
"audit_events": {
|
||||
"before": {
|
||||
"rows": 632,
|
||||
"checksum": "d4f2e8b30c014080b33a588eb0d8afe2"
|
||||
},
|
||||
"after": {
|
||||
"rows": 645,
|
||||
"checksum": "88c2047620eb3fad4d2a2837ed3daef5"
|
||||
}
|
||||
},
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 104,
|
||||
"checksum": "463aff806806b9fa2e4dff3310f516ec"
|
||||
},
|
||||
"after": {
|
||||
"rows": 104,
|
||||
"checksum": "4963d5a25fecf3352cf0d7aee73a1e63"
|
||||
}
|
||||
},
|
||||
"project_locations": {
|
||||
"before": {
|
||||
"rows": 0,
|
||||
"checksum": "d41d8cd98f00b204e9800998ecf8427e"
|
||||
},
|
||||
"after": {
|
||||
"rows": 28,
|
||||
"checksum": "80b4e44b11208a023fcfb989e738b95a"
|
||||
}
|
||||
},
|
||||
"projects": {
|
||||
"before": {
|
||||
"rows": 16,
|
||||
"checksum": "af127d727cfc1050c26b99130e397109"
|
||||
},
|
||||
"after": {
|
||||
"rows": 16,
|
||||
"checksum": "17fb48a69b09e1e8ec81b0d30e29ce80"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 11,
|
||||
"checksum": "912e728cc332bfc41a7e0f94c84e118d"
|
||||
},
|
||||
"after": {
|
||||
"rows": 15,
|
||||
"checksum": "713242c22c549258fab61d1b9cd993ef"
|
||||
}
|
||||
}
|
||||
},
|
||||
"unchanged_tables": 169
|
||||
},
|
||||
"exact_29_approved_fiche_identities_preserved": true,
|
||||
"synthetic_fiches_transported": 0
|
||||
},
|
||||
"Git_preservation": {
|
||||
"accepted_base_receipt": "cdf8fcfb",
|
||||
"previous_installed": "8036b9b0",
|
||||
"candidate": "cf2ddf21a1457f4852fe6aa10069ec3b854f1567",
|
||||
"protected_files_unchanged": {
|
||||
"app/Services/InvestmentComplements.php": true,
|
||||
"app/Services/InvestmentConsumerScope.php": true,
|
||||
"app/Services/InvestorPath.php": true,
|
||||
"app/Services/SimulationFormDrafts.php": true,
|
||||
"resources/js/components/investment-complements.tsx": true,
|
||||
"resources/js/components/dossier-prefill.tsx": true,
|
||||
"resources/js/components/investment-requirements.tsx": true
|
||||
},
|
||||
"matrix_changed_rows_since_accepted_receipt": [
|
||||
"AUD-REL-02",
|
||||
"AUD-LEG-06"
|
||||
],
|
||||
"other_matrix_records_preserved": 3421,
|
||||
"accepted_receipt_updates_preserved": [
|
||||
"AUD-SIM-INT03",
|
||||
"AUD-SIM-INT06"
|
||||
],
|
||||
"schema_migrations_added": [],
|
||||
"stats_AI_code_changed": false,
|
||||
"force_push": false
|
||||
},
|
||||
"manifest_verification": {
|
||||
"Git_LF_sha256": "d2893d0a638d630435aca1890f79a8094dc58eb65bbdd65a470bb685fa075190",
|
||||
"initial_QA_Windows_bytes_sha256": "dc3ae2014da51005d95780e2e4ae87e55e000e66e0765f0671c6e44a958026a0",
|
||||
"canonicalization": "CRLF to LF only; identical JSON and accepted relations",
|
||||
"first_active_preview": "refused before writes; corrected canonical preview and apply succeeded"
|
||||
},
|
||||
"next": "Tempo final navigation and presentation evaluation",
|
||||
"not_a_claim_of_complete_transversal_implementation": true,
|
||||
"installed_public_delta": {
|
||||
"catalogue": "https://teste-investidor.tempo.co.mz/carteira?kind=project§or=Agro-ind%C3%BAstria%20e%20agricultura&province_id=f57ff041-6275-57b9-8800-c35e46e0d475",
|
||||
"results": 1,
|
||||
"fiche": "57a4ee7a-4c07-4e26-b8f5-e07726e41512",
|
||||
"source": "portfolio:57a4ee7a-4c07-4e26-b8f5-e07726e41512",
|
||||
"territories_visible": 4,
|
||||
"search_return_preserves_filters": true,
|
||||
"preparation_GET_same_identity_and_province": true,
|
||||
"homologation_test_dossiers_or_submissions_created": 0
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"date": "2026-10-23",
|
||||
"status": "executable_in_isolated_QA_not_deployed",
|
||||
"status": "installed_in_homologation_delta_verified",
|
||||
"functional_commit": "1afdfee8",
|
||||
"base": "bc84fbdb",
|
||||
"accepted_deliveries_preserved": [
|
||||
@@ -79,5 +79,11 @@
|
||||
"path": "outputs/multi-opportunity-fix-20261023/treatment-exports/second-print.html",
|
||||
"sha256": "dffff89a9d4f186698bbc077a8a5031bd95290e12bcdba7b00ec7cd1a095bc4a"
|
||||
}
|
||||
]
|
||||
],
|
||||
"installation": {
|
||||
"status": "installed_in_homologation_delta_verified",
|
||||
"commit": "8036b9b071229dbf7e85ea748db70abcbeefc379",
|
||||
"receipt": "treatment-scope-installation-receipt-20261023.json",
|
||||
"delta_verified": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
{
|
||||
"scope": "Shared administrative maps stabilization",
|
||||
"source_revision": "cf2ddf21",
|
||||
"candidate": "066707ec",
|
||||
"owner_decision": "Tempo 2026-10-24: public consultation of the exact accepted administrative contours; originals private, no parcels or other internal layers",
|
||||
"diagnosis": {
|
||||
"data_loss": false,
|
||||
"common_consumers": "Public-only filter excluded all 408 internal administrative boundaries",
|
||||
"administration": "Legacy manage-portal gate excluded both approved superusers",
|
||||
"comparison": "No change in common geometry service/controller/components between 30aed7cd and cf2ddf21",
|
||||
"base_map": "Provider tiles and served assets respond; browser framing is checked after installation"
|
||||
},
|
||||
"qa": {
|
||||
"database": "simulator_fiscal_delta_20261021_test",
|
||||
"port": 55441,
|
||||
"tests": 6,
|
||||
"assertions": 64,
|
||||
"result": "passed",
|
||||
"phpstan": "passed",
|
||||
"writes": "Only isolated QA transactions, rolled back"
|
||||
},
|
||||
"baseline": {
|
||||
"published_fiches": 29,
|
||||
"territorial_relations": 28,
|
||||
"geometries": 408,
|
||||
"geometry_rows_checksum": "7d8b71d3e65d89ffdc43c748b0572dbc"
|
||||
},
|
||||
"backup": {
|
||||
"tables": 174,
|
||||
"files_verified": 369,
|
||||
"restore_tables_verified": 174,
|
||||
"restore_network": "none",
|
||||
"dump_sha256": "2fb5b4488799bb6072c38ee41ccf91fc2a55561363c19e280ab066363d9e0647"
|
||||
},
|
||||
"public_manifest_sha256": "06ab905fcf9b19115c3521bf81de03f37873880f7765f229b9e1f79d99df7adc",
|
||||
"installed": {
|
||||
"status": "installed",
|
||||
"commit": "066707ece631f0a7c963031c211844fbdd68916b",
|
||||
"release": "/var/www/investmoz-homologacao/releases/066707ece631f0a7c963031c211844fbdd68916b-6b7bb5bd",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/cf2ddf21a1457f4852fe6aa10069ec3b854f1567-7749f82e",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0
|
||||
},
|
||||
"deferred": [
|
||||
"Statistics",
|
||||
"AI"
|
||||
],
|
||||
"accepted_tests_repeated": false,
|
||||
"public_projection": {
|
||||
"available": 408,
|
||||
"levels": {
|
||||
"admin_post": 264,
|
||||
"district": 133,
|
||||
"province": 11
|
||||
},
|
||||
"failures": [],
|
||||
"manifest_sha256": "06ab905fcf9b19115c3521bf81de03f37873880f7765f229b9e1f79d99df7adc"
|
||||
},
|
||||
"preservation": {
|
||||
"tables": 174,
|
||||
"changed_tables": {
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 104,
|
||||
"checksum": "5d172b4d252c7b025f23ac70cf570cb6"
|
||||
},
|
||||
"after": {
|
||||
"rows": 104,
|
||||
"checksum": "a60f3e47e1ae28937404f05f45e33135"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 6,
|
||||
"checksum": "dcdb7eba3f3e8f29f40ec3f7542be6ce"
|
||||
},
|
||||
"after": {
|
||||
"rows": 7,
|
||||
"checksum": "0059c0b0e16d532c6658fd420582f2e9"
|
||||
}
|
||||
}
|
||||
},
|
||||
"unchanged_tables": 172
|
||||
},
|
||||
"installed_file_sha256": {
|
||||
"app/Services/ApprovedAdministrativeBoundaries.php": "401fd62795ca8f33106be6e07130d9207d6661695440bfc40f62f6f6b42bec64",
|
||||
"app/Services/TerritoryGeometry.php": "00ce3e6dde92868b0d34b963b8e59a26e6663149cdc0398c645ef636ca382966",
|
||||
"app/Http/Controllers/InvestmentTerritoryController.php": "3b184c6ea1b97f0abe86d01567d3d73444c49192c638478a6d53619e63d5d18d",
|
||||
"app/Http/Middleware/EnsureScopedPortalAdministration.php": "1474db760f6bd6003a5325ae721698e90e2709a2354b51abde77f920a9dad81a",
|
||||
"docs/investmoz/unification/approved-administrative-boundaries-20261024.json": "06ab905fcf9b19115c3521bf81de03f37873880f7765f229b9e1f79d99df7adc"
|
||||
},
|
||||
"pipeline_summaries": [
|
||||
"OK (1 test, 3106 assertions)",
|
||||
"built in 24.58s",
|
||||
"OK (57 tests, 309 assertions)",
|
||||
"# tests 216",
|
||||
"# pass 216",
|
||||
"# fail 0"
|
||||
],
|
||||
"proofs": {
|
||||
"anonymous_http": {
|
||||
"status": 200,
|
||||
"territory_id": "dd219b89-cc17-5944-8c7d-d2766c82b526",
|
||||
"selected": "DONDO",
|
||||
"ancestor": "Sofala",
|
||||
"areas": 2
|
||||
},
|
||||
"browser": {
|
||||
"province_to_district": "passed",
|
||||
"framing": "selected district with ancestor context",
|
||||
"reload_preserves_selection": true,
|
||||
"zoom": "passed",
|
||||
"visible_tiles_loaded": 36,
|
||||
"visible_tiles_failed": 0,
|
||||
"screenshot": "outputs/map-stabilization-20261024/dondo-installed.png",
|
||||
"screenshot_sha256": "7569f3b66aceb7ef9816c31bfaa172ebcdfa10e4911961b67a129a654b5cd349"
|
||||
},
|
||||
"business_rows_unchanged": true,
|
||||
"active_synthetic_requests_created": 0
|
||||
},
|
||||
"status": "installed_delta_verified",
|
||||
"remaining_in_scope": []
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"date": "2026-10-23",
|
||||
"candidate": "1afdfee8",
|
||||
"native_report_fix": "2856240c",
|
||||
"deployment_status": "native_saved_PDF_verified_ready_for_authorised_Git_delivery",
|
||||
"deployment_status": "installed_in_homologation_delta_verified",
|
||||
"origin_main_checked": "55136b44",
|
||||
"accepted_scopes_retested": false,
|
||||
"new_test": "tests/frontend/native-pdf-scope.test.mjs: 1 passed",
|
||||
@@ -52,5 +52,12 @@
|
||||
"inventory_sha256": "7d2c0c36fa51b05ce97dfd25c997b77eccf7136a99220ed8607fcd2436fd3d39",
|
||||
"no_homologation_loss_inferred": true
|
||||
},
|
||||
"statistics_and_AI": "deferred"
|
||||
"statistics_and_AI": "deferred",
|
||||
"installation": {
|
||||
"status": "installed_in_homologation_delta_verified",
|
||||
"commit": "8036b9b071229dbf7e85ea748db70abcbeefc379",
|
||||
"receipt": "treatment-scope-installation-receipt-20261023.json",
|
||||
"delta_verified": true
|
||||
},
|
||||
"status": "installed_in_homologation_delta_verified"
|
||||
}
|
||||
|
||||
@@ -35,8 +35,9 @@
|
||||
"number": 3,
|
||||
"component": "Navegação contextual e manifestação de interesse",
|
||||
"historic_status": "Disponível",
|
||||
"current_preservation_status": "Navegação/percurso preservados; carteira documental reposta em 23/10: 29 dossiers, incluindo 15 projectos âncora.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/investimentos/iniciar) · Início, contexto e navegação abrem; gravação/recuperação aceites em QA reutilizadas. Sem dossier real no destino."
|
||||
"current_preservation_status": "Continuity and multi-opportunity consumers delivered: 55136b44, 8036b9b0, cf2ddf21. Accepted proofs preserved.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/investimentos/iniciar) · Início, contexto e navegação abrem; gravação/recuperação aceites em QA reutilizadas. Sem dossier real no destino.",
|
||||
"status_before_stabilization_closure": "Navegação/percurso preservados; carteira documental reposta em 23/10: 29 dossiers, incluindo 15 projectos âncora."
|
||||
},
|
||||
{
|
||||
"number": 4,
|
||||
@@ -175,8 +176,9 @@
|
||||
"number": 23,
|
||||
"component": "Cartografia e consumidores territoriais restantes",
|
||||
"historic_status": "Não demonstrado",
|
||||
"current_preservation_status": "Demarcação reposta: 408 geometrias. Polígonos de localidades e correspondências já pendentes não são nova regressão.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/oportunidades) · Catálogos/mapas abrem. 1 921 referências geográficas no alvo versus 1 990 locais; diferença não reconciliada por item fora do manifesto."
|
||||
"current_preservation_status": "Shared maps delivered 066707ec/5d45541a: 408 accepted contours publicly available; originals private, 29 fiches and 28 relations preserved. Missing locality polygons remain future work.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/oportunidades) · Catálogos/mapas abrem. 1 921 referências geográficas no alvo versus 1 990 locais; diferença não reconciliada por item fora do manifesto.",
|
||||
"status_before_stabilization_closure": "Demarcação reposta: 408 geometrias. Polígonos de localidades e correspondências já pendentes não são nova regressão."
|
||||
},
|
||||
{
|
||||
"number": 24,
|
||||
@@ -210,8 +212,9 @@
|
||||
"number": 28,
|
||||
"component": "Pesquisa — estados do recorte R2",
|
||||
"historic_status": "Disponível",
|
||||
"current_preservation_status": "Pesquisa e selectores corrigidos em 22/10; a carteira vazia é tratada como perda separada.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/oportunidades) · Catálogos abrem; quatro estados e protecção contra respostas antigas preservados do R2, sem repetir ensaios aceites."
|
||||
"current_preservation_status": "Accepted search/selectors preserved; portfolio visibility and anchor continuity restored and delivered cf2ddf21. No current portfolio-empty fault.",
|
||||
"evidence": "[Abrir](https://teste-investidor.tempo.co.mz/oportunidades) · Catálogos abrem; quatro estados e protecção contra respostas antigas preservados do R2, sem repetir ensaios aceites.",
|
||||
"status_before_stabilization_closure": "Pesquisa e selectores corrigidos em 22/10; a carteira vazia é tratada como perda separada."
|
||||
},
|
||||
{
|
||||
"number": 29,
|
||||
@@ -945,5 +948,79 @@
|
||||
"new_roles_or_approvers": false,
|
||||
"new_content_approval": false
|
||||
},
|
||||
"qa_recovery_preparation_note": "An initial QA audit-key collision rolled back atomically. Audit identity was scoped per original before the successful QA and destination recovery; no active attempt used the faulty key."
|
||||
"qa_recovery_preparation_note": "An initial QA audit-key collision rolled back atomically. Audit identity was scoped per original before the successful QA and destination recovery; no active attempt used the faulty key.",
|
||||
"stabilization_closure_20261024": {
|
||||
"basis": "Tempo explicit sequence and technical preservation responsibility, 24/10/2026",
|
||||
"installed_functional_baseline": "066707ece631f0a7c963031c211844fbdd68916b",
|
||||
"map_receipt": "5d45541a",
|
||||
"known_open_faults_in_delimited_stabilization_scope": [],
|
||||
"does_not_close_all_43_components": true,
|
||||
"prior_losses_do_not_share_a_proven_single_cause": true,
|
||||
"accepted_closures": [
|
||||
"6b544548/4098192a",
|
||||
"d8224ba8/af926180",
|
||||
"55136b44/b6a626c9",
|
||||
"8036b9b0/cdf8fcfb",
|
||||
"cf2ddf21/c1f4a719",
|
||||
"066707ec/5d45541a"
|
||||
],
|
||||
"documentary_limits": [
|
||||
"Six legacy opportunity/anchor-cluster pairs without documented identity remain indeterminate: AUD-REL-02",
|
||||
"Two incomplete legacy originals retain their existing documentary limit"
|
||||
],
|
||||
"not_yet_proven_component_numbers": [
|
||||
6,
|
||||
18,
|
||||
21,
|
||||
22,
|
||||
24,
|
||||
25,
|
||||
35
|
||||
],
|
||||
"future_requirement_ids": [
|
||||
"AUD-MARKET-01",
|
||||
"AUD-ESTABLISHMENT-01",
|
||||
"AUD-FUND-01",
|
||||
"AUD-COMPANY-01",
|
||||
"AUD-COMPANY-02",
|
||||
"AUD-CAPITAL-01",
|
||||
"AUD-CAPITAL-02",
|
||||
"AUD-FINTECH-01"
|
||||
],
|
||||
"territorial_count_reconciliation": {
|
||||
"source": "outputs/preservation-inventory-20261023/local.json and homologation.json",
|
||||
"public_active_local": 1921,
|
||||
"public_active_target": 1921,
|
||||
"local_archived_internal_groups": [
|
||||
32,
|
||||
32,
|
||||
5
|
||||
],
|
||||
"individual_identity_comparison_of_archived_69_claimed": false,
|
||||
"reactivation_authorized": false
|
||||
},
|
||||
"new_control": {
|
||||
"test": "tests/Unit/ApprovedAdministrativeBoundariesTest.php",
|
||||
"automatic_delivery_suite": "Unit",
|
||||
"tests": 2,
|
||||
"assertions": 8,
|
||||
"result": "passed",
|
||||
"scope": "Approved public snapshot identity; changed geometry/metadata, wrong territory and new internal identity rejected",
|
||||
"http_access_contract": "tests/Feature/TerritoryGeometryConsumerAccessTest.php",
|
||||
"http_contract_run_when": "Geometry/access/hierarchy changes, on isolated QA only; existing accepted result reused here"
|
||||
},
|
||||
"technical_preservation_owner": "Codex and programmers",
|
||||
"Tempo_review": "Utility, clarity and presentation; no obligation to rediscover technical regressions",
|
||||
"sequence": [
|
||||
"Corrections and stabilization",
|
||||
"Fiscal simulator with defined scope",
|
||||
"Real estate",
|
||||
"Consumer goods and franchises",
|
||||
"Statistics and dashboards",
|
||||
"AI"
|
||||
],
|
||||
"accepted_acceptance_tests_repeated": false,
|
||||
"active_database_writes": 0,
|
||||
"runtime_application_source_changes": 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,73 @@
|
||||
# Rastreabilidade, utilização e formação
|
||||
|
||||
## Fecho do lote de estabilização e sequência de referência — 24/10/2026
|
||||
|
||||
**Ordem expressa da Tempo:** (1) correcções e estabilização; (2) simulador fiscal com âmbito definido; (3) Imobiliário; (4) Bens de consumo e franquias; (5) Estatística e painéis; (6) IA. A preservação técnica é responsabilidade do Codex e dos programadores. A Tempo avalia utilidade, clareza e apresentação; não tem de redescobrir regressões para comprovar preservação.
|
||||
|
||||
Consolidação sobre a revisão instalada `066707ec`, recibo `5d45541a`, mantendo a mesma matriz e o inventário dos 43 componentes. Nesta passagem não foi encontrada nova falha executável nos recortes de estabilização já delimitados. A revisão de código confirma que a primeira oportunidade usada na migração do contexto comum não substitui o âmbito dos consumidores: `InvestmentConsumerScope` filtra a escolha antes do snapshot e dos relatórios. Não foram repetidas as provas aceites, impressões, submissões ou alterações de dados. A confirmação da Tempo anterior baseou-se no relatório comunicado, sem conferência do recibo local; não é registada como uma nova prova técnica ou visual.
|
||||
|
||||
| Situação no lote | Percursos e saldo concreto |
|
||||
| --- | --- |
|
||||
| Resolvido e entregue | Gravação/idioma, proveniência do relatório e Beira/sete oportunidades: `6b544548`/`4098192a`. Complementos: `d8224ba8`/`af926180`. Zonas/parques, Terra/DUAT, Balcão e manifestação por oportunidade: `55136b44`/`b6a626c9`. Selector do simulador, etapas/requisitos e pedido Terra correcto, incluindo PDF guardado: `8036b9b0`/`cdf8fcfb`. Âncoras, sector/localização e continuidade: `cf2ddf21`/`c1f4a719`. Mapas: `066707ec`/`5d45541a`. Pendências históricas destes trechos ficam superadas pelas respectivas entregas. |
|
||||
| Falha conhecida ainda aberta neste lote | **Nenhuma identificada nos recortes enumerados.** Não equivale a aceitação integral dos 43 componentes ou de todas as variantes do portal. Não se inventa uma nova correcção para justificar outra ronda. |
|
||||
| Pendência documental preservada | `AUD-REL-02`: os pares das seis oportunidades legadas com âncoras/clusters continuam indeterminados quando não há relação documentada. Não confundir com as 28 relações recuperadas dos projectos. Preservar a preparação independente; não associar por proximidade ou nome. Dois originais incompletos do acervo legado conservam o limite documental já registado, sem representar perda causada pelos mapas. |
|
||||
| Ainda sem prova no âmbito próprio | Inventário existente: consolidação de duplicados distintos (componente 6); aplicação/editor e versões de checklists (18); partilha e variantes de sala (21/35); modalidades/SLA e fecho operacional/documental (22/25); acessibilidade além das provas aceites (24). Não foram identificadas novas regressões nesses itens; não os declarar concluídos nem exigir processos reais/sintéticos na homologação para fechar este lote. Mantêm os critérios próprios da matriz, sem atribuição de novo prazo ou prioridade. |
|
||||
| Desenvolvimento futuro, separado de regressões | Negócios similares por raio (`AUD-MARKET-01`), importador de empresas/empreendimentos (`AUD-ESTABLISHMENT-01`), catálogo de fundos (`AUD-FUND-01`), comparador societário e modelos específicos (`AUD-COMPANY-01/02`), guiões de capitalização/Bolsa (`AUD-CAPITAL-01/02`), polígonos próprios ainda inexistentes e enquadramento Fintech específico. Variantes de Imobiliário/franquias, Estatística/painéis e IA seguem a ordem acima; SuiteCRM mantém a opção anterior de desactivação. Não se declara que todo o código destes módulos esteja ausente. |
|
||||
|
||||
**Causas independentes:** os mapas tinham filtro público e dependência de uma permissão antiga; a carteira sofreu perda de visibilidade de registos presentes; as relações de âncoras tinham omissão no transporte entre identidades documentais. As provas delimitam esses casos e não estabelecem a causa de todas as perdas anteriores. O inventário histórico territorial tinha 1 990 linhas locais contra 1 921 no destino: **1 921 públicas activas em ambos, mais 69 internas arquivadas apenas no local**, repartidas em 32+32+5. Isto explica a diferença agregada; não é prova de correspondência individual das 69 nem autoriza reactivá-las. Nenhuma reposição adicional decorre dessa contagem.
|
||||
|
||||
### Controlo técnico nas próximas entregas
|
||||
|
||||
Reutilizar o inventário/recibos e comparar apenas o delta e as dependências afectadas. O pipeline existente conserva detecção de alterações concorrentes na árvore instalada, contrato de schema, QA isolado, assets imutáveis, troca atómica e reversão por falha de saúde. A suite normal de entrega passa também a incluir `ApprovedAdministrativeBoundariesTest`: identidade aceite e recusa de novo contorno interno, território trocado, geometria ou metadados alterados. É controlo novo de âmbito público, não repetição da demonstração visual aceite. As duas provas novas passaram, com oito asserções e sem acesso à base.
|
||||
|
||||
Quando se alterar acesso, hierarquia ou serviço de mapas, executar o delta correspondente de `TerritoryGeometryConsumerAccessTest` em QA isolado; cobre o filtro público e os perfis aprovados sem `manage-portal`, incluindo MFA administrativo. O teste unitário isolado não substitui esse contrato HTTP. Para alterações de contexto, usar os casos afectados de `InvestmentTreatmentScopeTest`, `InvestmentAnchorIntegrationTest` e consumidores/complementos, sem repetir indiscriminadamente toda a suite de aceitação. No destino, comparar identidades/fontes/estado de publicação das 29 fichas, 28 relações e 408 geometrias com os manifestos aceites, configuração e permissões equivalentes; mudanças legítimas posteriores são reconciliadas explicitamente, não sobrescritas. Backup/restauro e acção autenticada precedem qualquer escrita de dados activos.
|
||||
|
||||
**Saldo de fecho:** zero falhas técnicas conhecidas abertas neste lote; limites documentais, itens sem prova e desenvolvimento futuro permanecem identificados acima e nas mesmas linhas da matriz. Não se declara a aplicação transversal integralmente concluída. O próximo lote é a delimitação do simulador fiscal; esta passagem não activa cálculos, fontes, estatísticas ou IA. A avaliação de navegação/apresentação da Tempo pode continuar pelo percurso normal e alimenta apenas falhas concretamente observadas.
|
||||
|
||||
## Mapas — estabilização comum e divulgação delimitada, 24/10/2026
|
||||
|
||||
Diagnóstico por leitura autenticada na homologação `cf2ddf21`: **29 fichas, 28 relações territoriais e 408 geometrias válidas**, sem eliminação. Os 408 limites INE/2019 conservam classificação interna, propósito administrativo e SRID 4326. O fingerprint integral das linhas é `7d8b71d3e65d89ffdc43c748b0572dbc`. Não há RLS nas tabelas comparadas. O serviço comum não mudou desde `30aed7cd`: os consumidores gerais pediam exclusivamente geometrias públicas; o cadastro usava ainda `manage-portal`, ausente nos dois superutilizadores aprovados. A prova anterior demonstrava o cadastro privado, não a divulgação pública. O mapa base, tiles e assets carregam; a resposta territorial vazia explica a ausência de contornos e de enquadramento do território escolhido.
|
||||
|
||||
**Decisão expressa da Tempo nesta passagem:** «Sim, disponibilizar os contornos administrativos aceites». Implementada uma projecção pública de leitura dos [408 snapshots exactos](approved-administrative-boundaries-20261024.json), conferindo identidade e hashes da geometria original e metadados. Não há reimportação, reclassificação de linhas, publicação de parcelas, acesso aos ficheiros originais ou abertura de outras camadas internas. Alterações posteriores não recebem divulgação automática. Os perfis autorizados reutilizam o acesso privado já aprovado; a leitura administrativa conserva MFA. Respostas privadas não são guardadas em cache partilhada.
|
||||
|
||||
QA isolado `simulator_fiscal_delta_20261021_test:55441`: seis testes dirigidos, 64 asserções; selecção, gravação/recuperação no dossier e prefill do simulador com a mesma identidade, leitura pública autorizada, bloqueio de camadas não autorizadas e de snapshots alterados, permissões/MFA e fingerprint original preservado. PHPStan dos quatro ficheiros funcionais passou. Backup fresco: 174 tabelas, 369 ficheiros conferidos; restauro isolado sem rede reproduziu as 174 tabelas.
|
||||
|
||||
**Entregue na homologação em `066707ece631f0a7c963031c211844fbdd68916b`**, por avanço normal do Git, preservando `cf2ddf21` e as alterações concorrentes. Instalador: contrato 1/3106, PHP 57/309, frontend 216/216 e build aprovados; zero migrações e zero importações. Os cinco ficheiros funcionais instalados coincidem com o Git. Consulta pública pelo serviço instalado: **408/408 disponíveis**, 11 províncias, 133 distritos e 264 postos, zero falhas. HTTP anónimo recupera Dondo e Sofala pela identidade canónica, com Dondo seleccionado e Sofala como contexto ancestral. Conferência visual: mudança de província para distrito actualiza o contorno e enquadramento; escolha preservada após recarregar, zoom operacional e 36 tiles carregados sem falha na observação final. Houve falhas transitórias de tiles na janela anterior; os mesmos URLs responderam 200 e o recarregamento recuperou a base, sem alteração de configuração ou fornecedor.
|
||||
|
||||
Comparação das 174 tabelas: **172 iguais por contagem/hash**, diferenças apenas em `cache` e `sessions`; tabelas de negócio, geometrias, permissões e fontes intactas. Conservados 29 fichas, 28 relações e o fingerprint integral das 408 geometrias. Nenhum dossier/pedido sintético criado na homologação. [Recibo da estabilização](map-stabilization-receipt-20261024.json); prova visual em `outputs/map-stabilization-20261024/dondo-installed.png`. O saldo técnico desta reposição está encerrado; a avaliação de navegação e apresentação pela Tempo permanece o próximo trabalho.
|
||||
|
||||
Preservados os fechos `d8224ba8`, `55136b44`, `8036b9b0` e `cf2ddf21`/`c1f4a719`, sem repetição das provas aceites. Localidades sem polígono próprio conservam apenas o contexto ancestral explicitamente identificado; não são inventadas coordenadas ou parcelas. Estatísticas e IA permanecem adiadas. Esta estabilização não declara concluída a aplicação transversal nem substitui a avaliação de navegação e apresentação pela Tempo.
|
||||
|
||||
## Projectos âncora — entregues na homologação em cf2ddf21, 23/10/2026
|
||||
|
||||
Reconciliado o saldo de `6985f82e` com as provas territoriais de 7 de Outubro e os recibos de reposição. A leitura autenticada da homologação, com o papel da aplicação e transacção apenas de leitura, confirmou **29 fichas publicadas, 13 relações de clusters e zero ligações em `project_locations`**. As cinco tabelas comparadas não usam RLS. Os projectos transportados têm identificadores diferentes dos originais e perderam as 28 ligações territoriais e os respectivos metadados de citação; não desapareceram as 29 fichas. A reposição de visibilidade anterior não abrangia estas relações. A comparação delimita a omissão no transporte; não identifica por si só o instante em que ocorreu.
|
||||
|
||||
O [manifesto das 28 relações aceites](approved-anchor-territories-20261023.json) conserva identidades históricas, fontes, citações e papéis primary/secondary/impact, mapeando os projectos e dossiers actuais por identidade documental verificada. A ferramenta `tools/restore-approved-anchor-territories.php` confere hashes, versões, território e prévia; recusa conflitos e exemplares arquivados/restritos; preserva metadados concorrentes, guarda estado anterior e produz auditoria. Não publica fichas nem cria ofertas. Em QA foram repostas 28 relações de 13 projectos; a repetição foi demonstrada sem duplicação. A01/A02 continuam sem implantação individual inventada; Norte da Zambézia conserva o papel de impacto parcial.
|
||||
|
||||
Incrementos: pesquisa explícita pelo sector documental em conjunto com a localização; entrada directa da ficha pública para preparar uma ideia, mesmo sem oportunidade publicada; origem `portfolio:<id>` guardada no dossier e no snapshot/relatório do simulador. A cobertura documental não é atribuída como implantação. A localização explicitamente escolhida na pesquisa acompanha a entrada; uma localização já guardada conserva-se, com divergência explicada. Títulos e dados deliberadamente editados mantêm-se na comparação existente. A retoma autenticada da manifestação conserva a mesma ficha e os filtros e não cria pedidos por GET. A preparação iniciada pela manifestação usa a associação já existente ao dossier, com controlo de proprietário e versões; não submete o pedido.
|
||||
|
||||
Provas dirigidas: `InvestmentAnchorIntegrationTest` (4 casos, 116 asserções) e `anchor-integration.test.mjs` (2 casos); ver [recibo de QA e reconciliação](anchor-integration-receipt-20261023.json). Mantidos os percursos já aceites de carteira → oportunidade associada → dossier/simulador, complementos `d8224ba8`, consumidores `55136b44` e tratamento `8036b9b0`/recibo `cdf8fcfb`. Nenhuma nova impressão de PDF, prova Word/ZIP ou ronda dos fechos aceites. Estatísticas e IA permanecem adiadas.
|
||||
|
||||
**Entregue e delta conferido** na revisão `cf2ddf21a1457f4852fe6aa10069ec3b854f1567`, após integração `3fd5128c` e correcção delimitada da verificação de finais de linha do manifesto entre Windows e Git. A primeira prévia recusou o hash divergente antes de qualquer escrita; a prévia canónica passou. A reposição autenticada recuperou **28 relações em 13 projectos**, com 13 eventos de auditoria, zero novas fichas e zero alterações de publicação. As **29 identidades aprovadas, conteúdos e fontes** permanecem exactamente iguais; preservadas as 13 relações de clusters e os corredores. A comparação das 174 tabelas encontrou 169 iguais por contagem/hash; as diferenças de domínio limitam-se a projectos/metadados, relações territoriais e auditoria; cache e sessões tiveram alterações técnicas. O backup restaurou 174 tabelas iguais numa base isolada sem rede e verificou 369 ficheiros.
|
||||
|
||||
Os 15 ficheiros funcionais instalados coincidem com o Git. Instalador: zero migrações e zero importações automáticas; controlos habituais aprovados (contrato 1/3106, PHP 57/309 e frontend 216/216). Conferência pública apenas do delta: pesquisa A06 por sector documental e Sofala encontra a ficha original; quatro localizações e respectivas fontes recuperadas; retorno conserva filtros; a entrada para preparar ideia usa `portfolio:<id>` e a província escolhida. Nenhum dossier, pedido ou manifestação de ensaio foi criado na homologação. Os ensaios sintéticos continuam exclusivamente em QA.
|
||||
|
||||
**Saldo técnico deste recorte: sem pendências de código, reposição ou disponibilização identificadas.** Segue a avaliação final de navegação e apresentação pela Tempo. Este fecho não declara implementadas funcionalidades futuras nem a conclusão integral da aplicação transversal; Estatísticas e IA continuam adiadas. O inventário e as provas anteriores permanecem preservados, sem nova ronda dos casos aceites.
|
||||
|
||||
## Oportunidade em tratamento — entregue na homologação em 8036b9b0, 23/10/2026
|
||||
|
||||
Concluída a disponibilização autorizada da candidata **`1afdfee8`**, incluindo a correcção delimitada do relatório **`2856240c`**, na revisão instalada **`8036b9b071229dbf7e85ea748db70abcbeefc379`**. Integração normal por fast-forward desde `55136b44`, sem force e sem alterações concorrentes em `main` na conferência prévia. [Recibo de instalação e delta](treatment-scope-installation-receipt-20261023.json).
|
||||
|
||||
O PDF original guardado foi encontrado pelo nome automático na pasta indicada, conferido em texto e nas **dez páginas renderizadas**, sem o regenerar. Conservados nome, bytes e SHA-256 `010eb4ea12015563c1b2f8bc255b1078c276f824c50690732541d5bffe34b8a6`. A revisão 13 contém a segunda oportunidade/Manica, os cinco requisitos específicos e os valores 123456/45678/77 778,00 MZN, com paginação legível. A diferença do nome literal pedido explica o erro anterior de localização; a máquina, conta, sessão e extensão foram confirmadas.
|
||||
|
||||
Instalador: **installed**, conclusão `2026-10-23T16:46:13.798467+00:00`, zero migrations/importações, observador activo e fila vazia. Revisão pública confirmou `8036b9b0`, build `16:46:11.203132 UTC`, manifesto SHA-256 `6021421c4ab12146c5fae9c8966e3dae5c8bd1361132e12184e65e00b7e8951e`. Os **15 ficheiros funcionais** afectados coincidem por hash com os blobs Git instalados. Os controlos automáticos do instalador passaram; não se repetiu a ronda manual de provas aceites.
|
||||
|
||||
**Delta instalado conferido por leitura autenticada:** ficha real **Florestas — Corredor da Beira**, oportunidade **53**, dossier existente `958df138-7980-4685-8389-fa90be02ed6b`. Novas ligações Simular/Etapas transportam a mesma chave; selector do dossier mostra 53/Sofala; atalhos preservam o âmbito. GET do contexto devolve `consumer_opportunity=opportunity:53`, snapshot apenas dessa oportunidade e dos seus requisitos. A decisão existente «Não precisa de terra» conserva a dispensa da acção no dossier observado. Versão do dossier **5**, igual ao recibo anterior; não foram criados, gravados ou submetidos pedidos no destino, nem aberta a edição do rascunho privado do simulador. As provas positivas de dois pedidos/duas oportunidades feitas em QA são reutilizadas, sem as reproduzir na homologação.
|
||||
|
||||
Complementos `d8224ba8`, fechos `6b544548`/`4098192a` e quatro consumidores `55136b44`/`b6a626c9` preservados; nenhuma fixture sintética, alteração de schema/configuração/permissões, Estatísticas ou IA integra este transporte. Mantidas todas as identidades da matriz e as linhas alheias. O recibo posterior fica na branch de trabalho, sem provocar outra instalação apenas documental.
|
||||
|
||||
**Saldo corrente:** esta frente está **entregue na homologação**, com PDF e delta instalados conferidos. A frente dos projectos âncora mantém a análise `6985f82e`: filtro sectorial e ideia directa sem oferta por implementar; reconciliação territorial entre ambientes e prova dirigida de interesse/autenticação por concluir. Não é declarado fecho global do percurso nem realizada antecipadamente a avaliação final pela Tempo. As indicações de «QA», «aguarda PDF» ou «não entregue» nas passagens históricas seguintes estão superadas apenas para este recorte.
|
||||
|
||||
## PDF nativo guardado — conferência concluída, 23/10/2026
|
||||
|
||||
Conferido o ficheiro **existente**, sem regenerar o PDF ou repetir Word/ZIP/provas aceites: `outputs/multi-opportunity-fix-20261023/Relatório — SYNTHETIC QA - escolha comum aos tres consumidores.pdf`. A pasta era a indicada; o nome foi o título automático do navegador, não `candidata-1afdfee8.pdf`. Leitura na máquina **ONALA**, utilizador **macbook**, sessão **Console**; extensão real `.pdf`, 191637 bytes. O erro anterior era «Cannot find path … candidata-1afdfee8.pdf … because it does not exist» para esse nome literal; a listagem da mesma pasta encontrou o original. Não houve renomeação, cópia nem mudança de máquina.
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
{
|
||||
"status": "installed_in_homologation_delta_verified",
|
||||
"date": "2026-10-23",
|
||||
"target": "https://teste-investidor.tempo.co.mz",
|
||||
"served_commit": "8036b9b071229dbf7e85ea748db70abcbeefc379",
|
||||
"functional_commits": [
|
||||
"1afdfee8",
|
||||
"2856240c"
|
||||
],
|
||||
"previous_main": "55136b446deb710adf58ce2460e571bb19e94375",
|
||||
"public_revision": {
|
||||
"commit": "8036b9b071229dbf7e85ea748db70abcbeefc379",
|
||||
"branch": "main",
|
||||
"built_at": "2026-10-23T16:46:11.203132+00:00",
|
||||
"manifest_sha256": "6021421c4ab12146c5fae9c8966e3dae5c8bd1361132e12184e65e00b7e8951e"
|
||||
},
|
||||
"installer": {
|
||||
"status": "installed",
|
||||
"commit": "8036b9b071229dbf7e85ea748db70abcbeefc379",
|
||||
"release": "/var/www/investmoz-homologacao/releases/8036b9b071229dbf7e85ea748db70abcbeefc379-5e851af2",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/55136b446deb710adf58ce2460e571bb19e94375-cad6589e",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"8036b9b071229dbf7e85ea748db70abcbeefc379"
|
||||
],
|
||||
"finished_at": "2026-10-23T16:46:13.798467+00:00"
|
||||
},
|
||||
"pipeline_summaries": [
|
||||
"OK (1 test, 3106 assertions)",
|
||||
"built in 24.30s",
|
||||
"OK (57 tests, 309 assertions)",
|
||||
"# tests 214",
|
||||
"# pass 214",
|
||||
"# fail 0"
|
||||
],
|
||||
"preservation": {
|
||||
"fast_forward": true,
|
||||
"force": false,
|
||||
"protected_files": {
|
||||
"app/Services/InvestmentComplements.php": true,
|
||||
"resources/js/components/investment-complements.tsx": true,
|
||||
"docs/investmoz/unification/continuity-corrections-installation-receipt-20261023.json": true
|
||||
},
|
||||
"matrix_changed_rows": [
|
||||
"AUD-REL-02",
|
||||
"AUD-LEG-06",
|
||||
"AUD-SIM-INT03",
|
||||
"AUD-SIM-INT06"
|
||||
],
|
||||
"unrelated_matrix_records_preserved": 3419,
|
||||
"schema_config_fixtures_shipped": false
|
||||
},
|
||||
"native_saved_pdf": {
|
||||
"actual_file": "C:\\laragon\\www\\portal-investidor\\outputs\\multi-opportunity-fix-20261023\\Relatório — SYNTHETIC QA - escolha comum aos tres consumidores.pdf",
|
||||
"sha256": "010eb4ea12015563c1b2f8bc255b1078c276f824c50690732541d5bffe34b8a6",
|
||||
"pages": 10,
|
||||
"revision": 13,
|
||||
"checks": {
|
||||
"second_opportunity": true,
|
||||
"manica": true,
|
||||
"land_requirement": true,
|
||||
"sector_requirement": true,
|
||||
"human_state": true,
|
||||
"technical_state_absent": true,
|
||||
"first_location_absent": true,
|
||||
"total": true,
|
||||
"secured": true,
|
||||
"gap": true
|
||||
},
|
||||
"visual_review": {
|
||||
"status": "passed",
|
||||
"pages_inspected": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
10
|
||||
],
|
||||
"pagination": "1/10 through 10/10; A4; repeated table headers; no clipped rows or visible overlaps",
|
||||
"last_page": "sparse final page contains final source rows and annex statement; not blank"
|
||||
},
|
||||
"discovery": {
|
||||
"machine": "ONALA",
|
||||
"user": "macbook",
|
||||
"session": "Console",
|
||||
"extension": ".pdf",
|
||||
"size_bytes": 191637,
|
||||
"requested_basename_not_found": "candidata-1afdfee8.pdf",
|
||||
"actual_basename": "Relatório — SYNTHETIC QA - escolha comum aos tres consumidores.pdf",
|
||||
"resolution": "existing file discovered by listing the exact requested directory; no rename, copy or PDF regeneration"
|
||||
},
|
||||
"regenerated": false
|
||||
},
|
||||
"installed_delta": {
|
||||
"real_opportunity": 53,
|
||||
"scope": {
|
||||
"case_id": "958df138-7980-4685-8389-fa90be02ed6b",
|
||||
"case_version": 5,
|
||||
"context_revision": 1,
|
||||
"simulator_opportunity": "opportunity:53",
|
||||
"snapshot_choices": [
|
||||
"opportunity:53"
|
||||
],
|
||||
"snapshot_territory": "Sofala",
|
||||
"land_need": "no",
|
||||
"land_step": {
|
||||
"code": "S10",
|
||||
"title": "Regularização da terra",
|
||||
"state": "dispensed",
|
||||
"applicability": "not_needed_for_preparation",
|
||||
"reason": "",
|
||||
"context_review_required": true
|
||||
},
|
||||
"requirements_scopes": [
|
||||
"opportunity:53"
|
||||
]
|
||||
},
|
||||
"checks": [
|
||||
"new fiche links preserve opportunity53",
|
||||
"dossier explicitly selects same opportunity and keeps tool query scope",
|
||||
"authenticated context GET returns canonical simulator opportunity53 and its own requirements",
|
||||
"existing no-land decision hides land action in the inspected dossier",
|
||||
"15 changed functional file hashes equal Git release sources"
|
||||
],
|
||||
"case_version_unchanged_from_prior_receipt": true,
|
||||
"requests_created_updated_submitted": 0,
|
||||
"accepted_business_tests_repeated": false,
|
||||
"qa_second_opportunity_cases_reused": true
|
||||
},
|
||||
"remaining_scope": {
|
||||
"anchors": "analysis6985f82e: two implementation gaps, territorial reconciliation and directed interest/authentication proof; not implemented by this delivery",
|
||||
"statistics_and_AI": "deferred"
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/integration-preservation.json",
|
||||
"sha256": "c6fcae5f64986d13216948589a35d1fa2d9f62229f4bd7a8a8c9f559f463fd6b"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installer-status.json",
|
||||
"sha256": "f7875ffe9fa47092e5f0288ecbd97f4f016413628b2faed6815977287c26461e"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/public-revision.json",
|
||||
"sha256": "23325ab4cce9fced625b237c9793e3af309d923f12abbd047de96670611c8cac"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installed-hashes.json",
|
||||
"sha256": "91f9df68c0d3b9c0ace6948145362f303291c5698bb2594bff9bb9c3aabc159c"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installed-links.json",
|
||||
"sha256": "bf73f59ecfaccf8d10f45a72c36bd684e1b12abb667a65e0d2cda4dd396eb324"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installed-scope-summary.json",
|
||||
"sha256": "fd410fa10ee63b8c09c311530cab78ca4f1f2b961c3d31cc78c40b86bc7af255"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installed-dossier.txt",
|
||||
"sha256": "b5577b82ad0bce03131ffddbc365f1d039229549d6b83227ad57baffd1037f07"
|
||||
},
|
||||
{
|
||||
"path": "outputs/treatment-install-20261023/installed-dossier.png",
|
||||
"sha256": "9a3133a9fb6ca11fc64e0681393d518676bb72bceb75bfc95950466271158509"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -34,6 +34,7 @@ export type ContextReference = {
|
||||
version: number | string | null;
|
||||
sha256: string;
|
||||
fields: Record<string, string>;
|
||||
analysis?: {documented_sector?: string | null; documented_location?: string | null; [key:string]:unknown};
|
||||
documents?: ContextDocument[];
|
||||
visibility?: 'private' | 'public';
|
||||
state?: string | null;
|
||||
@@ -63,7 +64,7 @@ export type DossierContext = {
|
||||
revision: number;
|
||||
selection: Partial<
|
||||
Record<
|
||||
'opportunity' | 'sector' | 'territory' | 'park',
|
||||
'portfolio' | 'opportunity' | 'sector' | 'territory' | 'park',
|
||||
ContextReference
|
||||
>
|
||||
>;
|
||||
|
||||
@@ -285,6 +285,7 @@ function makeSections(
|
||||
);
|
||||
if (context.version === 1) {
|
||||
const section = sections.get('sources');
|
||||
if (context.portfolio_origin) section?.rows.push({field:'Projecto ou carteira de origem', value:context.portfolio_origin.title, origin:`${context.portfolio_origin.key}; versão ${context.portfolio_origin.version}; ${context.portfolio_origin.href}`, classification:'Origem documental; localização e oferta não presumidas'});
|
||||
if (context.consumer_opportunity) section?.rows.push({field:'Oportunidade em tratamento', value:context.consumer_opportunity, origin:context.opportunity_choices?.[0]?.opportunity?.title ?? 'Escolha guardada no dossier', classification:'Âmbito desta análise'});
|
||||
for (const step of context.path?.steps ?? []) {
|
||||
if (step.applicability === 'not_needed_for_preparation') section?.paragraphs.push(`${step.code} — preparação não necessária neste âmbito: ${step.reason || 'Decisão guardada do promotor'}. Histórico conservado; não constitui dispensa legal.`);
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
const levels = ['province_id', 'district_id', 'admin_post_id', 'locality_id'];
|
||||
const searchRoutes = ['/carteira', '/oportunidades', '/zonas', '/educacao'];
|
||||
|
||||
/** Keep search geography explicit; a documentary origin is never an invented offer. */
|
||||
export function portfolioPreparationHref(id: string, pageUrl: string): string {
|
||||
const source = new URL(pageUrl, 'https://portal.invalid');
|
||||
const inherited = source.searchParams.has('catalogue_query') ? new URLSearchParams(source.searchParams.get('catalogue_query')!) : source.searchParams;
|
||||
const query = new URLSearchParams({source: `portfolio:${id}`});
|
||||
for (const field of levels) if (inherited.get(field)) query.set(field, inherited.get(field)!);
|
||||
return '/investimentos/iniciar?' + query.toString();
|
||||
}
|
||||
|
||||
/** Preserve an explicit complementary selection while consulting its canonical public fiche. */
|
||||
export function complementPreparationHref(pageUrl: string, target?: string): string | null {
|
||||
const params = new URL(pageUrl, 'https://portal.invalid').searchParams;
|
||||
|
||||
@@ -82,6 +82,7 @@ type Props = {
|
||||
version: number;
|
||||
payload: Partial<Payload>;
|
||||
opportunity_id?: number | null;
|
||||
dossier_id?: string | null;
|
||||
status: string;
|
||||
};
|
||||
references: References;
|
||||
@@ -395,6 +396,7 @@ function Editor({
|
||||
dossier. Associar reutiliza o contexto autorizado;
|
||||
campos já editados conservam-se.
|
||||
</p>
|
||||
{s.dossier_id && <p><Link className="underline" href={'/investimentos/iniciar?source=' + encodeURIComponent('portfolio:' + s.dossier_id) + '&submission=' + encodeURIComponent(s.id)}>Preparar investimento com a ficha de origem</Link>. A manifestação ficará ligada ao dossier que escolher.</p>}
|
||||
<label className="grid gap-1">
|
||||
Dossier autorizado para esta manifestação
|
||||
<select
|
||||
|
||||
@@ -12,6 +12,7 @@ export default function ContextStart({
|
||||
step = null,
|
||||
entryQuery = {},
|
||||
entryComplements = [],
|
||||
entrySubmission = null,
|
||||
}: {
|
||||
contexts: { id: string; title: string; version: number }[];
|
||||
source: ContextReference | null;
|
||||
@@ -19,6 +20,7 @@ export default function ContextStart({
|
||||
step?: string | null;
|
||||
entryQuery?: Record<string, string>;
|
||||
entryComplements?: Complement[];
|
||||
entrySubmission?: {id:string;version:number} | null;
|
||||
}) {
|
||||
const [chosen, setChosen] = useState('');
|
||||
const [title, setTitle] = useState(entryComplements[0]?.kind === 'need' ? `Preparação de ${entryComplements[0].title} — ${entryComplements[0].origin.title}`.slice(0,200) : source?.title ?? opportunityChoices[0]?.opportunity.title ?? '');
|
||||
@@ -28,6 +30,13 @@ export default function ContextStart({
|
||||
const [key] = useState(createOperationKey);
|
||||
const sourceSuffix = opportunityChoices.length ? '?' + opportunityChoices.map(c => `opportunities[]=${encodeURIComponent(c.opportunity.id)}`).join('&') : source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const suffix = sourceSuffix || Object.keys(entryQuery).length ? (sourceSuffix || '?')+(sourceSuffix ? '&' : '')+'selection_key='+encodeURIComponent(key)+'&'+new URLSearchParams(entryQuery).toString() : '';
|
||||
const continueIn = async (id: string) => {
|
||||
if (entrySubmission) {
|
||||
const view = await contextApi<{case:{version:number}}>(`/investimentos/${id}/contexto`);
|
||||
await contextApi(`/investidor/manifestacoes/${entrySubmission.id}/contexto`, {case_id:id,case_version:view.case.version,version:entrySubmission.version});
|
||||
}
|
||||
window.location.assign(`/investimentos/${id}/contexto/editar${suffix}`);
|
||||
};
|
||||
return (
|
||||
<Frame title="Iniciar ou continuar um investimento">
|
||||
<SelectedComplements items={entryComplements}/>
|
||||
@@ -44,9 +53,11 @@ export default function ContextStart({
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
{source.kind === 'portfolio' && <p>Sector documentado: {source.analysis?.documented_sector ?? 'Por definir'}. Cobertura documental: {source.analysis?.documented_location ?? 'Por definir'}. Confirme o enquadramento e a localização do seu investimento no dossier.</p>}
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
{entrySubmission && <p>Ao continuar, esta manifestação será associada ao dossier escolhido, conservando a ficha de origem. Nenhum pedido será submetido.</p>}
|
||||
<h2 className="text-xl font-bold">
|
||||
Continuar um dossier existente
|
||||
</h2>
|
||||
@@ -65,20 +76,23 @@ export default function ContextStart({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{chosen && (
|
||||
<Link
|
||||
{chosen && entrySubmission && (
|
||||
<button
|
||||
className={button}
|
||||
href={
|
||||
step && !source && !opportunityChoices.length
|
||||
? `/investimentos/${chosen}#${step}`
|
||||
: `/investimentos/${chosen}/contexto/editar${suffix}`
|
||||
}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (step && !source && !opportunityChoices.length) {window.location.assign(`/investimentos/${chosen}#${step}`);return;}
|
||||
setBusy(true);setError('');void continueIn(chosen).catch(e=>{setError(e.message);setBusy(false);});
|
||||
}}
|
||||
>
|
||||
{step && !source && !opportunityChoices.length
|
||||
? 'Abrir ' + step + ' no mesmo dossier'
|
||||
: 'Preparar neste dossier'}
|
||||
</Link>
|
||||
</button>
|
||||
)}
|
||||
{chosen && !entrySubmission && <Link className={button} href={step && !source && !opportunityChoices.length ? `/investimentos/${chosen}#${step}` : `/investimentos/${chosen}/contexto/editar${suffix}`}>
|
||||
{step && !source && !opportunityChoices.length ? 'Abrir ' + step + ' no mesmo dossier' : 'Preparar neste dossier'}
|
||||
</Link>}
|
||||
<p>
|
||||
Se já preparou este investimento, continue nele. Não é
|
||||
necessário criar outro dossier.
|
||||
@@ -95,11 +109,7 @@ export default function ContextStart({
|
||||
client_key: key,
|
||||
reuse_consent: consent,
|
||||
})
|
||||
.then((r) =>
|
||||
window.location.assign(
|
||||
`/investimentos/${r.id}/contexto/editar${suffix}`,
|
||||
),
|
||||
)
|
||||
.then((r) => continueIn(r.id))
|
||||
.catch((e) => setError(e.message))
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
|
||||
@@ -30,7 +30,7 @@ type Options = {
|
||||
parks: { id: string; name: string; version_no: number }[];
|
||||
search_limited: boolean;
|
||||
};
|
||||
type Slot = 'opportunity' | 'sector' | 'territory' | 'park';
|
||||
type Slot = 'portfolio' | 'opportunity' | 'sector' | 'territory' | 'park';
|
||||
export default function ContextEditor({
|
||||
initial,
|
||||
options: initialOptions,
|
||||
@@ -41,6 +41,7 @@ export default function ContextEditor({
|
||||
entrySources = [],
|
||||
entryLocationDifferences = [],
|
||||
entryComplements = [],
|
||||
entryTerritory = null,
|
||||
}: {
|
||||
initial: ContextView;
|
||||
options: Options;
|
||||
@@ -49,6 +50,7 @@ export default function ContextEditor({
|
||||
requestedChoices?: OpportunityChoice[] | null;
|
||||
entrySources?: string[];
|
||||
entryComplements?: Complement[];
|
||||
entryTerritory?: ContextReference | null;
|
||||
entryLocationDifferences?: {title:string;saved:string;requested:string}[];
|
||||
draft?: {draft_sequence?:number;needs_review?:boolean;selection?:Partial<Record<Slot,string>>;declarations?:Record<string,string>;replace_fields?:string[];document_links?:Record<string,string|null>}|null;
|
||||
}) {
|
||||
@@ -81,12 +83,12 @@ export default function ContextEditor({
|
||||
const [options, setOptions] = useState(initialOptions);
|
||||
const [query, setQuery] = useState('');
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(() =>
|
||||
draft?.selection ?? (source
|
||||
({...(draft?.selection ?? {}), ...(entryTerritory && !draft?.selection?.territory && !initial.context.selection.territory ? {territory: entryTerritory.key} : {}), ...(source?.kind === 'portfolio' ? {portfolio: source.key} : draft?.selection ? {} : source
|
||||
? {
|
||||
[source.kind === 'business' ? 'opportunity' : source.kind]:
|
||||
source.key,
|
||||
}
|
||||
: {}),
|
||||
: {})}),
|
||||
);
|
||||
const [declarations, setDeclarations] = useState<Record<string, string>>(
|
||||
draft?.declarations ?? {},
|
||||
@@ -311,6 +313,11 @@ export default function ContextEditor({
|
||||
{draft?.needs_review&&<p role="status">O rascunho foi recuperado, mas o dossier recebeu outras alterações. Reveja os dados antes de confirmar.</p>}
|
||||
{draftStatus.startsWith('Rascunho não guardado')&&<button type="button" className="underline" onClick={()=>setDraftRetry(v=>v+1)}>Tentar guardar novamente</button>}
|
||||
<OpportunityChoices corridors={corridors} choices={choices} disabled={busy||corridorLoading||!!corridorError} onChange={next=>{setChoices(next);setManageChoices(true);setPlan(null);}}/>
|
||||
{(changes.portfolio || view.context.selection.portfolio) && <p className="rounded border p-3">
|
||||
Origem documental: <a className="underline" href={source?.kind === 'portfolio' ? source.href : view.context.selection.portfolio?.href}>{source?.kind === 'portfolio' ? source.title : view.context.selection.portfolio?.title}</a>.
|
||||
{' '}A ficha é conservada como origem. Escolha o sector e a localização do investimento abaixo; a cobertura documental não é uma implantação atribuída.
|
||||
</p>}
|
||||
{entryTerritory && view.context.selection.territory && entryTerritory.key !== view.context.selection.territory.key && <p role="status">A pesquisa indicava {entryTerritory.title}. Conservou-se a localização guardada, {view.context.selection.territory.title}; pode alterá-la explicitamente abaixo e conferir os impactos.</p>}
|
||||
<ContextDocuments source={source ?? view.context.selection.opportunity} />
|
||||
{view.context.revision > 0 && !Object.keys(changes).length && JSON.stringify(choices) === JSON.stringify(view.context.opportunity_choices ?? []) && <InvestmentRequirements assessment={view.context.requirements_assessment} contextId={view.case.id}/>}
|
||||
<label className="block">Acrescentar uma oportunidade à escolha<select className={input} value="" onChange={e=>{const o=options.opportunities.find(o=>o.key===e.target.value);if(o && !choices.some(c=>c.opportunity.key===o.key)){setChoices([...choices,{opportunity:{...o,id:o.key.split(':')[1],href:'/oportunidades',version:null,sha256:'',fields:{}},territory:null,location_reason:'',location_state:'undetermined'}]);setManageChoices(true);setPlan(null);}}}><option value="">Seleccionar ficha</option>{options.opportunities.filter(o=>o.kind==='opportunity'&&!choices.some(c=>c.opportunity.key===o.key)).map(o=><option key={o.key} value={o.key}>{o.title}</option>)}</select></label>
|
||||
|
||||
@@ -444,6 +444,10 @@ export default function InvestmentPath(path: Path) {
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
{path.investment_context?.selection.portfolio && <p className="rounded border p-4">
|
||||
Origem documental: <Link className="underline" href={path.investment_context.selection.portfolio.href}>{path.investment_context.selection.portfolio.title}</Link>.
|
||||
{' '}A localização do investimento é escolhida no contexto.
|
||||
</p>}
|
||||
{!!path.opportunity_options?.length && <label className="block rounded border p-4">Oportunidade em tratamento
|
||||
<select className="ml-2 rounded border p-2" value={path.context_opportunity ?? ''} onChange={event => router.get(`/investimentos/${path.case.id}`, event.target.value ? {opportunity:event.target.value} : {}, {preserveState:false})}>
|
||||
<option value="">Escolha a oportunidade</option>
|
||||
|
||||
@@ -14,12 +14,15 @@ export default function Index({
|
||||
management,
|
||||
filters,
|
||||
territorySelection = [],
|
||||
sectors = [],
|
||||
}: {
|
||||
records: Paginated<Dossier>;
|
||||
management: boolean;
|
||||
sectors?: string[];
|
||||
filters: {
|
||||
q?: string;
|
||||
kind?: string;
|
||||
sector?: string;
|
||||
province_id?: string;
|
||||
district_id?: string;
|
||||
admin_post_id?: string;
|
||||
@@ -30,6 +33,7 @@ export default function Index({
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
kind: filters.kind ?? '',
|
||||
sector: filters.sector ?? '',
|
||||
province_id: filters.province_id ?? '',
|
||||
district_id: filters.district_id ?? '',
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
@@ -77,6 +81,12 @@ export default function Index({
|
||||
<option value="project">Projectos âncora</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Sector documentado">
|
||||
<select className={control} value={form.data.sector} onChange={(e) => form.setData('sector', e.target.value)}>
|
||||
<option value="">Todos os sectores</option>
|
||||
{sectors.map((sector) => <option key={sector} value={sector}>{sector}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
onChange={(path) =>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Link, useForm, router, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { catalogueReturnHref } from '@/lib/catalogue-context';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import { searchTerritoryHref, portfolioPreparationHref } from '@/lib/search-territory';
|
||||
import InvestmentMapPanel from '@/components/investment-map-panel';
|
||||
import StructureGeographyPanel, {
|
||||
type StructureGeography,
|
||||
@@ -94,6 +94,14 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{!management && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<Link className="underline" href={portfolioPreparationHref(record.id, pageUrl)}>
|
||||
Preparar investimento a partir desta ficha
|
||||
</Link>
|
||||
<p>A ficha acompanha o dossier como origem documental. A localização do investimento e as ofertas associadas são escolhas próprias.</p>
|
||||
</div>
|
||||
)}
|
||||
{(record.project_id || record.cluster_id) && (
|
||||
<PartnershipSourceLinks
|
||||
type={record.project_id ? 'project' : 'cluster'}
|
||||
@@ -270,7 +278,7 @@ function Editor({
|
||||
Para associar esta referência a uma manifestação privada,
|
||||
entre na sua conta. Esta ficha continuará pública e não será
|
||||
copiada nem publicada no seu nome.{' '}
|
||||
<Link className="underline" href="/login">
|
||||
<Link className="underline" href={'/carteira/' + record.id + '/interesse' + (() => { const query = new URL(pageUrl, 'https://portal.invalid').searchParams.get('catalogue_query'); return query ? '?catalogue_query=' + encodeURIComponent(query) : ''; })()}>
|
||||
Entrar
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -92,6 +92,7 @@ Route::middleware(['auth', 'verified', \App\Http\Middleware\EnsureDocumentManage
|
||||
Route::get('/artigos/{id}', [\App\Http\Controllers\EditorialArticleController::class, 'show'])->whereNumber('id')->name('editorial.show');
|
||||
Route::get('/carteira', [InvestmentPortfolioController::class, 'index'])->name('portfolio.index');
|
||||
Route::get('/carteira/{id}', [InvestmentPortfolioController::class, 'show'])->whereUuid('id')->name('portfolio.show');
|
||||
Route::get('/carteira/{id}/interesse', [InvestmentPortfolioController::class, 'resumeInterest'])->whereUuid('id')->middleware(['auth', \App\Http\Middleware\VerifiedOrSimpleParticipation::class])->name('portfolio.interest');
|
||||
Route::get('/oportunidades', [InvestmentDiscoveryController::class, 'index'])->name('portal.opportunities');
|
||||
Route::get('/oportunidades/{slug}', [InvestmentDiscoveryController::class, 'detail'])->name('portal.opportunity');
|
||||
Route::get('/negocios', [PublicBusinessOpportunityController::class, 'index'])->name('business-marketplace.index');
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\User;
|
||||
use App\Services\ApprovedAnchorTerritories;
|
||||
use App\Services\InvestmentRelations;
|
||||
use App\Services\InvestorContext;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Routing\Middleware\ThrottleRequests;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestmentAnchorIntegrationTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
private User $actor;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
|
||||
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
$this->withoutVite();
|
||||
$this->withoutMiddleware(ThrottleRequests::class);
|
||||
config(['investor-path.enabled' => true, 'investor-path.private_preparation' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actor = User::factory()->create();
|
||||
}
|
||||
|
||||
public function test_documented_sector_filter_is_explicit_and_preserves_the_catalogue_scope(): void
|
||||
{
|
||||
$anchor = InvestmentPortfolioController::visible()->where('content->code', 'A06')->firstOrFail();
|
||||
$sector = $anchor->content['sector'];
|
||||
$this->get('/carteira?'.http_build_query(['kind' => 'project', 'sector' => $sector]))->assertOk()
|
||||
->assertInertia(fn (Assert $p) => $p->where('filters.sector', $sector)->has('records.data', 1)->where('records.data.0.id', $anchor->id)->has('sectors'));
|
||||
$this->get('/carteira?sector=sector-inexistente')->assertOk()->assertInertia(fn (Assert $p) => $p->has('records.data', 0));
|
||||
$this->get('/carteira')->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.total', InvestmentPortfolioController::visible()->count()));
|
||||
}
|
||||
|
||||
public function test_accepted_territories_are_recovered_by_identity_with_citations_and_idempotence(): void
|
||||
{
|
||||
$service = app(ApprovedAnchorTerritories::class);
|
||||
$before = DB::table('investment_dossiers')->orderBy('id')->get()->toJson();
|
||||
$plan = $service->plan();
|
||||
$this->assertCount(28, $plan['links']);
|
||||
$this->assertCount(13, $plan['projects']);
|
||||
$result = $service->apply($plan);
|
||||
$this->assertSame(count(array_filter($plan['links'], fn ($link) => ! $link['already_present'])), $result['relations_restored']);
|
||||
$this->assertSame(0, $result['publication_changes']);
|
||||
$this->assertSame($before, DB::table('investment_dossiers')->orderBy('id')->get()->toJson());
|
||||
$second = $service->apply($service->plan());
|
||||
$this->assertSame(0, $second['relations_restored']);
|
||||
$this->assertSame(0, $second['projects_updated']);
|
||||
$anchor = InvestmentPortfolioController::visible()->where('content->code', 'A06')->firstOrFail();
|
||||
$locations = app(InvestmentRelations::class)->projectLocations($anchor->project_id);
|
||||
$this->assertCount(4, $locations);
|
||||
$this->assertNotEmpty($locations[0]['source_quote']);
|
||||
$this->assertSame('secondary', $locations[0]['role']);
|
||||
$province = $locations[0]['id'];
|
||||
$this->get('/carteira?'.http_build_query(['kind' => 'project', 'sector' => $anchor->content['sector'], 'province_id' => $province]))->assertOk()
|
||||
->assertInertia(fn (Assert $p) => $p->has('records.data', 1)->where('records.data.0.id', $anchor->id));
|
||||
$this->assertCount(0, app(InvestmentRelations::class)->projectLocations(InvestmentPortfolioController::visible()->where('content->code', 'A01')->firstOrFail()->project_id));
|
||||
}
|
||||
|
||||
public function test_anchor_without_offer_survives_login_dossier_and_simulator_as_documentary_origin(): void
|
||||
{
|
||||
$anchor = InvestmentPortfolioController::visible()->where('content->code', 'A06')->firstOrFail();
|
||||
$source = 'portfolio:'.$anchor->id;
|
||||
$entry = '/investimentos/iniciar?'.http_build_query(['source' => $source]);
|
||||
$this->get($entry)->assertRedirect(route('login'));
|
||||
$this->assertStringEndsWith($entry, session('url.intended'));
|
||||
$this->actingAs($this->actor);
|
||||
$this->get($entry)->assertOk()->assertInertia(fn (Assert $p) => $p->where('source.key', $source)->has('opportunityChoices', 0));
|
||||
$reference = app(InvestorContext::class)->reference($source);
|
||||
$this->assertArrayNotHasKey('province_id', $reference['fields']);
|
||||
$this->assertFalse($reference['analysis']['available_opportunity']);
|
||||
$id = $this->postJson('/investimentos', ['title' => 'SYNTHETIC QA - ideia propria', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$body = ['version' => $this->getJson('/investimentos/'.$id.'/contexto')->json('case.version'), 'selection' => ['portfolio' => $source]];
|
||||
$preview = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
|
||||
$this->assertSame('SYNTHETIC QA - ideia propria', $preview['fields']['project_title']);
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $preview['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$this->assertSame($source, $view['context']['selection']['portfolio']['key']);
|
||||
$this->assertSame([], $view['context']['opportunity_choices']);
|
||||
$snapshot = json_decode($view['prefill']['simulator']['context_applicability_snapshot'], true);
|
||||
$this->assertSame($source, $snapshot['portfolio_origin']['key']);
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => ['purpose' => 'simulate_only', 'project_title' => 'SYNTHETIC QA - titulo proprio', 'context_applicability_snapshot' => json_encode($snapshot)]], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
|
||||
$saved = $this->getJson('/api/v1/simulation-drafts/'.$draft.'?context='.$id)->assertOk()->json('data.economic_snapshot');
|
||||
$this->assertSame($source, json_decode($saved['context_applicability_snapshot'], true)['portfolio_origin']['key']);
|
||||
$this->assertSame('SYNTHETIC QA - titulo proprio', $saved['project_title']);
|
||||
$anchor->publication_status = 'draft';
|
||||
$anchor->save();
|
||||
$this->get($entry)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_interest_resumption_keeps_the_same_anchor_and_filters_without_creating_a_request_on_get(): void
|
||||
{
|
||||
$anchor = InvestmentPortfolioController::visible()->where('content->code', 'A06')->firstOrFail();
|
||||
$query = http_build_query(['sector' => $anchor->content['sector'], 'kind' => 'project']);
|
||||
$entry = '/carteira/'.$anchor->id.'/interesse?'.http_build_query(['catalogue_query' => $query]);
|
||||
$before = DB::table('investment_submissions')->count();
|
||||
$this->get($entry)->assertRedirect(route('login'));
|
||||
$this->assertStringEndsWith($entry, session('url.intended'));
|
||||
$this->actingAs($this->actor);
|
||||
$this->get($entry)->assertRedirect('/carteira/'.$anchor->id.'?'.http_build_query(['catalogue_query' => $query, 'prepare_interest' => '1']));
|
||||
$this->assertSame($before, DB::table('investment_submissions')->count());
|
||||
$response = $this->postJson('/investidor/manifestacoes', ['dossier_id' => $anchor->id])->assertCreated();
|
||||
$row = DB::table('investment_submissions')->where('id', $response->json('id'))->first();
|
||||
$this->assertSame($anchor->id, $row->dossier_id);
|
||||
$start = '/investimentos/iniciar?'.http_build_query(['source' => 'portfolio:'.$anchor->id, 'submission' => $row->id]);
|
||||
$this->get($start)->assertOk()->assertInertia(fn (Assert $p) => $p->where('entrySubmission.id', $row->id)->where('entrySubmission.version', (int) $row->version));
|
||||
$other = InvestmentPortfolioController::visible()->where('id', '!=', $anchor->id)->firstOrFail();
|
||||
$this->get('/investimentos/iniciar?'.http_build_query(['source' => 'portfolio:'.$other->id, 'submission' => $row->id]))->assertUnprocessable();
|
||||
$case = $this->postJson('/investimentos', ['title' => 'SYNTHETIC QA - manifesto e ancora', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$version = $this->getJson('/investimentos/'.$case.'/contexto')->json('case.version');
|
||||
$this->postJson('/investidor/manifestacoes/'.$row->id.'/contexto', ['case_id' => $case, 'case_version' => $version, 'version' => (int) $row->version])->assertOk();
|
||||
$this->assertSame($row->id, DB::table('desk_cases')->where('id', $case)->value('submission_id'));
|
||||
$this->assertSame($anchor->id, DB::table('investment_submissions')->where('id', $row->id)->value('dossier_id'));
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->get($start)->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\ApprovedAdministrativeBoundaries;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Routing\Middleware\ThrottleRequests;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class TerritoryGeometryConsumerAccessTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private string $territory;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
|
||||
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
$this->withoutVite();
|
||||
$this->withoutMiddleware(ThrottleRequests::class);
|
||||
config(['portal.profile_access_enabled' => true, 'portal.managers' => [], 'investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
|
||||
$this->actor = User::factory()->create(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()]);
|
||||
$other = User::factory()->create();
|
||||
DB::table('portal_superuser_pair')->updateOrInsert(['id' => 1], ['first_user_id' => $this->actor->id, 'second_user_id' => $other->id, 'approved_by' => $other->id]);
|
||||
$this->territory = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id')
|
||||
->where('g.source_system', 'ine-cod-ab')->where('g.data_classification', 'internal')->where('l.location_type', 'province')->value('l.id');
|
||||
$this->assertNotEmpty($this->territory);
|
||||
}
|
||||
|
||||
public function test_general_consumer_uses_existing_authenticated_read_access_without_the_legacy_gate(): void
|
||||
{
|
||||
$this->assertFalse($this->actor->can('manage-portal'));
|
||||
$before = $this->fingerprint();
|
||||
$this->actingAs($this->actor)->getJson('/api/v1/investment/territory-geometries?territory_id='.$this->territory)
|
||||
->assertOk()->assertJsonPath('selected_geometry_available', true)->assertJsonPath('geometry_scope', 'authorized_internal')
|
||||
->assertJsonPath('areas.0.territory_id', $this->territory)->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->assertSame($before, $this->fingerprint());
|
||||
}
|
||||
|
||||
public function test_existing_administration_reaches_the_same_geometry_with_its_completed_mfa_session(): void
|
||||
{
|
||||
$this->actingAs($this->actor)->withSession(['portal.mfa_actor' => $this->actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $this->actor->portal_access_revision]);
|
||||
$this->getJson('/management/territory-geometries?territory_id='.$this->territory)->assertOk()->assertJsonPath('selected_geometry_available', true);
|
||||
session()->forget(['portal.mfa_actor', 'portal.mfa_at']);
|
||||
$this->getJson('/management/territory-geometries?territory_id='.$this->territory)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_anonymous_and_ordinary_accounts_do_not_receive_or_publish_internal_layers(): void
|
||||
{
|
||||
$before = $this->fingerprint();
|
||||
$url = '/api/v1/investment/territory-geometries?territory_id='.$this->territory;
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('geometry_scope', 'public')->assertJsonPath('selected_geometry_available', false)->assertJsonCount(0, 'areas');
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertOk()->assertJsonPath('geometry_scope', 'public')->assertJsonCount(0, 'areas');
|
||||
$this->getJson('/management/territory-geometries?territory_id='.$this->territory)->assertForbidden();
|
||||
$this->assertSame($before, $this->fingerprint());
|
||||
}
|
||||
|
||||
public function test_saved_territory_is_recovered_in_dossier_and_simulator_and_the_map_uses_that_identity(): void
|
||||
{
|
||||
$this->actingAs($this->actor);
|
||||
$id = $this->postJson('/investimentos', ['title' => 'SYNTHETIC QA - mapa recuperado', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$body = ['version' => $this->getJson('/investimentos/'.$id.'/contexto')->json('case.version'), 'selection' => ['territory' => 'territory:'.$this->territory]];
|
||||
$preview = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
|
||||
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $preview['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
|
||||
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
|
||||
$this->assertSame($this->territory, $view['context']['selection']['territory']['id']);
|
||||
$this->assertSame($this->territory, $view['prefill']['simulator']['province_id']);
|
||||
$this->getJson('/api/v1/investment/territory-geometries?territory_id='.$view['prefill']['simulator']['province_id'])
|
||||
->assertOk()->assertJsonPath('selected_geometry_available', true)->assertJsonPath('areas.0.selected_territory', true);
|
||||
$this->assertSame($this->territory, $this->getJson('/investimentos/'.$id.'/contexto')->json('context.selection.territory.id'));
|
||||
}
|
||||
|
||||
public function test_only_the_approved_unchanged_snapshot_is_public_without_reclassifying_the_original(): void
|
||||
{
|
||||
$before = $this->fingerprint();
|
||||
$row = DB::table('geo_geometries as g')->where('geo_location_id', $this->territory)->first([
|
||||
'g.id', 'g.geo_location_id', DB::raw("encode(sha256(ST_AsEWKB(g.geom)),'hex') as geometry_sha256"),
|
||||
DB::raw("encode(sha256(convert_to(g.properties::text,'UTF8')),'hex') as properties_sha256"),
|
||||
]);
|
||||
// The QA import has its own identities; never copy or replace production rows.
|
||||
$approved = $this->partialMock(ApprovedAdministrativeBoundaries::class);
|
||||
$approved->shouldReceive('snapshots')->andReturn([$row->id => [
|
||||
'territory_id' => $row->geo_location_id, 'geometry_sha256' => $row->geometry_sha256,
|
||||
'properties_sha256' => $row->properties_sha256,
|
||||
]]);
|
||||
$url = '/api/v1/investment/territory-geometries?territory_id='.$this->territory;
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('selected_geometry_available', true)
|
||||
->assertJsonPath('areas.0.data_classification', 'public')->assertJsonPath('investment_site', false);
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertOk()->assertJsonPath('selected_geometry_available', true);
|
||||
$this->assertSame($before, $this->fingerprint());
|
||||
$this->assertSame('internal', DB::table('geo_geometries')->where('id', $row->id)->value('data_classification'));
|
||||
DB::table('geo_geometries')->where('id', $row->id)->update(['properties' => DB::raw("properties || '{\"qa_changed\":true}'::jsonb")]);
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('selected_geometry_available', false)->assertJsonCount(0, 'areas');
|
||||
$this->actingAs($this->actor)->getJson($url)->assertOk()->assertJsonPath('selected_geometry_available', true);
|
||||
}
|
||||
|
||||
public function test_public_manifest_has_the_exact_approved_scope_and_immutable_hash(): void
|
||||
{
|
||||
$items = app(ApprovedAdministrativeBoundaries::class)->snapshots();
|
||||
$this->assertCount(408, $items);
|
||||
$this->assertCount(408, array_unique(array_column($items, 'territory_id')));
|
||||
$this->assertSame(['2019-06-07'], array_values(array_unique(array_column($items, 'source_version'))));
|
||||
}
|
||||
|
||||
private function fingerprint(): string
|
||||
{
|
||||
return DB::selectOne("select md5(string_agg(row_to_json(g)::text,E'\\n' order by id)) as hash from geo_geometries g")->hash;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\ApprovedAdministrativeBoundaries;
|
||||
use Tests\TestCase;
|
||||
|
||||
/** Runs in the normal delivery unit suite, without database or external services. */
|
||||
final class ApprovedAdministrativeBoundariesTest extends TestCase
|
||||
{
|
||||
public function test_public_scope_keeps_the_accepted_identity_and_refuses_changed_or_new_internal_shapes(): void
|
||||
{
|
||||
$approved = new ApprovedAdministrativeBoundaries;
|
||||
$items = $approved->snapshots();
|
||||
$this->assertCount(408, $items);
|
||||
$item = reset($items);
|
||||
$this->assertTrue($approved->allows($item['id'], $item['territory_id'], $item['geometry_sha256'], $item['properties_sha256']));
|
||||
$this->assertFalse($approved->allows('00000000-0000-0000-0000-000000000000', $item['territory_id'], $item['geometry_sha256'], $item['properties_sha256']));
|
||||
$this->assertFalse($approved->allows($item['id'], '00000000-0000-0000-0000-000000000000', $item['geometry_sha256'], $item['properties_sha256']));
|
||||
$this->assertFalse($approved->allows($item['id'], $item['territory_id'], str_repeat('0', 64), $item['properties_sha256']));
|
||||
$this->assertFalse($approved->allows($item['id'], $item['territory_id'], $item['geometry_sha256'], str_repeat('0', 64)));
|
||||
}
|
||||
|
||||
public function test_the_public_scope_keeps_the_accepted_edition_and_unique_territories(): void
|
||||
{
|
||||
$items = (new ApprovedAdministrativeBoundaries)->snapshots();
|
||||
$this->assertCount(408, array_unique(array_column($items, 'territory_id')));
|
||||
$this->assertSame(['2019-06-07'], array_values(array_unique(array_column($items, 'source_version'))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { portfolioPreparationHref } from '../../resources/js/lib/search-territory.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
test('anchor preparation keeps exact identity and explicit search geography', () => {
|
||||
const query = new URLSearchParams({sector:'Agro-indústria e agricultura',province_id:'province-1',district_id:'district-1'});
|
||||
const href = portfolioPreparationHref('anchor-1','/carteira/anchor-1?catalogue_query='+encodeURIComponent(query.toString()));
|
||||
const params = new URL(href,'https://portal.invalid').searchParams;
|
||||
assert.equal(params.get('source'),'portfolio:anchor-1');
|
||||
assert.equal(params.get('province_id'),'province-1');
|
||||
assert.equal(params.get('district_id'),'district-1');
|
||||
assert.equal(params.has('opportunity'),false);
|
||||
assert.equal(params.has('sector_id'),false);
|
||||
});
|
||||
|
||||
test('report identifies the saved documentary anchor without asserting an available offer', () => {
|
||||
const context = {version:1,portfolio_origin:{key:'portfolio:anchor-1',title:'Âncora documental',version:2,href:'/carteira/anchor-1'}};
|
||||
const report = createProjectDossierReport({context_applicability_snapshot:JSON.stringify(context)},{selectedSections:new Set(['sources'])});
|
||||
const row = report.sections.find(section=>section.id==='sources').rows.find(row=>row.field==='Projecto ou carteira de origem');
|
||||
assert.equal(row.value,'Âncora documental');
|
||||
assert.match(row.origin,/portfolio:anchor-1; versão 2/);
|
||||
assert.match(row.classification,/localização e oferta não presumidas/);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
// Delimited replay of accepted territorial relations, not a new publication.
|
||||
declare(strict_types=1);
|
||||
use App\Services\ApprovedAnchorTerritories;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
ini_set('zend.exception_ignore_args', '1');
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$args = getopt('', ['qa', 'apply', 'output:', 'preview-sha256:', 'backup:']);
|
||||
$qa = isset($args['qa']);
|
||||
$apply = isset($args['apply']);
|
||||
$expected = $qa ? 'simulator_fiscal_delta_20261021_test' : 'teste_investidor';
|
||||
$port = $qa ? 55441 : 5432;
|
||||
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
|
||||
if ($identity->name !== $expected || (int) $identity->port !== $port) {
|
||||
throw new RuntimeException('Named isolated QA or homologation required.');
|
||||
}
|
||||
if (! $qa && (! getenv('SSH_CONNECTION') || ! function_exists('posix_geteuid') || posix_geteuid() !== 0 || rtrim(config('app.url'), '/') !== 'https://teste-investidor.tempo.co.mz')) {
|
||||
throw new RuntimeException('Authenticated destination operator required.');
|
||||
}
|
||||
$output = $args['output'] ?? '';
|
||||
if (! $output || is_file($output) || str_contains(str_replace('\\', '/', $output), '/public/')) {
|
||||
throw new RuntimeException('New private receipt path required.');
|
||||
}
|
||||
$service = app(ApprovedAnchorTerritories::class);
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::statement($apply ? 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE' : 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
if ($apply) {
|
||||
DB::select('select pg_advisory_xact_lock(231026,28)');
|
||||
}
|
||||
$plan = $service->plan();
|
||||
$hash = hash('sha256', json_encode([$expected, $plan], JSON_THROW_ON_ERROR));
|
||||
$result = ['mode' => $apply ? 'applied' : 'preview', 'database' => $expected, 'port' => $port, 'qa' => $qa, 'manifest_sha256' => ApprovedAnchorTerritories::HASH, 'preview_sha256' => $hash, 'relations' => count($plan['links']), 'projects' => count($plan['projects'])];
|
||||
if ($apply) {
|
||||
if (! hash_equals($hash, $args['preview-sha256'] ?? '')) {
|
||||
throw new RuntimeException('Destination changed after preview.');
|
||||
}
|
||||
if (! $qa) {
|
||||
$directory = $args['backup'] ?? '';
|
||||
$backup = json_decode(file_get_contents($directory.'/backup-receipt.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$restore = json_decode(file_get_contents($directory.'/restore-receipt.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (! $restore['restore_verified'] || $backup['target']['database'] !== $expected || (int) $backup['target']['port'] !== $port
|
||||
|| ! hash_equals($backup['sha256'], $restore['source_dump_sha256']) || ! hash_equals($backup['sha256'], hash_file('sha256', $backup['dump_path']))) {
|
||||
throw new RuntimeException('Matching backup and isolated restoration required.');
|
||||
}
|
||||
}
|
||||
file_put_contents($output.'.before.json', json_encode($plan, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
if (! $qa) {
|
||||
chmod($output.'.before.json', 0600);
|
||||
}
|
||||
$result += $service->apply($plan);
|
||||
DB::commit();
|
||||
} else {
|
||||
DB::rollBack();
|
||||
}
|
||||
file_put_contents($output, json_encode([...$result, 'plan' => $plan], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
if (! $qa) {
|
||||
chmod($output, 0600);
|
||||
}
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable $error) {
|
||||
if (DB::transactionLevel()) {
|
||||
DB::rollBack();
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
Reference in New Issue
Block a user