Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e7d51f18f | ||
|
|
fd341b627e | ||
|
|
1350b4df73 | ||
|
|
8cf820ef49 | ||
|
|
210b7d273b | ||
|
|
be49f4c39c | ||
|
|
9b3c20fc2a | ||
|
|
de061b81aa | ||
|
|
6e439def02 | ||
|
|
74b081e93e | ||
|
|
9d148ca241 | ||
|
|
5be831ac44 | ||
|
|
f0e26e0d8a | ||
|
|
9ab721c97f | ||
|
|
02d4e6b2fd | ||
|
|
507387502c | ||
|
|
97a08df2a0 |
@@ -5,15 +5,24 @@ namespace App\Console\Commands;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Sleep;
|
||||
use Throwable;
|
||||
|
||||
class CheckDevelopmentEnvironment extends Command
|
||||
{
|
||||
protected $signature = 'portal:dev-check';
|
||||
protected $signature = 'portal:dev-check {--wait=0 : Segundos para aguardar uma falha transitória do PostgreSQL}';
|
||||
|
||||
protected $description = 'Verifica o arranque local sem alterar dados ou mostrar credenciais';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$wait = filter_var($this->option('wait'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 3600]]);
|
||||
if ($wait === false) {
|
||||
$this->error('--wait deve ser um inteiro entre 0 e 3600 segundos.');
|
||||
|
||||
return self::INVALID;
|
||||
}
|
||||
|
||||
$checks = [
|
||||
'PHP >= 8.4.1' => version_compare(PHP_VERSION, '8.4.1', '>='),
|
||||
'Driver PostgreSQL activo' => extension_loaded('pdo_pgsql'),
|
||||
@@ -25,14 +34,17 @@ class CheckDevelopmentEnvironment extends Command
|
||||
];
|
||||
|
||||
if ($checks['Driver PostgreSQL activo'] && $checks['Base PostgreSQL configurada']) {
|
||||
$checks['Ligação à base de dados'] = $this->checkConnection($wait);
|
||||
}
|
||||
|
||||
if ($checks['Ligação à base de dados'] ?? false) {
|
||||
try {
|
||||
DB::selectOne('SELECT 1');
|
||||
$checks['Ligação à base de dados'] = true;
|
||||
$checks['Extensão PostGIS instalada'] = (bool) DB::selectOne("SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'postgis') AS installed")->installed;
|
||||
$checks['Tabelas principais instaladas'] = collect(['migrations', 'users', 'sectors', 'opportunities', 'sessions', 'cache', 'jobs'])
|
||||
->every(fn (string $table): bool => Schema::hasTable($table));
|
||||
} catch (\Throwable) {
|
||||
$checks['Ligação à base de dados'] = false;
|
||||
} catch (Throwable) {
|
||||
$checks['Esquema da base de dados verificável'] = false;
|
||||
$this->warn('A ligação foi estabelecida, mas a verificação do esquema falhou. Verifique as permissões e a preparação QA.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,4 +60,61 @@ class CheckDevelopmentEnvironment extends Command
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function checkConnection(int $wait): bool
|
||||
{
|
||||
$deadline = microtime(true) + $wait;
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
DB::selectOne('SELECT 1');
|
||||
|
||||
return true;
|
||||
} catch (Throwable $error) {
|
||||
[$reason, $retryable] = $this->connectionFailure($error);
|
||||
$remaining = $deadline - microtime(true);
|
||||
if (! $retryable || $remaining <= 0) {
|
||||
$this->warn($reason);
|
||||
if ($retryable) {
|
||||
$this->warn('Inicie Docker Desktop e execute ./deploy/local/start.ps1. Consulte os registos com docker compose --env-file .env -f deploy/local/compose.yaml logs --tail 40 postgres.');
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->line('[AGUARDA] '.$reason.' Nova tentativa; prazo restante: '.(int) ceil($remaining).' s.');
|
||||
DB::purge();
|
||||
Sleep::for(min(5, $remaining))->seconds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{string, bool} */
|
||||
private function connectionFailure(Throwable $error): array
|
||||
{
|
||||
// Inspect the chain internally; never print exception messages, DSNs or credentials.
|
||||
$messages = '';
|
||||
do {
|
||||
$messages .= ' '.strtolower($error->getMessage()).' '.strtolower((string) $error->getCode());
|
||||
$error = $error->getPrevious();
|
||||
} while ($error !== null);
|
||||
|
||||
if (str_contains($messages, '28p01') || str_contains($messages, '28000')
|
||||
|| str_contains($messages, 'password authentication failed') || str_contains($messages, 'no pg_hba.conf entry')) {
|
||||
return ['Autenticação PostgreSQL recusada. Verifique as credenciais e as regras de acesso; aguardar não corrige este erro.', false];
|
||||
}
|
||||
if (str_contains($messages, '3d000') || preg_match('/database .* does not exist/', $messages)) {
|
||||
return ['A base PostgreSQL configurada não existe. Verifique a configuração e a preparação QA.', false];
|
||||
}
|
||||
if (str_contains($messages, '57p03') || str_contains($messages, 'recovery mode')
|
||||
|| str_contains($messages, 'not yet accepting connections') || str_contains($messages, 'database system is starting up')) {
|
||||
return ['PostgreSQL em arranque ou recuperação; aguarde a conclusão sem remover o volume.', true];
|
||||
}
|
||||
if (preg_match('/\b08[0-9a-z]{3}\b/', $messages) || str_contains($messages, 'connection refused')
|
||||
|| str_contains($messages, '57p01') || str_contains($messages, '57p02')) {
|
||||
return ['PostgreSQL indisponível. Verifique se Docker Desktop e o contentor local estão iniciados.', true];
|
||||
}
|
||||
|
||||
return ['Falha PostgreSQL não transitória. Verifique a configuração e os registos do servidor.', false];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,9 @@ class InterestRequestController extends Controller
|
||||
{
|
||||
public function store(StoreInterestRequestRequest $request, InterestSubmission $submission): JsonResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$validated = [...$request->validated(), '_actor_id' => $request->user()->id];
|
||||
$key = $request->header('Idempotency-Key');
|
||||
abort_unless(is_string($key), 422, 'Identificador do envio em falta.');
|
||||
Validator::make(['idempotency_key' => $key], ['idempotency_key' => [$key === null ? 'nullable' : 'required', 'uuid']])->validate();
|
||||
|
||||
try {
|
||||
@@ -53,7 +54,7 @@ class InterestRequestController extends Controller
|
||||
'phone' => $validated['phone'] ?? null,
|
||||
'investor_type' => $validated['investorType'],
|
||||
'country' => $validated['country'],
|
||||
'metadata' => ['declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
|
||||
'metadata' => ['portal_user_id' => $request->user()->id, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
|
||||
'sector_interest' => $validated['sectorInterest'],
|
||||
'opportunity_reference' => $validated['opportunityReference'] ?? null,
|
||||
'investment_range' => $validated['investmentRange'] ?? null,
|
||||
@@ -77,6 +78,19 @@ class InterestRequestController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
$row = \App\Models\InvestmentSubmission::create([
|
||||
'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id,
|
||||
'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1,
|
||||
'payload' => ['simple_participation' => true, 'opportunity_title' => $opportunity?->title ?? $business?->title, 'opportunity_reference' => $opportunity?->reference, 'phone' => $validated['phone'] ?? null, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null, 'full_name' => $validated['fullName'], 'email' => $validated['email'],
|
||||
'objective' => $validated['message'], 'sector' => $validated['sectorInterest'],
|
||||
'country' => $validated['country'], 'existing_business_id' => $business?->id,
|
||||
'modality' => $validated['modality'] ?? null],
|
||||
]);
|
||||
\Illuminate\Support\Facades\DB::table('investment_submission_events')->insert([
|
||||
'submission_id' => $row->id, 'actor_id' => $request->user()->id,
|
||||
'action' => 'submitted', 'version' => 1, 'created_at' => now(),
|
||||
]);
|
||||
$interest->forceFill(['metadata' => [...$interest->metadata, 'submission_id' => $row->id]])->save();
|
||||
return $interest;
|
||||
});
|
||||
|
||||
@@ -85,7 +99,8 @@ class InterestRequestController extends Controller
|
||||
'message' => 'Manifestação de interesse registada com sucesso.',
|
||||
'data' => [
|
||||
'reference' => $interestRequest->reference,
|
||||
'status' => 'received',
|
||||
'status' => $interestRequest->status,
|
||||
'tracking_url' => '/investidor/manifestacoes',
|
||||
],
|
||||
], 201);
|
||||
} catch (IdempotencyConflict) {
|
||||
|
||||
@@ -36,6 +36,7 @@ class OpportunityController extends Controller
|
||||
$term = $validated['q'];
|
||||
$query->where(fn ($q) => $q
|
||||
->whereLike('title', "%{$term}%")
|
||||
->orWhereLike('description', "%{$term}%")
|
||||
->orWhereLike('summary', "%{$term}%")
|
||||
->orWhereLike('reference', "%{$term}%")
|
||||
->orWhereLike('province', "%{$term}%")
|
||||
@@ -54,7 +55,7 @@ class OpportunityController extends Controller
|
||||
}
|
||||
|
||||
if (! empty($validated['maturity_level'])) {
|
||||
$query->where('maturity_level', $validated['maturity_level']);
|
||||
\App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
||||
}
|
||||
|
||||
$results = $query->orderByDesc('is_featured')
|
||||
|
||||
@@ -11,8 +11,8 @@ class DocumentMalwareController extends Controller
|
||||
{
|
||||
public function retry(Request $request, string $id): RedirectResponse
|
||||
{
|
||||
DB::transaction(function () use ($id): void {
|
||||
$document = DB::table('documents')->where('id', $id)->lockForUpdate()->first();
|
||||
DB::transaction(function () use ($id, $request): void {
|
||||
$document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
|
||||
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
|
||||
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
|
||||
|
||||
@@ -78,6 +78,7 @@ class EditorialArticleController extends Controller
|
||||
public function edit(int $id)
|
||||
{
|
||||
$this->installed();
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
|
||||
$r = DB::table('portal_resources')->find($id);
|
||||
abort_unless($r, 404);
|
||||
$content = $r->editorial_content ? json_decode($r->editorial_content, true) : null;
|
||||
@@ -108,6 +109,7 @@ class EditorialArticleController extends Controller
|
||||
DB::transaction(function () use ($request, $id, $data) {
|
||||
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($r, 404);
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||
abort_unless((int) $r->metadata_version === (int) $data['metadata_version'], 409, 'O artigo foi alterado noutra sessão. Recarregue antes de editar.');
|
||||
if (! empty($data['image_resource_id'])) {
|
||||
abort_unless($this->publicResources()->where('r.id', $data['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->exists(), 422, 'Escolha uma imagem pública disponível na biblioteca.');
|
||||
|
||||
@@ -67,7 +67,7 @@ class ExistingBusinessController extends Controller
|
||||
$business = app(BusinessRepository::class)->find($id);
|
||||
Gate::authorize('view', $business);
|
||||
app(CompatibilityShadow::class)->schedule($id);
|
||||
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'modalityFormType' => \App\Services\ExistingBusinessProfileCategory::formType($business->modality), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||
'canTriage' => $request->user()->can('triage', $business),
|
||||
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
||||
|
||||
@@ -53,7 +53,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
if (! empty($filters['geo_location_id'])) {
|
||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, app(InvestmentGeography::class)->descendants($filters['geo_location_id']));
|
||||
}
|
||||
foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) {
|
||||
foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation'] as $field) {
|
||||
if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) {
|
||||
return $query->whereRaw('false')->get();
|
||||
}
|
||||
@@ -75,9 +75,9 @@ class InvestmentDiscoveryController extends Controller
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString());
|
||||
}
|
||||
|
||||
public function references(InvestmentCatalogue $catalogue): JsonResponse
|
||||
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->references());
|
||||
return response()->json($catalogue->references(false, $catalogue->filters($request)));
|
||||
}
|
||||
|
||||
public function detail(Request $request, string $slug, InvestmentCatalogue $catalogue): Response
|
||||
@@ -131,7 +131,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
{
|
||||
$filters = $catalogue->filters($request);
|
||||
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
|
||||
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
|
||||
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
|
||||
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
|
||||
$zoneFilters = $filters;
|
||||
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
|
||||
|
||||
@@ -31,7 +31,14 @@ class InvestmentSubmissionController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$submissions = InvestmentSubmission::where('user_id', $request->user()->id)->latest()->paginate(20)->through(function ($row) {
|
||||
$query = InvestmentSubmission::where('user_id', $request->user()->id);
|
||||
if (! $request->user()->hasVerifiedEmail()) {
|
||||
// The existing payload is encrypted; scope after decryption, never infer ownership from email.
|
||||
$simpleIds = InvestmentSubmission::where('user_id', $request->user()->id)->where('status', 'submitted')->get(['id', 'payload'])
|
||||
->filter(fn ($row) => ($row->payload['simple_participation'] ?? false) === true)->modelKeys();
|
||||
$query->whereIn('id', $simpleIds);
|
||||
}
|
||||
$submissions = $query->latest()->paginate(20)->through(function ($row) {
|
||||
$interest = $row->interest_request_id ? InterestRequest::find($row->interest_request_id) : null;
|
||||
|
||||
return ['id' => $row->id, 'status' => $row->status, 'version' => $row->version, 'created_at' => $row->created_at,
|
||||
@@ -118,29 +125,32 @@ class InvestmentSubmissionController extends Controller
|
||||
$target = $row->opportunity_id ? Opportunity::published()->find($row->opportunity_id) : null;
|
||||
$dossier = $row->dossier_id ? InvestmentPortfolioController::visible()->find($row->dossier_id) : null;
|
||||
$zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']);
|
||||
$boundCase = DB::table('desk_cases')->where('submission_id', $id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first();
|
||||
$contextChoices = (int) $row->user_id === (int) $request->user()->id && $row->status === 'draft' && ! $boundCase
|
||||
$contextAvailable = app(VirtualDesk::class)->installed();
|
||||
$boundCase = $contextAvailable ? DB::table('desk_cases')->where('submission_id', $id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first() : null;
|
||||
$contextChoices = $contextAvailable && (int) $row->user_id === (int) $request->user()->id && $row->status === 'draft' && ! $boundCase
|
||||
? DB::table('desk_cases')->where('user_id', $request->user()->id)->whereNotNull('journey_id')->whereNull('closed_at')->whereNull('submission_id')->orderBy('title')->get(['id', 'title', 'version']) : [];
|
||||
$data = ['contextDossierId' => $boundCase?->id, 'contextChoices' => $contextChoices, 'boundContextRevision' => app(InvestorContextConsumers::class)->submissionRevision($id), 'countries' => app(CountryCatalogue::class)->all(), 'submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
|
||||
'target' => ($target ? $target->title : null) ?? ($dossier ? $dossier->title : null), 'references' => [
|
||||
$data = ['contextDossierId' => $boundCase?->id, 'contextChoices' => $contextChoices, 'boundContextRevision' => $contextAvailable ? app(InvestorContextConsumers::class)->submissionRevision($id) : 0, 'countries' => app(CountryCatalogue::class)->all(), 'submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
|
||||
'target' => ($target ? $target->title : null) ?? ($dossier ? $dossier->title : null) ?? ($row->payload['opportunity_title'] ?? null), 'references' => [
|
||||
...$catalogue->references(), 'options' => DB::table('investment_reference_options')->orderBy('label')->get()],
|
||||
'needs' => InvestmentSpecificNeed::where('submission_id', $id)->get(),
|
||||
'attachments' => DB::table('investment_submission_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
|
||||
->where('a.submission_id', $id)->whereNull('d.deleted_at')->get(['a.id', 'd.file_name']),
|
||||
'events' => DB::table('investment_submission_events')->where('submission_id', $id)->orderBy('id')->get(['action', 'version', 'created_at']),
|
||||
'events' => DB::table('investment_submission_events')->where('submission_id', $id)->orderBy('id')->get(['action', 'version', 'created_at'])
|
||||
->concat($interest ? DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)->orderBy('created_at')->get(['to_status', 'created_at'])->map(fn ($event) => ['action' => $event->to_status, 'version' => $row->version, 'created_at' => $event->created_at]) : [])->sortBy('created_at')->values(),
|
||||
'revisions' => DB::table('investment_submission_revisions')->where('submission_id', $id)->orderByDesc('version')->get(['version', 'created_at']),
|
||||
'messages' => DB::table('investment_messages')->where('submission_id', $id)->orderBy('created_at')->get(['id', 'sender_role', 'body', 'created_at'])->map(function ($message) {
|
||||
$message->body = Crypt::decryptString($message->body);
|
||||
|
||||
return $message;
|
||||
}),
|
||||
'receipt' => $interest?->only(['reference', 'status']), 'management' => (int) $row->user_id !== $request->user()->id];
|
||||
'receipt' => $interest?->only(['reference', 'status', 'next_action', 'next_action_due_at']), 'management' => (int) $row->user_id !== $request->user()->id];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/submission', $data);
|
||||
}
|
||||
|
||||
public function bindContext(Request $request, string $id): JsonResponse
|
||||
{
|
||||
abort_unless(app(VirtualDesk::class)->installed(), 422, 'O vínculo ao percurso do investimento não está disponível neste destino. A manifestação e a sua origem permanecem guardadas.');
|
||||
abort_if(array_diff(array_keys($request->all()), ['case_id', 'case_version', 'version', '_token']), 422, 'Parâmetros de associação inválidos.');
|
||||
$data = $request->validate(['case_id' => 'required|uuid', 'case_version' => 'required|integer|min:1', 'version' => 'required|integer|min:1']);
|
||||
$result = DB::transaction(function () use ($request, $id, $data) {
|
||||
@@ -395,7 +405,7 @@ class InvestmentSubmissionController extends Controller
|
||||
|
||||
private function event(InvestmentSubmission $row, Request $request, string $action): void
|
||||
{
|
||||
$boundCase = DB::table('desk_cases')->where('submission_id', $row->id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first();
|
||||
$boundCase = app(VirtualDesk::class)->installed() ? DB::table('desk_cases')->where('submission_id', $row->id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first() : null;
|
||||
$binding = null;
|
||||
if ($boundCase) {
|
||||
$binding = app(InvestorContextConsumers::class)->submissionRevision($row->id);
|
||||
|
||||
@@ -98,7 +98,7 @@ class InvestmentZoneController extends Controller
|
||||
abort_if((! empty($filters['development_status']) || ! empty($filters['availability_status'])) && ! Schema::hasColumn('investment_zones', 'source_evidence'), 503,
|
||||
'Os filtros de desenvolvimento e disponibilidade estarão disponíveis após a migração do catálogo de zonas.');
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
$publicColumns = ['version_no', 'id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'];
|
||||
$publicColumns = ['primary_territory_id', 'version_no', 'id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'];
|
||||
if(app(\App\Services\InvestmentZoneOperationalDetails::class)->installed()){$publicColumns[]='operational_details';}
|
||||
$publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
|
||||
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
|
||||
@@ -113,6 +113,8 @@ class InvestmentZoneController extends Controller
|
||||
->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
|
||||
->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'zl.scope_type']));
|
||||
|
||||
if (! $management) { $zone->makeHidden('primary_territory_id'); }
|
||||
|
||||
return $management ? $zone : [...app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->toArray()),'operational_details_public'=>app(\App\Services\InvestmentZoneOperationalDetails::class)->publicData($zone)];
|
||||
});
|
||||
$props = ['detailsInstallation'=>$management ? app(\App\Services\InvestmentZoneOperationalDetailsInstallation::class)->preview($request->user()) : null, 'installation' => $management ? app(InvestmentZoneProfileInstallation::class)->preview($request->user()) : null, 'records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path,
|
||||
|
||||
@@ -98,7 +98,13 @@ class OpportunityResourceController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'assessment' => $this->assessment($resources)]);
|
||||
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'librarySources' => !app(\App\Services\PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(\App\Services\OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(\App\Services\OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)]);
|
||||
}
|
||||
|
||||
public function reuseLibrary(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$row = app(\App\Services\OpportunityLibrarySupport::class)->attach($request->user(), Opportunity::findOrFail($id), $request->all());
|
||||
return response()->json(['id' => $row->id, 'message' => 'Original associado como suporte privado, sem copiar ficheiros ou publicar.']);
|
||||
}
|
||||
|
||||
public function save(Request $request, int $id, string $kind, OpportunityResources $service, ?string $resourceId = null): JsonResponse
|
||||
@@ -144,11 +150,15 @@ class OpportunityResourceController extends Controller
|
||||
{
|
||||
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
|
||||
$opportunity = Opportunity::findOrFail($id);
|
||||
app(\App\Services\PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
|
||||
abort_if($opportunity->status === 'archived', 404);
|
||||
$record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']);
|
||||
abort_unless($record !== null, 404, 'Recurso indisponível ou excluído logicamente.');
|
||||
abort_unless($record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
|
||||
|
||||
$support = DB::table($service->table($kind))->where('id', $resourceId)->first();
|
||||
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($support, $record);
|
||||
if (request()->filled('source_sha256')) abort_unless(hash_equals(trim($record->sha256), (string)request('source_sha256')), 409, 'O original já não corresponde à versão consultada.');
|
||||
return app(VerifiedDocumentBinary::class)->respond($record);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Mail\ContactMessageReceivedMail;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
class PortalContactController extends Controller
|
||||
{
|
||||
// Adapter for investidor's contact form: preserve its fields and validation,
|
||||
// using the configured mail transport without adding a database dependency.
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => ['required', 'string', 'min:2', 'max:150'],
|
||||
'email' => ['required', 'email', 'max:255'],
|
||||
'phone' => ['nullable', 'string', 'max:30'],
|
||||
'subject' => ['required', 'string', 'min:3', 'max:100'],
|
||||
'message' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
]);
|
||||
|
||||
try {
|
||||
Mail::to(config('contact_messages.recipient'))
|
||||
->send(new ContactMessageReceivedMail([
|
||||
'name' => $data['name'], 'email' => $data['email'], 'phone' => $data['phone'] ?? null,
|
||||
'subject' => $data['subject'], 'message' => $data['message'], 'platform' => 'InvesteMoz',
|
||||
]));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Falha no envio de contacto do portal.', ['exception' => $exception::class]);
|
||||
|
||||
return response()->json(['success' => false, 'message' => 'Ocorreu um erro ao enviar a mensagem.'], 500);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'message' => 'Mensagem enviada com sucesso.'], 201);
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,36 @@ class PortalManagementController extends Controller
|
||||
return Inertia::render('management/history', ['events' => $events]);
|
||||
}
|
||||
|
||||
private function interestAssignmentEtag(InterestRequest $interest): string
|
||||
{
|
||||
return hash('sha256',json_encode([$interest->id,$interest->status,$interest->assigned_to,$interest->updated_at?->format('Y-m-d H:i:s.u')],JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function interestAssignments(Request $request): Response|JsonResponse
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
||||
$rows=InterestRequest::whereNotIn('status',['cancelled','closed','refused','converted'])->orderBy('id')->get(['id','reference','status','assigned_to','updated_at'])
|
||||
->map(fn($row)=>['id'=>$row->id,'protocol'=>$row->reference,'status'=>$row->status,'analyst_id'=>$row->assigned_to,'version'=>0,'etag'=>$this->interestAssignmentEtag($row),'due_at'=>null]);
|
||||
$data=['kind'=>'interest','requests'=>$rows,'analysts'=>$this->interestAssignees()->get(['id','name'])];
|
||||
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
|
||||
}
|
||||
|
||||
public function assignInterest(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
||||
$data=$request->validate(['etag'=>'required|string|size:64','analyst_id'=>['required','integer',Rule::in($this->interestAssignees()->pluck('id'))],'reason'=>'required|string|min:10|max:2000'],['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 10 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.in'=>'Seleccione um responsável autorizado.']);
|
||||
DB::transaction(function()use($request,$interest,$data){
|
||||
$row=InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
|
||||
if (!hash_equals($this->interestAssignmentEtag($row),$data['etag'])) throw ValidationException::withMessages(['etag'=>'A atribuição mudou. Recupere a lista actual e tente novamente.']);
|
||||
if (in_array($row->status,['cancelled','closed','refused','converted'],true)) throw ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
||||
$owner=(int)($row->metadata['portal_user_id']??0);
|
||||
abort_if($owner===(int)$data['analyst_id'] || InvestmentSubmission::where('interest_request_id',$row->id)->where('user_id',$data['analyst_id'])->exists(),422,'O interessado não pode acompanhar o seu próprio pedido como equipa.');
|
||||
PortalAudit::save($row,['assigned_to'=>(int)$data['analyst_id']],$request->user()->id);
|
||||
app(\App\Services\PortalProfileAccess::class)->audit($request->user(),'interest_assigned',['interest_id'=>$row->id,'assigned_to'=>(int)$data['analyst_id'],'reason'=>$data['reason']]);
|
||||
});
|
||||
return $request->expectsJson()?response()->json(['ok'=>true]):back()->with('success','Responsável atribuído.');
|
||||
}
|
||||
|
||||
public function interests(Request $request): Response
|
||||
{
|
||||
$filters = $request->validate([
|
||||
@@ -65,6 +95,7 @@ class PortalManagementController extends Controller
|
||||
$query = InterestRequest::query()->with('assignee:id,name')->select([
|
||||
'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
||||
]);
|
||||
app(\App\Services\ScopedPortalAdministration::class)->interestQuery($query, $request->user());
|
||||
if ($country = $filters['country'] ?? null) {
|
||||
$values = app(CountryCatalogue::class)->filterValues($country);
|
||||
$query->whereIn(DB::raw('LOWER(BTRIM(country))'), $values);
|
||||
@@ -111,6 +142,7 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function interest(InterestRequest $interest): Response
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
||||
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
|
||||
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
|
||||
->map(function ($row) {
|
||||
@@ -138,12 +170,18 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
||||
$validated = $request->validate([
|
||||
'status' => ['required', Rule::in(self::STATES)],
|
||||
'note' => ['nullable', 'string', 'min:10', 'max:2000'],
|
||||
'next_action' => ['nullable', 'required_with:next_action_due_at', 'string', 'max:180'],
|
||||
'next_action_due_at' => ['nullable', 'required_with:next_action', 'date', 'after_or_equal:today'],
|
||||
'assigned_to' => ['nullable', 'integer', Rule::in($this->interestAssignees()->pluck('id'))],
|
||||
], [
|
||||
'next_action_due_at.required_with' => 'Indique o prazo da próxima acção.',
|
||||
'next_action_due_at.date' => 'Indique uma data válida para a próxima acção.',
|
||||
'next_action_due_at.after_or_equal' => 'O prazo da próxima acção deve ser hoje ou uma data futura.',
|
||||
'next_action.required_with' => 'Descreva a próxima acção correspondente ao prazo indicado.',
|
||||
]);
|
||||
$before = $interest->status;
|
||||
$updated = $workflow->transition($request->user(), $interest, $validated['status'], $validated['note'] ?? null,
|
||||
@@ -160,6 +198,7 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
$this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent');
|
||||
|
||||
@@ -169,6 +208,7 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
$this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest');
|
||||
|
||||
@@ -217,7 +257,9 @@ class PortalManagementController extends Controller
|
||||
['triagers', 'reviewers', 'approvers_l1', 'approvers_l2', 'publishers'],
|
||||
)));
|
||||
|
||||
return User::query()->whereNotNull('email_verified_at')->whereIn(DB::raw('lower(email)'), $emails)->orderBy('name');
|
||||
return User::query()->whereNotNull('email_verified_at')->where(function ($q) use ($emails) {
|
||||
$q->whereIn(DB::raw('lower(email)'), $emails)->orWhereIn('id', DB::table('portal_superuser_pair')->select('first_user_id'))->orWhereIn('id', DB::table('portal_superuser_pair')->select('second_user_id'));
|
||||
})->orderBy('name');
|
||||
}
|
||||
|
||||
public function catalog(Request $request, string $resource): Response
|
||||
|
||||
@@ -286,17 +286,47 @@ class PortalServicesController extends Controller
|
||||
return app(VerifiedDocumentBinary::class)->respond($document, true);
|
||||
}
|
||||
|
||||
public function downloadForManager(string $id): BinaryFileResponse|\Illuminate\Http\Response
|
||||
public function downloadForManager(Request $request, string $id): BinaryFileResponse|\Illuminate\Http\Response
|
||||
{
|
||||
$document = DB::table('documents')->where('id', $id)->whereNull('deleted_at')->first();
|
||||
$document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->first();
|
||||
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
|
||||
|
||||
return app(VerifiedDocumentBinary::class)->respond($document);
|
||||
}
|
||||
|
||||
public function manage(MalwareScanner $scanner): Response
|
||||
public function manage(Request $request, MalwareScanner $scanner): Response
|
||||
{
|
||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
||||
if (! $access->full($request->user())) {
|
||||
$documents = $access->documents($request->user())->where('status', '!=', 'deleted');
|
||||
$health = $scanner->health();
|
||||
$health['signatures_at'] = $health['signatures_at']?->format(DATE_ATOM);
|
||||
|
||||
$editorial = $access->editorial($request->user());
|
||||
$resources = $editorial ? $access->editorialResources($request->user())->orderByDesc('r.updated_at')
|
||||
->get(['r.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.status as file_status', 'd.data_classification', 'd.version_no as file_version', 'd.rights_status as file_rights_status', 'd.malware_scan_status', 'd.malware_failure_reason']) : collect();
|
||||
$links = DB::table('portal_resource_links')->whereIn('resource_id', $resources->pluck('id'))->orderBy('id')->get()->groupBy('resource_id');
|
||||
$revisions = DB::table('portal_resource_revisions')->whereIn('resource_id', $resources->pluck('id'))->orderByDesc('revision_no')->get(['resource_id', 'revision_no', 'change_type', 'actor_user_id', 'created_at'])->groupBy('resource_id');
|
||||
$resources->each(function ($resource) use ($links, $revisions) {
|
||||
$resource->links = $links->get($resource->id, collect())->values();
|
||||
$resource->revisions = $revisions->get($resource->id, collect())->values();
|
||||
});
|
||||
return Inertia::render('portal/manage', [
|
||||
'documentAccessOnly' => ! $editorial, 'editorialScopeOnly' => $editorial, 'resources' => $resources, 'partnerships' => [], 'territories' => [],
|
||||
'requirementCatalogue' => [], 'requirementAssociationsEnabled' => false,
|
||||
'disclosureAuthorization' => null, 'incompleteCount' => $resources->filter(fn ($r) => ! $r->description || ! $r->issuer || ! $r->source_url || $r->source_confirmation === 'unconfirmed' || $r->legal_status === 'unknown' || $r->rights_status === 'unconfirmed')->count(), 'possibleDuplicates' => $resources->whereNotNull('duplicate_of_resource_id')->count(),
|
||||
'documents' => (clone $documents)->latest()->limit(250)->get([
|
||||
'id', 'file_name', 'media_type', 'size_bytes', 'issuer', 'issued_on', 'valid_until',
|
||||
'uploaded_by', 'created_at', 'status', 'data_classification', 'version_no', 'sha256',
|
||||
'rights_status', 'malware_scan_status', 'malware_scanned_at', 'malware_failure_reason',
|
||||
'malware_engine_version', 'malware_signatures_at', 'malware_scan_attempts',
|
||||
]),
|
||||
'malwareCounts' => (clone $documents)->select('malware_scan_status', DB::raw('count(*) as total'))
|
||||
->groupBy('malware_scan_status')->pluck('total', 'malware_scan_status'),
|
||||
'malwareHealth' => $health,
|
||||
]);
|
||||
}
|
||||
$disclosureAuthorization = DB::table('audit_events')->where('source_system', 'user-instruction')
|
||||
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
|
||||
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
|
||||
@@ -378,6 +408,7 @@ class PortalServicesController extends Controller
|
||||
$id = DB::transaction(function () use ($data, $request): int {
|
||||
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
||||
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
||||
$identity = $this->identityKey($data);
|
||||
if ($identity) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
||||
@@ -406,9 +437,11 @@ class PortalServicesController extends Controller
|
||||
DB::transaction(function () use ($data, $request, $id, $expectedVersion): void {
|
||||
$resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($resource !== null, 404);
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||
abort_if((int) $resource->metadata_version !== $expectedVersion, 409, 'O documento foi alterado por outra sessão. Recarregue a revisão antes de editar.');
|
||||
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
||||
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
||||
$identity = $this->identityKey($data);
|
||||
if ($identity) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
||||
@@ -437,6 +470,11 @@ class PortalServicesController extends Controller
|
||||
|
||||
public function moderate(Request $request, string $type, int $id): RedirectResponse
|
||||
{
|
||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
||||
if (! $access->full($request->user())) {
|
||||
abort_unless($type === 'resources', 403);
|
||||
$access->assertEditableResource($request->user(), $id);
|
||||
}
|
||||
if ($type === 'partnerships' && Schema::hasColumn('portal_partnerships', 'partnership_type')) {
|
||||
return redirect('/parcerias/'.$id)->with('success', 'Reveja a proposta e registe uma decisão fundamentada na ficha da Bolsa.');
|
||||
}
|
||||
@@ -444,6 +482,7 @@ class PortalServicesController extends Controller
|
||||
$table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships';
|
||||
DB::transaction(function () use ($request, $data, $table, $type, $id) {
|
||||
abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404);
|
||||
if ($type === 'resources') app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||
if ($type === 'resources' && $data['published']) {
|
||||
$resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->where('r.id', $id)->first(['r.document_type', 'r.legislation', 'r.source_confirmation', 'r.legal_status', 'r.rights_status',
|
||||
|
||||
@@ -148,7 +148,7 @@ class VirtualDeskController extends Controller
|
||||
$data = ['boundContextRevision' => app(InvestorContextConsumers::class)->requestRevision($row), 'countries' => app(CountryCatalogue::class)->all(), 'toolPrefill' => $desk->requestToolPrefill($request->user(), $row), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
|
||||
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
|
||||
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
|
||||
'owner' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'), 'analyst' => (int) $row->analyst_id === $request->user()->id,
|
||||
'owner' => $desk->owns($request->user(), $case), 'manager' => app(\App\Services\ScopedPortalAdministration::class)->deskDecision($request->user(),$row), 'analyst' => (int) $row->analyst_id === $request->user()->id,
|
||||
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
|
||||
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
||||
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
|
||||
@@ -176,14 +176,26 @@ class VirtualDeskController extends Controller
|
||||
return $request->expectsJson() ? response()->json(['version' => $row->version, 'status' => $row->status]) : back()->with('success', 'Decisão interna registada.');
|
||||
}
|
||||
|
||||
public function assignments(Request $request): JsonResponse|Response
|
||||
{
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
||||
// Triage projection deliberately excludes payloads, documents, investor identity and case titles.
|
||||
$data=['requests'=>DB::table('desk_requests')->whereNotIn('status',['draft','cancelled','closed'])->orderBy('created_at')->get(['id','protocol','status','version','analyst_id','due_at']),
|
||||
'analysts'=>User::whereNotNull('email_verified_at')->orderBy('name')->get(['id','name'])];
|
||||
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
|
||||
}
|
||||
|
||||
public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
abort_unless($request->user()->can('manage-portal'), 403);
|
||||
$data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date']);
|
||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||
$data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date'], ['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 3 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.exists'=>'Seleccione um responsável com conta disponível.']);
|
||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, false, true);
|
||||
$case = $desk->case($request->user(), $row->case_id);
|
||||
abort_unless((int) $row->version === (int) $data['version'] && ! in_array($row->status, ['draft', 'cancelled', 'closed'], true), 409);
|
||||
$row = DB::table('desk_requests')->where('id',$id)->lockForUpdate()->first();
|
||||
abort_unless($row,404);
|
||||
$case = DB::table('desk_cases')->where('id',$row->case_id)->first();
|
||||
abort_unless($case,404);
|
||||
if ((int)$row->version !== (int)$data['version']) throw \Illuminate\Validation\ValidationException::withMessages(['version'=>'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
|
||||
if (in_array($row->status,['draft','cancelled','closed'],true)) throw \Illuminate\Validation\ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
||||
$analyst = User::where('id', $data['analyst_id'])->firstOrFail();
|
||||
abort_unless($analyst->hasVerifiedEmail(), 422, 'O responsável deve ter conta verificada.');
|
||||
abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.');
|
||||
@@ -217,13 +229,18 @@ class VirtualDeskController extends Controller
|
||||
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Mensagem privada guardada.');
|
||||
}
|
||||
|
||||
public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse
|
||||
public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse|\Illuminate\Http\Response
|
||||
{
|
||||
$row = $desk->request($request->user(), $id);
|
||||
abort_unless($row->protocol && $row->submitted_snapshot, 404);
|
||||
$snapshot = $desk->decode($row->submitted_snapshot);
|
||||
$format = $request->validate(['format' => 'nullable|in:html'])['format'] ?? null;
|
||||
$this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded');
|
||||
|
||||
if ($format === 'html') {
|
||||
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $desk->definition($row)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
return response()->streamDownload(function () use ($row, $snapshot) {
|
||||
echo 'Balcão Virtual — recibo de submissão interna'.PHP_EOL.$row->protocol.PHP_EOL.'Data: '.$row->submitted_at.PHP_EOL.'Versão: '.$row->version.PHP_EOL;
|
||||
echo json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsureDocumentManagement
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
abort_unless($actor, 403);
|
||||
$access = app(DocumentManagementAccess::class);
|
||||
if ($access->full($actor)) {
|
||||
return $next($request); // Preserve existing management controls.
|
||||
}
|
||||
$allowed = $access->limited($actor) || $access->editorial($actor);
|
||||
$access->audit($actor, $allowed ? 'document_access_allowed' : 'document_access_denied', [
|
||||
'scope' => $access->editorial($actor) ? 'approved-editorial-catalogue-and-own-files' : 'own-portal-services-files', 'method' => $request->method(), 'path' => $request->path(),
|
||||
]);
|
||||
abort_unless($allowed, 403, 'O acesso documental exige autorização, email confirmado e autenticação MFA nesta sessão.');
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
namespace App\Http\Middleware;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
/** Environment reservation is not a portal identity or a business permission. */
|
||||
class EnsureHomologationAccess
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (!config('portal.homologation_only', false)) return $next($request);
|
||||
$mode=config('portal.homologation_access_mode', 'reviewers');
|
||||
if ($mode==='perimeter') {
|
||||
// Set only by the trusted server after its environment-access check.
|
||||
// A client HTTP_INVESTMOZ_* header is deliberately not accepted.
|
||||
abort_unless($request->server('INVESTMOZ_HOMOLOGATION_ACCESS')==='granted',403,
|
||||
'Este ambiente de homologação tem acesso reservado à Tempo.');
|
||||
$response=$next($request);
|
||||
$response->headers->set('Cache-Control','private, no-store');
|
||||
$response->headers->set('X-Robots-Tag','noindex, nofollow, noarchive');
|
||||
return $response;
|
||||
}
|
||||
abort_unless($mode==='reviewers',503,'A reserva da homologação não está configurada.');
|
||||
// Compatibility until an independent perimeter is explicitly configured.
|
||||
if ($request->is('login','logout','register','forgot-password','reset-password','reset-password/*',
|
||||
'email/verify','email/verify/*','email/verification-notification','two-factor-challenge',
|
||||
'user/confirm-password','user/confirmed-password-status','user/two-factor-*',
|
||||
'settings/security','settings/password','user/password','passkeys/*','user/passkeys/*','up')) return $next($request);
|
||||
$actor=$request->user();
|
||||
if (!$actor) return $request->expectsJson()
|
||||
? response()->json(['message'=>'Entre na conta autorizada para homologação.'],401)
|
||||
: redirect()->guest(route('login'));
|
||||
abort_unless($actor->hasVerifiedEmail() && in_array(strtolower(trim($actor->email)),config('portal.homologation_reviewers',[]),true),403,
|
||||
'Esta homologação está reservada às contas indicadas pela Tempo.');
|
||||
$response=$next($request);$response->headers->set('Cache-Control','private, no-store');return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
namespace App\Http\Middleware;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
class EnsureScopedEditorial
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
abort_unless($actor, 403);
|
||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
||||
if ($access->full($actor)) {
|
||||
return $next($request);
|
||||
}
|
||||
abort_unless($access->editorial($actor), 403);
|
||||
$allowed = in_array($request->route()->getName(), ['editorial.edit', 'editorial.save', 'services.resource', 'services.resource.update'], true)
|
||||
|| ($request->route()->getName() === 'services.moderate' && $request->route('type') === 'resources');
|
||||
abort_unless($allowed, 403);
|
||||
if ($request->route('id') !== null) {
|
||||
$access->assertEditableResource($actor, (int) $request->route('id'));
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
namespace App\Http\Middleware;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use App\Services\ScopedPortalAdministration;
|
||||
|
||||
final class EnsureScopedPortalAdministration
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor=$request->user();abort_unless($actor,403);
|
||||
$scope=app(ScopedPortalAdministration::class);
|
||||
$path=$request->path();
|
||||
$interests=$request->is('management/interests','management/interests/*','api/v1/investment/admin/interests/*');
|
||||
// Exact areas of P1; unrelated management, fiscal rules and private records keep their gate.
|
||||
$catalogue=$request->is('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/*',
|
||||
'management/balcao/atribuicoes','management/balcao/atribuicoes/*','management/balcao/servicos',
|
||||
'management/balcao/fontes') || ($request->isMethod('GET') && $path==='management/balcao-install');
|
||||
$allowed=$interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor));
|
||||
abort_unless($allowed || ($actor->can('manage-portal') && !app(\App\Services\PortalProfileAccess::class)->has($actor,'auditor')),403,'Acesso reservado ao âmbito já designado.');
|
||||
$response=$next($request);
|
||||
if (!$request->isMethod('GET') && $response->getStatusCode()<400) {
|
||||
app(\App\Services\PortalProfileAccess::class)->audit($actor,'scoped_administration',[
|
||||
'method'=>$request->method(),'route'=>$request->route()?->uri(),'scope'=>$interests?'assigned-interest':'catalogue-administration']);
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -51,8 +51,10 @@ class HandleInertiaRequests extends Middleware
|
||||
return [
|
||||
...parent::share($request),
|
||||
'name' => config('app.name'),
|
||||
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||
'portalOperator' => config('portal.operator_name'),
|
||||
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
|
||||
'legacyContentEnabled' => app(LegacyContent::class)->available(),
|
||||
'educationEnabled' => (bool) config('education.enabled', false),
|
||||
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
|
||||
@@ -67,6 +69,15 @@ class HandleInertiaRequests extends Middleware
|
||||
'installationHref' => '/management/opportunity-management-install',
|
||||
] : null,
|
||||
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
|
||||
'scopedAdministration' => $request->user() && app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()) ? [
|
||||
['label'=>'Zonas e parques','href'=>'/management/investment/zones'],
|
||||
['label'=>'Referências económicas','href'=>'/management/economic-references/lot-01'],
|
||||
['label'=>'Referências e formulários','href'=>'/management/investment/references'],
|
||||
['label'=>'Educação e competências','href'=>'/management/education'],
|
||||
['label'=>'Interesses atribuídos','href'=>'/management/interests'],
|
||||
['label'=>'Atribuições de interesses','href'=>'/management/interests/atribuicoes'],
|
||||
['label'=>'Atribuições do Balcão','href'=>'/management/balcao/atribuicoes'],
|
||||
] : [],
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\InvestmentSubmission;
|
||||
use Closure;
|
||||
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** Tempo 19/10/2026: exception for simple participation only; formal operations retain verification. */
|
||||
class VerifiedOrSimpleParticipation
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) return $next($request);
|
||||
if ($request->isMethod('GET') && $request->is('investidor/manifestacoes', 'api/v1/investment/submissions')) return $next($request);
|
||||
$id = $request->route('id');
|
||||
$show = $request->isMethod('GET') && $request->is('investidor/manifestacoes/'.$id, 'api/v1/investment/submissions/'.$id);
|
||||
$message = $request->isMethod('POST') && $request->is('investidor/manifestacoes/'.$id.'/messages', 'api/v1/investment/submissions/'.$id.'/messages');
|
||||
if ($id && ($show || $message)) {
|
||||
$row = InvestmentSubmission::whereKey($id)->where('user_id', $request->user()->id)->firstOrFail();
|
||||
if ($row->status === 'submitted' && ($row->payload['simple_participation'] ?? false) === true) return $next($request);
|
||||
}
|
||||
return app(EnsureEmailIsVerified::class)->handle($request, $next);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ class StoreInterestRequestRequest extends FormRequest
|
||||
|
||||
return [
|
||||
'fullName' => ['required', 'string', 'min:3', 'max:150'],
|
||||
'email' => ['required', 'email:rfc,dns', 'max:150'],
|
||||
'email' => ['required', 'email:rfc', 'max:150'],
|
||||
'phone' => ['nullable', 'string', 'max:30'],
|
||||
'investorType' => ['required', 'string', Rule::in([
|
||||
'individual', 'empresa', 'fundo', 'entidade_publica', 'outro',
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
// Adapted from investidor/app/Mail/ContactMessageReceivedMail.php.
|
||||
class ContactMessageReceivedMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/** @param array{name: string, email: string, phone?: string|null, subject: string, message: string, platform: string} $contactMessage */
|
||||
public function __construct(public readonly array $contactMessage) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
replyTo: [new Address($this->contactMessage['email'], $this->contactMessage['name'])],
|
||||
subject: $this->contactMessage['subject'],
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
view: 'emails.contact-message-received',
|
||||
text: 'emails.contact-message-received-text',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ class ExistingBusinessPolicy
|
||||
public function scopeReviewQueue(Builder $query, User $user): void
|
||||
{
|
||||
if (app(PortalProfileAccess::class)->available()) {
|
||||
$query->where('modality', 'company_sale');
|
||||
$query->whereIn('modality',array_keys(\App\Services\ExistingBusinessProfileCategory::MAP));
|
||||
$ids = (clone $query)->get()->filter(fn (ExistingBusiness $business) => $this->view($user, $business))->modelKeys();
|
||||
$query->whereKey($ids);
|
||||
}
|
||||
@@ -156,9 +156,8 @@ class ExistingBusinessPolicy
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->available()) {
|
||||
// Only the existing company-sale consumer is reconciled in this increment.
|
||||
// Do not translate other modalities or invent an organization from free text.
|
||||
if (($business !== null && $business->modality !== 'company_sale') || ! $access->mfa($user)) {
|
||||
$category=$business ? \App\Services\ExistingBusinessProfileCategory::category($business) : null;
|
||||
if (($business !== null && $category === null) || ! $access->mfa($user) || $access->has($user,'auditor')) {
|
||||
return false;
|
||||
}
|
||||
$role = $designation === 'publishers' ? 'publisher' : 'validator';
|
||||
@@ -166,8 +165,10 @@ class ExistingBusinessPolicy
|
||||
return false;
|
||||
}
|
||||
foreach ($access->grants($user, $role) as $grant) {
|
||||
if ($grant->organization_id === null
|
||||
&& in_array('business_sale', json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR), true)) {
|
||||
$organizationMatches = $grant->organization_id === null
|
||||
|| ($business !== null && $grant->organization_id === $business->organization_id);
|
||||
if ($organizationMatches
|
||||
&& ($category !== null ? in_array($category,json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR),true) : array_intersect(array_values(\App\Services\ExistingBusinessProfileCategory::MAP),json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR)) !== [])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,8 +100,11 @@ final class BusinessFormSchema
|
||||
$rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.source_date'][] = 'date_format:Y-m-d';
|
||||
$rules['payload.official_source_url'][] = 'url';
|
||||
$rules['payload.equity_percentage'][] = 'numeric';
|
||||
$rules['payload.equity_percentage'][] = 'between:0,100';
|
||||
// The field limit is a text length, not an 8% ceiling.
|
||||
$rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
|
||||
function ($attribute, $value, $fail) {
|
||||
if (strlen((string) $value) > 8) $fail('Indique a percentagem com até 8 caracteres.');
|
||||
}];
|
||||
foreach (['valid_until', 'mandate_valid_until'] as $date) {
|
||||
$rules['payload.'.$date][] = 'date_format:Y-m-d';
|
||||
}
|
||||
@@ -116,8 +119,12 @@ final class BusinessFormSchema
|
||||
/** @param array<string,mixed> $payload */
|
||||
public static function validateSubmission(array $payload, ?int $sectorId, string $modality): void
|
||||
{
|
||||
if (($payload['opportunity_type'] ?? null) !== $modality) {
|
||||
throw ValidationException::withMessages(['opportunity_type' => 'O tipo da oportunidade não corresponde à classificação guardada.']);
|
||||
$expectedType = ExistingBusinessProfileCategory::formType($modality);
|
||||
if ($expectedType === null) {
|
||||
throw ValidationException::withMessages(['opportunity_type' => 'Esta modalidade pode ser guardada em preparação. O formulário de submissão correspondente ainda não está definido; a modalidade não será alterada automaticamente.']);
|
||||
}
|
||||
if (($payload['opportunity_type'] ?? null) !== $expectedType) {
|
||||
throw ValidationException::withMessages(['opportunity_type' => 'O tipo de oportunidade não corresponde à modalidade guardada. Recupere o formulário; a modalidade original foi preservada.']);
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
|
||||
@@ -12,17 +12,19 @@ final class DeclaredOriginStatistics
|
||||
/** @return array<string, list<array{code: string|null, name: string, count: int}>> */
|
||||
public function forManager(User $actor, ?string $origin = null): array
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->interestOperator($actor), 403);
|
||||
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
|
||||
$groups = [];
|
||||
foreach (DB::table('interest_requests')->whereNull('deleted_at')->select('metadata')->cursor() as $row) {
|
||||
$interests=DB::table('interest_requests')->whereNull('deleted_at');
|
||||
app(ScopedPortalAdministration::class)->interestQuery($interests,$actor);
|
||||
foreach ($interests->select('metadata')->cursor() as $row) {
|
||||
$metadata = json_decode($row->metadata ?? '{}', true);
|
||||
$code = $metadata['declared_origin_country_code'] ?? null;
|
||||
$key = is_string($code) && isset($names[$code]) ? $code : '';
|
||||
$groups[$key] = ($groups[$key] ?? 0) + 1;
|
||||
}
|
||||
$desk = [];
|
||||
if (Schema::hasTable('desk_requests')) {
|
||||
if ($actor->can('manage-portal') && Schema::hasTable('desk_requests')) {
|
||||
foreach (DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled'])->select('payload')->cursor() as $row) {
|
||||
$code = app(VirtualDesk::class)->decode($row->payload)['declared_origin_country_code'] ?? null;
|
||||
$key = is_string($code) && isset($names[$code]) ? $code : '';
|
||||
@@ -30,7 +32,7 @@ final class DeclaredOriginStatistics
|
||||
}
|
||||
}
|
||||
$businesses = [];
|
||||
if (Schema::hasTable('existing_businesses')) {
|
||||
if ($actor->can('manage-portal') && Schema::hasTable('existing_businesses')) {
|
||||
foreach (app(BusinessRepository::class)->query()->whereNotIn('status', ['draft', 'cancelled'])->cursor() as $business) {
|
||||
$code = $business->payload['declared_origin_country_code'] ?? null;
|
||||
$key = is_string($code) && isset($names[$code]) ? $code : '';
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class DocumentManagementAccess
|
||||
{
|
||||
public function full(User $actor): bool
|
||||
{
|
||||
return Gate::forUser($actor)->allows('manage-portal');
|
||||
}
|
||||
|
||||
public function limited(User $actor): bool
|
||||
{
|
||||
// Explicit Tempo authorisation; registration itself never grants access.
|
||||
return $actor->hasVerifiedEmail()
|
||||
&& in_array(strtolower(trim($actor->email)), config('portal.document_managers', []), true)
|
||||
&& app(PortalProfileAccess::class)->mfa($actor);
|
||||
}
|
||||
|
||||
/** Restore the approved editorial operation without a global management grant. */
|
||||
public function editorial(User $actor): bool
|
||||
{
|
||||
return config('portal.homologation_only', false)
|
||||
&& in_array(strtolower(trim($actor->email)), config('homologation_editorial.accounts', []), true)
|
||||
&& app(PortalProfileAccess::class)->superuser($actor)
|
||||
&& ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
||||
&& app(PortalProfileAccess::class)->mfa($actor);
|
||||
}
|
||||
|
||||
public function editorialResources(User $actor): Builder
|
||||
{
|
||||
abort_unless($this->editorial($actor), 403);
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
||||
->where(function ($query) use ($actor) {
|
||||
$query->where(function ($own) use ($actor) {
|
||||
$own->where('r.created_by', $actor->id)->where('d.uploaded_by', $actor->id)
|
||||
->where('d.source_system', 'portal-services');
|
||||
});
|
||||
foreach (config('homologation_editorial.resources', []) as $item) {
|
||||
$query->orWhere(function ($listed) use ($item) {
|
||||
$listed->where('r.id', $item['id'])->where('d.sha256', $item['sha256'])
|
||||
->where('d.external_id', $item['external_id']);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function assertEditableResource(User $actor, int $id): void
|
||||
{
|
||||
abort_unless($this->full($actor) || $this->editorialResources($actor)->where('r.id', $id)->exists(), 403);
|
||||
}
|
||||
|
||||
public function documents(User $actor): Builder
|
||||
{
|
||||
$query = DB::table('documents')->whereNull('deleted_at');
|
||||
if (! $this->full($actor)) {
|
||||
$editorial = $this->editorial($actor);
|
||||
abort_unless($this->limited($actor) || $editorial, 403);
|
||||
$query->where(function ($scope) use ($actor, $editorial) {
|
||||
$scope->where(fn ($own) => $own->where('uploaded_by', $actor->id)->where('source_system', 'portal-services'));
|
||||
if ($editorial) {
|
||||
$scope->orWhereIn('id', $this->editorialResources($actor)->select('d.id'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public function audit(User $actor, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert([
|
||||
'source_system' => 'document-access-v1', 'entity_type' => 'authorization',
|
||||
'actor_user_id' => $actor->id, 'action' => $action,
|
||||
'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
|
||||
'after_data' => json_encode($data, JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class EconomicReferenceInstallation
|
||||
|
||||
private function authorize(User $actor, bool $write = false, string $operation = ''): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'), 403, 'Acesso reservado à gestão autorizada.');
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Acesso reservado à gestão autorizada.');
|
||||
if (! $write) { return; }
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_if($access->has($actor, 'auditor'), 403, 'A restrição de Auditor permite apenas consulta.');
|
||||
|
||||
@@ -37,7 +37,7 @@ final class ExistingBusinessIntake
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
$profileWorkflow = $business->modality === 'company_sale' && app(PortalProfileAccess::class)->available();
|
||||
$profileWorkflow = ExistingBusinessProfileCategory::category($business) !== null && app(PortalProfileAccess::class)->available();
|
||||
$ability = match ($action) {
|
||||
OpportunityStatus::Submitted->value, OpportunityStatus::Withdrawn->value => 'owns',
|
||||
OpportunityStatus::Triage->value => 'triage',
|
||||
@@ -65,6 +65,14 @@ final class ExistingBusinessIntake
|
||||
OpportunityStatus::Triage->value, OpportunityStatus::InReview->value, OpportunityStatus::NeedsInformation->value],
|
||||
];
|
||||
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
|
||||
// Reuse the bounded delivery contract: profile correspondence is access, not functional enablement.
|
||||
$category = ExistingBusinessProfileCategory::category($business);
|
||||
if ($category !== null && in_array($action, ['submitted', 'published'], true)) {
|
||||
$blockers = app(OpportunityCanonicalContract::class)->deliveryBlockers(['opportunity_category' => $category]);
|
||||
if ($blockers) {
|
||||
throw ValidationException::withMessages(['modality' => implode(' ', array_values($blockers))]);
|
||||
}
|
||||
}
|
||||
if ($action === 'submitted') {
|
||||
if (($business->payload['wizard_version'] ?? null) === '2') {
|
||||
BusinessFormSchema::validateSubmission($business->payload, $business->sector_id, $business->modality);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
|
||||
/** Access correspondence, never evidence of legality, title, finance or publication. */
|
||||
final class ExistingBusinessProfileCategory
|
||||
{
|
||||
// Exact catalogue correspondences plus the explicit mappings already present
|
||||
// in BusinessWizard and the transaction variants in OpportunityCategoryFields.
|
||||
public const MAP = [
|
||||
'company_sale'=>'business_sale', 'participation_sale'=>'business_sale',
|
||||
'buyer_search'=>'business_sale', 'succession'=>'business_sale',
|
||||
'franchise'=>'franchise', 'real_estate'=>'real_estate', 'land_right'=>'land_rights',
|
||||
'investment_project'=>'investment_project', 'expansion'=>'investment_project',
|
||||
'internationalization'=>'investment_project', 'agricultural_investment'=>'investment_project',
|
||||
'business_partnership'=>'business_partnership', 'strategic_partner'=>'business_partnership',
|
||||
'joint_venture'=>'business_partnership', 'capital_increase'=>'financing',
|
||||
'financial_investor'=>'financing', 'financing_request'=>'financing',
|
||||
'concession_opportunity'=>'concession', 'supply_opportunity'=>'supply',
|
||||
];
|
||||
|
||||
// Native form types are separate from the persisted modality. No default to a project.
|
||||
public const FORM_TYPES = [
|
||||
'investment_project'=>'investment_project', 'company_sale'=>'company_sale',
|
||||
'asset_sale'=>'asset_sale', 'business_partnership'=>'business_partnership',
|
||||
'financing_request'=>'financing_request', 'concession_opportunity'=>'concession_opportunity',
|
||||
'supply_opportunity'=>'supply_opportunity', 'participation_sale'=>'company_sale',
|
||||
'asset_lease'=>'asset_sale', 'capital_increase'=>'financing_request',
|
||||
'financial_investor'=>'financing_request', 'strategic_partner'=>'business_partnership',
|
||||
'joint_venture'=>'business_partnership', 'expansion'=>'investment_project',
|
||||
'agricultural_investment'=>'investment_project', 'internationalization'=>'investment_project',
|
||||
'buyer_search'=>'company_sale', 'succession'=>'company_sale',
|
||||
];
|
||||
|
||||
public static function category(ExistingBusiness $business): ?string
|
||||
{
|
||||
return self::MAP[$business->modality] ?? null;
|
||||
}
|
||||
|
||||
public static function formType(string $modality): ?string
|
||||
{
|
||||
return self::FORM_TYPES[$modality] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ final class InterestWorkflow
|
||||
|
||||
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
|
||||
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->interest($actor,$locked),403);
|
||||
$from = $locked->status;
|
||||
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
|
||||
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
|
||||
|
||||
@@ -18,6 +18,7 @@ class InvestmentCatalogue
|
||||
public function filters(Request $request): array
|
||||
{
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
|
||||
@@ -40,6 +41,17 @@ class InvestmentCatalogue
|
||||
'publication_state' => ['nullable', 'in:published'],
|
||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
app(InvestmentGeography::class)->selection($filters);
|
||||
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
||||
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
||||
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
||||
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
|
||||
throw \Illuminate\Validation\ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
|
||||
}
|
||||
if (\Illuminate\Support\Str::isUuid($filters['association_target'])) {
|
||||
$filters[$alias] = $filters['association_target'];
|
||||
unset($filters['association_type'], $filters['association_target']);
|
||||
}
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
@@ -51,6 +63,7 @@ class InvestmentCatalogue
|
||||
public function query(array $filters): Builder
|
||||
{
|
||||
$query = Opportunity::published()->with('sector:id,name,slug');
|
||||
$associated = $this->publicAssociatedIds($filters);
|
||||
if (($filters['territory_basis'] ?? 'all') === 'direct') {
|
||||
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
|
||||
} elseif (($filters['territory_basis'] ?? 'all') === 'context') {
|
||||
@@ -92,15 +105,17 @@ class InvestmentCatalogue
|
||||
}
|
||||
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) {
|
||||
if (! empty($filters[$field])) {
|
||||
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()
|
||||
$legacy = app(InvestmentZones::class)->links()->where('zl.association_type', '<>', 'proximity')
|
||||
->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
|
||||
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $category)
|
||||
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id'));
|
||||
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id');
|
||||
$query->where(fn ($matches) => $matches->whereIn('opportunities.id', $legacy)
|
||||
->orWhereIn('opportunities.id', $associated[$field] ?? []));
|
||||
}
|
||||
}
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.$filters['q'].'%';
|
||||
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
|
||||
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('description', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
|
||||
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term))
|
||||
->orWhereExists(fn ($g) => $g->selectRaw('1')->from('geo_locations as search_location')->whereNull('search_location.deleted_at')->where('search_location.data_classification', 'public')
|
||||
->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
|
||||
@@ -116,11 +131,21 @@ class InvestmentCatalogue
|
||||
if (! empty($filters['sector'])) {
|
||||
SectorOrganization::constrain($query, $filters['sector']);
|
||||
}
|
||||
foreach (['province', 'district', 'maturity_level'] as $field) {
|
||||
foreach (['province', 'district'] as $field) {
|
||||
if (! empty($filters[$field])) {
|
||||
$query->where($field, $filters[$field]);
|
||||
}
|
||||
}
|
||||
if (! empty($filters['preparation'])) {
|
||||
OpportunityMaturity::constrainSearch($query, $filters['preparation']);
|
||||
} elseif (! empty($filters['maturity_level'])) {
|
||||
// Legacy links predate the eight-stage catalogue: retain their original meaning.
|
||||
OpportunityMaturity::constrainSearch($query, match ((int) $filters['maturity_level']) {
|
||||
7 => 'stage:implementation',
|
||||
8 => 'stage:operational',
|
||||
default => 'historical:'.$filters['maturity_level'],
|
||||
});
|
||||
}
|
||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||
if (! empty($filters[$foreign])) {
|
||||
$locationIds = $relation === 'locations'
|
||||
@@ -141,13 +166,15 @@ class InvestmentCatalogue
|
||||
continue;
|
||||
}
|
||||
if (in_array($relation, ['clusters', 'corridors'], true)) {
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
|
||||
$query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])
|
||||
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)));
|
||||
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)))
|
||||
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
|
||||
} else {
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
|
||||
$query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
|
||||
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)));
|
||||
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)))
|
||||
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,7 +214,9 @@ class InvestmentCatalogue
|
||||
* @return array<string,mixed> */
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
{
|
||||
$path = app(InvestmentGeography::class)->selection($territoryFilters);
|
||||
$result = ['classification' => app(OpportunityClassification::class)->options(),
|
||||
'preparationOptions' => OpportunityMaturity::searchOptions(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||
'categories' => OpportunityManagement::CATEGORIES,
|
||||
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||
@@ -205,18 +234,67 @@ class InvestmentCatalogue
|
||||
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
|
||||
}
|
||||
}
|
||||
if (! $management && $path !== [] && $relation !== 'locations') {
|
||||
$dossiers = InvestmentPortfolioController::visible();
|
||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
|
||||
app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
|
||||
$query->whereIn('id', $dossiers->whereNotNull($foreign)->select($foreign));
|
||||
}
|
||||
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
|
||||
}
|
||||
|
||||
$zones = app(InvestmentZones::class)->visible();
|
||||
if (! $management && $territoryFilters !== []) {
|
||||
$zones = app(InvestmentZones::class)->search($territoryFilters);
|
||||
// Opportunity words/modalities are not names/categories of zones.
|
||||
$zones = app(InvestmentZones::class)->search(\Illuminate\Support\Arr::only($territoryFilters,
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
||||
}
|
||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||
if (! $management && ($path !== [] || ! empty($territoryFilters['sector']))) {
|
||||
$scope = \Illuminate\Support\Arr::only($territoryFilters, ['sector','province_id','district_id','admin_post_id','locality_id','include_national']);
|
||||
$available = ['chain' => [], 'activity' => []];
|
||||
$this->query($scope)->reorder()->chunkById(200, function ($records) use (&$available) {
|
||||
foreach ($records as $record) {
|
||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
||||
if (isset($available[$row['target_type']])) $available[$row['target_type']][] = $row['target_id'];
|
||||
}
|
||||
foreach (['subsector_id','economic_activity_id'] as $key) {
|
||||
$id = $record->workflow_context['publication']['taxonomy'][$key] ?? null;
|
||||
if ($id) $available['activity'][] = $id;
|
||||
}
|
||||
}
|
||||
}, 'opportunities.id', 'id');
|
||||
foreach ($available as $kind => $ids) {
|
||||
$result['classification']['targets'][$kind] = collect($result['classification']['targets'][$kind])->whereIn('id', $ids)->values();
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function publicAssociatedIds(array $filters): array
|
||||
{
|
||||
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
|
||||
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
||||
$selected = array_filter(array_intersect_key($filters, $kinds));
|
||||
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
|
||||
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) unset($selected[$key]);
|
||||
}
|
||||
if ($selected === []) return [];
|
||||
$ids = [];
|
||||
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
||||
foreach ($records as $record) {
|
||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
||||
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') continue;
|
||||
foreach ($selected as $field => $target) {
|
||||
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) $ids[$field][] = $record->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return $ids;
|
||||
}
|
||||
|
||||
private function publicStructureIds(string $relation, string $foreign): \Illuminate\Database\Query\Builder
|
||||
{
|
||||
$table = self::RELATIONS[$relation][1];
|
||||
@@ -329,11 +407,11 @@ class InvestmentCatalogue
|
||||
DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'território declarado da oportunidade' ELSE 'contexto do projeto associado; implantação da oportunidade por confirmar' END AS basis")])
|
||||
->map(fn ($area) => ['geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')',
|
||||
'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null,
|
||||
'url' => '/oportunidades/'.$area->slug])->all();
|
||||
'url' => '/oportunidades/'.$area->slug.($filters === [] ? '' : '?'.http_build_query($filters))])->all();
|
||||
$located = 0;
|
||||
foreach ($records as $record) {
|
||||
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
|
||||
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug];
|
||||
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
|
||||
foreach ($relations as $relation => $groups) {
|
||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ class InvestmentZoneOperationalDetailsInstallation
|
||||
}
|
||||
private function authorize(User $actor,bool $write=false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
|
||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
||||
}
|
||||
private function evidence(array $target,string $code): array
|
||||
|
||||
@@ -31,7 +31,7 @@ class InvestmentZoneProfileInstallation
|
||||
}
|
||||
private function authorize(User $actor,bool $write=false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
|
||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
||||
}
|
||||
private function evidence(array $target,string $code): array
|
||||
|
||||
@@ -50,13 +50,24 @@ final class InvestorContext
|
||||
$href = '';
|
||||
$title = '';
|
||||
$version = null;
|
||||
$documents = [];
|
||||
$visibility = 'public';
|
||||
$state = null;
|
||||
if ($kind === 'opportunity') {
|
||||
abort_unless(ctype_digit($id), 422, 'Identificador de oportunidade inválido.');
|
||||
$o = Opportunity::published()->with('sector')->findOrFail((int) $id);
|
||||
$title = $o->title;
|
||||
$href = '/oportunidades/'.$o->slug;
|
||||
$o = Opportunity::with('sector')->findOrFail((int) $id);
|
||||
$published = Opportunity::published()->whereKey($o->id)->exists();
|
||||
if (!$published) {
|
||||
abort_unless(request()->user() && $o->status !== 'archived' && app(PortalProfileAccess::class)->canView(request()->user(), $o), 404, 'Ficha privada indisponível neste âmbito.');
|
||||
$visibility = 'private';
|
||||
$state = app(PortalProfileAccess::class)->state($o);
|
||||
}
|
||||
if (request()->user()) $documents = app(OpportunityLibrarySupport::class)->snapshot(request()->user(), $o);
|
||||
$draft = !$published ? app(OpportunityManagement::class)->values($o) : [];
|
||||
$title = $draft['canonical']['official_title'] ?? $o->title;
|
||||
$href = $published ? '/oportunidades/'.$o->slug : '/minhas-oportunidades/'.$o->id.'/view';
|
||||
$version = $o->management_version;
|
||||
$fields = ['project_title' => $o->title, 'project_summary' => $o->summary];
|
||||
$fields = ['project_title' => $title, 'project_summary' => $draft['canonical']['executive_summary'] ?? $o->summary];
|
||||
if ($o->sector) {
|
||||
$fields['sector_id'] = (string) $o->sector_id;
|
||||
$fields['sector'] = $o->sector->name;
|
||||
@@ -123,6 +134,7 @@ final class InvestorContext
|
||||
}
|
||||
$fields = array_filter($fields, fn ($v) => is_scalar($v) && trim((string) $v) !== '');
|
||||
$record = ['key' => $key, 'kind' => $kind, 'id' => $id, 'title' => $title, 'version' => $version, 'href' => $href, 'fields' => $fields];
|
||||
if ($documents || $visibility === 'private') $record += ['documents' => $documents, 'visibility' => $visibility, 'state' => $state];
|
||||
|
||||
return [...$record, 'sha256' => hash('sha256', json_encode($record, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
@@ -156,6 +168,10 @@ final class InvestorContext
|
||||
foreach (Opportunity::published()->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get(['id', 'title']) as $o) {
|
||||
$items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title, 'kind' => 'opportunity'];
|
||||
}
|
||||
if (request()->user()) {
|
||||
$private = app(PortalProfileAccess::class)->scope(Opportunity::query(), request()->user())->where('status', '!=', 'published')->where('status', '!=', 'archived')->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get();
|
||||
foreach ($private as $o) if (app(PortalProfileAccess::class)->canView(request()->user(), $o)) $items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title.' — preparação privada', 'kind' => 'opportunity'];
|
||||
}
|
||||
if (config('existing-business.enabled')) {
|
||||
foreach (ExistingBusiness::published()->when($query, fn ($q) => $q->where('public_title', 'ilike', '%'.$query.'%'))->orderBy('public_title')->limit(51)->get(['id', 'public_title']) as $o) {
|
||||
$items[] = ['key' => 'business:'.$o->id, 'title' => $o->public_title, 'kind' => 'business'];
|
||||
|
||||
@@ -40,7 +40,7 @@ final class LegacyContent
|
||||
abort_unless($this->available(), 404);
|
||||
$identity = config('legacy_content.articles.'.$slug);
|
||||
abort_unless(is_array($identity) && ($identity['publishable'] ?? false), 404);
|
||||
$row = $this->publicResources()->where('d.external_id', $identity['external_id'])->first();
|
||||
$row = $this->identityResources()->get($identity['external_id']);
|
||||
abort_unless($row !== null, 404);
|
||||
$binary = app(VerifiedDocumentBinary::class)->respond($row);
|
||||
$bytes = $binary instanceof BinaryFileResponse ? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
|
||||
@@ -106,7 +106,7 @@ final class LegacyContent
|
||||
public function articleForResource(int $resourceId): array
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$externalId = $this->publicResources()->where('r.id', $resourceId)->first()?->external_id;
|
||||
$externalId = $this->identityResources()->firstWhere('resource_id', $resourceId)?->legacy_identity;
|
||||
foreach (config('legacy_content.articles', []) as $slug => $identity) {
|
||||
if ($identity['external_id'] === $externalId && $identity['publishable']) {
|
||||
return $this->article($slug);
|
||||
@@ -132,7 +132,7 @@ final class LegacyContent
|
||||
private function related(string $group, ?string $except = null): array
|
||||
{
|
||||
$identities = array_filter(config('legacy_content.articles', []), fn ($identity, $slug) => $identity['group'] === $group && $identity['publishable'] && $slug !== $except, ARRAY_FILTER_USE_BOTH);
|
||||
$resources = $this->publicResources()->whereIn('d.external_id', array_column($identities, 'external_id'))->get()->keyBy('external_id');
|
||||
$resources = $this->identityResources();
|
||||
$result = [];
|
||||
foreach ($identities as $slug => $identity) {
|
||||
$row = $resources->get($identity['external_id']);
|
||||
@@ -146,8 +146,7 @@ final class LegacyContent
|
||||
|
||||
private function localLinks(string $html): string
|
||||
{
|
||||
$public = $this->publicResources()->whereIn('d.external_id', array_column(config('legacy_content.articles', []), 'external_id'))
|
||||
->get()->keyBy('external_id');
|
||||
$public = $this->identityResources();
|
||||
$links = [];
|
||||
foreach (config('legacy_content.articles', []) as $slug => $identity) {
|
||||
if ($identity['publishable'] && $public->get($identity['external_id'])?->source_url === $identity['source_url']) {
|
||||
@@ -208,6 +207,39 @@ final class LegacyContent
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve explicit transport aliases without changing original IDs, versions or relations. */
|
||||
private function identityResources(): \Illuminate\Support\Collection
|
||||
{
|
||||
$identities = array_column(config('legacy_content.articles', []), 'external_id');
|
||||
$aliases = config('legacy_content_aliases', []);
|
||||
$rows = $this->publicResources()->where(function ($query) use ($identities, $aliases) {
|
||||
$query->whereIn('d.external_id', $identities);
|
||||
if ($aliases !== []) {
|
||||
$query->orWhereIn('r.id', array_column($aliases, 'resource_id'));
|
||||
}
|
||||
})->get();
|
||||
$resolved = collect();
|
||||
foreach ($rows as $row) {
|
||||
$identity = in_array($row->external_id, $identities, true) ? $row->external_id : null;
|
||||
foreach ($aliases as $original => $alias) {
|
||||
if ((int) $row->resource_id === (int) $alias['resource_id']
|
||||
&& $row->external_id === $alias['external_id']
|
||||
&& hash_equals($alias['sha256'], trim($row->sha256))
|
||||
&& $row->source_url === $alias['source_url']) {
|
||||
abort_if($identity !== null && $identity !== $original, 409, 'Correspondência de artigo em reconciliação.');
|
||||
$identity = $original;
|
||||
}
|
||||
}
|
||||
if ($identity === null) {
|
||||
continue;
|
||||
}
|
||||
abort_if($resolved->has($identity), 409, 'Correspondência de artigo em reconciliação.');
|
||||
$row->legacy_identity = $identity;
|
||||
$resolved->put($identity, $row);
|
||||
}
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
private function publicResources(): Builder
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
|
||||
@@ -169,14 +169,23 @@ final class ClamDScanner implements MalwareScanner
|
||||
throw new RuntimeException('No production scanner is configured.');
|
||||
}
|
||||
|
||||
$host = (string) config('services.malware.host', '127.0.0.1');
|
||||
$port = (int) config('services.malware.port', 3310);
|
||||
if ($host === '' || in_array($host, ['0.0.0.0', '::'], true) || $port < 1 || $port > 65535) {
|
||||
throw new RuntimeException('The ClamD endpoint is invalid.');
|
||||
$unix = config('services.malware.socket');
|
||||
if ($unix !== null && $unix !== '') {
|
||||
if (! is_string($unix) || ! str_starts_with($unix, '/') || str_contains($unix, "\0") || strlen($unix) > 107) {
|
||||
throw new RuntimeException('The ClamD Unix socket is invalid.');
|
||||
}
|
||||
$endpoint = 'unix://'.$unix;
|
||||
} else {
|
||||
$host = (string) config('services.malware.host', '127.0.0.1');
|
||||
$port = (int) config('services.malware.port', 3310);
|
||||
if ($host === '' || in_array($host, ['0.0.0.0', '::'], true) || $port < 1 || $port > 65535) {
|
||||
throw new RuntimeException('The ClamD endpoint is invalid.');
|
||||
}
|
||||
$endpoint = "tcp://{$host}:{$port}";
|
||||
}
|
||||
|
||||
$timeout = max(1, (int) config('services.malware.timeout_seconds', 120));
|
||||
$socket = @stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage, min(10, $timeout));
|
||||
$socket = @stream_socket_client($endpoint, $errorCode, $errorMessage, min(10, $timeout));
|
||||
if (! is_resource($socket)) {
|
||||
throw new RuntimeException('ClamD is unavailable.');
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class OpportunityCanonicalContract
|
||||
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function schema(bool $draft = false): array
|
||||
public function schema(bool $draft = false, array $payload = []): array
|
||||
{
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
if ($bytes === false) {
|
||||
@@ -59,11 +59,14 @@ class OpportunityCanonicalContract
|
||||
$schema = app(OpportunityCategoryFields::class)->enrich($schema);
|
||||
$schema = app(OpportunityModularProfiles::class)->extend($schema);
|
||||
$schema = app(OpportunityClassification::class)->extend($schema);
|
||||
$schema = app(OpportunityInitiativeApplicability::class)->schema($schema, $payload);
|
||||
$schema = $this->writeSchema($schema, $draft);
|
||||
$properties = &$schema['$defs']['opportunityCreate']['properties'];
|
||||
unset($properties['mutation_context']); // Actor, audit reason and revision are server-owned.
|
||||
$properties['sector_id'] = ['type' => 'integer', 'minimum' => 1];
|
||||
$properties['promoter_id'] = ['type' => ['string', 'integer']];
|
||||
if (! app(OpportunityInitiativeApplicability::class)->enabled($payload)) {
|
||||
$properties['promoter_id'] = ['type' => ['string', 'integer']];
|
||||
}
|
||||
// References point to the existing collections; their metadata is recovered on the server.
|
||||
foreach (['locations', 'documents', 'images'] as $field) {
|
||||
$properties[$field]['items'] = ['type' => 'string', 'format' => 'uuid'];
|
||||
@@ -144,7 +147,7 @@ class OpportunityCanonicalContract
|
||||
/** @param array<string,mixed> $payload */
|
||||
private function validateSchema(array $payload, bool $draft): void
|
||||
{
|
||||
$schema = $this->schema($draft);
|
||||
$schema = $this->schema($draft, $payload);
|
||||
$validator = new CompliantValidator(null, 100, false);
|
||||
$data = $this->schemaData($payload, $schema['$defs']['opportunityCreate'], $schema['$defs']);
|
||||
$result = $validator->validate($data, json_decode(json_encode($schema, JSON_THROW_ON_ERROR)));
|
||||
@@ -168,6 +171,11 @@ class OpportunityCanonicalContract
|
||||
}
|
||||
$prefix = rtrim('canonical.'.implode('.', $node->data()->fullPath()), '.');
|
||||
$args = $node->args();
|
||||
if ($node->keyword() === 'type' && in_array($prefix, ['canonical.initiative.responsible_name', 'canonical.initiative.coverage_statement'], true)) {
|
||||
$errors[$prefix][] = 'Informação em falta: preencha este campo antes de submeter.';
|
||||
return;
|
||||
}
|
||||
|
||||
if ($node->keyword() === 'required') {
|
||||
foreach ($args['missing'] ?? [] as $field) {
|
||||
$errors[$prefix.'.'.$field][] = 'Preencha este campo antes de submeter.';
|
||||
@@ -241,15 +249,21 @@ class OpportunityCanonicalContract
|
||||
{
|
||||
$values = app(OpportunityManagement::class)->values($record);
|
||||
$payload = $values['canonical'] ?? [];
|
||||
$this->validateSchema($payload, false);
|
||||
$errors = [];
|
||||
$initiative = app(OpportunityInitiativeApplicability::class);
|
||||
$initiative->validate($payload, $errors);
|
||||
try {
|
||||
$this->validateSchema($payload, false);
|
||||
} catch (ValidationException $failure) {
|
||||
throw ValidationException::withMessages([...$failure->errors(), ...$errors]);
|
||||
}
|
||||
$check = function (bool $valid, string $path, string $message) use (&$errors): void {
|
||||
if (! $valid) {
|
||||
$errors['canonical.'.$path] = $message;
|
||||
}
|
||||
};
|
||||
$check(($payload['opportunity_category'] ?? null) === $record->opportunity_category, 'opportunity_category', 'A categoria deve coincidir com o registo e a autorização.');
|
||||
$check(($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Identifique o promotor real da oportunidade; o operador do portal não o substitui.');
|
||||
$check($initiative->enabled($payload) || ($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Identifique o promotor real da oportunidade; o operador do portal não o substitui.');
|
||||
$previous = app(OpportunityManagement::class)->values($record)['canonical'] ?? [];
|
||||
$sameTaxonomy = ($previous['sector_id'] ?? null) === ($payload['sector_id'] ?? null)
|
||||
&& ($previous['subsector_id'] ?? null) === ($payload['subsector_id'] ?? null)
|
||||
@@ -284,6 +298,7 @@ class OpportunityCanonicalContract
|
||||
&& hash_equals(trim($file->sha256), trim((string) $file->malware_scanned_sha256)), "$kind.$index", 'Original ativo com análise antimalware correspondente obrigatória.');
|
||||
if ($file) {
|
||||
// Verify actual bytes/cipher integrity as well as the recorded scan hash.
|
||||
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($row, $file);
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
$row->sha256 = trim($file->sha256);
|
||||
}
|
||||
@@ -296,7 +311,7 @@ class OpportunityCanonicalContract
|
||||
$check(! $hasArea || $hasUnit, "locations.$index.area_unit", 'Indique a unidade da área antes de submeter; a preparação incompleta continua guardada nos recursos.');
|
||||
$check(! $hasUnit || $hasArea, "locations.$index.area_value", 'Indique o valor da área antes de submeter; a unidade não determina o valor.');
|
||||
$check(! $hasUnit || in_array($location['area_unit'], OpportunityResources::AREA_UNITS, true), "locations.$index.area_unit", 'Use uma unidade do catálogo existente: sqm, ha ou sqkm.');
|
||||
$check(! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
|
||||
$check(! $initiative->applicable($payload, 'physical_site') || (! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location)), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
|
||||
app(InvestmentGeography::class)->selection($location, true);
|
||||
$country = $location['country_code'] ?? null;
|
||||
$check($country === 'MZ', "locations.$index.country_code", 'A hierarquia administrativa moçambicana deve declarar MZ; outros países exigem localização própria.');
|
||||
@@ -306,8 +321,8 @@ class OpportunityCanonicalContract
|
||||
}
|
||||
$locations = $resources['locations'] ?? [];
|
||||
$primary = array_filter($locations, fn ($l) => $l['payload']['is_primary'] ?? false);
|
||||
$check(count($primary) === 1, 'locations', 'Selecione exatamente uma localização principal.');
|
||||
$check($payload['location_mode'] !== 'single' || count($locations) === 1, 'location_mode', 'Modo single exige uma localização.');
|
||||
$check(! $initiative->applicable($payload, 'physical_site') || count($primary) === 1, 'locations', 'Selecione exatamente uma localização principal.');
|
||||
$check(! $initiative->applicable($payload, 'physical_site') || ($payload['location_mode'] ?? null) !== 'single' || count($locations) === 1, 'location_mode', 'Modo single exige uma localização.');
|
||||
foreach ($payload['evidences'] as $i => $evidence) {
|
||||
$check(isset($resources['documents'][$evidence['document_id']]), "evidences.$i.document_id", 'Evidência deve usar um documento ativo desta oportunidade incluído no contrato.');
|
||||
}
|
||||
@@ -356,7 +371,7 @@ class OpportunityCanonicalContract
|
||||
$errors['canonical.'.$module] = 'Módulo incompatível com a categoria. Preserve-o noutra versão antes de mudar de categoria.';
|
||||
}
|
||||
}
|
||||
if ($category === 'investment_project') {
|
||||
if ($category === 'investment_project' && app(OpportunityInitiativeApplicability::class)->applicable($p, 'unit_investment')) {
|
||||
$total = $p['total_investment'];
|
||||
$sum = array_sum(array_column($p['investment_breakdown'], 'amount'));
|
||||
$secured = array_sum(array_column($p['secured_financing'], 'amount'));
|
||||
|
||||
@@ -65,7 +65,12 @@ class OpportunityCategoryFields
|
||||
// The extracted Create property was opaque, preventing completion through the UI.
|
||||
$common['environmental_social'] = ['$ref' => '#/$defs/environmentalSocialCreate'];
|
||||
$common['maturity_stage']['enum'] = [...array_keys(OpportunityMaturity::STAGES), null];
|
||||
$common['financial_indicators'] = $this->object(['npv' => ['type' => 'number'], 'irr' => ['type' => 'number'], 'payback_years' => $n, 'scenario' => $s, 'horizon_years' => ['type' => 'integer', 'minimum' => 1], 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'], 'discount_rate' => $n, 'model_document_id' => $d], ['npv', 'irr', 'payback_years', 'scenario', 'horizon_years', 'currency', 'discount_rate', 'model_document_id']);
|
||||
$common['financial_indicators'] = $this->object(['npv' => ['type' => 'number'], 'irr' => ['type' => 'number'], 'payback_years' => $n, 'scenario' => $s, 'horizon_years' => ['type' => 'integer', 'minimum' => 1], 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'], 'discount_rate' => $n, 'model_document_id' => $d]);
|
||||
// OP-9f173ed3-0043: a historical scenario is not a completed feasibility model.
|
||||
$defs['opportunityCreate']['allOf'][] = [
|
||||
'if' => ['properties' => ['maturity_stage' => ['enum' => ['feasibility', 'structured', 'investment_ready', 'implementation', 'operational']]], 'required' => ['maturity_stage']],
|
||||
'then' => ['required' => ['financial_indicators'], 'properties' => ['financial_indicators' => ['required' => ['npv', 'irr', 'payback_years', 'scenario', 'horizon_years', 'currency', 'discount_rate', 'model_document_id']]]],
|
||||
];
|
||||
$defs['milestoneCreate']['properties'] += ['start_date' => $date, 'end_date' => $date, 'responsible_name' => $s, 'dependencies' => $strings];
|
||||
$defs['milestoneCreate']['required'] = array_values(array_unique([...$defs['milestoneCreate']['required'], 'start_date', 'end_date', 'responsible_name']));
|
||||
$defs['riskCreate']['properties']['mitigation']['minLength'] = 1;
|
||||
@@ -166,7 +171,7 @@ class OpportunityCategoryFields
|
||||
foreach ($p['risks'] as $i => $risk) {
|
||||
$fail(($risk['likelihood'] < 4 && $risk['severity'] < 4) || ! empty($risk['mitigation']), "risks.$i.mitigation", 'Risco com probabilidade ou gravidade alta exige mitigação.');
|
||||
}
|
||||
if (in_array($p['maturity_stage'], ['feasibility', 'structured', 'investment_ready', 'implementation', 'operational'], true)) {
|
||||
if (app(OpportunityInitiativeApplicability::class)->applicable($p, 'unit_investment') && in_array($p['maturity_stage'], ['feasibility', 'structured', 'investment_ready', 'implementation', 'operational'], true)) {
|
||||
$fail(! empty($p['financial_indicators']), 'financial_indicators', 'A partir de viabilidade, indique cenário, indicadores e modelo financeiro.');
|
||||
$fail(count(array_filter($p['evidences'], fn ($e) => in_array($e['evidence_type'], ['feasibility_study', 'feasibility'], true))) > 0, 'evidences', 'Associe o estudo de viabilidade desta etapa.');
|
||||
}
|
||||
|
||||
@@ -383,7 +383,7 @@ class OpportunityClassification
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => $r['authority_id'] === $filters['authority_id']);
|
||||
}
|
||||
if (! empty($filters['subsector_id'])) {
|
||||
$matches = $matches && (($record->workflow_context['publication']['taxonomy']['subsector_id'] ?? '') === $filters['subsector_id'] || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
|
||||
$matches = $matches && (in_array($filters['subsector_id'], array_intersect_key($record->workflow_context['publication']['taxonomy'] ?? [], array_flip(['subsector_id','economic_activity_id'])), true) || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
|
||||
}
|
||||
if ($matches) {
|
||||
$ids[] = $record->id;
|
||||
|
||||
@@ -11,7 +11,7 @@ class OpportunityCompleteness
|
||||
* @return array<string,mixed> */
|
||||
public function calculate(array $payload): array
|
||||
{
|
||||
$schema = app(OpportunityCanonicalContract::class)->schema();
|
||||
$schema = app(OpportunityCanonicalContract::class)->schema(false, $payload);
|
||||
$validator = new Validator;
|
||||
$paths = [];
|
||||
$walk = function (mixed $value, array $node, string $path) use (&$walk, &$paths, $schema, $validator): void {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Tempo decision: programme/portfolio applicability; persisted in existing canonical JSON. */
|
||||
class OpportunityInitiativeApplicability
|
||||
{
|
||||
public const GROUPS = [
|
||||
'physical_site' => ['location_mode', 'licenses', 'environmental_social'],
|
||||
'individual_business' => ['promoter_id', 'promoter_type', 'opportunity_type', 'investor_profiles', 'products', 'assets', 'inputs', 'markets', 'competitive_advantage', 'employment', 'impact_indicators', 'enterprise_size'],
|
||||
'unit_investment' => ['total_investment', 'currency', 'investment_breakdown', 'secured_financing', 'funding_sought', 'financial_indicators'],
|
||||
];
|
||||
|
||||
public function enabled(array $p): bool
|
||||
{
|
||||
return ($p['opportunity_category'] ?? null) === 'investment_project'
|
||||
&& in_array($p['initiative']['kind'] ?? null, ['program', 'portfolio'], true);
|
||||
}
|
||||
|
||||
public function applicable(array $p, string $group): bool
|
||||
{
|
||||
return ! $this->enabled($p) || ($p['initiative']['applicability'][$group] ?? 'missing') !== 'not_applicable';
|
||||
}
|
||||
|
||||
public function schema(array $schema, array $payload): array
|
||||
{
|
||||
$base = &$schema['$defs']['opportunityCreate'];
|
||||
$text = ['type' => ['string', 'null'], 'maxLength' => 4000];
|
||||
$base['properties']['initiative'] = ['type' => 'object', 'additionalProperties' => false,
|
||||
'required' => ['kind', 'responsible_name', 'coverage_statement', 'applicability'],
|
||||
'properties' => [
|
||||
'kind' => ['enum' => ['program', 'portfolio']],
|
||||
'responsible_name' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 500],
|
||||
'coverage_statement' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 4000],
|
||||
'aggregate_budget_statement' => $text,
|
||||
'applicability' => ['type' => 'object', 'additionalProperties' => false,
|
||||
'required' => array_keys(self::GROUPS),
|
||||
'properties' => array_fill_keys(array_keys(self::GROUPS), ['enum' => ['applicable', 'not_applicable', 'missing']])],
|
||||
]];
|
||||
if (! $this->enabled($payload)) {
|
||||
// A profile cannot relax requirements of another category.
|
||||
if (isset($payload['initiative'])) {
|
||||
$base['allOf'][] = ['properties' => ['opportunity_category' => ['const' => 'investment_project']]];
|
||||
}
|
||||
return $schema;
|
||||
}
|
||||
$ignored = [];
|
||||
foreach (self::GROUPS as $group => $fields) {
|
||||
if (! $this->applicable($payload, $group)) {
|
||||
$ignored = [...$ignored, ...$fields];
|
||||
}
|
||||
}
|
||||
// Program responsibility is distinct from component promoter identity, in all cases.
|
||||
$ignored = array_unique([...$ignored, 'promoter_id', 'promoter_type']);
|
||||
$base['required'] = array_values(array_diff($base['required'], $ignored));
|
||||
$base['required'][] = 'initiative';
|
||||
foreach ($ignored as $field) {
|
||||
$base['properties'][$field] = ['description' => 'Not applicable; retained without alteration']; // Retain old bytes; do not validate an inapplicable placeholder.
|
||||
}
|
||||
foreach ($base['allOf'] as &$condition) {
|
||||
if (isset($condition['then']['required'])) {
|
||||
$condition['then']['required'] = array_values(array_diff($condition['then']['required'], $ignored));
|
||||
}
|
||||
if (isset($condition['then']['properties'])) {
|
||||
$condition['then']['properties'] = array_diff_key($condition['then']['properties'], array_flip($ignored));
|
||||
}
|
||||
// Location counts apply to implantation, not to the coverage resources.
|
||||
if (! $this->applicable($payload, 'physical_site') && isset($condition['if']['properties']['location_mode'])) {
|
||||
$condition = ['description' => 'Coverage is distinct from physical implantation'];
|
||||
}
|
||||
}
|
||||
unset($condition);
|
||||
if (! $this->applicable($payload, 'physical_site')) {
|
||||
unset($base['properties']['locations']['minItems']);
|
||||
}
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public function validate(array $p, array &$errors): void
|
||||
{
|
||||
if (! $this->enabled($p)) {
|
||||
return;
|
||||
}
|
||||
if (! in_array($p['maturity_stage'] ?? null, array_keys(OpportunityMaturity::STAGES), true)) {
|
||||
$errors['canonical.maturity_stage'] = 'Indique a etapa conhecida do programa/carteira; a classificação não confirma preparação ou viabilidade.';
|
||||
}
|
||||
foreach (self::GROUPS as $group => $fields) {
|
||||
if (($p['initiative']['applicability'][$group] ?? 'missing') === 'missing') {
|
||||
$errors['canonical.initiative.applicability.'.$group] = 'Informação em falta: indique se este grupo é aplicável ou não aplicável à ficha; não invente dados das componentes.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** An existing opportunity resource references the original document. No binary or permission is copied. */
|
||||
class OpportunityLibrarySupport
|
||||
{
|
||||
public function choices(User $actor): array
|
||||
{
|
||||
return $this->sources($actor)->orderBy('r.id')->limit(100)->get(['r.id', 'r.title', 'r.version_label', 'r.metadata_version', 'r.published', 'd.sha256'])->all();
|
||||
}
|
||||
|
||||
private function sources(User $actor)
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
||||
->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
|
||||
->whereIn('d.data_classification', ['internal', 'public'])
|
||||
->when(! $actor->can('manage-portal'), function ($query) use ($actor) {
|
||||
$query->where(function ($scope) use ($actor) {
|
||||
$scope->where(fn ($public) => $public->where('r.published',true)->where('d.data_classification','public')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256'));
|
||||
if ($actor->hasVerifiedEmail()) {
|
||||
$scope->orWhere(fn ($own) => $own->where('r.created_by',$actor->id)->where('d.uploaded_by',$actor->id));
|
||||
}
|
||||
$editorial=app(DocumentManagementAccess::class);
|
||||
if ($editorial->editorial($actor)) {
|
||||
$scope->orWhereIn('r.id',$editorial->editorialResources($actor)->select('r.id'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function attach(User $actor, Opportunity $opportunity, array $input): \stdClass
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$data = Validator::make($input, ['resource_id' => 'required|integer|min:1', 'creation_key' => 'required|uuid', 'etag' => 'required|string|size:64', 'reason' => 'required|string|min:20|max:1000', 'section' => 'nullable|string|max:255', 'supported_statement' => 'nullable|string|max:2000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $opportunity, $data) {
|
||||
$opportunity = Opportunity::whereKey($opportunity->id)->lockForUpdate()->firstOrFail();
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$source = $this->sources($actor)->where('r.id', $data['resource_id'])->lockForUpdate()->first(['r.*', 'd.id as original_id', 'd.sha256', 'd.version_no']);
|
||||
abort_unless($source, 403, 'O acesso actual à biblioteca não permite reutilizar este original.');
|
||||
$existing = DB::table('opportunity_documents')->where('opportunity_id', $opportunity->id)->whereNull('deleted_at')->where('document_id', $source->original_id)->first();
|
||||
if ($existing) {
|
||||
$payload = json_decode($existing->payload, true);
|
||||
abort_unless(($payload['library_source']['resource_id'] ?? null) === $source->id, 409, 'Original já associado por outro percurso; recuperar o suporte existente.');
|
||||
abort_unless(($payload['section'] ?? null) === ($data['section'] ?? null) && ($payload['supported_statement'] ?? null) === ($data['supported_statement'] ?? null), 409, 'Original já associado com outra referência; editar explicitamente o suporte existente.');
|
||||
return $existing;
|
||||
}
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($opportunity), $data['etag']), 409, 'A ficha mudou; preserve a selecção e recupere a versão actual.');
|
||||
abort_if(DB::table('opportunity_documents')->where('id', $data['creation_key'])->exists(), 409, 'Chave já utilizada noutro suporte.');
|
||||
abort_if(DB::table('opportunity_documents')->where('opportunity_id', $opportunity->id)->whereNull('deleted_at')->count() >= 100, 422, 'Limite de documentos atingido.');
|
||||
$payload = ['title' => $source->title, 'category' => $source->category, 'issuer' => null, 'edition' => $source->version_label,
|
||||
'classification' => 'internal', 'visibility' => 'internal', 'source_reference' => $source->source_reference,
|
||||
'section' => $data['section'] ?? null, 'supported_statement' => $data['supported_statement'] ?? null,
|
||||
'library_source' => ['resource_id' => $source->id, 'document_id' => $source->original_id, 'metadata_version' => $source->metadata_version,
|
||||
'document_version' => $source->version_no, 'edition' => $source->version_label, 'sha256' => trim($source->sha256), 'source_reference' => $source->source_reference]];
|
||||
$now = now();
|
||||
DB::table('opportunity_documents')->insert(['id' => $data['creation_key'], 'opportunity_id' => $opportunity->id, 'document_id' => $source->original_id,
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'version' => 1, 'created_by' => $actor->id, 'created_at' => $now, 'updated_at' => $now]);
|
||||
$after = DB::table('opportunity_documents')->where('id', $data['creation_key'])->first();
|
||||
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => 'documents', 'actor_user_id' => $actor->id,
|
||||
'action' => 'library_original_reused', 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString('null')]),
|
||||
'after_data' => json_encode(['opportunity_id' => $opportunity->id, 'resource_id' => $after->id, 'version' => 1,
|
||||
'reason' => Crypt::encryptString($data['reason']), 'snapshot' => Crypt::encryptString(json_encode($after, JSON_THROW_ON_ERROR))])]);
|
||||
$opportunity->management_version++;
|
||||
$opportunity->save();
|
||||
return $after;
|
||||
});
|
||||
}
|
||||
|
||||
public function assertAvailable(\stdClass $resource, \stdClass $document): void
|
||||
{
|
||||
$payload = is_string($resource->payload) ? json_decode($resource->payload, true) : $resource->payload;
|
||||
$pin = $payload['library_source'] ?? null;
|
||||
if (! $pin) return;
|
||||
$source = DB::table('portal_resources')->where('id', $pin['resource_id'])->first();
|
||||
abort_unless($source && $source->rights_status !== 'restricted' && $document->rights_status !== 'restricted'
|
||||
&& in_array($document->data_classification, ['internal', 'public'], true)
|
||||
&& $document->id === $pin['document_id'] && hash_equals($pin['sha256'], trim($document->sha256)), 403, 'O original está retirado, restrito ou já não corresponde à versão guardada.');
|
||||
}
|
||||
|
||||
public function snapshot(User $actor, Opportunity $opportunity): array
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (! $access->canView($actor, $opportunity)) return [];
|
||||
return collect(app(OpportunityResources::class)->listing($opportunity->id, 'documents'))->filter(fn ($r) => ! $r->deleted_at && isset($r->payload['library_source']))->map(function ($r) use ($opportunity) {
|
||||
$pin = $r->payload['library_source'];
|
||||
return [...$pin, 'title' => $r->payload['title'], 'support_id' => $r->id, 'support_version' => $r->version,
|
||||
'section' => $r->payload['section'] ?? null, 'opportunity_id' => $opportunity->id,
|
||||
'download_url' => '/minhas-oportunidades/'.$opportunity->id.'/resources/documents/'.$r->id.'/download?source_sha256='.$pin['sha256']];
|
||||
})->values()->all();
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,32 @@ final class OpportunityMaturity
|
||||
|
||||
public const LEGACY_LABELS = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
|
||||
|
||||
/** Public selection is explicit; historical numbers never stand for current stages. */
|
||||
public static function searchOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach (self::STAGES as $code => $label) {
|
||||
$options[] = ['value' => 'stage:'.$code, 'label' => $label, 'group' => 'Etapas de preparação'];
|
||||
}
|
||||
foreach (self::LEGACY_LABELS as $level => $label) {
|
||||
$options[] = ['value' => 'historical:'.$level, 'label' => $label.' — registo histórico', 'group' => 'Classificações históricas'];
|
||||
}
|
||||
return $options;
|
||||
}
|
||||
|
||||
public static function constrainSearch(\Illuminate\Database\Eloquent\Builder $query, string $selection): void
|
||||
{
|
||||
[$kind, $value] = explode(':', $selection, 2);
|
||||
if ($kind === 'stage') {
|
||||
$query->where('workflow_context->publication->maturity->catalogue_version', self::VERSION)
|
||||
->where('workflow_context->publication->maturity->stage', $value);
|
||||
} else {
|
||||
$query->where(fn ($q) => $q->where('workflow_context->publication->maturity->catalogue_version', self::LEGACY)
|
||||
->orWhere(fn ($old) => $old->whereNull('workflow_context->publication->maturity->catalogue_version')->whereNull('workflow_context->publication->maturity->stage')))
|
||||
->where('maturity_level', (int) $value);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @return array<string,mixed> */
|
||||
public function normalize(array $data): array
|
||||
|
||||
@@ -62,6 +62,11 @@ class OpportunityResources
|
||||
'payload' => 'present|array',
|
||||
])->validate();
|
||||
$payload = $this->validatePayload($kind, $data['payload'], $opportunityId);
|
||||
if ($kind === 'documents' && $id && $file) {
|
||||
$linked = DB::table($table)->where('id', $id)->where('opportunity_id', $opportunityId)->first();
|
||||
abort_if($linked && isset(json_decode($linked->payload, true)['library_source']), 422,
|
||||
'Este suporte reutiliza um original da biblioteca; seleccionar outra versão pela biblioteca.');
|
||||
}
|
||||
$stored = null;
|
||||
$documentId = null;
|
||||
if ($file) {
|
||||
@@ -114,6 +119,10 @@ class OpportunityResources
|
||||
abort_unless(Storage::disk('local')->put($stored, Crypt::encryptString($original)) === true, 500, 'Falha ao cifrar original.');
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'opportunity-resources', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored, 'storage_encryption' => 'laravel', 'sha256' => $hash, 'status' => 'quarantined', 'data_classification' => 'restricted', 'size_bytes' => $file->getSize(), 'uploaded_by' => $actor->id]);
|
||||
}
|
||||
if ($record && $kind === 'documents' && isset(json_decode($record->payload, true)['library_source'])) {
|
||||
abort_if($file !== null, 422, 'Este suporte reutiliza um original da biblioteca; seleccionar outra versão pela biblioteca.');
|
||||
$payload['library_source'] = json_decode($record->payload, true)['library_source'];
|
||||
}
|
||||
$values = ['payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'version' => $record ? $record->version + 1 : 1, 'updated_at' => now()];
|
||||
if ($kind !== 'locations' && $documentId) {
|
||||
$values['document_id'] = $documentId;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
|
||||
/** Read-only presentation of existing references. Does not reconcile, confirm or save data. */
|
||||
class OpportunityTerritorialPresentation
|
||||
{
|
||||
public function describe(Opportunity $record, array $locations): array
|
||||
{
|
||||
$path = array_values(array_filter(app(InvestmentGeography::class)->path($record->primary_territory_id, true), fn ($node) => in_array($node->location_type, ['province', 'district', 'admin_post', 'locality'], true)));
|
||||
$mainIds = array_column($path, 'id', 'location_type');
|
||||
$differences = [];
|
||||
foreach ($locations as $location) {
|
||||
if ($location->deleted_at || empty($location->payload['is_primary']) || !$path) continue;
|
||||
$p = $location->payload;
|
||||
$different = false;
|
||||
foreach ($mainIds as $level => $id) if (!empty($p[$level.'_id']) && $p[$level.'_id'] !== $id) $different = true;
|
||||
$foreign = !empty($p['country_code']) && $p['country_code'] !== 'MZ';
|
||||
if ($foreign || $different) {
|
||||
$differences[] = ['resource_id' => $location->id, 'title' => $p['title'] ?? 'Localização sem título',
|
||||
'message' => 'A referência principal da ficha e esta localização documentada apontam para territórios diferentes. Confirme se a distinção é intencional; nenhum valor foi substituído.'];
|
||||
}
|
||||
}
|
||||
return ['path' => $path, 'differences' => $differences];
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,18 @@ class PortalProfileInstallation
|
||||
return hash('sha256', json_encode(array_map(fn ($path) => hash_file('sha256', $path), array_unique($files)), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function authorize(User $actor, bool $write = false): void
|
||||
public function designatedBootstrap(User $actor): bool
|
||||
{
|
||||
$emails = config('portal_profiles.bootstrap_designated_emails', []);
|
||||
if (! config('portal.homologation_only', false) || count(array_unique($emails)) !== 2
|
||||
|| ! in_array(strtolower(trim($actor->email)), $emails, true)) {
|
||||
return false;
|
||||
}
|
||||
$target = config('portal_profiles.bootstrap_designated_database', '');
|
||||
return $target !== '' && DB::selectOne('SELECT current_database() AS database')->database === $target;
|
||||
}
|
||||
|
||||
public function authorize(User $actor, bool $write = false, bool $bootstrapOnly = false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail(), 403);
|
||||
if (Schema::hasTable('portal_role_assignments')) {
|
||||
@@ -33,7 +44,7 @@ class PortalProfileInstallation
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->exists(), 403, 'A restrição do Auditor prevalece.');
|
||||
}
|
||||
$pair = Schema::hasTable('portal_superuser_pair') ? DB::table('portal_superuser_pair')->where('id', 1)->first() : null;
|
||||
abort_unless($pair ? in_array($actor->id, [(int) $pair->first_user_id, (int) $pair->second_user_id], true) : $actor->can('manage-portal'), 403, 'Gestor de instalação ou titular da dupla necessário.');
|
||||
abort_unless($pair ? in_array($actor->id, [(int) $pair->first_user_id, (int) $pair->second_user_id], true) : ($actor->can('manage-portal') || ($bootstrapOnly && $this->access->installed() && $this->designatedBootstrap($actor))), 403, 'Gestor de instalação ou titular designado necessário.');
|
||||
if ($write) {
|
||||
abort_unless($this->access->mfa($actor), 403, 'Conclua MFA nesta sessão; configuração de MFA isoladamente não autoriza a operação.');
|
||||
}
|
||||
@@ -42,7 +53,7 @@ class PortalProfileInstallation
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
$this->authorize($actor, false, true);
|
||||
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
||||
$schema = [];
|
||||
@@ -126,7 +137,7 @@ class PortalProfileInstallation
|
||||
|
||||
public function bootstrap(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true);
|
||||
$this->authorize($actor, true, true);
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid',
|
||||
'first_user_id' => 'required|integer|exists:users,id', 'second_user_id' => 'required|integer|different:first_user_id|exists:users,id', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
abort_unless((int) $data['first_user_id'] === $actor->id, 403, 'O primeiro titular deve apresentar o seu próprio pedido; não é permitido inicializar terceiros.');
|
||||
@@ -135,6 +146,9 @@ class PortalProfileInstallation
|
||||
abort_unless(hash_equals($p['hash'], $data['hash']), 409, 'Plano alterado.');
|
||||
abort_unless($p['installed'] && $p['consistent'] && ! in_array(false, $p['dependencies'], true) && ! $p['bootstrap']['initialized'], 409, 'Schema consistente instalado e dupla não inicializada necessários.');
|
||||
$second = User::findOrFail($data['second_user_id']);
|
||||
if ($this->designatedBootstrap($actor)) {
|
||||
abort_unless($this->designatedBootstrap($second), 403, 'Use os dois titulares expressamente designados para este destino.');
|
||||
}
|
||||
foreach ([$actor, $second] as $user) app(PortalSuperusers::class)->validateBootstrapHolder($user);
|
||||
abort_if(DB::table('portal_security_approvals')->where('kind', 'bootstrap')->whereNull('consumed_at')->where('expires_at', '>', now())->exists(), 409, 'Já existe pedido pendente. Recupere-o; não duplique a cerimónia.');
|
||||
$id = (string) \Illuminate\Support\Str::uuid();
|
||||
@@ -180,7 +194,7 @@ class PortalProfileInstallation
|
||||
abort_unless(hash_equals($view['hash'], $data['hash']), 409, 'Pedido alterado; consulte novamente.');
|
||||
abort_unless($view['can_confirm'], 409, 'Pedido expirado, já consumido ou revisão/destino alterados.');
|
||||
$first = User::findOrFail($row->requested_by);
|
||||
$this->authorize($first);
|
||||
$this->authorize($first, false, true);
|
||||
$p = $this->preview($first);
|
||||
abort_unless($p['installed'] && $p['consistent'] && ! in_array(false, $p['dependencies'], true) && ! $p['bootstrap']['initialized'], 409, 'Dependências ou dupla alteradas.');
|
||||
app(PortalSuperusers::class)->validateBootstrapHolder($first);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\InterestRequest;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Reuses approved administration; never changes the global gate or private-record ACL. */
|
||||
final class ScopedPortalAdministration
|
||||
{
|
||||
public function administrative(?User $actor): bool
|
||||
{
|
||||
if (!$actor || !$actor->hasVerifiedEmail()) return false;
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->has($actor, 'auditor')) return false;
|
||||
return ($access->superuser($actor) && $access->mfa($actor))
|
||||
|| ($access->legacyWriteAllowed($actor) && $access->mfa($actor));
|
||||
}
|
||||
|
||||
public function interestOperator(?User $actor): bool
|
||||
{
|
||||
if (!$actor || !$actor->hasVerifiedEmail()) return false;
|
||||
$access=app(PortalProfileAccess::class);
|
||||
return !$access->has($actor,'auditor') && $access->mfa($actor)
|
||||
&& ($this->administrative($actor) || DB::table('interest_requests')->where('assigned_to',$actor->id)->whereNull('deleted_at')->exists());
|
||||
}
|
||||
|
||||
public function interest(User $actor, InterestRequest $record): bool
|
||||
{
|
||||
return $this->interestOperator($actor)
|
||||
&& ($actor->can('manage-portal') || (int)$record->assigned_to===$actor->id);
|
||||
}
|
||||
|
||||
public function interestQuery($query, User $actor): void
|
||||
{
|
||||
if (!$actor->can('manage-portal')) $query->where('assigned_to',$actor->id);
|
||||
}
|
||||
|
||||
public function deskDecision(User $actor, object $request): bool
|
||||
{
|
||||
return $actor->can('manage-portal')
|
||||
|| ($this->administrative($actor) && (int)$request->analyst_id===$actor->id);
|
||||
}
|
||||
|
||||
public function deskCaseDecision(User $actor, string $id): bool
|
||||
{
|
||||
return $actor->can('manage-portal') || ($this->administrative($actor)
|
||||
&& DB::table('desk_requests')->where('case_id',$id)->where('analyst_id',$actor->id)->exists());
|
||||
}
|
||||
}
|
||||
@@ -59,9 +59,10 @@ class VerifiedDocumentBinary
|
||||
if ($table === 'opportunity_images') {
|
||||
$query->orWhereRaw("payload->'derivatives' @> ?::jsonb", [json_encode([['document_id' => $document->id]], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
$links = $links->concat($query->get(['opportunity_id', 'deleted_at']));
|
||||
$links = $links->concat($query->get(['opportunity_id', 'deleted_at', 'payload']));
|
||||
}
|
||||
$privateOrigin = in_array($document->source_system ?? null, ['opportunity-resources', 'opportunity-image-derivatives'], true);
|
||||
if (! $privateOrigin) $links = $links->reject(fn ($link) => isset(json_decode($link->payload, true)['library_source']));
|
||||
if ($links->isEmpty() && ! $privateOrigin) {
|
||||
return; // Other consumers retain their own publication/authorization rules.
|
||||
}
|
||||
|
||||
@@ -388,7 +388,7 @@ class VirtualDesk
|
||||
abort_if($this->owns($actor, $case, false), 403, 'O proponente não pode analisar ou decidir o seu próprio pedido.');
|
||||
abort_unless($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id, 403);
|
||||
if (in_array($data['status'], ['accepted', 'rejected', 'closed'], true)) {
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskDecision($actor,$request), 403);
|
||||
}
|
||||
abort_unless(in_array($data['status'], config('virtual-desk.transitions.'.$request->status, []), true), 409, 'Transição inválida.');
|
||||
}
|
||||
@@ -412,13 +412,13 @@ class VirtualDesk
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$case = $this->case($actor, $id, false, true);
|
||||
abort_unless($this->owns($actor, $case) || $actor->can('manage-portal'), 403);
|
||||
abort_unless($this->owns($actor, $case) || app(ScopedPortalAdministration::class)->deskCaseDecision($actor,$case->id), 403);
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409);
|
||||
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR);
|
||||
$current = $workflow[$data['stage']];
|
||||
$decision = in_array($data['status'], ['completed', 'not_applicable'], true);
|
||||
if ($decision) {
|
||||
abort_unless($actor->can('manage-portal') && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskCaseDecision($actor,$case->id) && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
|
||||
abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Identifique a evidência documental.');
|
||||
foreach ($current['dependencies'] as $dependency) {
|
||||
abort_unless(in_array($workflow[$dependency]['status'], ['completed', 'not_applicable'], true) || (($data['exception'] ?? false) && ($data['document_id'] ?? null)), 422, 'Dependência '.$dependency.' pendente; uma exceção exige evidência própria.');
|
||||
|
||||
+2
-5
@@ -19,7 +19,7 @@ use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
$app = Application::configure(basePath: dirname(__DIR__))
|
||||
return Application::configure(basePath: dirname(__DIR__))
|
||||
->withRouting(
|
||||
web: __DIR__.'/../routes/web.php',
|
||||
api: __DIR__.'/../routes/api.php',
|
||||
@@ -30,6 +30,7 @@ $app = Application::configure(basePath: dirname(__DIR__))
|
||||
$middleware->encryptCookies(except: ['appearance', 'sidebar_state', EnsureSimulationRecoveryCookie::NAME]);
|
||||
|
||||
$middleware->web(append: [
|
||||
\App\Http\Middleware\EnsureHomologationAccess::class,
|
||||
PortalProfileSession::class,
|
||||
ProtectPrivilegedIdentity::class,
|
||||
AuditProfileDecision::class,
|
||||
@@ -106,7 +107,3 @@ $app = Application::configure(basePath: dirname(__DIR__))
|
||||
return $response;
|
||||
});
|
||||
})->create();
|
||||
|
||||
(require __DIR__.'/storage.php')($app->basePath(), $app->storagePath());
|
||||
|
||||
return $app;
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@
|
||||
],
|
||||
"dev": [
|
||||
"Composer\\Config::disableProcessTimeout",
|
||||
"@php artisan portal:dev-check",
|
||||
"@php artisan portal:dev-check --wait=900",
|
||||
"@php artisan dev"
|
||||
],
|
||||
"lint": [
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
// Same recipient configuration as investidor/config/contact_messages.php.
|
||||
return [
|
||||
'recipient' => env('CONTACT_MESSAGES_TO', env('MAIL_FROM_ADDRESS')),
|
||||
];
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
return json_decode(<<<'JSON'
|
||||
{
|
||||
"accounts": [
|
||||
"nala@tempo.co.mz",
|
||||
"onala@me.com"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": 8,
|
||||
"sha256": "ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53",
|
||||
"external_id": "homologation-fdcb31f1b5b9-ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"sha256": "ccf2a8deeca820f2dd076b4b2141b1efe3f6a806568c3a587ca59a8e92f4c251",
|
||||
"external_id": "homologation-fdcb31f1b5b9-ccf2a8deeca820f2dd076b4b2141b1efe3f6a806568c3a587ca59a8e92f4c251"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"sha256": "11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5",
|
||||
"external_id": "homologation-fdcb31f1b5b9-11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"sha256": "5c69b6f189a1d3f5307e0cf7dd8224554705158a682637d3105afad615db26e2",
|
||||
"external_id": "homologation-fdcb31f1b5b9-5c69b6f189a1d3f5307e0cf7dd8224554705158a682637d3105afad615db26e2"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"sha256": "5e3840705cf98226d1f189cf665aaa98cb05da96c645159a1332a1d429d642eb",
|
||||
"external_id": "homologation-fdcb31f1b5b9-5e3840705cf98226d1f189cf665aaa98cb05da96c645159a1332a1d429d642eb"
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"sha256": "0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2",
|
||||
"external_id": "homologation-fdcb31f1b5b9-0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2"
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"sha256": "26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1",
|
||||
"external_id": "homologation-fdcb31f1b5b9-26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"sha256": "538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211",
|
||||
"external_id": "homologation-fdcb31f1b5b9-538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211"
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"sha256": "05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032",
|
||||
"external_id": "homologation-fdcb31f1b5b9-05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"sha256": "e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678",
|
||||
"external_id": "homologation-fdcb31f1b5b9-e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678"
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"sha256": "8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d",
|
||||
"external_id": "homologation-fdcb31f1b5b9-8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d"
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"sha256": "345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97",
|
||||
"external_id": "homologation-fdcb31f1b5b9-345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97"
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"sha256": "4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e",
|
||||
"external_id": "homologation-fdcb31f1b5b9-4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e"
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"sha256": "0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c",
|
||||
"external_id": "homologation-fdcb31f1b5b9-0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c"
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa",
|
||||
"external_id": "homologation-fdcb31f1b5b9-28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"sha256": "0a2c50d91dad3a6007544634540e0f61b11d3506682a5a19066bae03cdcba490",
|
||||
"external_id": "homologation-fdcb31f1b5b9-0a2c50d91dad3a6007544634540e0f61b11d3506682a5a19066bae03cdcba490"
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"sha256": "8e58544e49e719f9c865c91e07ef1030155a9e3d59260e6dc93e9c9e25674e39",
|
||||
"external_id": "homologation-fdcb31f1b5b9-8e58544e49e719f9c865c91e07ef1030155a9e3d59260e6dc93e9c9e25674e39"
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"sha256": "fe9a2e382e385b35f6e61ae320e199a979678677fd327fb7d4b07d8ce0111c11",
|
||||
"external_id": "homologation-fdcb31f1b5b9-fe9a2e382e385b35f6e61ae320e199a979678677fd327fb7d4b07d8ce0111c11"
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"sha256": "2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb",
|
||||
"external_id": "homologation-fdcb31f1b5b9-2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb"
|
||||
},
|
||||
{
|
||||
"id": 29,
|
||||
"sha256": "0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0",
|
||||
"external_id": "homologation-fdcb31f1b5b9-0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0"
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"sha256": "926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941",
|
||||
"external_id": "homologation-fdcb31f1b5b9-926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"sha256": "3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54",
|
||||
"external_id": "homologation-fdcb31f1b5b9-3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54"
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"sha256": "8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72",
|
||||
"external_id": "homologation-fdcb31f1b5b9-8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"sha256": "dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf",
|
||||
"external_id": "homologation-fdcb31f1b5b9-dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"sha256": "88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a",
|
||||
"external_id": "homologation-fdcb31f1b5b9-88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a"
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"sha256": "48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9",
|
||||
"external_id": "homologation-fdcb31f1b5b9-48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9"
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"sha256": "a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c",
|
||||
"external_id": "homologation-fdcb31f1b5b9-a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c"
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"sha256": "514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d",
|
||||
"external_id": "homologation-fdcb31f1b5b9-514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"sha256": "43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5",
|
||||
"external_id": "homologation-fdcb31f1b5b9-43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5"
|
||||
}
|
||||
],
|
||||
"authority": "Tempo approved owner administration/acervo decisions 11 and 18 October, reconciled 19 October; no universal private access"
|
||||
}
|
||||
JSON, true, 512, JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
// Explicit correspondence from the authorised transport manifest; no record IDs are rewritten.
|
||||
return json_decode(<<<'JSON'
|
||||
{
|
||||
"legacy-tempo-post-171985-20260420": {
|
||||
"resource_id": 13,
|
||||
"external_id": "homologation-fdcb31f1b5b9-0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2",
|
||||
"sha256": "0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2",
|
||||
"source_url": "https://investemoz.tempo.co.mz/agronegocio"
|
||||
},
|
||||
"legacy-tempo-post-171981-20260430": {
|
||||
"resource_id": 18,
|
||||
"external_id": "homologation-fdcb31f1b5b9-26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1",
|
||||
"sha256": "26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1",
|
||||
"source_url": "https://investemoz.tempo.co.mz/energia-mineracao"
|
||||
},
|
||||
"legacy-tempo-post-172679-20260430": {
|
||||
"resource_id": 1,
|
||||
"external_id": "homologation-fdcb31f1b5b9-2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb",
|
||||
"sha256": "2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb",
|
||||
"source_url": "https://investemoz.tempo.co.mz/energia/"
|
||||
},
|
||||
"legacy-tempo-post-172674-20260430": {
|
||||
"resource_id": 2,
|
||||
"external_id": "homologation-fdcb31f1b5b9-3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54",
|
||||
"sha256": "3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54",
|
||||
"source_url": "https://investemoz.tempo.co.mz/mineracao"
|
||||
},
|
||||
"legacy-tempo-post-171990-20260616": {
|
||||
"resource_id": 19,
|
||||
"external_id": "homologation-fdcb31f1b5b9-8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72",
|
||||
"sha256": "8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72",
|
||||
"source_url": "https://investemoz.tempo.co.mz/turismo"
|
||||
},
|
||||
"legacy-tempo-post-172263-20260414": {
|
||||
"resource_id": 3,
|
||||
"external_id": "homologation-fdcb31f1b5b9-538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211",
|
||||
"sha256": "538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-da-zambezia-onde-os-corredores-de-mocambique-convergem-com-a-natureza-a-cultura-e-o-turismo-sustentavel"
|
||||
},
|
||||
"legacy-tempo-post-172256-20260414": {
|
||||
"resource_id": 4,
|
||||
"external_id": "homologation-fdcb31f1b5b9-dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf",
|
||||
"sha256": "dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-sofala-onde-a-natureza-a-historia-e-o-futuro-do-turismo-convergem/"
|
||||
},
|
||||
"legacy-tempo-post-172261-20260414": {
|
||||
"resource_id": 5,
|
||||
"external_id": "homologation-fdcb31f1b5b9-88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a",
|
||||
"sha256": "88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-tete-onde-o-rio-zambeze-a-cultura-viva-e-a-conservacao-comunitaria-criam-o-futuro-do-turismo/"
|
||||
},
|
||||
"legacy-tempo-post-172258-20260417": {
|
||||
"resource_id": 20,
|
||||
"external_id": "homologation-fdcb31f1b5b9-48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9",
|
||||
"sha256": "48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-manica-onde-o-turismo-de-montanha-natureza-e-cultura-encontra-o-proximo-ciclo-de-investimento/"
|
||||
},
|
||||
"legacy-tempo-post-172253-20260414": {
|
||||
"resource_id": 6,
|
||||
"external_id": "homologation-fdcb31f1b5b9-e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678",
|
||||
"sha256": "e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-inhambane-um-destino-estrategico-para-investimento-turistico/"
|
||||
},
|
||||
"legacy-tempo-post-172240-20260414": {
|
||||
"resource_id": 21,
|
||||
"external_id": "homologation-fdcb31f1b5b9-8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d",
|
||||
"sha256": "8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d",
|
||||
"source_url": "https://investemoz.tempo.co.mz/maputo-cidade-plataforma-estrategica-de-turismo-negocios-e-investimento-sustentavel/"
|
||||
},
|
||||
"legacy-tempo-post-172237-20260417": {
|
||||
"resource_id": 22,
|
||||
"external_id": "homologation-fdcb31f1b5b9-a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c",
|
||||
"sha256": "a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-maputo-turismo/"
|
||||
},
|
||||
"legacy-tempo-post-172233-20260417": {
|
||||
"resource_id": 23,
|
||||
"external_id": "homologation-fdcb31f1b5b9-345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97",
|
||||
"sha256": "345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-gaza-oportunidades-mais-solidas-e-estrategicas-de-investimento-no-turismo-no-sul-de-mocambique/"
|
||||
},
|
||||
"legacy-tempo-post-172230-20260414": {
|
||||
"resource_id": 24,
|
||||
"external_id": "homologation-fdcb31f1b5b9-4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e",
|
||||
"sha256": "4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e",
|
||||
"source_url": "https://investemoz.tempo.co.mz/provincia-de-nampula-perfil-de-investimento-no-setor-do-turismo/"
|
||||
},
|
||||
"legacy-tempo-post-172223-20260414": {
|
||||
"resource_id": 25,
|
||||
"external_id": "homologation-fdcb31f1b5b9-514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d",
|
||||
"sha256": "514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d",
|
||||
"source_url": "https://investemoz.tempo.co.mz/cabo-delgado-pemba-a-capital-do-turismo-costeiro-do-norte-de-mocambique/"
|
||||
},
|
||||
"legacy-tempo-post-172219-20260414": {
|
||||
"resource_id": 26,
|
||||
"external_id": "homologation-fdcb31f1b5b9-0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c",
|
||||
"sha256": "0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c",
|
||||
"source_url": "https://investemoz.tempo.co.mz/niassa-o-ultimo-grande-destino-virgem-do-turismo-africano/"
|
||||
},
|
||||
"legacy-tempo-post-171992-20260430": {
|
||||
"resource_id": 17,
|
||||
"external_id": "homologation-fdcb31f1b5b9-05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032",
|
||||
"sha256": "05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032",
|
||||
"source_url": "https://investemoz.tempo.co.mz/infraestruturas"
|
||||
},
|
||||
"legacy-tempo-post-173209-20260623": {
|
||||
"resource_id": 28,
|
||||
"external_id": "homologation-fdcb31f1b5b9-926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941",
|
||||
"sha256": "926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941",
|
||||
"source_url": "https://investemoz.tempo.co.mz/tech-fintech"
|
||||
},
|
||||
"legacy-tempo-post-173218-20260616": {
|
||||
"resource_id": 7,
|
||||
"external_id": "homologation-fdcb31f1b5b9-43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5",
|
||||
"sha256": "43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5",
|
||||
"source_url": "https://investemoz.tempo.co.mz/imobiliario"
|
||||
},
|
||||
"legacy-tempo-post-173213-20260616": {
|
||||
"resource_id": 29,
|
||||
"external_id": "homologation-fdcb31f1b5b9-0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0",
|
||||
"sha256": "0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0",
|
||||
"source_url": "https://investemoz.tempo.co.mz/bens-de-consumo-franquias"
|
||||
}
|
||||
}
|
||||
JSON, true, 512, JSON_THROW_ON_ERROR);
|
||||
@@ -1,6 +1,14 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// Technical homologation reservation, independent of roles and publication.
|
||||
// Technical access mechanism; no new portal role or MFA requirement.
|
||||
'homologation_access_mode' => env('INVESTMOZ_HOMOLOGATION_ACCESS_MODE', 'reviewers'),
|
||||
'homologation_only' => (bool) env('INVESTMOZ_HOMOLOGATION_ONLY', false),
|
||||
'homologation_reviewers' => array_values(array_filter(array_map(
|
||||
fn ($email) => strtolower(trim($email)),
|
||||
explode(',', (string) env('INVESTMOZ_HOMOLOGATION_REVIEWERS', '')),
|
||||
))),
|
||||
'organization_country_enabled' => env('PORTAL_ORGANIZATION_COUNTRY_ENABLED', false),
|
||||
'legacy_content_enabled' => env('PORTAL_LEGACY_CONTENT_ENABLED', false),
|
||||
'legacy_content_qa_enabled' => env('PORTAL_LEGACY_CONTENT_QA_ENABLED', false),
|
||||
@@ -14,6 +22,8 @@ return [
|
||||
'opportunity_modular_profiles_qa_enabled' => env('PORTAL_OPPORTUNITY_MODULAR_PROFILES_QA_ENABLED', false),
|
||||
'opportunity_other_qa_subtypes' => [],
|
||||
'operator_name' => env('PORTAL_OPERATOR_NAME'),
|
||||
// Tempo, 19/10/2026: institutional contact; commercial department remains separate.
|
||||
'institutional_contact_email' => env('PORTAL_INSTITUTIONAL_CONTACT_EMAIL', 'info@tempo.co.mz'),
|
||||
'support' => [
|
||||
'email' => env('PORTAL_SUPPORT_EMAIL'),
|
||||
'phone' => env('PORTAL_SUPPORT_PHONE'),
|
||||
@@ -23,6 +33,10 @@ return [
|
||||
'notifications_enabled' => env('PORTAL_NOTIFICATIONS_ENABLED', false),
|
||||
'notification_recipients' => array_values(array_filter(array_map('trim', explode(',', (string) env('PORTAL_NOTIFICATION_RECIPIENTS', ''))))),
|
||||
// Explicit access list; public registration never grants management access.
|
||||
'document_managers' => array_values(array_filter(array_map(
|
||||
fn ($email) => strtolower(trim($email)),
|
||||
explode(',', (string) env('PORTAL_DOCUMENT_MANAGER_EMAILS', '')),
|
||||
))),
|
||||
'managers' => array_values(array_filter(array_map(
|
||||
fn ($email) => strtolower(trim($email)),
|
||||
explode(',', (string) env('PORTAL_MANAGER_EMAILS', '')),
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// Explicit deployment designation; grants only the separate bootstrap ceremony.
|
||||
'bootstrap_designated_emails' => array_values(array_filter(array_map(fn ($email) => strtolower(trim($email)), explode(',', (string) env('INVESTMOZ_PROFILE_BOOTSTRAP_HOLDERS', ''))))),
|
||||
'bootstrap_designated_database' => (string) env('INVESTMOZ_PROFILE_BOOTSTRAP_DATABASE', ''),
|
||||
'proof_directory' => storage_path('app/private/investmoz-v2/portal-profile-installation'),
|
||||
// Scoped execution flags are set and reset only by the authenticated services.
|
||||
'authenticated_installation' => false,
|
||||
|
||||
@@ -4,6 +4,7 @@ return [
|
||||
|
||||
'malware' => [
|
||||
'scanner' => env('MALWARE_SCANNER', 'clamd'),
|
||||
'socket' => env('CLAMD_SOCKET'),
|
||||
'host' => env('CLAMD_HOST', '127.0.0.1'),
|
||||
'port' => (int) env('CLAMD_PORT', 3310),
|
||||
'timeout_seconds' => (int) env('CLAMD_TIMEOUT_SECONDS', 120),
|
||||
|
||||
@@ -8,7 +8,7 @@ use Illuminate\Support\Facades\Schema;
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
if (!config('investment-zone-profile.authenticated_installation') && !\App\Support\IsolatedQaDatabase::allowsSchemaChanges()) { throw new RuntimeException('Use a ação autenticada de instalação nominal da ficha.'); }
|
||||
if (!config('investment-zone-profile.authenticated_installation')) { throw new RuntimeException('Use a ação autenticada de instalação nominal da ficha.'); }
|
||||
Schema::table('investment_zones',fn(Blueprint $table)=>$table->text('editorial_draft')->nullable());
|
||||
}
|
||||
public function down(): void
|
||||
|
||||
@@ -8,7 +8,7 @@ use Illuminate\Support\Facades\Schema;
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
if(!config('investment-zone-details.authenticated_installation') && !\App\Support\IsolatedQaDatabase::allowsSchemaChanges()){throw new RuntimeException('Use a instalação autenticada nominal L1.');}
|
||||
if(!config('investment-zone-details.authenticated_installation')){throw new RuntimeException('Use a instalação autenticada nominal L1.');}
|
||||
if(!Schema::hasColumn('investment_zones','editorial_draft') || !DB::table('migrations')->where('migration','2026_10_16_130000_add_investment_zone_editorial_draft')->exists()){throw new RuntimeException('Instale/verifique primeiro a base 130000.');}
|
||||
Schema::table('investment_zones',fn(Blueprint $table)=>$table->jsonb('operational_details')->nullable());
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! config('investor-context.authenticated_installation') && ! \App\Support\IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||
if (! config('investor-context.authenticated_installation')) {
|
||||
throw new RuntimeException('Use a ação autenticada nominal de instalação do contexto.');
|
||||
}
|
||||
Schema::create('investor_navigation_preferences', function (Blueprint $t) {
|
||||
|
||||
@@ -9,7 +9,7 @@ return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (!config('editorial.authenticated_installation') && !\App\Support\IsolatedQaDatabase::allowsSchemaChanges()) { throw new RuntimeException('Use a instalação editorial autenticada.'); }
|
||||
if (!config('editorial.authenticated_installation')) { throw new RuntimeException('Use a instalação editorial autenticada.'); }
|
||||
Schema::table('portal_resources', fn (Blueprint $t) => $t->jsonb('editorial_content')->nullable());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
__pycache__/
|
||||
@@ -0,0 +1,44 @@
|
||||
# Disponibilização automática da homologação
|
||||
|
||||
Destino: `https://teste-investidor.tempo.co.mz`. Branch escolhida pela Tempo: `main`.
|
||||
|
||||
## Trabalho dos programadores
|
||||
|
||||
1. Trabalhar numa branch, fazer commits e enviar para o Git existente.
|
||||
2. Rever e integrar em `main` segundo as designações já aprovadas pela Tempo.
|
||||
3. O push em `main` activa o webhook existente. A fila serializa as execuções; a revisão mais recente é verificada e compilada numa pasta nova.
|
||||
4. Conferir o commit efectivamente servido em `/build/revision.json`. Um commit no Git só está instalado quando consta desse endereço. Em caso de falha, a revisão anterior continua servida; o operador consulta os relatórios e logs protegidos.
|
||||
|
||||
Não editar a pasta servida. Uma alteração manual detectada interrompe a substituição até ser reconciliada, preservando os ficheiros existentes.
|
||||
|
||||
## O que segue o Git
|
||||
|
||||
Fontes, menus, estilos e formulários são instalados com o build da mesma revisão. Não são transportados por Git a base de dados, ficheiros carregados, contas, permissões, segredos nem estados de publicação.
|
||||
|
||||
As migrations são comparadas com o contrato nominal protegido do destino. Uma alteração nesse contrato exige análise e autorização específicas; este executor não executa SQL de migração no destino. A criação do schema durante a verificação usa exclusivamente PostgreSQL/PostGIS descartável, em `127.0.0.1:55441`, com nome terminado em `_test` e identidade conferida pela guarda QA.
|
||||
|
||||
## Operação e recuperação
|
||||
|
||||
O receptor `/deploy` conserva a protecção própria do Nginx e a assinatura HMAC do Gitea. As páginas públicas não exigem a credencial ambiental; as operações privadas conservam login, permissões e MFA aplicável.
|
||||
|
||||
O executor instalado e a configuração em `/etc/investmoz-deploy` são controlados pelo operador. Alterar as suas fontes no repositório não substitui automaticamente esse controlo. A imagem de CI é fixada por digest; não modifica o PostgreSQL ou PostGIS da aplicação.
|
||||
|
||||
O operador consulta:
|
||||
|
||||
- `systemctl status teste-investidor-deploy.service teste-investidor-deploy.path`
|
||||
- `/var/lib/investmoz-deploy/reports/`: commit solicitado, resultado e revisão instalada.
|
||||
- `/var/lib/investmoz-deploy/logs/`: detalhe protegido da verificação e compilação.
|
||||
|
||||
Para reverter, suspender primeiro novas execuções com `systemctl stop teste-investidor-deploy.path` e aguardar a execução em curso. Executar, como o utilizador de disponibilização existente:
|
||||
|
||||
```sh
|
||||
python3 /var/www/deploy/investmoz-pipeline.py --config /etc/investmoz-deploy/delivery.json --rollback
|
||||
```
|
||||
|
||||
A reversão verifica os hashes, repõe a release anterior e reinicia graciosamente os workers. Conserva a base, uploads, configurações partilhadas e dados posteriores. Não é restauro integral de dados. Repor uma release incompatível com dados/schema posteriores exige análise específica. Retomar a path unit apenas depois da decisão de corrigir ou voltar a disponibilizar a revisão integrada.
|
||||
|
||||
O checkout físico anterior é preservado; não é feito `reset --hard` nele. Assets com nomes hash permanecem num conjunto partilhado para conservar páginas já abertas. Não há eliminação automática de releases ou dados.
|
||||
|
||||
## Limites
|
||||
|
||||
Uma verificação automática não publica conteúdos nem comprova todos os percursos de negócio. Mantêm-se as provas aceites e as pendências funcionais da matriz. Falhas do fluxo devem indicar o comando e o log concreto, sem exposição de segredos ao visitante.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"repository": "nala/Investidor-V2",
|
||||
"branch": "main",
|
||||
"target_url": "https://teste-investidor.tempo.co.mz",
|
||||
"legacy_root": "/var/www/html/teste-investidor.tempo.co.mz",
|
||||
"state_root": "/var/lib/investmoz-deploy",
|
||||
"release_root": "/var/www/investmoz-homologacao/releases",
|
||||
"current_link": "/var/www/html/teste-investidor.tempo.co.mz/current",
|
||||
"shared_assets": "/var/www/investmoz-homologacao/shared/build-assets",
|
||||
"php": "/usr/bin/php8.4",
|
||||
"schema_contract": "/etc/investmoz-deploy/schema-contract.json",
|
||||
"ci_environment": "/etc/investmoz-deploy/ci-environment.json",
|
||||
"postgis_image": "postgis/postgis:17-3.5",
|
||||
"test_database": "investmoz_ci_test",
|
||||
"qa_port": 55441,
|
||||
"retention": "No automatic deletion of releases or data"
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Gitea -> isolated verification/build -> immutable release -> atomic switch.
|
||||
|
||||
Runs as the existing deployment OS user. Never resets the served checkout,
|
||||
copies a database, runs production migrations, imports content or changes grants.
|
||||
The installed copy and /etc configuration are controlled by the server operator.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, base64, contextlib, datetime, hashlib, io, json, os, re
|
||||
import shutil, socket, subprocess, tarfile, time, urllib.request, uuid
|
||||
from pathlib import Path
|
||||
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
def write_json(path: Path, value: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name('.'+path.name+'.'+uuid.uuid4().hex)
|
||||
temporary.write_text(json.dumps(value, indent=2)+'\n', encoding='utf-8')
|
||||
os.chmod(temporary, 0o640)
|
||||
os.replace(temporary, path)
|
||||
|
||||
def source_contract(root: Path) -> dict[str, str]:
|
||||
return {p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes().replace(b'\r\n', b'\n')).hexdigest()
|
||||
for p in sorted((root/'database/migrations').glob('*.php'))}
|
||||
|
||||
def tree_hashes(root: Path) -> dict[str, str]:
|
||||
result = {}
|
||||
for directory, folders, files in os.walk(root, followlinks=False):
|
||||
parent = Path(directory)
|
||||
folders[:] = [name for name in folders if not (parent/name).is_symlink()
|
||||
and name not in ['.git', 'node_modules']
|
||||
and (parent/name).relative_to(root).as_posix() not in ['storage', 'bootstrap/cache']]
|
||||
for name in files:
|
||||
path=parent/name;rel=path.relative_to(root).as_posix()
|
||||
if path.is_symlink() or rel=='.env' or rel.startswith('public/build/assets/'):continue
|
||||
result[rel]=digest(path)
|
||||
return result
|
||||
|
||||
def refuse_drift(root: Path, expected: dict[str, str]) -> None:
|
||||
actual = tree_hashes(root)
|
||||
if actual != expected:
|
||||
changed = sorted(p for p in actual.keys() | expected.keys() if actual.get(p) != expected.get(p))
|
||||
raise RuntimeError('Source/build drift requires reconciliation: '+', '.join(changed[:12]))
|
||||
|
||||
def archive_source(data: bytes, root: Path) -> None:
|
||||
with tarfile.open(fileobj=io.BytesIO(data)) as archive:
|
||||
members = archive.getmembers()
|
||||
for item in members:
|
||||
path = (root/item.name).resolve()
|
||||
if not path.is_relative_to(root.resolve()) or not (item.isfile() or item.isdir()):
|
||||
raise RuntimeError('Unsafe source archive entry')
|
||||
if item.name == '.env' or item.name == 'public/hot' or (item.isfile()
|
||||
and item.name.startswith('storage/app/private/') and item.name != 'storage/app/private/.gitignore'):
|
||||
raise RuntimeError('Private/runtime files must not be distributed by Git')
|
||||
# Debian's installed Python predates tarfile extraction filters. Validate
|
||||
# every entry first, then create only ordinary directories/files ourselves.
|
||||
for item in members:
|
||||
path=root/item.name
|
||||
if item.isdir():
|
||||
path.mkdir(mode=0o750,parents=True,exist_ok=True)
|
||||
else:
|
||||
path.parent.mkdir(mode=0o750,parents=True,exist_ok=True)
|
||||
source=archive.extractfile(item)
|
||||
if source is None:raise RuntimeError('Missing archive source bytes')
|
||||
with source, path.open('xb') as destination:shutil.copyfileobj(source,destination)
|
||||
os.chmod(path,0o644 | (item.mode & 0o111))
|
||||
|
||||
def point_current(link: Path, target: Path) -> None:
|
||||
if link.exists() and not link.is_symlink():
|
||||
raise RuntimeError('Current path is not a symlink; existing directory preserved')
|
||||
temporary = link.with_name('.'+link.name+'.'+uuid.uuid4().hex)
|
||||
temporary.symlink_to(target, target_is_directory=True)
|
||||
os.replace(temporary, link)
|
||||
|
||||
def promote(link: Path, candidate: Path, health) -> Path | None:
|
||||
previous = link.resolve() if link.is_symlink() else None
|
||||
point_current(link, candidate)
|
||||
try:
|
||||
health()
|
||||
except Exception:
|
||||
if previous is not None:
|
||||
point_current(link, previous)
|
||||
else:
|
||||
link.unlink()
|
||||
raise
|
||||
return previous
|
||||
|
||||
class Delivery:
|
||||
def __init__(self, config: dict):
|
||||
self.c = config
|
||||
self.state = Path(config['state_root'])
|
||||
self.releases = Path(config['release_root'])
|
||||
self.current = Path(config['current_link'])
|
||||
self.legacy = Path(config['legacy_root'])
|
||||
self.mirror = self.state/'repository.git'
|
||||
self.log = None
|
||||
self.process_env = dict(os.environ)
|
||||
# Do not inherit an application/CI connection accidentally from the calling shell.
|
||||
for key in list(self.process_env):
|
||||
if key.startswith(('DB_', 'APP_', 'MAIL_', 'CACHE_', 'SESSION_', 'QUEUE_', 'VITE_', 'PORTAL_', 'INVESTMOZ_')):
|
||||
self.process_env.pop(key)
|
||||
|
||||
def run(self, argv, cwd=None, env=None, timeout=900, log_output=True) -> bytes:
|
||||
result = subprocess.run([str(x) for x in argv], cwd=cwd, env=env or self.process_env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
|
||||
if self.log and log_output:
|
||||
self.log.write(result.stdout); self.log.flush()
|
||||
if result.returncode:
|
||||
raise RuntimeError('Verification command failed: '+str(argv[0])+' (see protected build log)')
|
||||
return result.stdout
|
||||
|
||||
def git(self, *args) -> str:
|
||||
return self.run(['git', '--git-dir', self.mirror, *args], timeout=120).decode().strip()
|
||||
|
||||
def latest(self) -> str:
|
||||
branch = self.c['branch']
|
||||
self.git('check-ref-format', 'refs/heads/'+branch)
|
||||
self.git('fetch', '--no-tags', 'origin', '+refs/heads/'+branch+':refs/heads/delivery-target')
|
||||
target = self.git('rev-parse', 'refs/heads/delivery-target')
|
||||
if not SHA.fullmatch(target):
|
||||
raise RuntimeError('Invalid fetched revision')
|
||||
return target
|
||||
|
||||
def ci_env(self) -> dict:
|
||||
flags = json.loads(Path(self.c['ci_environment']).read_text())
|
||||
# This file contains only reviewed non-secret feature booleans.
|
||||
if not all(re.fullmatch(r'(PORTAL_|INVESTMOZ_)[A-Z0-9_]+', k) and v in ['true', 'false'] for k,v in flags.items()):
|
||||
raise RuntimeError('Unexpected CI feature setting')
|
||||
env = {**self.process_env, **flags}
|
||||
env.update(APP_ENV='testing', APP_DEBUG='false', APP_URL='http://127.0.0.1',
|
||||
APP_KEY='base64:'+base64.b64encode(os.urandom(32)).decode(), APP_NAME='InvesteMoz',
|
||||
DB_CONNECTION='pgsql', DB_URL='', DB_HOST='127.0.0.1', DB_PORT='55441',
|
||||
DB_DATABASE=self.c['test_database'], DB_USERNAME='investmoz_ci',
|
||||
DB_PASSWORD='isolated-ci-only', MAIL_MAILER='array', CACHE_STORE='array',
|
||||
SESSION_DRIVER='array', QUEUE_CONNECTION='sync',
|
||||
INVESTMOZ_HOMOLOGATION_ONLY='false', INVESTMOZ_SCHEMA_TESTS='1',
|
||||
PORTAL_NOTIFICATIONS_ENABLED='false', VITE_APP_NAME='InvesteMoz',
|
||||
NODE_OPTIONS='--max-old-space-size=1536')
|
||||
if self.c['qa_port'] != 55441 or not env['DB_DATABASE'].endswith('_test'):
|
||||
raise RuntimeError('Refuse a non-isolated test target')
|
||||
return env
|
||||
|
||||
@contextlib.contextmanager
|
||||
def qa_database(self):
|
||||
with socket.socket() as probe:
|
||||
if probe.connect_ex(('127.0.0.1', 55441)) == 0:
|
||||
raise RuntimeError('QA port already occupied; do not reuse or stop another database')
|
||||
name = 'investmoz-ci-'+uuid.uuid4().hex[:16]
|
||||
# Existing Docker; private loopback only, PostgreSQL itself listens on the guarded QA port.
|
||||
cid = self.run(['docker','run','--detach','--name',name,'--label','investmoz.scope=homologacao-ci','--memory=768m','--cpus=1',
|
||||
'--publish','127.0.0.1:55441:55441','--env','POSTGRES_USER=investmoz_ci',
|
||||
'--env','POSTGRES_PASSWORD=isolated-ci-only','--env','POSTGRES_DB='+self.c['test_database'],
|
||||
self.c['postgis_image'],'postgres','-p','55441'], timeout=180).decode().strip().splitlines()[-1]
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', cid):
|
||||
raise RuntimeError('Cannot identify isolated QA container')
|
||||
try:
|
||||
for _ in range(60):
|
||||
ready = subprocess.run(['docker','exec',cid,'pg_isready','-p','55441','-U','investmoz_ci'],
|
||||
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
if ready.returncode == 0: break
|
||||
time.sleep(1)
|
||||
else: raise RuntimeError('Isolated database did not start')
|
||||
identity = self.run(['docker','exec',cid,'psql','-p','55441','-U','investmoz_ci','-d',self.c['test_database'],
|
||||
'-X','-At','-c','SELECT current_database(), current_setting(\'port\');']).decode().strip()
|
||||
if identity != self.c['test_database']+'|55441':
|
||||
raise RuntimeError('QA identity verification failed')
|
||||
yield
|
||||
finally:
|
||||
# Only the newly created, fully identified CI container and its anonymous volumes.
|
||||
self.run(['docker','rm','--force','--volumes',cid], timeout=60)
|
||||
|
||||
def build(self, target: str, release: Path, attach_runtime: bool = True) -> None:
|
||||
data = self.run(['git','--git-dir',self.mirror,'archive','--format=tar',target], timeout=120,log_output=False)
|
||||
# Binary archives must never be appended to text build logs.
|
||||
archive_source(data, release)
|
||||
expected = json.loads(Path(self.c['schema_contract']).read_text())
|
||||
if source_contract(release) != expected:
|
||||
raise RuntimeError('Schema source changed: explicit compatibility/migration decision required; no production SQL executed')
|
||||
env = self.ci_env()
|
||||
bindir = self.state/'bin';bindir.mkdir(exist_ok=True)
|
||||
php = bindir/'php'
|
||||
if not php.exists(): php.symlink_to(self.c['php'])
|
||||
env['PATH'] = str(bindir)+os.pathsep+self.process_env.get('PATH','/usr/bin:/bin')
|
||||
(release/'.env').write_text('APP_ENV=testing\n')
|
||||
(release/'bootstrap/cache').mkdir(parents=True,exist_ok=True)
|
||||
for directory in ['app/private','app/public','framework/cache/data','framework/sessions','framework/views','logs']:
|
||||
(release/'storage'/directory).mkdir(parents=True,exist_ok=True)
|
||||
with self.qa_database():
|
||||
self.run(['composer','install','--no-interaction','--prefer-dist','--no-scripts'],cwd=release,env=env)
|
||||
self.run([self.c['php'],'artisan','package:discover','--ansi'],cwd=release,env=env)
|
||||
# The guard is verified against the actual PostgreSQL identity, not only environment strings.
|
||||
guard = "require 'vendor/autoload.php'; $app=require 'bootstrap/app.php'; $app->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap(); if (!App\\Support\\IsolatedQaDatabase::allowsSchemaChanges()) exit(91);"
|
||||
self.run([self.c['php'],'-r',guard],cwd=release,env=env)
|
||||
# The project intentionally gates later schemas behind nominal authenticated
|
||||
# installation. Reuse its accepted isolated baseline lifecycle test instead
|
||||
# of bypassing those guards with a generic migrate of every module.
|
||||
self.run([self.c['php'],'vendor/bin/phpunit','--configuration=phpunit.investmoz.xml','--do-not-cache-result'],cwd=release,env=env)
|
||||
self.run(['npm','ci','--no-audit','--no-fund'],cwd=release,env=env)
|
||||
self.run(['npm','run','build'],cwd=release,env=env)
|
||||
self.run(['npm','run','types:check'],cwd=release,env=env)
|
||||
self.run([self.c['php'],'tools/portal-diagnostics-deployment-guard.php'],cwd=release,env=env)
|
||||
# Unit fixtures mock DB/mail and select their own feature settings.
|
||||
# Do not inject the destination's enabled-module flags into those mocks.
|
||||
unit_env={k:v for k,v in env.items() if not k.startswith(('PORTAL_','INVESTMOZ_'))}
|
||||
self.run([self.c['php'],'vendor/bin/phpunit','--configuration=phpunit.xml','--testsuite','Unit','--do-not-cache-result'],cwd=release,env=unit_env)
|
||||
tests=sorted((release/'tests/frontend').glob('*.test.mjs'))
|
||||
self.run(['node','--test',*tests],cwd=release,env=env)
|
||||
# Final production vendor from the same lock, before linking any real configuration.
|
||||
self.run(['composer','install','--no-dev','--no-scripts','--no-interaction','--prefer-dist','--optimize-autoloader'],cwd=release,env=env)
|
||||
self.run(['composer','check-platform-reqs','--no-dev'],cwd=release,env=env)
|
||||
if (release/'public/hot').exists(): raise RuntimeError('Development Vite marker must not ship')
|
||||
manifest=json.loads((release/'public/build/manifest.json').read_text())
|
||||
for entry in manifest.values():
|
||||
for path in [entry.get('file'),*entry.get('css',[]),*entry.get('assets',[])]:
|
||||
if path and not (release/'public/build'/path).is_file(): raise RuntimeError('Missing compiled asset')
|
||||
if not attach_runtime:
|
||||
return
|
||||
# Discard only this release's synthetic runtime, retaining it privately outside the served tree.
|
||||
(release/'storage').rename(self.state/'qa-runtime'/release.name)
|
||||
(release/'.env').unlink()
|
||||
for path in (release/'bootstrap/cache').glob('*.php'): path.unlink()
|
||||
(release/'storage').symlink_to(self.legacy/'storage',target_is_directory=True)
|
||||
(release/'.env').symlink_to(self.legacy/'.env')
|
||||
if (release/'public/storage').exists():raise RuntimeError('Unexpected distributed public storage')
|
||||
(release/'public/storage').symlink_to(self.legacy/'storage/app/public',target_is_directory=True)
|
||||
shared=Path(self.c['shared_assets']);shared.mkdir(parents=True,exist_ok=True)
|
||||
assets=release/'public/build/assets'
|
||||
for path in assets.rglob('*'):
|
||||
if not path.is_file():continue
|
||||
dest=shared/path.relative_to(assets);dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
if dest.exists() and digest(dest)!=digest(path):raise RuntimeError('Immutable asset filename collision')
|
||||
if not dest.exists():shutil.copy2(path,dest)
|
||||
# Nginx serves this shared immutable asset pool; old browser bundles remain available.
|
||||
write_json(release/'public/build/revision.json',{'commit':target,'branch':self.c['branch'],
|
||||
'built_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
'manifest_sha256':digest(release/'public/build/manifest.json')})
|
||||
for directory in [release/'bootstrap/cache']:
|
||||
os.chmod(directory,0o2770)
|
||||
|
||||
def health(self, target: str) -> None:
|
||||
request=urllib.request.Request(self.c['target_url']+'/build/revision.json',headers={'User-Agent':'Mozilla/5.0 InvesteMoz-Delivery','Cache-Control':'no-cache'})
|
||||
with urllib.request.urlopen(request,timeout=20) as response:info=json.load(response)
|
||||
if info.get('commit')!=target:raise RuntimeError('Served commit differs from built commit')
|
||||
request=urllib.request.Request(self.c['target_url']+'/',headers={'User-Agent':'Mozilla/5.0 InvesteMoz-Delivery','Cache-Control':'no-cache'})
|
||||
with urllib.request.urlopen(request,timeout=20) as response:
|
||||
if response.status!=200 or response.headers.get('WWW-Authenticate'):raise RuntimeError('Public access regression')
|
||||
|
||||
def deliver(self, target: str) -> dict:
|
||||
installed_file=self.state/'installed.json'
|
||||
installed=json.loads(installed_file.read_text())
|
||||
if installed.get('commit')==target:
|
||||
refuse_drift(self.current.resolve(),installed['hashes'])
|
||||
return {'status':'already_installed','commit':target}
|
||||
refuse_drift(self.current.resolve(),installed['hashes'])
|
||||
self.releases.mkdir(parents=True,exist_ok=True)
|
||||
if shutil.disk_usage(self.releases).free < 5 * 1024**3:
|
||||
raise RuntimeError('Insufficient free space for an isolated build; active release preserved')
|
||||
release=self.releases/(target+'-'+uuid.uuid4().hex[:8]);release.mkdir(mode=0o750)
|
||||
self.build(target,release)
|
||||
if self.latest()!=target:
|
||||
latest=self.git('rev-parse','refs/heads/delivery-target')
|
||||
write_json(self.state/'requests'/(latest+'.json'),{'commit':latest,'reason':'newer integration during build'})
|
||||
return {'status':'superseded','commit':target,'newer_commit':latest}
|
||||
# A programmer may have edited the served release while CI was running.
|
||||
# Recheck immediately before the atomic switch, preserving that work.
|
||||
refuse_drift(self.current.resolve(),installed['hashes'])
|
||||
previous=promote(self.current,release,lambda:self.health(target))
|
||||
try:
|
||||
self.run([self.c['php'],str(release/'artisan'),'queue:restart'],cwd=release)
|
||||
write_json(self.state/'previous.json',installed)
|
||||
info={'status':'installed','commit':target,'release':str(release),'previous_release':str(previous),
|
||||
'hashes':tree_hashes(release),'database_migrations':0,'content_imports':0}
|
||||
write_json(installed_file,info)
|
||||
except Exception:
|
||||
if previous is not None:point_current(self.current,previous)
|
||||
raise
|
||||
return {key:value for key,value in info.items() if key!='hashes'}
|
||||
|
||||
def process(self) -> bool:
|
||||
import fcntl
|
||||
self.state.mkdir(parents=True,exist_ok=True)
|
||||
for directory in ['reports','logs','processed','qa-runtime']: (self.state/directory).mkdir(exist_ok=True)
|
||||
with (self.state/'delivery.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
succeeded=True
|
||||
for _ in range(3):
|
||||
requests=sorted((self.state/'requests').glob('*.json'))
|
||||
if not requests:return succeeded
|
||||
for path in requests:
|
||||
if not SHA.fullmatch(path.stem):raise RuntimeError('Unexpected queue entry')
|
||||
path.rename(self.state/'processed'/(path.stem+'-'+uuid.uuid4().hex[:8]+'.json'))
|
||||
target=None;report={}
|
||||
with (self.state/'logs'/(str(time.time_ns())+'.log')).open('wb') as self.log:
|
||||
try:
|
||||
target=self.latest();report=self.deliver(target)
|
||||
except Exception as error:
|
||||
succeeded=False
|
||||
report={'status':'failed','commit':target,'error':str(error),'active_release_preserved':True}
|
||||
finally:self.log=None
|
||||
report.update(requested_commits=[p.stem for p in requests],finished_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
|
||||
write_json(self.state/'reports'/((target or 'fetch-failed')+'-'+str(time.time_ns())+'.json'),report)
|
||||
print(json.dumps(report),flush=True)
|
||||
return succeeded
|
||||
|
||||
def rollback(self) -> dict:
|
||||
import fcntl
|
||||
with (self.state/'delivery.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
installed=json.loads((self.state/'installed.json').read_text())
|
||||
previous=json.loads((self.state/'previous.json').read_text())
|
||||
refuse_drift(self.current.resolve(),installed['hashes'])
|
||||
prior=Path(previous['release'])
|
||||
refuse_drift(prior,previous['hashes'])
|
||||
current=self.current.resolve()
|
||||
promote(self.current,prior,lambda:self.health(previous['commit']))
|
||||
try:
|
||||
self.run([self.c['php'],str(prior/'artisan'),'queue:restart'],cwd=prior)
|
||||
write_json(self.state/'installed.json',previous)
|
||||
write_json(self.state/'previous.json',installed)
|
||||
except Exception:
|
||||
point_current(self.current,current)
|
||||
write_json(self.state/'installed.json',installed)
|
||||
raise
|
||||
report={'status':'rolled_back','commit':previous['commit'],'release':str(prior),
|
||||
'database_restored':False,'shared_data_preserved':True,
|
||||
'finished_at':datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
||||
write_json(self.state/'reports'/('rollback-'+str(time.time_ns())+'.json'),report)
|
||||
return report
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--config',default='/etc/investmoz-deploy/delivery.json');parser.add_argument('--rollback',action='store_true');args=parser.parse_args()
|
||||
config=json.loads(Path(args.config).read_text())
|
||||
if config['target_url']!='https://teste-investidor.tempo.co.mz':raise SystemExit('Exact homologation target required')
|
||||
if Path(config['legacy_root']).resolve()!=Path('/var/www/html/teste-investidor.tempo.co.mz'):raise SystemExit('Unexpected persistent application target')
|
||||
runner=Delivery(config)
|
||||
if args.rollback:print(json.dumps(runner.rollback()),flush=True)
|
||||
else:raise SystemExit(0 if runner.process() else 1)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,446 @@
|
||||
{
|
||||
"base_commit": "507387502c6ef887433e8e9b5cf20ea39d4f17d4",
|
||||
"installed_revision": "423bd512d8c5",
|
||||
"approved_runtime_files_adopted": [
|
||||
{
|
||||
"path": "app/Http/Controllers/Api/V1/InterestRequestController.php",
|
||||
"remote_sha256": "50b65d0dd576d1c0e4357fe5a192744900eb77b2e5737191ecc553428e6ccf14"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/DocumentMalwareController.php",
|
||||
"remote_sha256": "b19b028ae53fcb8ed648745c9de0121e128e489a9cdd1c3eb8a4210c297416d4"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/EditorialArticleController.php",
|
||||
"remote_sha256": "41e34a865890c81191041ec1c34b0abc1ab052c99ae3b96edc930f841c5a33c5"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/ExistingBusinessController.php",
|
||||
"remote_sha256": "e73ac0fbe1c4ae3939c27e5ca1b6e76642611a5c117c7473f21c284235fe75da"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/InvestmentSubmissionController.php",
|
||||
"remote_sha256": "257837ff8100d5fbc3a432ec336aacc4f37af01d7044e0c44d37de2d4ec44b4c"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/InvestmentZoneController.php",
|
||||
"remote_sha256": "32ed3b3f662b7fcfb8fce09c7626680f3409b0b3bd6acd662088e0adc22cf53b"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/OpportunityResourceController.php",
|
||||
"remote_sha256": "da265c473a783423321fa75f1b02eb62f311b80e4cb317298d5ac4883630e2c6"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/PortalManagementController.php",
|
||||
"remote_sha256": "c49ba1d490f88e65daae21ad0038608a71aef547d7b77acd096cdc8a4d695c0d"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/PortalServicesController.php",
|
||||
"remote_sha256": "8e7595a42945876f9d2787a8fafaa7cec43c6dfafdc79a9aee73fa8aa533c359"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/VirtualDeskController.php",
|
||||
"remote_sha256": "e4620b41820945512283f7f0cdd46f70916b9935288ec91a00e3d1c388af950d"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/EnsureDocumentManagement.php",
|
||||
"remote_sha256": "7e373bffc2517366066a32889b36f277f5cea242c0f3277ef291e2c98fb8520e"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/EnsureHomologationAccess.php",
|
||||
"remote_sha256": "259f467b08d4ad5a1605a40c5f3ccb9e41b2a879643df1f8e4814f5d0c82a8b4"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/EnsureScopedEditorial.php",
|
||||
"remote_sha256": "62c4c16506f5e75ef76e3fa987d6b5ba42d5df953604f1aeecb89c87c7c5c7ca"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/EnsureScopedPortalAdministration.php",
|
||||
"remote_sha256": "3842b05ddd4433b5a26c0dea6b97542b2b3846f46f0393c5515872ded43f0f61"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/HandleInertiaRequests.php",
|
||||
"remote_sha256": "01083ba8e8aec0f0a346e6f86739155122b52fd44f736c066683f0c04c9bdc73"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Middleware/VerifiedOrSimpleParticipation.php",
|
||||
"remote_sha256": "301e0ce37a92e0985bfb5b914aa13a32a0081f8ead88842ff4911c043553780a"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Requests/StoreInterestRequestRequest.php",
|
||||
"remote_sha256": "a064fc0c71139b6ced9d209a490c1f339733ae9ad513c0128520b2942384eeac"
|
||||
},
|
||||
{
|
||||
"path": "app/Policies/ExistingBusinessPolicy.php",
|
||||
"remote_sha256": "69c75db509d876d6125da7d4254ac3be6e23e0ee942dea460bd86fc73aa02def"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/BusinessFormSchema.php",
|
||||
"remote_sha256": "bf7509574c8c66da49b2f2d488a4dbc9896a15daebd78404fa4832c0322fe6f7"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/DeclaredOriginStatistics.php",
|
||||
"remote_sha256": "b5a20759938e2d5652018d6ec0b1b1d8dda6cdddbd4f7767fd5dbfa0da0e2f4c"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/DocumentManagementAccess.php",
|
||||
"remote_sha256": "6b2a0e8b75cb99f8baa9f40b4eda7cd5171348dd2126833ca3399e252baed4d0"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/EconomicReferenceInstallation.php",
|
||||
"remote_sha256": "a22050130c8cefdb18f2dafe03a4158f3e1596c5158cb9fd262abbf63c5ab144"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/ExistingBusinessIntake.php",
|
||||
"remote_sha256": "30d2325030e4024da1a15bc08085db8037fa42d09b1ece9c071386f346597937"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/ExistingBusinessProfileCategory.php",
|
||||
"remote_sha256": "46c045c19bff743a507a2efe0fc333454e82a9a48c2b355cf56834b638951737"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/InterestWorkflow.php",
|
||||
"remote_sha256": "d29080a7757c07505b418d4148cdb4abaaeb213a7b004bc21c52a135af99dca8"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/InvestmentZoneOperationalDetailsInstallation.php",
|
||||
"remote_sha256": "2b9f47cf7e1ddf14069440691485733f29cbe5fc0fb5b0091d15e96f5b8391d9"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/InvestmentZoneProfileInstallation.php",
|
||||
"remote_sha256": "026d6e1752fc8c4c80c14d5ce87bf5ea53d585a917a0cd3cd2c9d522247bb7db"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/InvestorContext.php",
|
||||
"remote_sha256": "1e7d9c7096b72a23df17611247c315ae6c8e76472c87638409be987c3cbba273"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/LegacyContent.php",
|
||||
"remote_sha256": "7138d214165859ad9ae4f4be81de9ab39978257264025a357b9b84aa90e661bc"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/Malware/ClamDScanner.php",
|
||||
"remote_sha256": "b708454c18793cbdfa761010905a0e423adfbaddeaf49ac342d88b1dc2e5d3e0"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityCanonicalContract.php",
|
||||
"remote_sha256": "75ffb95495b630193710830f5b9913681f544baacebeac7e7be5d7f7815e59cd"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityCategoryFields.php",
|
||||
"remote_sha256": "d7d294c72b7c416bd91726e7d7e2a045968e85d62ddaf57137da921e0340f25c"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityCompleteness.php",
|
||||
"remote_sha256": "1497712c221332e5f879205d94470c5cbe657d543565a99f08eee4543da0ddfb"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityInitiativeApplicability.php",
|
||||
"remote_sha256": "7efeae3c445bc3e7feb3275bd66a54a0b1370931a1331ac5ef6d7bfa58b4cdb5"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityLibrarySupport.php",
|
||||
"remote_sha256": "2dea4f3efc76b16c4cccb97ffcfbeccbe4b3151a9a871fe8e2c175f7874fec11"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityResources.php",
|
||||
"remote_sha256": "cf3baa0e5592f0b039189877faca514c62db65ae2e2bd634b5380c74f56ab412"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityTerritorialPresentation.php",
|
||||
"remote_sha256": "81d91ffe07531c43e057c81887bfa2891e50c38ff7cda9414a26af67592a2b78"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/PortalProfileInstallation.php",
|
||||
"remote_sha256": "4ab58a07c93e743327c592434dc1931057baf1ba81f488f4b51a28022beec4ac"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/ScopedPortalAdministration.php",
|
||||
"remote_sha256": "013efc04ecfddaea7473f50c0d0c31f56b5d958bb1594ed913d3d3855b9b0372"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/VerifiedDocumentBinary.php",
|
||||
"remote_sha256": "3a602b504bcb26edd3c9182dcab83fef2fd25166e61a840d1503b7a4d98f0728"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/VirtualDesk.php",
|
||||
"remote_sha256": "dc958b808d91b353d2c8e7d1244f594c54fc5eb4924e64654818f1cbd1aebda9"
|
||||
},
|
||||
{
|
||||
"path": "bootstrap/app.php",
|
||||
"remote_sha256": "b6e04e06d1d7d17f43ca81370ced7d470d5b9274957680110203f20e44ffacc1"
|
||||
},
|
||||
{
|
||||
"path": "config/homologation_editorial.php",
|
||||
"remote_sha256": "451a24a9a93fcdc2fd2aec98fb5b8689e13de1239c9b1671906ec58eb1b4e09e"
|
||||
},
|
||||
{
|
||||
"path": "config/legacy_content_aliases.php",
|
||||
"remote_sha256": "c8bfbead3a0908c84f7e1d595154d6d75ecebd24737651dad396e8bd0c900c50"
|
||||
},
|
||||
{
|
||||
"path": "config/portal.php",
|
||||
"remote_sha256": "6f26c86f4599a93eb1b80bb6fa0657b72fdbc03935d2c262080858fd79287b00"
|
||||
},
|
||||
{
|
||||
"path": "config/portal_profiles.php",
|
||||
"remote_sha256": "2e9e3d40277980c9fc139a51eb33212fe3df71a74397c353fe355a5642f99a07"
|
||||
},
|
||||
{
|
||||
"path": "config/services.php",
|
||||
"remote_sha256": "98f2875d58ab9283018b5c8e3ba24000f2d2b8be4d67ff107ff33ceac578be7c"
|
||||
},
|
||||
{
|
||||
"path": "database/migrations/2026_10_16_130000_add_investment_zone_editorial_draft.php",
|
||||
"remote_sha256": "ff9b56f7c3d156bedfe0050953c2ea6c10811fd859524a8fb994e176527846f0"
|
||||
},
|
||||
{
|
||||
"path": "database/migrations/2026_10_16_140000_add_investment_zone_operational_details.php",
|
||||
"remote_sha256": "3d3e7f00df749475a67c4d098a42cbbc81f9015afc8b74e6be58c86dd1f2abfb"
|
||||
},
|
||||
{
|
||||
"path": "database/migrations/2026_10_16_150000_create_investor_navigation_preferences.php",
|
||||
"remote_sha256": "e12017e6a4d1a960057cf2d1df9dbd69faa867bf6a2d08a50dd3089a6a967100"
|
||||
},
|
||||
{
|
||||
"path": "database/migrations/2026_10_18_160000_add_portal_editorial_content.php",
|
||||
"remote_sha256": "b3aa3d2510cd17975dbb4ff5f49d741af9f67601ce7e181f6173cfa2368d6334"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/app.tsx",
|
||||
"remote_sha256": "858eabfe3f5bf45a2e5a11c08e123fdd8c3243c6648c0d54def6966a0a683f88"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/app-logo.tsx",
|
||||
"remote_sha256": "e8e95de1d180014edc8fce2a36851727e5721319a9e9dffa90c82734f7b5939c"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/context-documents.tsx",
|
||||
"remote_sha256": "516871523445ea1efd2415f73c63e1ae74be2da76ceb620708bdf39fe0605999"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/country-select.tsx",
|
||||
"remote_sha256": "291676dc034a5f3d4d6498f1b80aa9de01b2b256f092fc855177a232b29ec714"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/investment-map-panel.tsx",
|
||||
"remote_sha256": "7cee11792343dd3ac94d4aeb782e6b23a29cf826b56209dcc5b4291d57b738c5"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/investment-territory.tsx",
|
||||
"remote_sha256": "38b2945a59601c5a1cea33827f57f105fc521ed3679223d95d5aa76cf6e13855"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/opportunity-canonical-fields.tsx",
|
||||
"remote_sha256": "f3c763063eee9aeb2da354c54e84c86e3c54f46dfecce4665ee0e8c6c6970d05"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/opportunity-classification.tsx",
|
||||
"remote_sha256": "06bdcf091f51a7eb44f75790f7d40462172571d1f1219f12620ee84a64fd668e"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/opportunity-library-reuse.tsx",
|
||||
"remote_sha256": "e95e3358a0016edd00596b09eeb80f5c2f0d149bdb456d8bc2c812cfb32e62f7"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/partnership-search-results.tsx",
|
||||
"remote_sha256": "efc037858a9a01d643894b308af8145959a7111b2667e393392dae53a3e5ba88"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/password-input.tsx",
|
||||
"remote_sha256": "f13f872ca86ebfd48fe475efdea32d5ec667414a4bba4529efe19a3bf81b2c16"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/portal-grouped-menu.tsx",
|
||||
"remote_sha256": "0c1de9b30772632afadcef6871edd6938cdab8f838983fd00cbd473d135432e7"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/portal-product-identity.tsx",
|
||||
"remote_sha256": "a0d5e22d06bd9dd12dce152425645f0247c7cb88767c23d5f0367e4f91c1e0cc"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/search-feedback.tsx",
|
||||
"remote_sha256": "bbe5b489b55b5853de553f68bdc6d38708247ca7a0649dda8a26e60148a8905d"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/search-state.tsx",
|
||||
"remote_sha256": "70d705f327d561c822a679e0739ce02470fbe7a18e4c8b44c9305f7619b496d6"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/structure-geography.tsx",
|
||||
"remote_sha256": "62f7570cf0b9149f006721ea59d694d66038530702d368444abc3589128619d4"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/tempo-footer.tsx",
|
||||
"remote_sha256": "14bbdc61d82cf392b43f7bf35e326cec87ddb40fbcce22d9aab9da872f746bc6"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/hooks/use-interest-draft.ts",
|
||||
"remote_sha256": "787b3295f3bee1282b4cacfefc1e7650feea54738d35f542d879a4dc13c9d475"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/layouts/auth/auth-simple-layout.tsx",
|
||||
"remote_sha256": "6c2b046bd02e7e02017a536873add53b02df79ef17798476b8021c401546462b"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/layouts/portal-navigation.tsx",
|
||||
"remote_sha256": "08876167e7de425470d6b97133441221437081b2065b2f1e6ccc9efce40a0b45"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/investor-context.ts",
|
||||
"remote_sha256": "19e2e5e6ef85059c29354a0f2a14d26012fdcc9868b84144b18df5fc41a667f9"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/participation-identity.ts",
|
||||
"remote_sha256": "e4446f51529d787e83beeb044eede9a3e5f3894cf7f9c51d97542c403f563b6c"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/portal-api.ts",
|
||||
"remote_sha256": "2ad0ad502e7805ae834e2368982f17b90cd9e32e4c0de112d14c1f3ef9268ca8"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/portal-navigation.ts",
|
||||
"remote_sha256": "17e541f5f0add27bf4af1dc6dae0ce7cdeab96de0162f1b3663cbf4dea2d8c85"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/project-dossier-document.ts",
|
||||
"remote_sha256": "28e2ac9929038f9fdbc2fe5bf8dde46e4ff477db29964dc7921381bfbf00cc65"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/project-dossier-report.ts",
|
||||
"remote_sha256": "f4a428cd337912df60ec3029e95c6fe9beaf2d3f81cca903690c626828719f22"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/PortalInvestidor.tsx",
|
||||
"remote_sha256": "18885a653fe13ea9040a998fb721a9e21a77fc3ead359378fac7b7a740eb9c5d"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/auth/login.tsx",
|
||||
"remote_sha256": "3f9231ba2cb69216c61215c701e8929ff9b90fb164f9a179f42d00b7c30c3aa7"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/auth/register.tsx",
|
||||
"remote_sha256": "6ea92f1ec50058e39af8901b78256f4c99fcfbefd0f9ebb299acdff05c99d50a"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/desk/request.tsx",
|
||||
"remote_sha256": "7b3b8bec1a66a0403e6cdf9a11cf83d59b6a529f5f43b6a5871ba76c1bc7935d"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/business-interest.tsx",
|
||||
"remote_sha256": "0cfbde1ba8e4cd164bd2a904c9f5560e4603609c71854b3fdb6db91561b883c4"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/business-wizard.tsx",
|
||||
"remote_sha256": "03ce4217bcb34583ceeeab454e40b1ee8aa73ba361d24e833e3c16e5fa165ec4"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/business.tsx",
|
||||
"remote_sha256": "3682717821510a19f7e02c14179d72144f50ee822d96ebd011e48d37d6ab2055"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/catalogue.tsx",
|
||||
"remote_sha256": "7ac06e80303992fae94b6ba2313ede5cff13da974815460cf59100b07b1ce338"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/context.tsx",
|
||||
"remote_sha256": "50b86276a3ac238b678f06dfb536b61ca3711a495453debae2e795082cdc0053"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/detail.tsx",
|
||||
"remote_sha256": "743de540cd1caeda5f3afb2b2dc78c088ea56ebe527a5466a3d039b430548688"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/submission.tsx",
|
||||
"remote_sha256": "71f03043fd16a806632fa7c0bf503998f0dff99fdd1bbfcaa703a032a2fa6558"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/zones.tsx",
|
||||
"remote_sha256": "a1f0b395f027a05ecef134e1bd0c03a20a23b089c7d8c5aa45403eb1c7920a92"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investor-path/context-start.tsx",
|
||||
"remote_sha256": "36d95c80a64a09ee40bd0fec8f6c0f623a47e576667fe08fadf2e3dc8969691e"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investor-path/context.tsx",
|
||||
"remote_sha256": "823da4d6092f553fef7aa801fb1c7d809b53b2c96571aaaeffece67a92af454a"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investor-path/show.tsx",
|
||||
"remote_sha256": "5d56de96fe41ad5b8782a4f1c472c110cbb3e93493bc92f88626853a7dff563d"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/land-assistance/print.tsx",
|
||||
"remote_sha256": "6355e9adb55de69deb335abff1c5d872e8993845c329f3227b81cfee4f7484c8"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/management/desk-assignments.tsx",
|
||||
"remote_sha256": "4ce516c67caf67215a8f9fa2cb5ca7e7c959353fc0c0b661ef31c47751d97274"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/management/opportunity-draft.tsx",
|
||||
"remote_sha256": "4281780693b7d25f2d8bb8f764e89555a1bc628b551725b671691fd0a7760f01"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/management/opportunity-resources.tsx",
|
||||
"remote_sha256": "494aab642c84e3fd603cf7d0c03d8cbc317e1f52d9575d6bace00360e6334346"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/management/territory-associations.tsx",
|
||||
"remote_sha256": "23997e11cc0a6735e128fdabb1453be9022a51487addaa69fe4d301a49cc2725"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portal/manage.tsx",
|
||||
"remote_sha256": "b6b96686aaccf6699551b0090a92fc40a9828affb953a8a87568d35fdc90688b"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portal/services.tsx",
|
||||
"remote_sha256": "8685509a3678323d9471e5921edcd195ca7dd3a50cc301d44222117d5df690e2"
|
||||
},
|
||||
{
|
||||
"path": "resources/views/desk/receipt.blade.php",
|
||||
"remote_sha256": "74c52186b38f75cae100283081fad22b90b13ec69ead512c4cd4f91bc2ca3a44"
|
||||
},
|
||||
{
|
||||
"path": "resources/views/errors/403.blade.php",
|
||||
"remote_sha256": "608ca8b0af82357afc1e6246767b777d2ec8b260f06f7f667089b1a465b24100"
|
||||
},
|
||||
{
|
||||
"path": "routes/api.php",
|
||||
"remote_sha256": "03afdc58de664a5d42459f4dcbd7367788f49c7736ec821ebd4bfaab609c3444"
|
||||
},
|
||||
{
|
||||
"path": "routes/investment-zones.php",
|
||||
"remote_sha256": "34b2d9c5042e59e4442906399e72e057771422840655185733fe32e8d7013737"
|
||||
},
|
||||
{
|
||||
"path": "routes/investment.php",
|
||||
"remote_sha256": "ce048ba84c38cb4c3676c05f04853ab41686970eadf583ba849ac63d19fce011"
|
||||
},
|
||||
{
|
||||
"path": "routes/virtual-desk.php",
|
||||
"remote_sha256": "fcef540ff90f6212b84b097492f34398c585fb03c6aeaa332943234e134cc9cb"
|
||||
},
|
||||
{
|
||||
"path": "routes/web.php",
|
||||
"remote_sha256": "67da2d4dd4c2572f42c734bf0e538b86d0deb44180a11e8a999b325159352198"
|
||||
}
|
||||
],
|
||||
"unchanged_runtime_files": 676,
|
||||
"runtime_files_requiring_remote_read": [],
|
||||
"excluded": "All .env, storage, generated route helpers, vendor/node_modules, synthetic actors and records; no database imports. Wayfinder helpers regenerated from committed routes during build.",
|
||||
"existing_diagnostic_source_preserved": [
|
||||
"app/Console/Commands/CheckDevelopmentEnvironment.php"
|
||||
],
|
||||
"subsequent_diagnostic_resolution": {
|
||||
"commit": "9d148ca2419d2243489731287dc8019cfe117bd9",
|
||||
"decision": "Retain the newer origin/main implementation, including --wait and safe transient-failure diagnostics. The installed older implementation has no unique behaviour to discard. The reconciled baseline commit remains preserved in history."
|
||||
},
|
||||
"generated_helper_not_committed": [
|
||||
{
|
||||
"path": "resources/js/wayfinder/index.ts",
|
||||
"remote_sha256": "3efc1c9f2eaa4828a4169414a1239420fc1bea8d3752fbd7a95b4a6da4a60d11"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import importlib.util, io, json, os, tarfile, tempfile, unittest, threading, time
|
||||
from pathlib import Path
|
||||
|
||||
spec=importlib.util.spec_from_file_location('delivery',Path(__file__).with_name('pipeline.py'))
|
||||
delivery=importlib.util.module_from_spec(spec);spec.loader.exec_module(delivery)
|
||||
|
||||
class PreservationTests(unittest.TestCase):
|
||||
def test_archive_extracts_only_source_bytes(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
buf=io.BytesIO()
|
||||
with tarfile.open(fileobj=buf,mode='w') as archive:
|
||||
item=tarfile.TarInfo('app/source.php');item.size=4;archive.addfile(item,io.BytesIO(b'code'))
|
||||
delivery.archive_source(buf.getvalue(),Path(d))
|
||||
self.assertEqual((Path(d)/'app/source.php').read_bytes(),b'code')
|
||||
def test_archive_refuses_private_data_and_escaping_links(self):
|
||||
for name,kind in [('.env','file'),('storage/app/private/secret.pdf','file'),('../outside','file'),('public/escape','link')]:
|
||||
with self.subTest(name=name),tempfile.TemporaryDirectory() as d:
|
||||
buf=io.BytesIO()
|
||||
with tarfile.open(fileobj=buf,mode='w') as archive:
|
||||
item=tarfile.TarInfo(name)
|
||||
if kind=='link':item.type=tarfile.SYMTYPE;item.linkname='/etc/passwd'
|
||||
else:item.size=1
|
||||
archive.addfile(item,None if kind=='link' else io.BytesIO(b'x'))
|
||||
with self.assertRaises(RuntimeError):delivery.archive_source(buf.getvalue(),Path(d))
|
||||
|
||||
def test_source_edit_and_unlisted_file_stop_promotion(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);(root/'app').mkdir();(root/'app/code.php').write_text('before')
|
||||
original=delivery.tree_hashes(root);(root/'app/code.php').write_text('programmer change')
|
||||
with self.assertRaises(RuntimeError):delivery.refuse_drift(root,original)
|
||||
(root/'app/code.php').write_text('before');(root/'app/new.php').write_text('extra')
|
||||
with self.assertRaises(RuntimeError):delivery.refuse_drift(root,original)
|
||||
|
||||
def test_runtime_data_not_part_of_source_drift(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);(root/'app').mkdir();(root/'app/code.php').write_text('same')
|
||||
original=delivery.tree_hashes(root)
|
||||
(root/'storage/app/private').mkdir(parents=True);(root/'storage/app/private/new.pdf').write_bytes(b'later data')
|
||||
(root/'.env').write_text('APP_KEY=not-distributed')
|
||||
delivery.refuse_drift(root,original)
|
||||
|
||||
def test_schema_change_stops_before_database_or_build_commands(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);contract=root/'schema.json';contract.write_text('{}');release=root/'release';release.mkdir()
|
||||
archive=io.BytesIO()
|
||||
with tarfile.open(fileobj=archive,mode='w') as tar:
|
||||
item=tarfile.TarInfo('database/migrations/new.php');item.size=4;tar.addfile(item,io.BytesIO(b'code'))
|
||||
config={'state_root':d,'release_root':d,'current_link':str(root/'current'),'legacy_root':d,'schema_contract':str(contract)}
|
||||
runner=delivery.Delivery(config);calls=[]
|
||||
def source_only(argv,**kwargs):calls.append(argv);return archive.getvalue()
|
||||
runner.run=source_only
|
||||
with self.assertRaisesRegex(RuntimeError,'Schema source changed'):runner.build('a'*40,release)
|
||||
self.assertEqual(len(calls),1);self.assertIn('archive',calls[0])
|
||||
|
||||
@unittest.skipIf(os.name=='nt','Atomic release promotion is exercised on the Linux destination clone')
|
||||
def test_failed_health_restores_previous_release_and_later_shared_data(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);old=root/'old';new=root/'new';old.mkdir();new.mkdir()
|
||||
shared=root/'private';shared.mkdir();record=shared/'later.txt';record.write_text('new data')
|
||||
link=root/'current';link.symlink_to(old,target_is_directory=True)
|
||||
def failed():raise RuntimeError('observed HTTP failure')
|
||||
with self.assertRaises(RuntimeError):delivery.promote(link,new,failed)
|
||||
self.assertEqual(link.resolve(),old);self.assertEqual(record.read_text(),'new data')
|
||||
|
||||
def test_qa_refuses_unapproved_port_or_database(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);flags=root/'flags.json';flags.write_text('{}')
|
||||
config={'state_root':d,'release_root':d,'current_link':str(root/'current'),'legacy_root':d,
|
||||
'ci_environment':str(flags),'qa_port':5432,'test_database':'teste_investidor'}
|
||||
with self.assertRaises(RuntimeError):delivery.Delivery(config).ci_env()
|
||||
|
||||
@unittest.skipIf(os.name=='nt','Linux symlinks and flock')
|
||||
def test_explicit_rollback_preserves_later_private_records(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);old=root/'old';new=root/'new';old.mkdir();new.mkdir()
|
||||
(old/'code').write_text('old');(new/'code').write_text('new')
|
||||
shared=root/'storage';shared.mkdir();(shared/'later').write_text('keep')
|
||||
link=root/'current';link.symlink_to(new,target_is_directory=True)
|
||||
installed={'release':str(new),'commit':'b'*40,'hashes':delivery.tree_hashes(new)}
|
||||
previous={'release':str(old),'commit':'a'*40,'hashes':delivery.tree_hashes(old)}
|
||||
delivery.write_json(root/'installed.json',installed);delivery.write_json(root/'previous.json',previous)
|
||||
config={'state_root':d,'release_root':d,'current_link':str(link),'legacy_root':d,'php':'php'}
|
||||
runner=delivery.Delivery(config);runner.run=lambda *a,**k:b'';runner.health=lambda target:self.assertEqual(target,'a'*40)
|
||||
self.assertEqual(runner.rollback()['status'],'rolled_back')
|
||||
self.assertEqual(link.resolve(),old);self.assertEqual((shared/'later').read_text(),'keep')
|
||||
|
||||
@unittest.skipIf(os.name=='nt','Linux flock and systemd target')
|
||||
def test_concurrent_runner_and_new_event_do_not_lose_or_overlap_jobs(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);(root/'requests').mkdir();head=root/'head';head.write_text('a'*40)
|
||||
delivery.write_json(root/'requests'/('a'*40+'.json'),{'commit':'a'*40})
|
||||
entered=threading.Event();resume=threading.Event();calls=[];active=[0,0];guard=threading.Lock()
|
||||
config={'state_root':d,'release_root':d,'current_link':str(root/'current'),'legacy_root':d}
|
||||
class Fake(delivery.Delivery):
|
||||
def latest(self):return head.read_text()
|
||||
def deliver(self,target):
|
||||
with guard:active[0]+=1;active[1]=max(active[1],active[0])
|
||||
if target=='a'*40:entered.set();resume.wait(3)
|
||||
calls.append(target)
|
||||
with guard:active[0]-=1
|
||||
return {'status':'installed','commit':target}
|
||||
first=threading.Thread(target=Fake(config).process);first.start();self.assertTrue(entered.wait(3))
|
||||
head.write_text('b'*40);delivery.write_json(root/'requests'/('b'*40+'.json'),{'commit':'b'*40})
|
||||
second=threading.Thread(target=Fake(config).process);second.start();resume.set();first.join(5);second.join(5)
|
||||
self.assertFalse(first.is_alive() or second.is_alive());self.assertEqual(active[1],1)
|
||||
self.assertEqual(calls,['a'*40,'b'*40]);self.assertEqual(list((root/'requests').glob('*.json')),[])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Synthetic, loopback-only receiver rehearsal. Never calls the site's /deploy."""
|
||||
import hashlib,hmac,json,os,socket,subprocess,tempfile,time,unittest,urllib.request,urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
class ReceiverTests(unittest.TestCase):
|
||||
def test_signature_scope_replay_and_no_command_dispatch(self):
|
||||
source=Path(__file__).with_name('webhook.php')
|
||||
with tempfile.TemporaryDirectory(prefix='investmoz-webhook-QA-') as directory:
|
||||
root=Path(directory);state=root/'state';(state/'requests').mkdir(parents=True);(state/'incoming').mkdir()
|
||||
secret=root/'synthetic-secret';secret.write_text('SYNTHETIC-LOCAL-QA-ONLY')
|
||||
config=root/'config.json';config.write_text(json.dumps({'webhook_secret_file':str(secret),'repository':'nala/Investidor-V2','branch':'homologacao','state_root':str(state)}))
|
||||
env={**os.environ,'INVESTMOZ_DELIVERY_CONFIG':str(config)}
|
||||
with socket.socket() as reserve:reserve.bind(('127.0.0.1',0));port=reserve.getsockname()[1]
|
||||
with (root/'php.log').open('wb') as log:
|
||||
proc=subprocess.Popen(['php8.4','-S','127.0.0.1:'+str(port),'-t',str(source.parent)],env=env,stdout=log,stderr=log)
|
||||
try:
|
||||
for _ in range(60):
|
||||
if proc.poll() is not None:self.fail('Isolated PHP did not start')
|
||||
with socket.socket() as probe:
|
||||
if probe.connect_ex(('127.0.0.1',port))==0:break
|
||||
time.sleep(0.05)
|
||||
def post(payload,valid=True,event='push'):
|
||||
data=json.dumps(payload).encode();signature=hmac.new(secret.read_bytes(),data,hashlib.sha256).hexdigest() if valid else '0'*64
|
||||
req=urllib.request.Request('http://127.0.0.1:'+str(port)+'/webhook.php',data=data,headers={'Content-Type':'application/json','X-Gitea-Event':event,'X-Gitea-Signature':signature})
|
||||
try:res=urllib.request.urlopen(req,timeout=5)
|
||||
except urllib.error.HTTPError as error:res=error
|
||||
return res.status
|
||||
valid={'repository':{'full_name':'nala/Investidor-V2'},'ref':'refs/heads/homologacao','after':'a'*40}
|
||||
self.assertEqual(post(valid,False),403)
|
||||
self.assertEqual(post({**valid,'ref':'refs/heads/main'}),204)
|
||||
self.assertEqual(post({**valid,'repository':{'full_name':'someone/other'}}),204)
|
||||
self.assertEqual(post({**valid,'after':'a; touch /tmp/not-a-command'}),400)
|
||||
self.assertEqual(list((state/'requests').iterdir()),[])
|
||||
self.assertEqual(post(valid),202);self.assertEqual(post(valid),202)
|
||||
files=list((state/'requests').glob('*.json'));self.assertEqual(len(files),1)
|
||||
self.assertEqual(json.loads(files[0].read_text())['commit'],'a'*40)
|
||||
self.assertEqual(list((state/'incoming').iterdir()),[])
|
||||
finally:
|
||||
proc.terminate();proc.wait(timeout=5)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Queue approved integrations for InvesteMoz homologation
|
||||
|
||||
[Path]
|
||||
DirectoryNotEmpty=/var/lib/investmoz-deploy/requests
|
||||
Unit=teste-investidor-deploy.service
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=InvesteMoz homologation CI and atomic delivery
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=mario
|
||||
Group=www-data
|
||||
WorkingDirectory=/var/lib/investmoz-deploy
|
||||
ExecStart=/usr/bin/python3 /var/www/deploy/investmoz-pipeline.py --config /etc/investmoz-deploy/delivery.json
|
||||
UMask=0027
|
||||
TimeoutStartSec=3600
|
||||
Nice=10
|
||||
CPUQuota=150%
|
||||
MemoryMax=4G
|
||||
NoNewPrivileges=true
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// Nginx independently requires Basic on this exact endpoint. No portal identity is created.
|
||||
$configFile = getenv('INVESTMOZ_DELIVERY_CONFIG') ?: '/etc/investmoz-deploy/delivery.json';
|
||||
$config = json_decode((string) @file_get_contents($configFile), true);
|
||||
if (!is_array($config)) { http_response_code(503); exit('Deployment configuration unavailable'); }
|
||||
$secret = @file_get_contents($config['webhook_secret_file']);
|
||||
if (!is_string($secret) || trim($secret) === '') { http_response_code(503); exit('Webhook unavailable'); }
|
||||
$body = (string) file_get_contents('php://input');
|
||||
$signature = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? $_SERVER['HTTP_X_GOGS_SIGNATURE'] ?? '';
|
||||
if (!preg_match('/\A[0-9a-f]{64}\z/i', $signature)
|
||||
|| !hash_equals(hash_hmac('sha256', $body, trim($secret)), strtolower($signature))) {
|
||||
http_response_code(403); exit('Invalid signature');
|
||||
}
|
||||
$event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? $_SERVER['HTTP_X_GOGS_EVENT'] ?? '';
|
||||
if ($event !== 'push') { http_response_code(204); exit; }
|
||||
$payload = json_decode($body, true);
|
||||
if (!is_array($payload)) { http_response_code(400); exit('Invalid JSON'); }
|
||||
if (($payload['repository']['full_name'] ?? '') !== $config['repository']
|
||||
|| ($payload['ref'] ?? '') !== 'refs/heads/'.$config['branch']) {
|
||||
http_response_code(204); exit;
|
||||
}
|
||||
$commit = strtolower((string) ($payload['after'] ?? ''));
|
||||
if (!preg_match('/\A[0-9a-f]{40}\z/', $commit) || $commit === str_repeat('0', 40)) {
|
||||
http_response_code(400); exit('Invalid revision');
|
||||
}
|
||||
$directory = $config['state_root'].'/requests';
|
||||
$file = $directory.'/'.$commit.'.json';
|
||||
// Atomic publication, exact commit identity; retries do not create duplicate requests.
|
||||
$temporary = @tempnam($config['state_root'].'/incoming', 'incoming-');
|
||||
if ($temporary === false) { http_response_code(503); exit('Queue unavailable'); }
|
||||
chmod($temporary, 0640);
|
||||
$data = json_encode(['commit' => $commit, 'ref' => $payload['ref'], 'received_at' => gmdate(DATE_ATOM)], JSON_THROW_ON_ERROR);
|
||||
if (file_put_contents($temporary, $data) === false || !rename($temporary, $file)) {
|
||||
@unlink($temporary); http_response_code(503); exit('Queue unavailable');
|
||||
}
|
||||
// systemd.path observes the queue even if a previous build is still active.
|
||||
http_response_code(202);
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['accepted' => true, 'commit' => $commit]);
|
||||
+36
-1
@@ -22,14 +22,49 @@ composer run dev
|
||||
Abra http://127.0.0.1:8000. O comando inicia Laravel, o worker da fila e Vite.
|
||||
Use Ctrl+C para terminar. A base conserva os dados entre arranques.
|
||||
|
||||
`composer run dev` aguarda até 900 segundos se o PostgreSQL estiver indisponível
|
||||
ou em recuperação. Mostra o motivo e o progresso, sem revelar credenciais.
|
||||
Erros de autenticação ou de base inexistente interrompem o arranque imediatamente.
|
||||
O diagnóstico directo `php artisan portal:dev-check` continua sem espera;
|
||||
use `--wait=900` para aguardar. O comando não inicia Docker nem executa migrations.
|
||||
|
||||
O script de arranque executa estes passos, parando no primeiro erro:
|
||||
|
||||
```powershell
|
||||
docker compose --env-file .env -f deploy/local/compose.yaml up -d --wait
|
||||
docker compose --env-file .env -f deploy/local/compose.yaml up -d --wait --wait-timeout 900
|
||||
php tools/local-qa-bootstrap.php
|
||||
composer run dev
|
||||
```
|
||||
|
||||
O `start.ps1` usa `--wait-timeout 900`. O healthcheck admite 600 segundos de
|
||||
arranque antes de contar falhas e reconhece imediatamente um servidor pronto.
|
||||
O Compose concede 60 segundos para um encerramento normal do PostgreSQL.
|
||||
|
||||
### PostgreSQL em recuperação
|
||||
|
||||
Em 20/10/2026, os registos mostraram um encerramento incorrecto seguido de
|
||||
recuperação entre 09:59 e 10:07 (Africa/Johannesburg). Durante esse período,
|
||||
o servidor recusava ligações com `the database system is in recovery mode`.
|
||||
O teste anterior ocultava a causa e terminava na primeira falha.
|
||||
|
||||
Se voltar a acontecer, deixe a recuperação concluir e consulte:
|
||||
|
||||
```powershell
|
||||
docker compose --env-file .env -f deploy/local/compose.yaml ps -a
|
||||
docker compose --env-file .env -f deploy/local/compose.yaml logs --tail 40 postgres
|
||||
php artisan portal:dev-check --wait=900
|
||||
```
|
||||
|
||||
Se o contentor estiver parado, execute `./deploy/local/start.ps1` com Docker
|
||||
Desktop iniciado. Não remova o volume nem reinicie repetidamente durante a
|
||||
recuperação. Para parar a base normalmente, use
|
||||
`docker compose --env-file .env -f deploy/local/compose.yaml stop postgres`
|
||||
antes de encerrar Docker Desktop ou o computador.
|
||||
|
||||
A espera, os diagnósticos e estes prazos são escolhas técnicas para a correcção
|
||||
solicitada em 20/10/2026, sob as decisões Tempo de AGENTS.md; não criam regras
|
||||
de negócio nem alteram dados activos.
|
||||
|
||||
O preparador verifica configuração e identidade real da base antes de migrar.
|
||||
Só admite `investmoz_local_test`, TCP local e porta real 55441, sem DB_URL nem
|
||||
configuração em cache. Executa migrations em `testing`, como exigem as guardas
|
||||
|
||||
@@ -4,6 +4,7 @@ services:
|
||||
image: postgis/postgis:17-3.5
|
||||
command: ['postgres', '-p', '55441']
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 60s
|
||||
environment:
|
||||
POSTGRES_DB: investmoz_local_test
|
||||
POSTGRES_USER: investmoz_test
|
||||
@@ -16,6 +17,7 @@ services:
|
||||
test: ['CMD-SHELL', 'pg_isready -p 55441 -U investmoz_test -d investmoz_local_test']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
start_period: 600s
|
||||
retries: 20
|
||||
volumes:
|
||||
postgres-qa:
|
||||
|
||||
@@ -2,7 +2,7 @@ $ErrorActionPreference = 'Stop'
|
||||
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
Push-Location $projectRoot
|
||||
try {
|
||||
docker compose --progress plain --env-file .env -f deploy/local/compose.yaml up -d --wait --wait-timeout 120
|
||||
docker compose --progress plain --env-file .env -f deploy/local/compose.yaml up -d --wait --wait-timeout 900
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Inicie Docker Desktop e verifique o serviço PostgreSQL QA.' }
|
||||
php tools/local-qa-bootstrap.php
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Preparação QA interrompida; veja a mensagem acima.' }
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"branch": "codex/opportunity-search",
|
||||
"base_commit": "1350b4df73e70ab35a28d923402ded7d836ade38",
|
||||
"date": "2026-10-20",
|
||||
"scope": "QA only; review before main integration",
|
||||
"qa_url": "http://127.0.0.1:18570/oportunidades",
|
||||
"files": [
|
||||
{
|
||||
"path": "app/Http/Controllers/Api/V1/OpportunityController.php",
|
||||
"sha256": "04fd696ce73fae8660491976781ef1bd96898a30af96363460427e7a9d139fe1"
|
||||
},
|
||||
{
|
||||
"path": "app/Http/Controllers/InvestmentDiscoveryController.php",
|
||||
"sha256": "a7301ce6c6285d8ec374b7013b8f0a0bb9951da83625acc47da223d2c4275bbf"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/InvestmentCatalogue.php",
|
||||
"sha256": "4b44e18ca12c890e0220913c972ca6092e29f8975dfbc6d292b579b95f1c5e21"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityClassification.php",
|
||||
"sha256": "f9a24067807fa620142839ab9873dde465457fcfc61f501d1c8309534a6da175"
|
||||
},
|
||||
{
|
||||
"path": "app/Services/OpportunityMaturity.php",
|
||||
"sha256": "1cd73acb486d8e3ffa52c7419e48b9d69b450bb343f04664cd1a2b51e3317246"
|
||||
},
|
||||
{
|
||||
"path": "docs/investmoz/unification/traceability-and-manual.md",
|
||||
"sha256": "5596aa8edbbeff34a13613ec11f00f49c62e76a8e2185e5762d972fc70b667e7"
|
||||
},
|
||||
{
|
||||
"path": "docs/investmoz/v2/auditoria-portal/backlog-priorizado.csv",
|
||||
"sha256": "5d1de3418c5b021a0520bc6494a6a5efcef665ad1d20a45b11ae6aa702bedb01"
|
||||
},
|
||||
{
|
||||
"path": "docs/investmoz/v2/auditoria-portal/backlog.md",
|
||||
"sha256": "303b53346af2dad908f9d40d02c14a8f245155897dacf8b2538cdaae5a92bea7"
|
||||
},
|
||||
{
|
||||
"path": "docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv",
|
||||
"sha256": "4bbf47f7b5bfe54d2dd3b891eca3c04555329e92064c3bc6722a60c2f8eab4ce"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/catalogue-filter-context.tsx",
|
||||
"sha256": "b155d5e812b52fc52677cb9a8d44068f64821732c90a82dabb521eed44af047e"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/catalogue-navigation.tsx",
|
||||
"sha256": "88eccc6a9c2803fd26b678081f5da244a9c4ac9227664e7d0f1b57050b437239"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/country-select.tsx",
|
||||
"sha256": "53ef3742e4c55668d0ad85139be742405f5d1524196b3b1b3f3700c7bc311742"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/investment-map-panel.tsx",
|
||||
"sha256": "cfdb99b7dfa405d740f68cecef2b0df38488d2f63dc623da47a000037f0ec01e"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/investment-territory.tsx",
|
||||
"sha256": "35cef961efb51709cba271556f5e7c717b673ebbca480b680e37654c38cde324"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/opportunity-classification.tsx",
|
||||
"sha256": "fb4d843c8c056f10c34baa5ab9f2ba324e9796456a20455303b7a3b0747ee6cd"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/opportunity-search-filters.tsx",
|
||||
"sha256": "85e48e41537a5932e0398b7bc4bddd5322431ae517a91de2d53e83ef7927e54d"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/search-feedback.tsx",
|
||||
"sha256": "23ed85878e5b55a40e01928236f870f6dff4c2a7e19547beaa81a0a7d59c9c06"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/components/search-state.tsx",
|
||||
"sha256": "45cc210783625bcf96712064a0e7dd97f5681c499cdf60cedbe0e4127cba7aab"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/catalogue-context.ts",
|
||||
"sha256": "c499ebda27b7672b55ea3e3da98c63c7d2d2cd490dcde77df3cc38e09792af73"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/lib/portal-navigation.ts",
|
||||
"sha256": "0d3bae6d726538b064cd992e6d433245321951c18198de5db540993232e6daaf"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/business-marketplace.tsx",
|
||||
"sha256": "f45a56b250bbb5da19613c6b7ad94ba89ea501929f97636c797d92b4a2251b51"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/catalogue.tsx",
|
||||
"sha256": "9ea5742950e2737bebb7bd7f04ee24129c7f9917c1986cf070a3e282e7a22981"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/detail.tsx",
|
||||
"sha256": "c40926782a183fcde27415e0eda276f73189f071ba6ce715e79d007eb6388634"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/shared.tsx",
|
||||
"sha256": "f71d13f0e0b5b0e152cf262f02b9e0770a58d32472ac878aa0adbca53d2edf3f"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/zone.tsx",
|
||||
"sha256": "8cd64fb62af5e2d4582c46298568429e61e45247fca1b072287ad35ae07d76db"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/investment/zones.tsx",
|
||||
"sha256": "5fecb308c3800f6e2ee266fd8559d2b14bea3214f2ffbeb4b651b86f2bed7ea7"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portal/services.tsx",
|
||||
"sha256": "6f26cace5d1808f6d563d0d8b0ebed6b44748abed7205e465d9658f8b9cb2d17"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portfolio/index.tsx",
|
||||
"sha256": "2662cfe05c387cb876f8c352bd83a5a1d68056c615333e238ecb4e7b5489eb00"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portfolio/shared.tsx",
|
||||
"sha256": "27b9d1c8dbced48532e7a57ce184810a32e3dea7cdc3a37a549dc7fbe8c04426"
|
||||
},
|
||||
{
|
||||
"path": "resources/js/pages/portfolio/show.tsx",
|
||||
"sha256": "51883858d09c6b07f281426fa9ec149c4de9f12286cc88b285caee01e892c892"
|
||||
},
|
||||
{
|
||||
"path": "tests/Feature/OpportunitySearchTest.php",
|
||||
"sha256": "b2d57a838849a7d1c9e5b43c3f471d3e5d78c59a7cdb8e0f81f74de5d886d7d3"
|
||||
},
|
||||
{
|
||||
"path": "tests/Support/OpportunitySearchFixture.php",
|
||||
"sha256": "46804da2f403c031ad206211db07f41f3f20dbf4f789f838e278e3f241d021f1"
|
||||
},
|
||||
{
|
||||
"path": "tests/frontend/portal-navigation.test.mjs",
|
||||
"sha256": "f19ff2d17a385ab1f28c65f69233a13d88d6b8b6ec7285848fcd2a945b883ff9"
|
||||
}
|
||||
],
|
||||
"build_manifest_sha256": "da35948622e0754e4ecc25247b8926dfcafa63c4fcb78a94da91a3c6e8b47451",
|
||||
"migrations": [],
|
||||
"data_operations": [],
|
||||
"remote_operations": [],
|
||||
"new_dependencies": [],
|
||||
"permissions_changes": false,
|
||||
"proofs": "outputs/opportunity-search-20261020/receipt.json",
|
||||
"pending": [
|
||||
"Tempo review before main integration",
|
||||
"Natural-language interpretation not implemented; evidence_only remains separate",
|
||||
"Eight contractual gaps and P7 unchanged"
|
||||
],
|
||||
"rollback": "Restore previous source/build using existing release chain; keep database, uploads, permissions and later data.",
|
||||
"hash_basis": "Git index bytes; line endings normalized by repository attributes. Manifest itself excluded."
|
||||
}
|
||||
@@ -1286,3 +1286,238 @@ Interfaces QA: [atribuir interesses](http://127.0.0.1:18555/management/interests
|
||||
| P6 | Conferência do delta de conteúdos/consumidores após P3–P5; reutilizar provas actuais. Vínculo com dossier legítimo quando disponível. | 2–4 h |
|
||||
|
||||
**Saldo de disponibilização do produto existente: 11–20 h**, condicionado ao lote P4 e às pré-condições do destino; não inclui espera por decisão/acesso nem desenvolvimento dos contratos especializados. Os 27–46 h são referência inicial do conjunto, não saldo. Não há base para estimar de forma responsável em bloco o desenvolvimento das oito modalidades: concluir por modalidade exige contrato explícito, âmbito sem acesso indevido, gravação/recuperação e submissão/revisão compatíveis. Recuperação e cessão exigem primeiro identificar a operação concreta; não constituem automaticamente novos módulos. **P7 permanece fechado e separado**, sem bloquear P1–P6. Incrementos 36–39 e instalação remota continuam para decisão expressa. Importação privada e publicação mantêm-se separadas.
|
||||
|
||||
|
||||
## P1/P2 — prova complementar de actualização, 20/10/2026
|
||||
|
||||
Mantém-se a revisão QA `6508c44b9fc1` (56 fontes/177 assets, hashes conferidos). Origem `167b5db97653`; não reconstruir nem repetir provas aceites. Pela interface e login/MFA sintético: interesse actualizado de Recebido para Em análise, nota preservada no histórico após recarregar; pedido do Balcão actualizado de Submetido para Em análise pelo analista atribuído, resposta fundamentada e histórico recuperados. Reutilizadas as provas de atribuição, recuperação noutra sessão e recusa de outros registos. Zero alterações remotas, importações, publicações ou grants reais. Contas sintéticas novamente retiradas da allowlist HTTP.
|
||||
|
||||
Limite concreto: o agendamento por calendário não foi certificado — a entrada automatizada não actualizou o estado React e o validador existente recusou a falta de prazo. Esse erro ainda aparece em inglês. Não inferir falha de gravação do estado/nota, nem declarar o calendário aprovado. A relação entre próxima acção e prazo já existia; não foi criada exigência organizacional.
|
||||
|
||||
P1: 13 das 21 modalidades reconciliadas, oito lacunas de contrato/âmbito individualizadas na tabela anterior; não encerrar todos os contratos especializados. P2: composição QA concluída; sem nova alteração de código. P7 assistência fechada e separada. Saldo P1–P6: 11–20 h para disponibilização do recorte existente (P3 3–5, P4 4–8 condicionado ao lote, P5 2–3, P6 2–4); desenvolvimento especializado sem estimativa fechada e sem bloquear os restantes componentes. O delta de actualização agora concluído não justifica repetir nem voltar a somar horas de P1/P2. Manifesto actualizado apenas nas provas, mesma revisão de fontes.
|
||||
|
||||
|
||||
## P3/P4 preparados e proposta P5/P6 — 20/10/2026
|
||||
|
||||
Revisão QA `3fd1f15bd01c`, sucessora de `6508c44b9fc1`: 56 fontes e 177 assets do build preservado. Duas fontes PHP corrigidas: mensagens do prazo em português e limite funcional no MNE reutilizando OpportunityCanonicalContract::deliveryBlockers. ExistingBusinessIntake não consultava esse limite; agora submissão e publicação de financiamento/concessão/fornecimento não são habilitadas por correspondência de acesso. A preparação permanece guardável. Cinco modalidades verificadas por transacção/rollback: capital_increase, financial_investor, financing_request, concession_opportunity, supply_opportunity. Nenhum módulo experimental foi ligado. As seis categorias base mantêm os bloqueios anteriores. As oito lacunas contratuais e P7 permanecem separados.
|
||||
|
||||
Calendário: mensagem de falta de prazo traduzida; edição por teclado, gravação e recuperação de 21/10/2026 com a próxima acção passaram no navegador QA. Não se alterou o componente de data: o preenchimento automático isolado não actualizava o estado React, enquanto a edição por teclado o actualiza. Prova anterior de actualização e limites reutilizada; sem repetir importações, scans, restauros ou percursos aceites. Sintaxe PHP passou; hashes dos 177 assets preservados, sem recompilação desnecessária por alteração exclusivamente PHP.
|
||||
|
||||
P3, manifesto privado: 30 fichas com identidade e hash actual do QA técnico, secções da fonte e relações; dois originais identificados por SHA256, versão e correspondência por bytes no clone do destino. As fichas continuam privadas; IDs de actores/organizações QA não são transportáveis. Definições project-change e project-follow-up extraídas de config/virtual-desk.php, incluindo campos e hash, comparadas com as versões do clone. Não substituir project-preparation v5 nem reassociar pedidos existentes. Nenhuma importação foi executada. O manifesto de identidades não é ainda um payload de aplicação autenticada.
|
||||
|
||||
P4, lista nominal: 27 entradas de referência (quatro edições de catálogo, 12 sectores e 11 actividades) e 24 referências territoriais com origem/identidade/versão e correspondências no clone. São inventário para reconciliação; **zero referências novas autorizadas para escrita e zero geometrias novas ou substituídas incluídas**. Não transportar catálogos de exemplo ou fonte pendente apenas por existirem localmente. Referências existentes são reutilizáveis por identidade/edição; divergências ficam por item e nunca se resolve por coincidência de ID local. A lista completa está no MANIFESTO-P4-REFERENCIAS-GEOMETRIAS.json. A base é um clone local, não prova fresca do servidor.
|
||||
|
||||
| Ordem P5/P6 | Operação e condição verificável | Reversão / limite |
|
||||
|---|---|---|
|
||||
| 1 — preflight por leitura | Conferir revisão/hash dos ficheiros nominais, schema usado por P1/P2 e P3, flags, operador/MFA, scanner Unix, worker e armazenamento. Comparar cada identidade/edição/hash dos manifestos com o destino actual. Parar apenas a operação divergente e apresentar diferença. | Não executar pacote de migrations. Esta candidata contém zero migrations. Não usar o clone como prova de estado remoto fresco. |
|
||||
| 2 — backup fresco | Suspender escritas HTTP, tarefas agendadas e consumo de filas no recorte durante cópia consistente da base e ficheiros privados; registar inventário, hashes, UID/GID/modos. Incluir configuração e chaves de desencriptação no envelope protegido com recuperação fora do perfil Windows. Retomar só após fecho consistente. | Reutilizar prova aceite de restauro; nesta execução não criar backup nem repetir restauro. Recuperação total é contingência, não reversão normal. |
|
||||
| 3 — código/build | Guardar cópia anterior por caminho/hash; aplicar apenas payload da revisão identificada, incluindo um build; efectuar limpeza/recriação de caches compatível com destino e processo existente. | Repor só ficheiros ainda com hash aplicado. Ficheiro modificado posteriormente gera conflito para reconciliação; nunca sobrescrever. |
|
||||
| 4 — dados privados P3 | Produzir prévia fresca pelo importador existente; reusar originais por hash, confirmar scan real no destino, resolver custódia/permissões por identidade autorizada, criar apenas fichas inexistentes e referências compatíveis. Registar journal de IDs/criação/hash/versão/execução. | Não publicar recursos nem oportunidades; preservar edições posteriores. Sem apagar ficheiros partilhados, histórico ou relações. Corrigir/desactivar só registos deste lote pela recuperação suportada; versões usadas por dossiers permanecem. |
|
||||
| 5 — serviços internos | VirtualDeskInstallationController, fluxo autenticado de instalação: registar apenas project-change/project-follow-up ausentes; comparar hashes se já existirem. Versionar sem substituir versões anteriores. Activação interna do serviço deve constar da decisão de disponibilização; não equivale a publicação de conteúdo. | Conservar versões referidas por pedidos posteriores. Retirar da escolha para novos pedidos apenas por mecanismo suportado; não eliminar versões ou pedidos. Se esse mecanismo não estiver disponível, conservar definição instalada e reverter só apresentação/código. |
|
||||
| 6 — referências P4 | Nesta prévia não há operação nova de escrita de geometrias/catálogos. Revalidar correspondências e reutilizar destino. Nova edição real exige identificação nominal e revisão expressa do manifesto. | Nenhuma geometria existente é substituída. Não converter desconhecido em confirmado. |
|
||||
| 7 — verificações do delta | Entrada autorizada; guardar/recuperar próxima acção e data; limites MNE sem activar contratos; fichas privadas/originais e duas definições recuperáveis; pesquisa/filtros/contexto apenas onde alterados. Vínculo positivo com dossier legítimo quando existir. | Provas aceites reutilizadas; não criar processo fictício no destino. Se faltar dossier legítimo, registar essa única prova pendente, sem bloquear os restantes componentes. |
|
||||
| 8 — fecho | Retomar escritas/worker e entregar estado por componente com URLs, alterações nominais e impedimentos. Conservar manifesto de execução e reversão. | Reversão normal conserva dados posteriores e estruturas/definições aditivas utilizadas, sem down migrations nem dump antigo sobre dados recentes. |
|
||||
|
||||
**Saldo delimitado revisto: 7–13 h** — P3 2–4 h (staging privado/resolução de identidades/aplicação nominal); P4 1–2 h (reconciliação fresca da lista, sem novas geometrias); P5 2–3 h; P6 2–4 h. O calendário, tradução e protecção do limite funcional foram concluídos nesta passagem e estão contabilizados como trabalho realizado, não como horas adicionais futuras. Esta faixa substitui 11–20 h para este recorte delimitado; não cobre concluir todas as modalidades nem um futuro lote geográfico não identificado. Não inclui espera por acesso/decisão. P1/P2 ficam preparados em QA com os limites acima; P3/P4 preparados por leitura, não importados. Instalação, incrementos 36–39 e activação interna das duas definições precisam da decisão expressa identificada. Sem alterações remotas ou publicação nesta execução.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — c11a0c74766c, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote c11a0c74766c, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O novo adaptador passou sintaxe/integridade/bindings, sem repetir importação; aplicação desse adaptador ainda não ensaiada. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — 82dab3719ffc, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote 82dab3719ffc, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O adaptador foi aplicado apenas em clone isolado: 30 identidades/30 localizações/31 suportes/11 relações, login e MFA sintéticos normais; rollback antes do commit e recuperação após commit comprovados, repetição sem escritas. UUID de auditoria e recibo transaccional corrigidos; aplicação de 56 fontes inalterada. As questões de acesso público e diferenças visuais/login continuam separadas e abertas. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — 312965f2c653, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote 312965f2c653, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O adaptador foi aplicado apenas em clone isolado: 30 identidades/30 localizações/31 suportes/11 relações, login e MFA sintéticos normais; rollback antes do commit e recuperação após commit comprovados, repetição sem escritas. UUID de auditoria e recibo transaccional corrigidos; aplicação de 56 fontes inalterada. As questões de acesso público e diferenças visuais/login continuam separadas e abertas. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Execução autorizada 312965f2c653 em homologação — 2026-10-20T10:01:37Z
|
||||
|
||||
Autorização expressa da Tempo nesta conversa; aplicada exclusivamente em teste-investidor.tempo.co.mz. 56 fontes/177 assets (233 caminhos) conferidos; backup fresco consistente de 171 tabelas, privados, fontes/build e configuração, seis artefactos cifrados e recuperação existente preservada. Não foi repetido restauro aceite.
|
||||
|
||||
30 fichas privadas, 30 localizações, 31 suportes, 11 relações; dois originais internos com scan real limpo (uma tentativa cada), sem publicar. project-change/project-follow-up v1 internos activados; project-preparation v5 preservado. Reutilizadas 27 referências/25 territórios; zero escritas de catálogos/geometrias, migrations ou permissões. 160 tabelas integralmente iguais; registos anteriores nas tabelas acrescentadas conferidos por hash; 361 ficheiros anteriores fora do delta intactos. HTTP/fila activos. Recibo e acessos: outputs/investmoz-revisao-integrada-QA-20261019/p1-p2/modalidades-e-interface/RECIBO-EXECUCAO-312965.json.
|
||||
|
||||
Saldo: execução delimitada P1–P6 concluída; não somar outra vez as 4–7 h já executadas. Mantêm-se vínculo positivo com dossier legítimo, dados em falta/revisão independente, oito lacunas contratuais, capacidades por desenvolver, P7 e SuiteCRM. Reversão disponível só da apresentação: manter 56 fontes compatíveis, ambos os builds, dados, definições usadas e histórico. Não repor dump antigo sobre dados posteriores. As questões de autenticação prematura e diferenças visuais/login continuam separadas, com análise retomada; sem alteração remota adicional.
|
||||
|
||||
|
||||
### Retoma separada de autenticação e apresentação após 312965
|
||||
|
||||
Diagnóstico apenas em clone isolado: com a reserva ligada, GET /documentos devolve 302 para login; desligada só no processo QA, /documentos e /oportunidades devolvem 200 anónimo, enquanto /management/portal-services e /minhas-oportunidades continuam 302. A reserva global tem origem na decisão expressa da Tempo, não constitui uma nova obrigação pública de MFA e não foi desactivada no destino. Questão permanece aberta para distinguir claramente reserva do ambiente e percurso público.
|
||||
|
||||
Manifestos de build local principal e QA instalada são diferentes; app.tsx/layout AuthSimple iguais, login.tsx difere no reaproveitamento do email. O ecrã local já aberto conserva título Laravel e rodapé anterior; não foi recarregada ou alterada a base local activa. Comparação visual por composição/configuração/sessão continua aberta. Nenhuma correcção adicional de código foi incluída silenciosamente no pacote. Prova: RETOMADA-AUTH-VISUAL-QA.json na mesma pasta do recibo; sem novo backlog.
|
||||
|
||||
|
||||
## Consulta pública e coerência visual em QA — b0fdd083ca56, 20/10/2026
|
||||
|
||||
Origem: pedido expresso da Tempo de 20/10/2026. A reserva do ambiente permanece obrigatória; a dependência de uma identidade do portal para qualquer consulta era escolha de implementação. O middleware global confundia ambas. Modo `perimeter` preparado e demonstrado apenas no QA loopback: autorização do ambiente pelo servidor, consulta pública sem conta e autenticação nas operações identificadas. Ausência de autorização e cabeçalho HTTP forjado recusados. O modo `reviewers` continua como valor predefinido compatível até configurar uma reserva independente no destino por decisão expressa. Não basta activar a flag nem aceitar um cabeçalho do cliente.
|
||||
|
||||
Base visual: composição aprovada 3fd1f15bd01c, preservando início, navegação, editorial e rodapé. Builds diferentes e conteúdo/configuração em execução explicam a divergência observada com o local; não se copiou `.env` ou segredos. Login/registo ainda continham textos ingleses e logótipo Laravel. QA utiliza a marca Tempo existente, textos portugueses, formulário sem salto de foco e aviso da reserva. A ligação de entrada na ficha pública passa pelo fluxo existente `/participar/entrar`, conservando URL/contexto.
|
||||
|
||||
Provas: 13 fronteiras de acesso e seis verificações adicionais passaram; TypeScript e build com código 0. No navegador: consulta anónima → rascunho sintético → autenticação → mesma oportunidade, nome, país, sector e mensagem recuperados. Paragem antes do envio final; zero manifestações desta conta. Registo normal por HTTP em QA, sem confirmação artificial de email/MFA e sem email externo. Gestão privada continua protegida; a conta de participação não recebe permissões administrativas. Imagens antes/depois de início, login e registo guardadas no mesmo conjunto de provas. Não repetir importação, recibos completos, scans ou restauros.
|
||||
|
||||
Revisão QA `b0fdd083ca56`: 10 fontes e 177 ficheiros de build no manifesto `MANIFESTO-PUBLICO-VISUAL-QA.json`; pacote sem ambiente, chaves, actores, dados ou harness. QA: http://127.0.0.1:18561/ ; /oportunidades ; /login ; /register. Só acessível nesta máquina. Homologação remota mantém 312965f2c653; não instalada esta correcção e nenhuma abertura externa. Para futura disponibilização será necessário definir e conferir o perímetro independente, antes de activar `perimeter`. Oito lacunas contratuais, vínculo documental positivo ao dossier e P7 separados. Reversão desta preparação: restaurar as dez fontes/build anteriores e manter o modo reservado anterior; nenhum schema ou dado de negócio alterado por este delta.
|
||||
|
||||
|
||||
## Proposta consolidada após reconciliação dos programadores — 423bd512d8c5, 20/10/2026
|
||||
|
||||
Preservada b0fdd083ca56 integralmente por hash, sem a renomear nem substituir. É revisão de conteúdo do pacote, não commit Git. Origin/main foi consultado nesta passagem: 507387502c6ef887433e8e9b5cf20ea39d4f17d4, com dois commits posteriores ao HEAD local a128c5a1. A nova composição mantém a aplicação aprovada 3fd1f15bd01c/312965 e acrescenta 97a08df2 (cabeçalho/menu responsivo, institucional/contacto, rodapé e formulário) e 50738750 (compilação/carregamento diferido dos exportadores). As alterações de 14ad2f60, cb438b2b, becb211f e 9bc450e8 já estavam incorporadas na base e foram conservadas. 6e57d1f6 e a128c5a1 são documentação/reconciliação, não implementação de autenticação.
|
||||
|
||||
Inventário: 760 ficheiros runtime do Git presentes, 677 exactos após normalizar finais de linha e 83 sobreposições QA enumeradas. Presença não comprova funcionamento de todos os componentes. Cinco conflitos de composição resolvidos; preservados menus novos, editorial, email institucional configurável, acesso/contexto e corpo dos exportadores aceites. A refactorização dos programadores só deslocou o corpo de geração; foi conservada com o corpo QA aceite. Ferramentas de arranque local e respectivo comando/composer dev-check não precisam de instalação no servidor. Não aplicar checkout/reset/pull nem substituir uma árvore inteira.
|
||||
|
||||
Identidade: a expressão anterior «marca Tempo» referia o logótipo da proprietária usado na autenticação, não autorização para mudar a identidade do produto. A composição agora identifica explicitamente InvesteMoz, propriedade da Tempo, Lda.; reutiliza o logótipo existente apenas para a proprietária. Não foi inventado outro logótipo de produto nem substituído um exemplar aprovado. Não foi localizado outro logótipo InvesteMoz entre os recursos públicos do repositório.
|
||||
|
||||
Reserva exacta: Nginx HTTPS com auth_basic independente, ficheiro protegido /etc/nginx/private/investmoz-homologation.htpasswd, snippet nominal e marcador FastCGI INVESTMOZ_HOMOLOGATION_ACCESS=granted só após autorização do ambiente. INV...HOMOLOGATION_ONLY=true mantido e ACCESS_MODE=perimeter. Document root /var/www/html/teste-investidor.tempo.co.mz/public, socket /run/php/php8.4-fpm.sock, vhost /etc/nginx/sites-available/teste-investidor.tempo.co.mz.conf. Configuração completa e hashes no pacote. /deploy e assets igualmente reservados; compatibilizar o cliente dos programadores antes da troca. Credenciais independentes por revisor autorizado, transmitidas por via protegida, sem reutilizar palavras-passe do portal ou alterar papéis/MFA.
|
||||
|
||||
Novas provas: oito casos HTTPS/Nginx/PHP-FastCGI passaram (401 sem autorização, 200 para convidado do portal autorizado no ambiente, 302 na operação privada), três passos da reversão da reserva e quatro casos do contacto com transporte simulado. Navegador: abrir/fechar/Escape do menu, navegação para contacto, erro do formulário e identidade em início/login/registo. Build/TypeScript passaram. Reutilizadas as 19 provas b0 e anteriores; sem nova importação, publicação, scan ou restauro. Clone Windows não comprova por si a instalação Linux. Última evidência remota continua a captura aceite de 20/10/2026; tentativa SSH desta passagem não autenticou (verificação da chave do host), sem ignorar essa verificação. Preflight fresco obrigatório antes da execução, com comparação também dos fontes que alimentam o build e detecção de ficheiros adicionais. Qualquer divergência bloqueia a troca e deve ser reconciliada.
|
||||
|
||||
Proposta única 423bd512d8c5: 40 fontes/recursos estáticos e 187 ficheiros de build, configurações e preflight somente leitura; zero migrations/importação/publicação. Reversão deste delta por ficheiro/hash e sequência da reserva, mantendo as 56 fontes compatíveis e dados introduzidos por 312965 e posteriores. Não é reposição integral da aplicação; não repor dump antigo. Oito lacunas contratuais, vínculo positivo ao dossier, geometrias e P7 separados. Estimativa operacional 90–150 minutos com preflight limpo e credenciais prontas, sem desenvolvimento das modalidades pendentes. Sem alterações remotas nesta passagem.
|
||||
|
||||
|
||||
## Preflight SSH e compatibilidade da reserva — 20/10/2026
|
||||
|
||||
Revisão 423bd512d8c5 preservada, ZIP SHA256 43b68aaf44daec2db0251f43a8ae254f038fbc0bb0157839327190f578d5d1af. Esta leitura substitui a limitação SSH do registo anterior: 669 verificações do preflight exacto passaram, incluindo 665 entradas de fontes; 125 ficheiros de dependências/base adicionais coincidem com a base aceite. HEAD remoto 9bc450e8; origin/main permanece 50738750. Build servido e vhost coincidem com as pré-condições do manifesto. Não apareceu conflito novo de código dos programadores.
|
||||
|
||||
Preservar um comando adicional de diagnóstico idêntico à base aceite, 149 auxiliares gerados (11 diferenças de comentários e três auxiliares antigos sem algumas rotas; nenhuma operação nova desconhecida) e 566 recursos adicionais do build. Não apagar nem regenerar no servidor. A aplicação recebe o build QA já aceite, não uma compilação remota.
|
||||
|
||||
Compatibilidade /deploy: ensaio isolado com o webhook efectivo confirmou 401 com HMAC válido mas sem credencial ambiental; 403 com credencial ambiental e HMAC inválido; 202 com ambos válidos, despacho interceptado, zero comandos reais e zero chamadas remotas. Nginx QA reposto. Não repetir as provas funcionais aceites.
|
||||
|
||||
O script remoto já recusa árvore Git alterada antes de fetch/reset/migrations; o estado failed resulta dessa guarda. A primeira leitura por palavras-chave sobre reset era incompleta: nenhuma guarda nova é necessária. Conservar script/serviço/HMAC. Não chamar /deploy para instalar esta revisão: o fluxo genérico inclui migrations automáticas, fora deste manifesto nominal de zero migrations.
|
||||
|
||||
Execução proposta: após decisão, backup fresco consistente; criar credenciais ambientais por via protegida; configurar no webhook Gitea existente Authorization Header = Basic <base64(utilizador:segredo ambiental)> ANTES de ligar a reserva, sem mudar URL/eventos/ramo/Secret HMAC; conferir novamente as pré-condições; aplicar nominalmente 40 fontes/recursos e 187 ficheiros de build; configuração Nginx exacta com /deploy igualmente reservado. Não usar Test Delivery ou push para testar, pois pode disparar o deploy genérico. O cabeçalho é configuração operacional, não credencial de conta do portal, e não entra em chat, URL ou recibo.
|
||||
|
||||
Avaliadores introduzem credencial ambiental e navegam no conteúdo público sem conta InvesteMoz. Operações identificadas continuam a exigir login/políticas/MFA aplicáveis. A futura abertura pública retirará a reserva por decisão própria, sem retirar a protecção privada ou a assinatura/guarda de /deploy. Identidade preservada: InvesteMoz, propriedade da Tempo, Lda.
|
||||
|
||||
Reversão: repor selectivamente o delta por hash e a reserva anterior, e só depois o cabeçalho anterior do cliente, sem alterar o Secret HMAC. Preservar alterações posteriores, 56 fontes compatíveis, dados, relações, definições e assets. Não é reposição integral da aplicação nem restauro de dump. Nenhuma alteração remota efectuada. Execução continua sujeita à decisão da Tempo; estimativa operacional 90–150 min com acessos prontos, excluindo esperas/divergências. Oito lacunas contratuais, vínculo documental legítimo, geometrias e P7 separados.
|
||||
|
||||
Provas: RECIBO-PREFLIGHT-423bd512d8c5.json, PREFLIGHT-EXACTO-423bd512d8c5.json e PROVA-COMPATIBILIDADE-DEPLOY-QA.json na pasta da mesma proposta. O manifesto/ZIP congelados não foram alterados; este recibo actualiza o preflight e a ordem operacional.
|
||||
|
||||
|
||||
## Execução autorizada 423bd512d8c5 — acesso pendente em 20/10/2026
|
||||
|
||||
A Tempo autorizou a execução nominal e a reserva independente. O preflight fresco passou (669 verificações). Staging protegido contém as mesmas 40 fontes/recursos e 187 ficheiros de build, sem alterar o ZIP. Dois hashes APR1 ambientais preparados em staging, sem activar a reserva. Credencial de Nala preparada em ficheiro local privado, restrito ao titular Windows/SYSTEM; nenhum valor em relatórios ou repositório.
|
||||
|
||||
Impedimento: o Gitea recusa a autenticação e o Authorization Header do webhook existente ainda não foi configurado. Não activar a reserva antes desta dependência. Pedido de autenticação/configuração local pendente; não falta nova autorização. Aplicação anterior preservada, sem manutenção, instalação, backup consistente iniciado, migrations, importação ou publicação. Retomar com acesso Gitea, backup fresco consistente e execução nominal já autorizada. Provas de consulta sem conta, conta simples e retoma por realizar após instalação. Disponibilização automática por Git não implementada e separada. Estado: ESTADO-EXECUCAO-AUTORIZADA-423.json na pasta da mesma proposta.
|
||||
|
||||
|
||||
## Disponibilização nominal 423bd512d8c5 — 20/10/2026
|
||||
|
||||
Executada exclusivamente na homologação reservada por autorização expressa da Tempo. Gitea: utilizador confirmou gravação do Authorization Header; presença Basic e Secret HMAC conferida sem expor valores. Não foi chamado /deploy, Test Delivery ou fluxo Git genérico. Disponibilização automática por Git não implementada e separada.
|
||||
|
||||
Backup fresco consistente concluído: manutenção HTTP, fila suspensa, bloqueios SHARE nas 171 tabelas públicas, hashes dos ficheiros estáveis antes/depois. Seis artefactos cifrados e conferidos: base, ficheiros privados/públicos de armazenamento e configuração/chaves da aplicação, fontes/build, configuração de servidor, ACL Linux e metadados. Envelope portátil de recuperação existente preservado, independente do perfil Windows; proprietário/grupo/permissões/ACL/xattrs registados. Não repetido o restauro integral aceite. Cópia anterior do delta e diário de hashes sob custódia root no destino.
|
||||
|
||||
Aplicadas 40 fontes/recursos e 187 ficheiros de build, exactamente pelos hashes do pacote congelado. Manifesto efectivamente servido: 41e9bdbf13dcd95865eefa8af25e2b1e40a5c607d293ad4755152dcea83f9d5d. HEAD Git permanece 9bc450e8 e não identifica sozinho a composição servida. Restantes fontes, comando adicional, 149 auxiliares gerados e todos os assets anteriores não substituídos pelo manifesto preservados (741 ficheiros antigos inventariados, zero perdas/alterações imprevistas). Vhost/snippet correspondem aos bytes do pacote; apenas cinco chaves nominais alteradas; restantes valores .env e proprietário/permissões preservados. Nginx validado antes de reload; PHP-FPM/scanner/base não reiniciados. Manutenção terminada e fila no estado anterior activo. Migrations registadas 88 antes/depois; zero migrations, importação, publicação, alterações de contas/grants/MFA.
|
||||
|
||||
13 verificações HTTPS do delta passaram: sem credencial ambiental, início/documentos/build e /deploy recusados (401); com credencial ambiental e sem conta do portal, início, documentos, oportunidades, sobre e contacto 200; áreas privadas redireccionam para login; manifesto HTTP igual ao instalado. Navegador: utilizador concluiu a entrada ambiental; início e os 29 documentos abrem com Entrar visível, sem conta InvesteMoz; Continuar no meu Balcão redireccionou para login. Retoma após login real e consulta com conta simples aguardam a sessão apropriada; não certificar esses dois passos pela prova anónima. Sem actores sintéticos ou impersonação no destino.
|
||||
|
||||
Credencial ambiental entregue por ficheiro local privado, restrito ao titular Windows/SYSTEM; não consta do repositório, Page ou recibos. Abertura pública continua separada e retirará a reserva por decisão própria, mantendo protecções privadas e /deploy.
|
||||
|
||||
Reversão aprovada: modo reviewers enquanto reserva independente permanece; repor selectivamente apresentação/rotas e configuração deste delta apenas se os hashes ainda coincidirem; preservar alterações posteriores; só depois repor reserva/cabeçalho anteriores. Manter 56 fontes compatíveis, dados/relações/definições e assets posteriores. Não é reposição integral nem restauro de dump. Oito lacunas contratuais, dossier legítimo, geometrias, P7 e automatização Git separados. Instalação concluída; saldo desta execução: 15–30 min de verificação com sessão real adequada, excluindo esperas; nenhum novo desenvolvimento incluído. Provas e recibo: RECIBO-EXECUCAO-423bd512d8c5.json e PROVA-HTTP/CONFIGURACAO/PRESERVACAO-DESTINO-423.json na mesma pasta da proposta.
|
||||
|
||||
|
||||
## Conferência da sessão real 423bd512d8c5 — 20/10/2026
|
||||
|
||||
Depois da entrada ambiental, o navegador apresentou início e biblioteca com 29 documentos sem conta do portal. Continuar no meu Balcão conduziu a /login. O titular concluiu a autenticação real e regressou automaticamente a /balcao-virtual/painel, com o título Balcão Virtual — acompanhamento e conta visível Osmane Nala. A página inicial voltou a abrir nessa sessão autenticada, sem pedir nova credencial. Esta evidência encerra a retoma no delta; não é prova de uma conta simples, pois a conta usada tem funções já autorizadas.
|
||||
|
||||
Não pedir novas contas para encerrar a instalação nem certificar a conta simples sem a observar. Única conferência específica restante deste recorte: consulta com uma conta simples real adequada, 5–10 min quando disponível, excluindo esperas. Não houve criação de conta, impersonação ou alteração de MFA/grants. Credencial ambiental, conta InvesteMoz e conta Gitea são independentes; para o trabalho corrente no portal, usar nala@tempo.co.mz. Não voltar a pedir autenticação nesta passagem.
|
||||
|
||||
Os seis directórios novos da instalação foram alinhados com o proprietário do repositório (mario:www-data, 0755), comprovadamente ausentes no arquivo fresco; permissões dos directórios existentes intactas. Sem alteração do pacote ou revisão. A sessão SSH encerrou pelo limite anterior; não foi reaberta apenas para actualizar o diário operacional remoto. Recibo final e provas actualizados localmente e na mesma Page. Revisão efectivamente servida continua 423bd512d8c5. Git automático, oito lacunas contratuais, dossier legítimo, geometrias e P7 separados.
|
||||
|
||||
|
||||
## Consulta pública sem autenticação ambiental — 20/10/2026
|
||||
|
||||
Decisão expressa da Tempo: retirar a autenticação ambiental das páginas públicas, preservando login, permissões e MFA das operações privadas e a protecção própria de /deploy. Esta decisão substitui a exigência de credencial ambiental para consultar os conteúdos públicos nesta homologação; não publica novos conteúdos nem altera contas ou funções.
|
||||
|
||||
Executado apenas o delta de configuração: removida a reserva Basic global do vhost; Basic mantido explicitamente na localização exacta /deploy com o mesmo htpasswd, e HMAC/Secret/cabeçalho Gitea preservados. Mantidos noindex/nofollow/noarchive e private/no-store no Nginx. INVESTMOZ_HOMOLOGATION_ONLY=false desactiva a reserva global do portal e a indicação desactualizada de ambiente reservado. O modo anterior permanece configurado mas inactivo para eventual reversão; marcador FastCGI de acesso ambiental retirado. Nenhuma alteração de código/build: revisão servida 423bd512d8c5, manifesto SHA256 41e9bdbf13dcd95865eefa8af25e2b1e40a5c607d293ad4755152dcea83f9d5d. Apenas reload Nginx após nginx -t; sem manutenção, migrations, imports, publicação ou reinício de base/fila/scanner.
|
||||
|
||||
Backup fresco apenas da configuração alterada, com hashes revalidados e metadados Linux, cifrado sob a custódia e envelope portátil existentes. Valores secretos não constam dos recibos. Cópias anteriores root-only no destino. Reversão: restaurar primeiro o vhost anterior condicionado aos hashes, validar/recarregar para repor a barreira ambiental; depois repor a flag anterior com conferência de conflitos/cache. Preservar edições posteriores e dados; não restaurar base antiga nem build.
|
||||
|
||||
16 verificações HTTPS passaram com CookieJar novo e sem Authorization na consulta: início, pesquisa /oportunidades?q=agronegocio (termo recuperado), documentos, ficha pública /documentos/13, artigo /agronegocio, sobre e contacto respondem 200, com componentes públicos e utilizador do portal ausente. Seis áreas privadas (/management/portal-services, /management/profile-install, /minhas-oportunidades, /investimentos, /investidor/manifestacoes e /balcao-virtual/painel) redireccionam para o login do portal sem desafio ambiental. /deploy continua 401 sem Basic e 403 com Basic válido mas HMAC inválido em JSON válido; serviço de deploy não disparado. Uma primeira sondagem com corpo vazio produziu 400 (JSON inválido); corrigida somente a sondagem negativa, sem alterar a aplicação ou repetir as restantes provas aceites.
|
||||
|
||||
A ausência do bloqueio é distinta de apenas esconder uma caixa do navegador: os componentes públicos efectivamente renderizam sem formulário de login e a pesquisa conserva o termo. Login num formulário InvesteMoz continua correcto nas operações privadas; se surgir na consulta pública, é falha a registar. Conferência visual em janela InPrivate nova solicitada ao utilizador, ainda pendente neste registo. Não declarar concluída essa parte pela prova HTTP isolada.
|
||||
|
||||
Recibo: RECIBO-CONFIGURACAO-PUBLICA-20261020.json; prova: PROVA-CONSULTA-SEM-CREDENCIAL-20261020.json, na pasta da mesma proposta. Oito lacunas contratuais, conta simples específica, dossier legítimo, geometrias, P7 e disponibilização automática por Git continuam separados. Não houve novas contas, concessões, desactivação de MFA ou publicação adicional.
|
||||
|
||||
|
||||
## Fecho da consulta pública sem credencial — 20/10/2026
|
||||
|
||||
O utilizador confirmou em janela Edge InPrivate nova: início, pesquisa /oportunidades?q=agronegocio e documentos abrem sem qualquer pedido de credenciais («ja funciona nestes 3»). Confirmação visual manual, distinta da prova automática HTTPS. A prova automática foi alargada apenas aos três consumidores adicionais afectados — zonas, sector Turismo e legislação — e passou em 19 verificações totais. Não repetidos scans, restauros, importações ou percursos anteriores.
|
||||
|
||||
Este delta de configuração fica concluído. Consulta pública não requer credencial ambiental nem conta InvesteMoz; seis operações privadas verificadas continuam a pedir login do portal, com permissões/MFA inalterados. /deploy conserva Basic + HMAC, com recusas 401/403 comprovadas e sem disparar o serviço. Prova de limites confirma que apenas /deploy contém Basic, o antigo include global e marcador FastCGI foram removidos, outros valores .env e proprietário/permissões estão intactos, webhook inalterado. Revisão de código/build continua 423bd512d8c5. Documentação anterior que exige credencial para a consulta pública fica superada por esta decisão expressa da Tempo.
|
||||
|
||||
Recibo e prova finais: RECIBO-CONFIGURACAO-PUBLICA-20261020.json e PROVA-CONSULTA-SEM-CREDENCIAL-20261020.json. Sem pendência neste recorte. Conta simples específica, oito lacunas contratuais, dossier legítimo, geometrias, P7 e automatização Git mantêm os saldos separados anteriores. Não se declara a aplicação inteira concluída por este ajuste.
|
||||
|
||||
|
||||
## Git main automático — 20/10/2026 — 8cf820ef
|
||||
|
||||
Disponibilização automática activa em main; revisão servida 8cf820ef497218d9adebe6a6a022b4c80d694dc3. Push real recebido pelo webhook às 17:28:44 e instalado às 17:29:56 (Maputo), sem despacho manual. Preservadas composição 423bd512d8c5 e alterações dos programadores até 02d4e6b2; conflito do menu resolvido mantendo layout novo, identidade InvesteMoz e administração delimitada. Build, TypeScript, 47 testes PHP, 156 frontend e 3106 asserções de schema passaram; nove testes Linux do executor e ensaio do webhook também passaram. Demonstração visual: Consultar oportunidades. 171 tabelas e 88 migrations permanecem; zero migrations no destino, importações, publicação ou novos grants. .env com bytes/proprietário/modo intactos; armazenamento partilhado e 869 assets anteriores preservados. Consulta pública 200 sem credenciais, gestão 302 para login e /deploy 401 sem Basic. Fila serial, recusa de drift e de alterações de migrations, releases separadas, logs/recibos protegidos e reversão de código/build com dados posteriores conservados. Oito lacunas contratuais, dossier legítimo, geometrias, conta simples específica e P7 mantêm saldo separado.
|
||||
|
||||
Procedimento dos programadores: trabalhar numa branch, rever segundo as designações da Tempo e integrar em `main`. O webhook existente dispara a verificação e compilação da revisão completa. Confirmar o commit em https://teste-investidor.tempo.co.mz/build/revision.json. Uma falha conserva a versão servida e deixa recibo/log protegido; não editar a pasta servida para a contornar.
|
||||
|
||||
O executor genérico com migrations automáticas foi substituído. O contrato nominal de 88 fontes de migrations fica protegido fora do Git; uma alteração exige compatibilidade/decisão específica. A CI usa PostGIS oficial fixado por digest, apenas em loopback 55441, base descartável `*_test` e identidade conferida. Não usa contas ou dados da aplicação. A guarda nominal e os testes de lifecycle existentes são preservados; não se contornam as instalações autenticadas.
|
||||
|
||||
Recuperação: parar a path unit, aguardar o executor e usar `python3 /var/www/deploy/investmoz-pipeline.py --config /etc/investmoz-deploy/delivery.json --rollback` como operador existente. Conferem-se hashes e saúde; a release anterior fica servida e o worker recebe reinício gracioso. Mantêm-se base, uploads, configuração e dados posteriores. Não é restauro integral. O checkout físico anterior e a cópia cifrada de configuração/metadados Linux permanecem disponíveis; a recuperação portátil existente foi reutilizada. Não foi repetido o restauro integral aceite.
|
||||
|
||||
As correcções do ensaio limitaram-se à composição: diagnóstico mais recente dos programadores, teste de exemplo sem migração inútil, fixtures unitárias independentes das flags do destino, expectativas dos menus/relatórios já aceites e guarda do cookie fora do navegador, com prova de CSRF preservado. Nenhuma nova regra organizacional.
|
||||
|
||||
Provas: outputs/investmoz-git-delivery-20261020/RECIBO-DISPONIBILIZACAO-GIT-MAIN.json; PROVA-ENSAIO-COMPLETO.json; PROVA-CONTROLO-FINAL-LINUX.json; PROVA-GITEA-EVENTO-E-INSTALACAO.json; PROVA-VISUAL-GIT-MAIN.png; deploy/homologacao/README.md; /build/revision.json. Manual versionado: `deploy/homologacao/README.md`. Esta entrega encerra o fluxo automático, não os restantes componentes da aplicação. As alterações documentais anteriores no checkout local foram preservadas.
|
||||
|
||||
|
||||
## Pesquisa transversal QA — 20/10/2026
|
||||
|
||||
Origem: instruções expressas da Tempo nesta conversa. A classificação multidimensional, dados, permissões, histórico e URLs mantêm-se. Os ajustes de interface/consulta são implementação do pedido, não novas regras organizacionais. Branch `codex/opportunity-search`, base `1350b4df`, QA HTTP `http://127.0.0.1:18570`. Não integrar em `main` antes da revisão: a integração desencadeia disponibilização automática.
|
||||
|
||||
**Causa reproduzida de 11 versus 0:** em `/oportunidades?sector=turismo` no destino, o selector provincial apresentava 11 opções através de `SearchState` como “11 resultados encontrados”, enquanto o paginador devolvia zero oportunidades públicas. São universos diferentes. Agora o primeiro diz “Província: 11 opções disponíveis”; o catálogo usa apenas o total do seu paginador. Não foram alterados dados para obter concordância. Foram ainda retirados o resumo global duplicado desta página, sugestões com critérios incompletos e resultados de parcerias que tinham pesquisa própria.
|
||||
|
||||
| Ecrã/URL | Problema | Correcção | Prova | Pendência/limite |
|
||||
|---|---|---|---|---|
|
||||
| Oportunidades — /oportunidades | Filtros duplicados, códigos internos, maturidades cruzadas, contagens concorrentes e mapa em grelha. | Filtro único, Mais filtros, preparação explícita, moeda obrigatória para montantes, pedidos canceláveis, estados e contexto únicos. | 6 testes PHP/112 asserções; navegador: parque, erro/repetição, moeda, vazio, retorno, hierarquia e teclado. | Revisão visual da Tempo; NLP separado. |
|
||||
| Negócios — /negocios | Classificação técnica visível, estados de auditoria e contagem territorial sem âmbito. | Sector básico, critérios especializados recolhidos em Mais filtros, estado de auditoria retirado do controlo público, contagem identificada e filtros removíveis. | HTTP/Inertia: universo results.meta.total=0; selector partilhado e código inspeccionados. | Nenhum contrato foi habilitado; oito lacunas contratuais mantidas fora deste lote. |
|
||||
| Sectores — /sectores; /sectores/{slug} | Navegação relacionada dispersa e contagens genéricas sem nome do universo. | Contagem identificada como Sectores; navegação comum preserva a entrada por sector e Fintech como especialização. | Inspecção de PublicPortalController, SectorOrganization e portalNavigation; testes de navegação. | Sem pesquisa autónoma no catálogo de sectores: não foi inventado um novo filtro. |
|
||||
| Localizações — /oportunidades?view=map | Mapa e contagem de oportunidades podiam usar universos diferentes sem explicação. | Mesmos filtros e permissões; locais com coordenadas e oportunidades sem coordenadas apresentados separadamente; fichas de contexto identificadas. | Teste de associação/lista/exportação; mapa do serviço exclui proximidade e preserva oportunidade sem coordenadas. | Nenhuma coordenada ou geometria criada. |
|
||||
| Carteira — /carteira | Menu local repetido, ausência de retorno explícito e de distinção entre ficha e pesquisa associada. | Contagem Fichas da carteira, chips removíveis, menu local redundante retirado, Consultar ficha e Ver oportunidades associadas; retorno com query local. | HTTP/Inertia de vazio; navegador de vazio; teste de contexto e navegação. | Provas anteriores de edição/publicação conservadas; não repetidas. |
|
||||
| Zonas e parques — /zonas; /zonas/{id} | Destinos repetidos, vazio atribuído indevidamente a falta de cadastro, retorno sem filtros. | Destinos relacionados recolhidos; vazio neutro; consultar ficha separado de oportunidades associadas; retorno e exportação preservam filtros. | HTTP/Inertia de vazio; inspecção da query/exportação e helpers de retorno. | Disponibilidade/incentivos continuam sujeitos aos dados de cada ficha. |
|
||||
| Clusters — /clusters → /carteira?kind=cluster | Mesmo padrão da carteira; não é um catálogo independente de oportunidades. | Reutiliza carteira, contagem nomeada e tipo de ficha removível; URL anterior preservada. | Redireccionamento verificado no teste PHP; consumidor comum inspeccionado. | Nenhuma equivalência entre implantação e associação criada. |
|
||||
| Corredores — /corredores → /carteira?kind=corridor | Mesmo padrão da carteira e risco de confundir ficha territorial com oportunidade. | Reutiliza carteira e ligações com finalidade explícita; URL anterior preservada. | Redireccionamento verificado no teste PHP; consumidor comum inspeccionado. | Nenhuma alteração de relações ou dados. |
|
||||
| Educação — /educacao | Herda formulário e contagens concorrentes das oportunidades. | Reutiliza integralmente a pesquisa corrigida com âmbito educação mantido. | HTTP/Inertia: results.total=0 com texto inexistente; filtros e componente comuns. | Gestão de procura/capacidade permanece separada e protegida; sem alteração de permissões. |
|
||||
| Biblioteca — /documentos | Dois resumos de contagem, filtros activos sem remoção individual, controlos sem opções e rodapé local repetido. | Resumo único nomeado Documentos, chips removíveis, controlos vazios ocultos sem apagar valores seleccionados, rodapé comum. | HTTP/Inertia e navegador: vazio e termos preservados; retorno documental existente conservado. | Não houve importação/publicação; a cópia QA usada não contém recursos públicos reais para nova prova positiva. |
|
||||
| Legislação — /legislacao | Mesmo padrão da biblioteca; não deve expor um universo concorrente. | Reutiliza a correcção da biblioteca e preserva filtros jurídicos/documentais pertinentes. | HTTP/Inertia: resources.total=0; consumidor e query pública partilhados. | Situação jurídica, consulta e cálculo continuam independentes. |
|
||||
|
||||
|
||||
### Utilização
|
||||
|
||||
1. Em oportunidades, preencher palavras, sector, modalidade e localização até ao nível conhecido. Usar “Mais filtros” para estruturas, actividades e cadeias. As opções territoriais não são a contagem das oportunidades.
|
||||
2. Para limites financeiros, escolher a moeda. Sem moeda, a pesquisa pede esse campo; não assume MZN nem converte montantes. Preparação tem etapas actuais e classificações históricas separadas.
|
||||
3. Retirar um critério pelo seu botão/ligação ou usar “Limpar filtros”. Alterar o pai territorial limpa os descendentes incompatíveis. Abrir a ficha e usar “Voltar à pesquisa” recupera os critérios.
|
||||
4. “Consultar ficha” consulta a estrutura territorial/documental; “Ver oportunidades associadas” pesquisa vínculos publicados. Proximidade ou o mesmo distrito não demonstram pertença. No mapa, registos sem coordenadas continuam identificados na lista, sem posições inventadas.
|
||||
5. Durante o pedido aparece “A pesquisar…”. Um erro apresenta “Tentar novamente” e preserva critérios; não aparece como resultado vazio. Pedidos anteriores são cancelados/ignorados ao mudar os filtros. Os estados têm `status`/`alert` e `aria-live`.
|
||||
|
||||
### Compatibilidade e provas
|
||||
|
||||
- A pesquisa antiga `maturity_level=1..6` conserva a classificação histórica, sem misturar a posição com a etapa actual. As posições 7/8, exclusivas das oito etapas, correspondem explicitamente a implementação/operacional. Novas selecções usam código de etapa ou classificação histórica explícita, sem reescrever os registos.
|
||||
- Balama real, ID `ed4d2fba-95d5-42e3-8ca7-1f520de1036a`: leitura pública do destino devolveu zero oportunidades associadas. Na cópia QA, essa ficha real está em rascunho; não foi publicada. A prova positiva usa um parque e oportunidades **SINTÉTICO QA**, incluindo associação preliminar, proximidade, território comum, outro parque e rascunho privado. Só a associação pública correspondente entra no filtro.
|
||||
- QA isolado `opportunity_search_20261020_test`, PostgreSQL local porta 55441; guarda impede testes na base activa. Testes transaccionais revertem apenas fixtures próprias; não foi executado `migrate:fresh`.
|
||||
- Seis testes PHP, 112 asserções: associação, confidencialidade, modalidades, maturidades distintas, moeda/combinações/vazio, referências, lista/exportação e HTTP dos consumidores/aliases. Seis testes frontend: navegação, flags, destinos únicos, quatro entradas e retorno local com query. Build e TypeScript conferidos no recibo final.
|
||||
- Navegador: consulta → ficha → retorno; parque isolado; validação de moeda → vazio; falha HTTP sintética de um único pedido → nova tentativa bem-sucedida; Inhambane/Vilankulo → Gaza limpa distrito e postos. A falha existe apenas no router privado do servidor QA, fora do pacote.
|
||||
- Móvel: dimensão real 390 px, largura de conteúdo 375 px, sem transbordo horizontal; teclado abre/fecha Mais filtros e Descoberta. A capacidade automática de viewport não aplicou a dimensão; a prova utilizou o modo responsivo do navegador. Não se atribui essa limitação à aplicação.
|
||||
- Antes/depois e estados: artefactos locais `opportunity-search-artifacts/{before-search.png,before-search-ax.txt,qa-after.png,qa-mobile.png,qa-error.png,qa-zero.png,backend-tests.log}`. As capturas do destino e QA usam acervos diferentes; os totais entre ambientes não são uma comparação de dados.
|
||||
- Inventário de reutilização de `investment-territory.tsx`: oportunidades, negócios, carteira, zonas, educação, análise educativa, formulário/recursos/editor de oportunidades, estruturas, associações territoriais, contexto do investimento, pedido do Balcão, terra/DUAT, formulários públicos e assistência existente. A alteração comum identifica o âmbito da contagem; não demonstra de novo edição/autorização desses consumidores privados. `CountrySelect` também identifica Países; `InvestmentMapPanel` identifica o universo cartográfico.
|
||||
- “Catatálogo” não foi encontrado nas fontes actuais inspeccionadas. O título servido usa “Catálogo”. O menu local redundante da carteira que exibia “InvestMoz” foi retirado; a identidade comum continua InvesteMoz, propriedade da Tempo.
|
||||
|
||||
### Assistência à pesquisa — saldo separado
|
||||
|
||||
`config/investmoz_ai.php`, `AiGateway` e `AssistiveRules` mostram pesquisa lexical/evidências e regras sobre campos estruturados, com `model=null`, sem pesquisa semântica. Não interpretam a frase “turismo em Inhambane até 500 mil USD” como filtros. `evidence_only` não comprova NLP. Nenhum serviço externo, custo ou envio de dados foi activado.
|
||||
|
||||
Incremento ainda necessário: interpretação delimitada de palavras/sector/geografia/montante/moeda; prévia editável dos filtros; pergunta apenas quando ambíguo; confirmação antes de executar exactamente a query manual; ausência de resultados sem alargamento silencioso. Estimativa de engenharia: 6–10 h para um interpretador local delimitado e casos de ambiguidade/testes; compreensão aberta com modelo externo exige proposta e decisão próprias. Esta estimativa não inclui as oito lacunas contratuais nem P7 e não bloqueia as correcções manuais.
|
||||
|
||||
### Integração e reversão
|
||||
|
||||
Rever a branch e o manifesto nominal; reconciliar novos commits dos programadores antes da integração. Após decisão da Tempo, a cadeia Git existente compila a revisão aprovada de fontes e build. Esta execução não envia para `main`, não escreve no servidor e não altera conteúdos, schema, contas, papéis, MFA ou configuração.
|
||||
|
||||
Não há migrations, importação ou publicação neste pacote. A reversão repõe as fontes/build da revisão anterior através da cadeia existente, preservando a base, uploads, referências, permissões e dados posteriores. Os helpers de contexto só transportam query local; não aceitam URL externa como destino de retorno. O manifesto lista fontes e hash do build QA; não inclui `.env`, credenciais, dumps, vendor/node_modules ou fixtures persistentes.
|
||||
|
||||
Conferência final dos consumidores: negócios também conferido no navegador com pesquisa vazia; retirado o resumo local repetido, conservando o resumo partilhado. Fintech é identificado como especialização do Mercado Financeiro também nesse selector. Os cartões de zonas traduzem categoria, desenvolvimento, disponibilidade e estado de actividade, preservando os códigos e significados persistidos. A vista combinada não repete na lista de não localizados a ficha que já aparece na lista principal.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2806,3 +2806,187 @@ Interfaces QA: [atribuir interesses](http://127.0.0.1:18555/management/interests
|
||||
| P6 | Conferência do delta de conteúdos/consumidores após P3–P5; reutilizar provas actuais. Vínculo com dossier legítimo quando disponível. | 2–4 h |
|
||||
|
||||
**Saldo de disponibilização do produto existente: 11–20 h**, condicionado ao lote P4 e às pré-condições do destino; não inclui espera por decisão/acesso nem desenvolvimento dos contratos especializados. Os 27–46 h são referência inicial do conjunto, não saldo. Não há base para estimar de forma responsável em bloco o desenvolvimento das oito modalidades: concluir por modalidade exige contrato explícito, âmbito sem acesso indevido, gravação/recuperação e submissão/revisão compatíveis. Recuperação e cessão exigem primeiro identificar a operação concreta; não constituem automaticamente novos módulos. **P7 permanece fechado e separado**, sem bloquear P1–P6. Incrementos 36–39 e instalação remota continuam para decisão expressa. Importação privada e publicação mantêm-se separadas.
|
||||
|
||||
|
||||
## P1/P2 — prova complementar de actualização, 20/10/2026
|
||||
|
||||
Mantém-se a revisão QA `6508c44b9fc1` (56 fontes/177 assets, hashes conferidos). Origem `167b5db97653`; não reconstruir nem repetir provas aceites. Pela interface e login/MFA sintético: interesse actualizado de Recebido para Em análise, nota preservada no histórico após recarregar; pedido do Balcão actualizado de Submetido para Em análise pelo analista atribuído, resposta fundamentada e histórico recuperados. Reutilizadas as provas de atribuição, recuperação noutra sessão e recusa de outros registos. Zero alterações remotas, importações, publicações ou grants reais. Contas sintéticas novamente retiradas da allowlist HTTP.
|
||||
|
||||
Limite concreto: o agendamento por calendário não foi certificado — a entrada automatizada não actualizou o estado React e o validador existente recusou a falta de prazo. Esse erro ainda aparece em inglês. Não inferir falha de gravação do estado/nota, nem declarar o calendário aprovado. A relação entre próxima acção e prazo já existia; não foi criada exigência organizacional.
|
||||
|
||||
P1: 13 das 21 modalidades reconciliadas, oito lacunas de contrato/âmbito individualizadas na tabela anterior; não encerrar todos os contratos especializados. P2: composição QA concluída; sem nova alteração de código. P7 assistência fechada e separada. Saldo P1–P6: 11–20 h para disponibilização do recorte existente (P3 3–5, P4 4–8 condicionado ao lote, P5 2–3, P6 2–4); desenvolvimento especializado sem estimativa fechada e sem bloquear os restantes componentes. O delta de actualização agora concluído não justifica repetir nem voltar a somar horas de P1/P2. Manifesto actualizado apenas nas provas, mesma revisão de fontes.
|
||||
|
||||
|
||||
## P3/P4 preparados e proposta P5/P6 — 20/10/2026
|
||||
|
||||
Revisão QA `3fd1f15bd01c`, sucessora de `6508c44b9fc1`: 56 fontes e 177 assets do build preservado. Duas fontes PHP corrigidas: mensagens do prazo em português e limite funcional no MNE reutilizando OpportunityCanonicalContract::deliveryBlockers. ExistingBusinessIntake não consultava esse limite; agora submissão e publicação de financiamento/concessão/fornecimento não são habilitadas por correspondência de acesso. A preparação permanece guardável. Cinco modalidades verificadas por transacção/rollback: capital_increase, financial_investor, financing_request, concession_opportunity, supply_opportunity. Nenhum módulo experimental foi ligado. As seis categorias base mantêm os bloqueios anteriores. As oito lacunas contratuais e P7 permanecem separados.
|
||||
|
||||
Calendário: mensagem de falta de prazo traduzida; edição por teclado, gravação e recuperação de 21/10/2026 com a próxima acção passaram no navegador QA. Não se alterou o componente de data: o preenchimento automático isolado não actualizava o estado React, enquanto a edição por teclado o actualiza. Prova anterior de actualização e limites reutilizada; sem repetir importações, scans, restauros ou percursos aceites. Sintaxe PHP passou; hashes dos 177 assets preservados, sem recompilação desnecessária por alteração exclusivamente PHP.
|
||||
|
||||
P3, manifesto privado: 30 fichas com identidade e hash actual do QA técnico, secções da fonte e relações; dois originais identificados por SHA256, versão e correspondência por bytes no clone do destino. As fichas continuam privadas; IDs de actores/organizações QA não são transportáveis. Definições project-change e project-follow-up extraídas de config/virtual-desk.php, incluindo campos e hash, comparadas com as versões do clone. Não substituir project-preparation v5 nem reassociar pedidos existentes. Nenhuma importação foi executada. O manifesto de identidades não é ainda um payload de aplicação autenticada.
|
||||
|
||||
P4, lista nominal: 27 entradas de referência (quatro edições de catálogo, 12 sectores e 11 actividades) e 24 referências territoriais com origem/identidade/versão e correspondências no clone. São inventário para reconciliação; **zero referências novas autorizadas para escrita e zero geometrias novas ou substituídas incluídas**. Não transportar catálogos de exemplo ou fonte pendente apenas por existirem localmente. Referências existentes são reutilizáveis por identidade/edição; divergências ficam por item e nunca se resolve por coincidência de ID local. A lista completa está no MANIFESTO-P4-REFERENCIAS-GEOMETRIAS.json. A base é um clone local, não prova fresca do servidor.
|
||||
|
||||
| Ordem P5/P6 | Operação e condição verificável | Reversão / limite |
|
||||
|---|---|---|
|
||||
| 1 — preflight por leitura | Conferir revisão/hash dos ficheiros nominais, schema usado por P1/P2 e P3, flags, operador/MFA, scanner Unix, worker e armazenamento. Comparar cada identidade/edição/hash dos manifestos com o destino actual. Parar apenas a operação divergente e apresentar diferença. | Não executar pacote de migrations. Esta candidata contém zero migrations. Não usar o clone como prova de estado remoto fresco. |
|
||||
| 2 — backup fresco | Suspender escritas HTTP, tarefas agendadas e consumo de filas no recorte durante cópia consistente da base e ficheiros privados; registar inventário, hashes, UID/GID/modos. Incluir configuração e chaves de desencriptação no envelope protegido com recuperação fora do perfil Windows. Retomar só após fecho consistente. | Reutilizar prova aceite de restauro; nesta execução não criar backup nem repetir restauro. Recuperação total é contingência, não reversão normal. |
|
||||
| 3 — código/build | Guardar cópia anterior por caminho/hash; aplicar apenas payload da revisão identificada, incluindo um build; efectuar limpeza/recriação de caches compatível com destino e processo existente. | Repor só ficheiros ainda com hash aplicado. Ficheiro modificado posteriormente gera conflito para reconciliação; nunca sobrescrever. |
|
||||
| 4 — dados privados P3 | Produzir prévia fresca pelo importador existente; reusar originais por hash, confirmar scan real no destino, resolver custódia/permissões por identidade autorizada, criar apenas fichas inexistentes e referências compatíveis. Registar journal de IDs/criação/hash/versão/execução. | Não publicar recursos nem oportunidades; preservar edições posteriores. Sem apagar ficheiros partilhados, histórico ou relações. Corrigir/desactivar só registos deste lote pela recuperação suportada; versões usadas por dossiers permanecem. |
|
||||
| 5 — serviços internos | VirtualDeskInstallationController, fluxo autenticado de instalação: registar apenas project-change/project-follow-up ausentes; comparar hashes se já existirem. Versionar sem substituir versões anteriores. Activação interna do serviço deve constar da decisão de disponibilização; não equivale a publicação de conteúdo. | Conservar versões referidas por pedidos posteriores. Retirar da escolha para novos pedidos apenas por mecanismo suportado; não eliminar versões ou pedidos. Se esse mecanismo não estiver disponível, conservar definição instalada e reverter só apresentação/código. |
|
||||
| 6 — referências P4 | Nesta prévia não há operação nova de escrita de geometrias/catálogos. Revalidar correspondências e reutilizar destino. Nova edição real exige identificação nominal e revisão expressa do manifesto. | Nenhuma geometria existente é substituída. Não converter desconhecido em confirmado. |
|
||||
| 7 — verificações do delta | Entrada autorizada; guardar/recuperar próxima acção e data; limites MNE sem activar contratos; fichas privadas/originais e duas definições recuperáveis; pesquisa/filtros/contexto apenas onde alterados. Vínculo positivo com dossier legítimo quando existir. | Provas aceites reutilizadas; não criar processo fictício no destino. Se faltar dossier legítimo, registar essa única prova pendente, sem bloquear os restantes componentes. |
|
||||
| 8 — fecho | Retomar escritas/worker e entregar estado por componente com URLs, alterações nominais e impedimentos. Conservar manifesto de execução e reversão. | Reversão normal conserva dados posteriores e estruturas/definições aditivas utilizadas, sem down migrations nem dump antigo sobre dados recentes. |
|
||||
|
||||
**Saldo delimitado revisto: 7–13 h** — P3 2–4 h (staging privado/resolução de identidades/aplicação nominal); P4 1–2 h (reconciliação fresca da lista, sem novas geometrias); P5 2–3 h; P6 2–4 h. O calendário, tradução e protecção do limite funcional foram concluídos nesta passagem e estão contabilizados como trabalho realizado, não como horas adicionais futuras. Esta faixa substitui 11–20 h para este recorte delimitado; não cobre concluir todas as modalidades nem um futuro lote geográfico não identificado. Não inclui espera por acesso/decisão. P1/P2 ficam preparados em QA com os limites acima; P3/P4 preparados por leitura, não importados. Instalação, incrementos 36–39 e activação interna das duas definições precisam da decisão expressa identificada. Sem alterações remotas ou publicação nesta execução.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — c11a0c74766c, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote c11a0c74766c, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O novo adaptador passou sintaxe/integridade/bindings, sem repetir importação; aplicação desse adaptador ainda não ensaiada. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — 82dab3719ffc, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote 82dab3719ffc, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O adaptador foi aplicado apenas em clone isolado: 30 identidades/30 localizações/31 suportes/11 relações, login e MFA sintéticos normais; rollback antes do commit e recuperação após commit comprovados, repetição sem escritas. UUID de auditoria e recibo transaccional corrigidos; aplicação de 56 fontes inalterada. As questões de acesso público e diferenças visuais/login continuam separadas e abertas. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Pacote executável P3/P4/P5/P6 — 312965f2c653, 20/10/2026
|
||||
|
||||
Staging privado concluído: 30 fichas actuais sem actores QA, dois originais com hash, duas definições internas. Destino conferido por SSH só leitura em 2026-10-20T08:37:24Z: fontes sem divergência, fichas/originais/duas definições ausentes, project-preparation v5 preservado. 27 referências e 25 territórios reconciliados (inclui Inhambane); zero escrita de catálogo/geometria. Aplicação QA 3fd1f15bd01c; pacote 312965f2c653, com adaptador de prévia/aplicação autenticada, backup consistente, instalação nominal e reversão de apresentação. Após uso só o manifesto de build anterior é reposto automaticamente; 56 fontes compatíveis, todos os assets, dados, definições usadas e histórico permanecem. O adaptador foi aplicado apenas em clone isolado: 30 identidades/30 localizações/31 suportes/11 relações, login e MFA sintéticos normais; rollback antes do commit e recuperação após commit comprovados, repetição sem escritas. UUID de auditoria e recibo transaccional corrigidos; aplicação de 56 fontes inalterada. As questões de acesso público e diferenças visuais/login continuam separadas e abertas. Saldo de aplicação/verificação 4–7 h; oito lacunas/P7 separados. Decisão pendente: executar revisão exacta, inclusão expressa 36–39/P3 e activação interna das duas definições. Não publicar fichas/documentos nem conceder novos papéis. Ver proposta única na mesma Page e RECIBO-PACOTE-EXECUTAVEL.json. Sem alteração remota nesta passagem.
|
||||
|
||||
|
||||
## Execução autorizada 312965f2c653 em homologação — 2026-10-20T10:01:37Z
|
||||
|
||||
Autorização expressa da Tempo nesta conversa; aplicada exclusivamente em teste-investidor.tempo.co.mz. 56 fontes/177 assets (233 caminhos) conferidos; backup fresco consistente de 171 tabelas, privados, fontes/build e configuração, seis artefactos cifrados e recuperação existente preservada. Não foi repetido restauro aceite.
|
||||
|
||||
30 fichas privadas, 30 localizações, 31 suportes, 11 relações; dois originais internos com scan real limpo (uma tentativa cada), sem publicar. project-change/project-follow-up v1 internos activados; project-preparation v5 preservado. Reutilizadas 27 referências/25 territórios; zero escritas de catálogos/geometrias, migrations ou permissões. 160 tabelas integralmente iguais; registos anteriores nas tabelas acrescentadas conferidos por hash; 361 ficheiros anteriores fora do delta intactos. HTTP/fila activos. Recibo e acessos: outputs/investmoz-revisao-integrada-QA-20261019/p1-p2/modalidades-e-interface/RECIBO-EXECUCAO-312965.json.
|
||||
|
||||
Saldo: execução delimitada P1–P6 concluída; não somar outra vez as 4–7 h já executadas. Mantêm-se vínculo positivo com dossier legítimo, dados em falta/revisão independente, oito lacunas contratuais, capacidades por desenvolver, P7 e SuiteCRM. Reversão disponível só da apresentação: manter 56 fontes compatíveis, ambos os builds, dados, definições usadas e histórico. Não repor dump antigo sobre dados posteriores. As questões de autenticação prematura e diferenças visuais/login continuam separadas, com análise retomada; sem alteração remota adicional.
|
||||
|
||||
|
||||
### Retoma separada de autenticação e apresentação após 312965
|
||||
|
||||
Diagnóstico apenas em clone isolado: com a reserva ligada, GET /documentos devolve 302 para login; desligada só no processo QA, /documentos e /oportunidades devolvem 200 anónimo, enquanto /management/portal-services e /minhas-oportunidades continuam 302. A reserva global tem origem na decisão expressa da Tempo, não constitui uma nova obrigação pública de MFA e não foi desactivada no destino. Questão permanece aberta para distinguir claramente reserva do ambiente e percurso público.
|
||||
|
||||
Manifestos de build local principal e QA instalada são diferentes; app.tsx/layout AuthSimple iguais, login.tsx difere no reaproveitamento do email. O ecrã local já aberto conserva título Laravel e rodapé anterior; não foi recarregada ou alterada a base local activa. Comparação visual por composição/configuração/sessão continua aberta. Nenhuma correcção adicional de código foi incluída silenciosamente no pacote. Prova: RETOMADA-AUTH-VISUAL-QA.json na mesma pasta do recibo; sem novo backlog.
|
||||
|
||||
|
||||
## Consulta pública e coerência visual em QA — b0fdd083ca56, 20/10/2026
|
||||
|
||||
Origem: pedido expresso da Tempo de 20/10/2026. A reserva do ambiente permanece obrigatória; a dependência de uma identidade do portal para qualquer consulta era escolha de implementação. O middleware global confundia ambas. Modo `perimeter` preparado e demonstrado apenas no QA loopback: autorização do ambiente pelo servidor, consulta pública sem conta e autenticação nas operações identificadas. Ausência de autorização e cabeçalho HTTP forjado recusados. O modo `reviewers` continua como valor predefinido compatível até configurar uma reserva independente no destino por decisão expressa. Não basta activar a flag nem aceitar um cabeçalho do cliente.
|
||||
|
||||
Base visual: composição aprovada 3fd1f15bd01c, preservando início, navegação, editorial e rodapé. Builds diferentes e conteúdo/configuração em execução explicam a divergência observada com o local; não se copiou `.env` ou segredos. Login/registo ainda continham textos ingleses e logótipo Laravel. QA utiliza a marca Tempo existente, textos portugueses, formulário sem salto de foco e aviso da reserva. A ligação de entrada na ficha pública passa pelo fluxo existente `/participar/entrar`, conservando URL/contexto.
|
||||
|
||||
Provas: 13 fronteiras de acesso e seis verificações adicionais passaram; TypeScript e build com código 0. No navegador: consulta anónima → rascunho sintético → autenticação → mesma oportunidade, nome, país, sector e mensagem recuperados. Paragem antes do envio final; zero manifestações desta conta. Registo normal por HTTP em QA, sem confirmação artificial de email/MFA e sem email externo. Gestão privada continua protegida; a conta de participação não recebe permissões administrativas. Imagens antes/depois de início, login e registo guardadas no mesmo conjunto de provas. Não repetir importação, recibos completos, scans ou restauros.
|
||||
|
||||
Revisão QA `b0fdd083ca56`: 10 fontes e 177 ficheiros de build no manifesto `MANIFESTO-PUBLICO-VISUAL-QA.json`; pacote sem ambiente, chaves, actores, dados ou harness. QA: http://127.0.0.1:18561/ ; /oportunidades ; /login ; /register. Só acessível nesta máquina. Homologação remota mantém 312965f2c653; não instalada esta correcção e nenhuma abertura externa. Para futura disponibilização será necessário definir e conferir o perímetro independente, antes de activar `perimeter`. Oito lacunas contratuais, vínculo documental positivo ao dossier e P7 separados. Reversão desta preparação: restaurar as dez fontes/build anteriores e manter o modo reservado anterior; nenhum schema ou dado de negócio alterado por este delta.
|
||||
|
||||
|
||||
## Proposta consolidada após reconciliação dos programadores — 423bd512d8c5, 20/10/2026
|
||||
|
||||
Preservada b0fdd083ca56 integralmente por hash, sem a renomear nem substituir. É revisão de conteúdo do pacote, não commit Git. Origin/main foi consultado nesta passagem: 507387502c6ef887433e8e9b5cf20ea39d4f17d4, com dois commits posteriores ao HEAD local a128c5a1. A nova composição mantém a aplicação aprovada 3fd1f15bd01c/312965 e acrescenta 97a08df2 (cabeçalho/menu responsivo, institucional/contacto, rodapé e formulário) e 50738750 (compilação/carregamento diferido dos exportadores). As alterações de 14ad2f60, cb438b2b, becb211f e 9bc450e8 já estavam incorporadas na base e foram conservadas. 6e57d1f6 e a128c5a1 são documentação/reconciliação, não implementação de autenticação.
|
||||
|
||||
Inventário: 760 ficheiros runtime do Git presentes, 677 exactos após normalizar finais de linha e 83 sobreposições QA enumeradas. Presença não comprova funcionamento de todos os componentes. Cinco conflitos de composição resolvidos; preservados menus novos, editorial, email institucional configurável, acesso/contexto e corpo dos exportadores aceites. A refactorização dos programadores só deslocou o corpo de geração; foi conservada com o corpo QA aceite. Ferramentas de arranque local e respectivo comando/composer dev-check não precisam de instalação no servidor. Não aplicar checkout/reset/pull nem substituir uma árvore inteira.
|
||||
|
||||
Identidade: a expressão anterior «marca Tempo» referia o logótipo da proprietária usado na autenticação, não autorização para mudar a identidade do produto. A composição agora identifica explicitamente InvesteMoz, propriedade da Tempo, Lda.; reutiliza o logótipo existente apenas para a proprietária. Não foi inventado outro logótipo de produto nem substituído um exemplar aprovado. Não foi localizado outro logótipo InvesteMoz entre os recursos públicos do repositório.
|
||||
|
||||
Reserva exacta: Nginx HTTPS com auth_basic independente, ficheiro protegido /etc/nginx/private/investmoz-homologation.htpasswd, snippet nominal e marcador FastCGI INVESTMOZ_HOMOLOGATION_ACCESS=granted só após autorização do ambiente. INV...HOMOLOGATION_ONLY=true mantido e ACCESS_MODE=perimeter. Document root /var/www/html/teste-investidor.tempo.co.mz/public, socket /run/php/php8.4-fpm.sock, vhost /etc/nginx/sites-available/teste-investidor.tempo.co.mz.conf. Configuração completa e hashes no pacote. /deploy e assets igualmente reservados; compatibilizar o cliente dos programadores antes da troca. Credenciais independentes por revisor autorizado, transmitidas por via protegida, sem reutilizar palavras-passe do portal ou alterar papéis/MFA.
|
||||
|
||||
Novas provas: oito casos HTTPS/Nginx/PHP-FastCGI passaram (401 sem autorização, 200 para convidado do portal autorizado no ambiente, 302 na operação privada), três passos da reversão da reserva e quatro casos do contacto com transporte simulado. Navegador: abrir/fechar/Escape do menu, navegação para contacto, erro do formulário e identidade em início/login/registo. Build/TypeScript passaram. Reutilizadas as 19 provas b0 e anteriores; sem nova importação, publicação, scan ou restauro. Clone Windows não comprova por si a instalação Linux. Última evidência remota continua a captura aceite de 20/10/2026; tentativa SSH desta passagem não autenticou (verificação da chave do host), sem ignorar essa verificação. Preflight fresco obrigatório antes da execução, com comparação também dos fontes que alimentam o build e detecção de ficheiros adicionais. Qualquer divergência bloqueia a troca e deve ser reconciliada.
|
||||
|
||||
Proposta única 423bd512d8c5: 40 fontes/recursos estáticos e 187 ficheiros de build, configurações e preflight somente leitura; zero migrations/importação/publicação. Reversão deste delta por ficheiro/hash e sequência da reserva, mantendo as 56 fontes compatíveis e dados introduzidos por 312965 e posteriores. Não é reposição integral da aplicação; não repor dump antigo. Oito lacunas contratuais, vínculo positivo ao dossier, geometrias e P7 separados. Estimativa operacional 90–150 minutos com preflight limpo e credenciais prontas, sem desenvolvimento das modalidades pendentes. Sem alterações remotas nesta passagem.
|
||||
|
||||
|
||||
## Preflight SSH e compatibilidade da reserva — 20/10/2026
|
||||
|
||||
Revisão 423bd512d8c5 preservada, ZIP SHA256 43b68aaf44daec2db0251f43a8ae254f038fbc0bb0157839327190f578d5d1af. Esta leitura substitui a limitação SSH do registo anterior: 669 verificações do preflight exacto passaram, incluindo 665 entradas de fontes; 125 ficheiros de dependências/base adicionais coincidem com a base aceite. HEAD remoto 9bc450e8; origin/main permanece 50738750. Build servido e vhost coincidem com as pré-condições do manifesto. Não apareceu conflito novo de código dos programadores.
|
||||
|
||||
Preservar um comando adicional de diagnóstico idêntico à base aceite, 149 auxiliares gerados (11 diferenças de comentários e três auxiliares antigos sem algumas rotas; nenhuma operação nova desconhecida) e 566 recursos adicionais do build. Não apagar nem regenerar no servidor. A aplicação recebe o build QA já aceite, não uma compilação remota.
|
||||
|
||||
Compatibilidade /deploy: ensaio isolado com o webhook efectivo confirmou 401 com HMAC válido mas sem credencial ambiental; 403 com credencial ambiental e HMAC inválido; 202 com ambos válidos, despacho interceptado, zero comandos reais e zero chamadas remotas. Nginx QA reposto. Não repetir as provas funcionais aceites.
|
||||
|
||||
O script remoto já recusa árvore Git alterada antes de fetch/reset/migrations; o estado failed resulta dessa guarda. A primeira leitura por palavras-chave sobre reset era incompleta: nenhuma guarda nova é necessária. Conservar script/serviço/HMAC. Não chamar /deploy para instalar esta revisão: o fluxo genérico inclui migrations automáticas, fora deste manifesto nominal de zero migrations.
|
||||
|
||||
Execução proposta: após decisão, backup fresco consistente; criar credenciais ambientais por via protegida; configurar no webhook Gitea existente Authorization Header = Basic <base64(utilizador:segredo ambiental)> ANTES de ligar a reserva, sem mudar URL/eventos/ramo/Secret HMAC; conferir novamente as pré-condições; aplicar nominalmente 40 fontes/recursos e 187 ficheiros de build; configuração Nginx exacta com /deploy igualmente reservado. Não usar Test Delivery ou push para testar, pois pode disparar o deploy genérico. O cabeçalho é configuração operacional, não credencial de conta do portal, e não entra em chat, URL ou recibo.
|
||||
|
||||
Avaliadores introduzem credencial ambiental e navegam no conteúdo público sem conta InvesteMoz. Operações identificadas continuam a exigir login/políticas/MFA aplicáveis. A futura abertura pública retirará a reserva por decisão própria, sem retirar a protecção privada ou a assinatura/guarda de /deploy. Identidade preservada: InvesteMoz, propriedade da Tempo, Lda.
|
||||
|
||||
Reversão: repor selectivamente o delta por hash e a reserva anterior, e só depois o cabeçalho anterior do cliente, sem alterar o Secret HMAC. Preservar alterações posteriores, 56 fontes compatíveis, dados, relações, definições e assets. Não é reposição integral da aplicação nem restauro de dump. Nenhuma alteração remota efectuada. Execução continua sujeita à decisão da Tempo; estimativa operacional 90–150 min com acessos prontos, excluindo esperas/divergências. Oito lacunas contratuais, vínculo documental legítimo, geometrias e P7 separados.
|
||||
|
||||
Provas: RECIBO-PREFLIGHT-423bd512d8c5.json, PREFLIGHT-EXACTO-423bd512d8c5.json e PROVA-COMPATIBILIDADE-DEPLOY-QA.json na pasta da mesma proposta. O manifesto/ZIP congelados não foram alterados; este recibo actualiza o preflight e a ordem operacional.
|
||||
|
||||
|
||||
## Execução autorizada 423bd512d8c5 — acesso pendente em 20/10/2026
|
||||
|
||||
A Tempo autorizou a execução nominal e a reserva independente. O preflight fresco passou (669 verificações). Staging protegido contém as mesmas 40 fontes/recursos e 187 ficheiros de build, sem alterar o ZIP. Dois hashes APR1 ambientais preparados em staging, sem activar a reserva. Credencial de Nala preparada em ficheiro local privado, restrito ao titular Windows/SYSTEM; nenhum valor em relatórios ou repositório.
|
||||
|
||||
Impedimento: o Gitea recusa a autenticação e o Authorization Header do webhook existente ainda não foi configurado. Não activar a reserva antes desta dependência. Pedido de autenticação/configuração local pendente; não falta nova autorização. Aplicação anterior preservada, sem manutenção, instalação, backup consistente iniciado, migrations, importação ou publicação. Retomar com acesso Gitea, backup fresco consistente e execução nominal já autorizada. Provas de consulta sem conta, conta simples e retoma por realizar após instalação. Disponibilização automática por Git não implementada e separada. Estado: ESTADO-EXECUCAO-AUTORIZADA-423.json na pasta da mesma proposta.
|
||||
|
||||
|
||||
## Disponibilização nominal 423bd512d8c5 — 20/10/2026
|
||||
|
||||
Executada exclusivamente na homologação reservada por autorização expressa da Tempo. Gitea: utilizador confirmou gravação do Authorization Header; presença Basic e Secret HMAC conferida sem expor valores. Não foi chamado /deploy, Test Delivery ou fluxo Git genérico. Disponibilização automática por Git não implementada e separada.
|
||||
|
||||
Backup fresco consistente concluído: manutenção HTTP, fila suspensa, bloqueios SHARE nas 171 tabelas públicas, hashes dos ficheiros estáveis antes/depois. Seis artefactos cifrados e conferidos: base, ficheiros privados/públicos de armazenamento e configuração/chaves da aplicação, fontes/build, configuração de servidor, ACL Linux e metadados. Envelope portátil de recuperação existente preservado, independente do perfil Windows; proprietário/grupo/permissões/ACL/xattrs registados. Não repetido o restauro integral aceite. Cópia anterior do delta e diário de hashes sob custódia root no destino.
|
||||
|
||||
Aplicadas 40 fontes/recursos e 187 ficheiros de build, exactamente pelos hashes do pacote congelado. Manifesto efectivamente servido: 41e9bdbf13dcd95865eefa8af25e2b1e40a5c607d293ad4755152dcea83f9d5d. HEAD Git permanece 9bc450e8 e não identifica sozinho a composição servida. Restantes fontes, comando adicional, 149 auxiliares gerados e todos os assets anteriores não substituídos pelo manifesto preservados (741 ficheiros antigos inventariados, zero perdas/alterações imprevistas). Vhost/snippet correspondem aos bytes do pacote; apenas cinco chaves nominais alteradas; restantes valores .env e proprietário/permissões preservados. Nginx validado antes de reload; PHP-FPM/scanner/base não reiniciados. Manutenção terminada e fila no estado anterior activo. Migrations registadas 88 antes/depois; zero migrations, importação, publicação, alterações de contas/grants/MFA.
|
||||
|
||||
13 verificações HTTPS do delta passaram: sem credencial ambiental, início/documentos/build e /deploy recusados (401); com credencial ambiental e sem conta do portal, início, documentos, oportunidades, sobre e contacto 200; áreas privadas redireccionam para login; manifesto HTTP igual ao instalado. Navegador: utilizador concluiu a entrada ambiental; início e os 29 documentos abrem com Entrar visível, sem conta InvesteMoz; Continuar no meu Balcão redireccionou para login. Retoma após login real e consulta com conta simples aguardam a sessão apropriada; não certificar esses dois passos pela prova anónima. Sem actores sintéticos ou impersonação no destino.
|
||||
|
||||
Credencial ambiental entregue por ficheiro local privado, restrito ao titular Windows/SYSTEM; não consta do repositório, Page ou recibos. Abertura pública continua separada e retirará a reserva por decisão própria, mantendo protecções privadas e /deploy.
|
||||
|
||||
Reversão aprovada: modo reviewers enquanto reserva independente permanece; repor selectivamente apresentação/rotas e configuração deste delta apenas se os hashes ainda coincidirem; preservar alterações posteriores; só depois repor reserva/cabeçalho anteriores. Manter 56 fontes compatíveis, dados/relações/definições e assets posteriores. Não é reposição integral nem restauro de dump. Oito lacunas contratuais, dossier legítimo, geometrias, P7 e automatização Git separados. Instalação concluída; saldo desta execução: 15–30 min de verificação com sessão real adequada, excluindo esperas; nenhum novo desenvolvimento incluído. Provas e recibo: RECIBO-EXECUCAO-423bd512d8c5.json e PROVA-HTTP/CONFIGURACAO/PRESERVACAO-DESTINO-423.json na mesma pasta da proposta.
|
||||
|
||||
|
||||
## Conferência da sessão real 423bd512d8c5 — 20/10/2026
|
||||
|
||||
Depois da entrada ambiental, o navegador apresentou início e biblioteca com 29 documentos sem conta do portal. Continuar no meu Balcão conduziu a /login. O titular concluiu a autenticação real e regressou automaticamente a /balcao-virtual/painel, com o título Balcão Virtual — acompanhamento e conta visível Osmane Nala. A página inicial voltou a abrir nessa sessão autenticada, sem pedir nova credencial. Esta evidência encerra a retoma no delta; não é prova de uma conta simples, pois a conta usada tem funções já autorizadas.
|
||||
|
||||
Não pedir novas contas para encerrar a instalação nem certificar a conta simples sem a observar. Única conferência específica restante deste recorte: consulta com uma conta simples real adequada, 5–10 min quando disponível, excluindo esperas. Não houve criação de conta, impersonação ou alteração de MFA/grants. Credencial ambiental, conta InvesteMoz e conta Gitea são independentes; para o trabalho corrente no portal, usar nala@tempo.co.mz. Não voltar a pedir autenticação nesta passagem.
|
||||
|
||||
Os seis directórios novos da instalação foram alinhados com o proprietário do repositório (mario:www-data, 0755), comprovadamente ausentes no arquivo fresco; permissões dos directórios existentes intactas. Sem alteração do pacote ou revisão. A sessão SSH encerrou pelo limite anterior; não foi reaberta apenas para actualizar o diário operacional remoto. Recibo final e provas actualizados localmente e na mesma Page. Revisão efectivamente servida continua 423bd512d8c5. Git automático, oito lacunas contratuais, dossier legítimo, geometrias e P7 separados.
|
||||
|
||||
|
||||
## Consulta pública sem autenticação ambiental — 20/10/2026
|
||||
|
||||
Decisão expressa da Tempo: retirar a autenticação ambiental das páginas públicas, preservando login, permissões e MFA das operações privadas e a protecção própria de /deploy. Esta decisão substitui a exigência de credencial ambiental para consultar os conteúdos públicos nesta homologação; não publica novos conteúdos nem altera contas ou funções.
|
||||
|
||||
Executado apenas o delta de configuração: removida a reserva Basic global do vhost; Basic mantido explicitamente na localização exacta /deploy com o mesmo htpasswd, e HMAC/Secret/cabeçalho Gitea preservados. Mantidos noindex/nofollow/noarchive e private/no-store no Nginx. INVESTMOZ_HOMOLOGATION_ONLY=false desactiva a reserva global do portal e a indicação desactualizada de ambiente reservado. O modo anterior permanece configurado mas inactivo para eventual reversão; marcador FastCGI de acesso ambiental retirado. Nenhuma alteração de código/build: revisão servida 423bd512d8c5, manifesto SHA256 41e9bdbf13dcd95865eefa8af25e2b1e40a5c607d293ad4755152dcea83f9d5d. Apenas reload Nginx após nginx -t; sem manutenção, migrations, imports, publicação ou reinício de base/fila/scanner.
|
||||
|
||||
Backup fresco apenas da configuração alterada, com hashes revalidados e metadados Linux, cifrado sob a custódia e envelope portátil existentes. Valores secretos não constam dos recibos. Cópias anteriores root-only no destino. Reversão: restaurar primeiro o vhost anterior condicionado aos hashes, validar/recarregar para repor a barreira ambiental; depois repor a flag anterior com conferência de conflitos/cache. Preservar edições posteriores e dados; não restaurar base antiga nem build.
|
||||
|
||||
16 verificações HTTPS passaram com CookieJar novo e sem Authorization na consulta: início, pesquisa /oportunidades?q=agronegocio (termo recuperado), documentos, ficha pública /documentos/13, artigo /agronegocio, sobre e contacto respondem 200, com componentes públicos e utilizador do portal ausente. Seis áreas privadas (/management/portal-services, /management/profile-install, /minhas-oportunidades, /investimentos, /investidor/manifestacoes e /balcao-virtual/painel) redireccionam para o login do portal sem desafio ambiental. /deploy continua 401 sem Basic e 403 com Basic válido mas HMAC inválido em JSON válido; serviço de deploy não disparado. Uma primeira sondagem com corpo vazio produziu 400 (JSON inválido); corrigida somente a sondagem negativa, sem alterar a aplicação ou repetir as restantes provas aceites.
|
||||
|
||||
A ausência do bloqueio é distinta de apenas esconder uma caixa do navegador: os componentes públicos efectivamente renderizam sem formulário de login e a pesquisa conserva o termo. Login num formulário InvesteMoz continua correcto nas operações privadas; se surgir na consulta pública, é falha a registar. Conferência visual em janela InPrivate nova solicitada ao utilizador, ainda pendente neste registo. Não declarar concluída essa parte pela prova HTTP isolada.
|
||||
|
||||
Recibo: RECIBO-CONFIGURACAO-PUBLICA-20261020.json; prova: PROVA-CONSULTA-SEM-CREDENCIAL-20261020.json, na pasta da mesma proposta. Oito lacunas contratuais, conta simples específica, dossier legítimo, geometrias, P7 e disponibilização automática por Git continuam separados. Não houve novas contas, concessões, desactivação de MFA ou publicação adicional.
|
||||
|
||||
|
||||
## Fecho da consulta pública sem credencial — 20/10/2026
|
||||
|
||||
O utilizador confirmou em janela Edge InPrivate nova: início, pesquisa /oportunidades?q=agronegocio e documentos abrem sem qualquer pedido de credenciais («ja funciona nestes 3»). Confirmação visual manual, distinta da prova automática HTTPS. A prova automática foi alargada apenas aos três consumidores adicionais afectados — zonas, sector Turismo e legislação — e passou em 19 verificações totais. Não repetidos scans, restauros, importações ou percursos anteriores.
|
||||
|
||||
Este delta de configuração fica concluído. Consulta pública não requer credencial ambiental nem conta InvesteMoz; seis operações privadas verificadas continuam a pedir login do portal, com permissões/MFA inalterados. /deploy conserva Basic + HMAC, com recusas 401/403 comprovadas e sem disparar o serviço. Prova de limites confirma que apenas /deploy contém Basic, o antigo include global e marcador FastCGI foram removidos, outros valores .env e proprietário/permissões estão intactos, webhook inalterado. Revisão de código/build continua 423bd512d8c5. Documentação anterior que exige credencial para a consulta pública fica superada por esta decisão expressa da Tempo.
|
||||
|
||||
Recibo e prova finais: RECIBO-CONFIGURACAO-PUBLICA-20261020.json e PROVA-CONSULTA-SEM-CREDENCIAL-20261020.json. Sem pendência neste recorte. Conta simples específica, oito lacunas contratuais, dossier legítimo, geometrias, P7 e automatização Git mantêm os saldos separados anteriores. Não se declara a aplicação inteira concluída por este ajuste.
|
||||
|
||||
|
||||
## Git main automático — 20/10/2026 — 8cf820ef
|
||||
|
||||
Disponibilização automática activa em main; revisão servida 8cf820ef497218d9adebe6a6a022b4c80d694dc3. Push real recebido pelo webhook às 17:28:44 e instalado às 17:29:56 (Maputo), sem despacho manual. Preservadas composição 423bd512d8c5 e alterações dos programadores até 02d4e6b2; conflito do menu resolvido mantendo layout novo, identidade InvesteMoz e administração delimitada. Build, TypeScript, 47 testes PHP, 156 frontend e 3106 asserções de schema passaram; nove testes Linux do executor e ensaio do webhook também passaram. Demonstração visual: Consultar oportunidades. 171 tabelas e 88 migrations permanecem; zero migrations no destino, importações, publicação ou novos grants. .env com bytes/proprietário/modo intactos; armazenamento partilhado e 869 assets anteriores preservados. Consulta pública 200 sem credenciais, gestão 302 para login e /deploy 401 sem Basic. Fila serial, recusa de drift e de alterações de migrations, releases separadas, logs/recibos protegidos e reversão de código/build com dados posteriores conservados. Oito lacunas contratuais, dossier legítimo, geometrias, conta simples específica e P7 mantêm saldo separado.
|
||||
|
||||
Procedimento dos programadores: trabalhar numa branch, rever segundo as designações da Tempo e integrar em `main`. O webhook existente dispara a verificação e compilação da revisão completa. Confirmar o commit em https://teste-investidor.tempo.co.mz/build/revision.json. Uma falha conserva a versão servida e deixa recibo/log protegido; não editar a pasta servida para a contornar.
|
||||
|
||||
O executor genérico com migrations automáticas foi substituído. O contrato nominal de 88 fontes de migrations fica protegido fora do Git; uma alteração exige compatibilidade/decisão específica. A CI usa PostGIS oficial fixado por digest, apenas em loopback 55441, base descartável `*_test` e identidade conferida. Não usa contas ou dados da aplicação. A guarda nominal e os testes de lifecycle existentes são preservados; não se contornam as instalações autenticadas.
|
||||
|
||||
Recuperação: parar a path unit, aguardar o executor e usar `python3 /var/www/deploy/investmoz-pipeline.py --config /etc/investmoz-deploy/delivery.json --rollback` como operador existente. Conferem-se hashes e saúde; a release anterior fica servida e o worker recebe reinício gracioso. Mantêm-se base, uploads, configuração e dados posteriores. Não é restauro integral. O checkout físico anterior e a cópia cifrada de configuração/metadados Linux permanecem disponíveis; a recuperação portátil existente foi reutilizada. Não foi repetido o restauro integral aceite.
|
||||
|
||||
As correcções do ensaio limitaram-se à composição: diagnóstico mais recente dos programadores, teste de exemplo sem migração inútil, fixtures unitárias independentes das flags do destino, expectativas dos menus/relatórios já aceites e guarda do cookie fora do navegador, com prova de CSRF preservado. Nenhuma nova regra organizacional.
|
||||
|
||||
Provas: outputs/investmoz-git-delivery-20261020/RECIBO-DISPONIBILIZACAO-GIT-MAIN.json; PROVA-ENSAIO-COMPLETO.json; PROVA-CONTROLO-FINAL-LINUX.json; PROVA-GITEA-EVENTO-E-INSTALACAO.json; PROVA-VISUAL-GIT-MAIN.png; deploy/homologacao/README.md; /build/revision.json. Manual versionado: `deploy/homologacao/README.md`. Esta entrega encerra o fluxo automático, não os restantes componentes da aplicação. As alterações documentais anteriores no checkout local foram preservadas.
|
||||
|
||||
|
||||
## Pesquisa transversal QA — 20/10/2026
|
||||
|
||||
Inventário finito AUD-SEARCH-T01–T11 na mesma matriz/CSV e comparação no manual. Correcções manuais na branch `codex/opportunity-search`, sem integração/remoto/publicação. Assistência NLP ainda não implementada: interpretador e prévia/confirmar da mesma query manual, 6–10 h para recorte local delimitado; modelo externo sujeito a decisão. As oito lacunas contratuais e P7 mantêm-se separados. Revisão Tempo pendente; as provas comuns não encerram requisitos de gestão ou publicação não alterados.
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 452 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 387 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 104 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 75 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
+307
-69
@@ -14,20 +14,59 @@
|
||||
background: #090909;
|
||||
color: #fff;
|
||||
}
|
||||
.tempo-logo-link {
|
||||
display: inline-flex;
|
||||
.tempo-header-inner {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
grid-template-rows: 72px;
|
||||
column-gap: 0.5rem;
|
||||
align-items: center;
|
||||
max-width: 1440px;
|
||||
margin-inline: auto;
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
.tempo-logo-link {
|
||||
grid-area: 1 / 1;
|
||||
display: inline-flex;
|
||||
width: fit-content;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
.tempo-header-logo {
|
||||
width: auto;
|
||||
height: 36px;
|
||||
object-fit: contain;
|
||||
}
|
||||
.tempo-primary-navigation {
|
||||
display: none;
|
||||
grid-area: 2 / 1 / auto / -1;
|
||||
min-width: 0;
|
||||
border-top: 1px solid #ffffff1a;
|
||||
}
|
||||
.tempo-primary-navigation > ul {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.25rem 0.5rem;
|
||||
padding-block: 0.75rem;
|
||||
}
|
||||
.tempo-primary-navigation .tempo-nav-trigger {
|
||||
font-size: 0.9375rem;
|
||||
padding-inline: 0.5rem;
|
||||
}
|
||||
.tempo-nav-trigger {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
justify-content: space-between;
|
||||
gap: 0.4rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0.4rem;
|
||||
font-size: 1rem;
|
||||
line-height: 1.5;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
color: #eee;
|
||||
transition:
|
||||
color 0.2s,
|
||||
@@ -45,16 +84,85 @@
|
||||
.tempo-nav-trigger[data-state='open'] > svg {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.tempo-nav-trigger {
|
||||
gap: 0.25rem;
|
||||
padding-inline: 0.25rem;
|
||||
font-size: 0.75rem;
|
||||
.tempo-primary-navigation .tempo-nav-trigger > svg {
|
||||
transform: none;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tempo-section-bar {
|
||||
border-top: 1px solid #ffffff14;
|
||||
background: inherit;
|
||||
}
|
||||
.tempo-section-inner {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 0.25rem 0.75rem;
|
||||
max-width: 1440px;
|
||||
margin-inline: auto;
|
||||
padding: 0 0.75rem 0.5rem;
|
||||
}
|
||||
.tempo-section-navigation {
|
||||
grid-area: 1 / 1 / auto / -1;
|
||||
min-width: 0;
|
||||
}
|
||||
.tempo-section-navigation > ul {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.tempo-section-navigation .tempo-nav-trigger {
|
||||
justify-content: center;
|
||||
min-height: 44px;
|
||||
gap: 0.25rem;
|
||||
padding: 0.5rem 0.375rem;
|
||||
border-radius: 0;
|
||||
font-size: 0.8125rem;
|
||||
letter-spacing: normal;
|
||||
}
|
||||
@media (min-width: 640px) {
|
||||
.tempo-section-navigation .tempo-nav-trigger {
|
||||
min-height: 48px;
|
||||
gap: 0.5rem;
|
||||
padding-inline: 0.75rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.tempo-nav-trigger > svg {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
}
|
||||
@media (min-width: 768px) {
|
||||
.tempo-section-inner {
|
||||
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
padding: 0.25rem 1.25rem;
|
||||
}
|
||||
.tempo-section-navigation {
|
||||
grid-area: 1 / 2;
|
||||
}
|
||||
.tempo-section-inner .tempo-panel-summary {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
.tempo-section-inner .tempo-interest-button {
|
||||
grid-area: 1 / 3;
|
||||
}
|
||||
}
|
||||
.tempo-header-extras {
|
||||
display: none;
|
||||
grid-area: 3 / 1 / auto / -1;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
padding-block: 0.75rem;
|
||||
border-top: 1px solid #ffffff1a;
|
||||
}
|
||||
.tempo-header[data-expanded] .tempo-primary-navigation {
|
||||
display: block;
|
||||
}
|
||||
.tempo-header[data-expanded] .tempo-header-extras {
|
||||
display: flex;
|
||||
}
|
||||
.tempo-header-utilities {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.tempo-utility-button {
|
||||
display: flex;
|
||||
@@ -63,7 +171,7 @@
|
||||
gap: 0.4rem;
|
||||
padding: 0.4rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
font-size: 0.8125rem;
|
||||
color: #e2e8f0;
|
||||
}
|
||||
.tempo-utility-button:hover {
|
||||
@@ -85,11 +193,6 @@
|
||||
transform: translateY(-2px);
|
||||
opacity: 0.8;
|
||||
}
|
||||
@media (max-width: 360px) {
|
||||
.tempo-header-social {
|
||||
width: 26px;
|
||||
}
|
||||
}
|
||||
.tempo-login-button {
|
||||
display: inline-flex;
|
||||
min-height: 40px;
|
||||
@@ -97,9 +200,10 @@
|
||||
gap: 0.5rem;
|
||||
border: 1px solid #ffffff50;
|
||||
border-radius: 0.4rem;
|
||||
padding: 0.5rem 0.85rem;
|
||||
font-size: 0.8rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
color: #fff;
|
||||
transition:
|
||||
background 0.2s,
|
||||
@@ -109,19 +213,23 @@
|
||||
background: #ed1c24;
|
||||
border-color: #ed1c24;
|
||||
}
|
||||
.tempo-login-button > span {
|
||||
max-width: clamp(2rem, calc(100vw - 18rem), 6rem);
|
||||
}
|
||||
.tempo-header-actions {
|
||||
order: 2;
|
||||
grid-area: 1 / 2;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
.tempo-interest-button {
|
||||
display: inline-flex;
|
||||
grid-area: 2 / 2;
|
||||
justify-self: end;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 40px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border: 1px solid #ed1c24;
|
||||
border-radius: 0.4rem;
|
||||
background: #ed1c24;
|
||||
@@ -135,56 +243,171 @@
|
||||
background: #c9151c;
|
||||
}
|
||||
.tempo-panel-summary {
|
||||
order: 4;
|
||||
grid-area: 2 / 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: 0.1rem;
|
||||
min-height: 44px;
|
||||
padding-block: 0.5rem;
|
||||
border-top: 1px solid #ffffff1a;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.tempo-panel-summary a {
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.4;
|
||||
color: #fff;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
.tempo-panel-summary a:hover {
|
||||
.tempo-panel-summary:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.tempo-panel-summary span {
|
||||
.tempo-panel-count {
|
||||
color: #cbd5e1;
|
||||
font-size: 0.6875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.tempo-header-actions {
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
padding-block: 0.65rem;
|
||||
.tempo-header-toggle {
|
||||
grid-area: 1 / 3;
|
||||
display: inline-flex;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid #ffffff33;
|
||||
border-radius: 0.4rem;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tempo-header-toggle:hover,
|
||||
.tempo-header-toggle[aria-expanded='true'] {
|
||||
background: #ffffff10;
|
||||
}
|
||||
@media (min-width: 640px) {
|
||||
.tempo-header-inner {
|
||||
padding-inline: 1.25rem;
|
||||
}
|
||||
.tempo-header-logo {
|
||||
height: 44px;
|
||||
}
|
||||
.tempo-primary-navigation > ul {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
@media (min-width: 1024px) {
|
||||
.tempo-header-inner {
|
||||
grid-template-rows: 88px;
|
||||
padding-inline: 1.5rem;
|
||||
}
|
||||
.tempo-header-logo {
|
||||
height: 56px;
|
||||
}
|
||||
}
|
||||
@media (min-width: 1280px) {
|
||||
.tempo-header-actions {
|
||||
order: 6;
|
||||
margin-left: 0;
|
||||
/* Shared columns keep each portal area below its institutional link. */
|
||||
.tempo-header-layout {
|
||||
display: grid;
|
||||
grid-template-columns: auto repeat(4, max-content) minmax(0, 1fr) auto;
|
||||
column-gap: 0.25rem;
|
||||
max-width: 1440px;
|
||||
margin-inline: auto;
|
||||
padding-inline: 2rem;
|
||||
}
|
||||
.tempo-header-inner .tempo-nav-trigger {
|
||||
padding-inline: 0.5rem;
|
||||
.tempo-header-inner {
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
min-height: 88px;
|
||||
column-gap: normal;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.tempo-logo-link {
|
||||
margin-right: 0.75rem;
|
||||
}
|
||||
.tempo-header-logo {
|
||||
height: 64px;
|
||||
}
|
||||
.tempo-header[data-expanded] .tempo-primary-navigation,
|
||||
.tempo-primary-navigation {
|
||||
display: grid;
|
||||
grid-area: 1 / 2 / 2 / 6;
|
||||
grid-template-columns: subgrid;
|
||||
border: 0;
|
||||
}
|
||||
.tempo-primary-navigation > ul {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
gap: normal;
|
||||
padding: 0;
|
||||
}
|
||||
.tempo-nav-trigger {
|
||||
justify-content: center;
|
||||
padding-inline: 0.875rem;
|
||||
font-size: 1.125rem;
|
||||
letter-spacing: 0.025em;
|
||||
}
|
||||
.tempo-primary-navigation .tempo-nav-trigger {
|
||||
padding-inline: 0.625rem;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
.tempo-header-extras {
|
||||
display: flex;
|
||||
grid-area: 1 / 6;
|
||||
justify-self: end;
|
||||
flex-shrink: 0;
|
||||
padding: 0 0.75rem;
|
||||
border-top: 0;
|
||||
border-inline: 1px solid #ffffff1a;
|
||||
}
|
||||
.tempo-header-utilities {
|
||||
flex-wrap: nowrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.tempo-header-social {
|
||||
width: 26px;
|
||||
}
|
||||
.tempo-header-toggle {
|
||||
display: none;
|
||||
}
|
||||
.tempo-header-actions {
|
||||
grid-area: 1 / 7;
|
||||
}
|
||||
.tempo-section-bar {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
.tempo-section-inner {
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
gap: normal;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
padding-inline: 0;
|
||||
}
|
||||
.tempo-section-navigation {
|
||||
display: grid;
|
||||
grid-area: 1 / 2 / 2 / 5;
|
||||
grid-template-columns: subgrid;
|
||||
}
|
||||
.tempo-section-navigation > ul {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
gap: normal;
|
||||
}
|
||||
.tempo-section-navigation .tempo-nav-trigger {
|
||||
padding-inline: 0.625rem;
|
||||
}
|
||||
.tempo-primary-navigation .tempo-nav-trigger,
|
||||
.tempo-section-navigation .tempo-nav-trigger {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.tempo-interest-button {
|
||||
padding-inline: 0.85rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.tempo-panel-summary {
|
||||
order: 0;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: 0.1rem;
|
||||
width: auto;
|
||||
min-width: 102px;
|
||||
border-top: 0;
|
||||
border-left: 1px solid #ffffff1a;
|
||||
padding-left: 0.75rem;
|
||||
.tempo-section-inner .tempo-interest-button {
|
||||
grid-area: 1 / 6 / 2 / -1;
|
||||
}
|
||||
}
|
||||
.tempo-header :is(a, button):focus-visible {
|
||||
@@ -223,18 +446,18 @@
|
||||
color: #fff;
|
||||
}
|
||||
.tempo-footer-heading {
|
||||
margin-bottom: 1.4rem;
|
||||
font-size: 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.15em;
|
||||
letter-spacing: 0.2em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.tempo-footer-link {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.5;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
color: #e2e8f0;
|
||||
transition:
|
||||
color 0.2s,
|
||||
@@ -252,7 +475,7 @@
|
||||
.tempo-contact-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
gap: 1rem;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
.tempo-contact-link:hover {
|
||||
@@ -260,8 +483,8 @@
|
||||
}
|
||||
.tempo-contact-icon {
|
||||
display: flex;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -271,7 +494,7 @@
|
||||
}
|
||||
.tempo-footer-social {
|
||||
display: flex;
|
||||
width: 40px;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -283,6 +506,14 @@
|
||||
border-color 0.2s,
|
||||
transform 0.2s;
|
||||
}
|
||||
.tempo-footer [aria-label='Redes sociais da Revista Tempo'] {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.tempo-footer-social > svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tempo-footer-social:hover {
|
||||
color: var(--social-color);
|
||||
border-color: var(--social-color);
|
||||
@@ -292,6 +523,13 @@
|
||||
outline: 2px solid #fb7185;
|
||||
outline-offset: 4px;
|
||||
}
|
||||
.tempo-source-page {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.tempo-about-page {
|
||||
--primary: #1f1f1f;
|
||||
--color-primary: #1f1f1f;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.tempo-header *,
|
||||
.tempo-footer *,
|
||||
|
||||
@@ -8,7 +8,7 @@ import AuthLayout from '@/layouts/auth-layout';
|
||||
import SettingsLayout from '@/layouts/settings/layout';
|
||||
import PortalNavigation from '@/layouts/portal-navigation';
|
||||
|
||||
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
|
||||
const appName = import.meta.env.VITE_APP_NAME || 'InvesteMoz';
|
||||
const pages = import.meta.glob<{ default: ComponentType }>('./pages/**/*.tsx');
|
||||
|
||||
void createInertiaApp({
|
||||
|
||||
@@ -1,11 +1,2 @@
|
||||
export default function AppLogo() {
|
||||
return (
|
||||
<img
|
||||
src="/images/logo/logo-vermelho.png"
|
||||
alt="Tempo"
|
||||
width="1787"
|
||||
height="564"
|
||||
className="h-8 w-auto max-w-full object-contain group-data-[collapsible=icon]:h-auto group-data-[collapsible=icon]:w-8"
|
||||
/>
|
||||
);
|
||||
}
|
||||
import PortalProductIdentity from '@/components/portal-product-identity';
|
||||
export default function AppLogo() { return <PortalProductIdentity />; }
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
q: 'Pesquisa',
|
||||
query: 'Pesquisa',
|
||||
sector: 'Sector',
|
||||
kind: 'Tipo de ficha',
|
||||
modality: 'Modalidade',
|
||||
category: 'Categoria',
|
||||
physical_category: 'Tipo de espaço',
|
||||
legal_regime: 'Regime',
|
||||
development_status: 'Desenvolvimento',
|
||||
availability_status: 'Disponibilidade',
|
||||
province_id: 'Província',
|
||||
district_id: 'Distrito',
|
||||
admin_post_id: 'Posto administrativo',
|
||||
locality_id: 'Localidade',
|
||||
geo_location_id: 'Localização',
|
||||
territory_id: 'Território',
|
||||
province: 'Província',
|
||||
activity: 'Actividade',
|
||||
document_type: 'Tipo de documento',
|
||||
topic: 'Tema',
|
||||
issuer: 'Entidade emissora',
|
||||
language: 'Idioma',
|
||||
legal_status: 'Situação documental',
|
||||
source_confirmation: 'Fonte',
|
||||
stage: 'Etapa',
|
||||
module: 'Área',
|
||||
association_type: 'Associação',
|
||||
association_target: 'Referência',
|
||||
association_purpose: 'Relação',
|
||||
association_state: 'Confirmação',
|
||||
chain_id: 'Cadeia de valor',
|
||||
subsector_id: 'Actividade',
|
||||
authority_id: 'Entidade',
|
||||
};
|
||||
const territoryKeys = [
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
];
|
||||
const values: Record<string, string> = {
|
||||
corridor: 'Corredores',
|
||||
cluster: 'Clusters',
|
||||
project: 'Projectos âncora',
|
||||
zee: 'ZEE',
|
||||
zfi: 'ZFI',
|
||||
industrial_park: 'Parque industrial',
|
||||
investment_project: 'Projecto de investimento',
|
||||
company_sale: 'Venda de empresa',
|
||||
company_purchase: 'Compra de empresa',
|
||||
real_estate: 'Imobiliário',
|
||||
land_right: 'Direitos fundiários',
|
||||
turismo: 'Turismo',
|
||||
agronegocio: 'Agronegócio',
|
||||
fintech: 'Fintech — especialização do Mercado Financeiro',
|
||||
'mercado-financeiro': 'Mercado Financeiro',
|
||||
legislation: 'Legislação',
|
||||
procedure: 'Procedimento oficial',
|
||||
official_form: 'Formulário oficial',
|
||||
guide: 'Guia',
|
||||
study: 'Estudo',
|
||||
unknown: 'Por confirmar',
|
||||
pt: 'Português',
|
||||
en: 'Inglês',
|
||||
confirmed: 'Confirmada',
|
||||
pending: 'Por confirmar',
|
||||
};
|
||||
/** Name each active criterion without exposing IDs or taxonomy codes. */
|
||||
export default function CatalogueFilterContext() {
|
||||
const page = usePage();
|
||||
const filters = page.props.filters as Record<string, unknown> | undefined;
|
||||
if (!filters) return null;
|
||||
const active = Object.entries(filters).filter(
|
||||
([key, value]) =>
|
||||
!['page', 'per_page', 'sort', 'view', 'publication_state'].includes(
|
||||
key,
|
||||
) &&
|
||||
value !== '' &&
|
||||
value != null &&
|
||||
value !== false &&
|
||||
(!Array.isArray(value) || value.length),
|
||||
);
|
||||
if (!active.length) return null;
|
||||
const describe = (key: string, value: unknown): string => {
|
||||
const path = page.props.territorySelection as
|
||||
| { id: string; name: string }[]
|
||||
| undefined;
|
||||
const place = path?.find((item) => item.id === value)?.name;
|
||||
if (place) return place;
|
||||
if (typeof value !== 'string') return 'seleccionado';
|
||||
return (
|
||||
values[value] ??
|
||||
(['q', 'query', 'province', 'topic', 'issuer'].includes(key)
|
||||
? value
|
||||
: 'seleccionado')
|
||||
);
|
||||
};
|
||||
const href = (remove?: string) => {
|
||||
const url = new URL(page.url, 'https://portal.invalid');
|
||||
const keys = remove
|
||||
? [
|
||||
remove,
|
||||
...territoryKeys
|
||||
.slice(territoryKeys.indexOf(remove) + 1)
|
||||
.filter(() => territoryKeys.includes(remove)),
|
||||
]
|
||||
: Object.keys(filters);
|
||||
for (const key of keys) {
|
||||
url.searchParams.delete(key);
|
||||
url.searchParams.delete(`${key}[]`);
|
||||
}
|
||||
url.searchParams.delete('page');
|
||||
return url.pathname + url.search;
|
||||
};
|
||||
return (
|
||||
<nav
|
||||
aria-label="Filtros activos"
|
||||
className="my-3 flex flex-wrap items-center gap-3"
|
||||
>
|
||||
<span className="font-semibold">Filtros activos:</span>
|
||||
{active.map(([key, value]) => (
|
||||
<Link
|
||||
key={key}
|
||||
href={href(key)}
|
||||
className="rounded border px-3 py-2 underline"
|
||||
aria-label={`Remover ${labels[key] ?? 'critério'}`}
|
||||
>
|
||||
{labels[key] ?? 'Critério seleccionado'}:{' '}
|
||||
{describe(key, value)} ×
|
||||
</Link>
|
||||
))}
|
||||
<Link href={href()} className="underline">
|
||||
Limpar filtros
|
||||
</Link>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -73,34 +73,32 @@ export default function CatalogueNavigation({
|
||||
],
|
||||
};
|
||||
return (
|
||||
<nav
|
||||
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
|
||||
aria-label="Explorar dentro do catálogo"
|
||||
>
|
||||
{Object.entries(sections).map(([title, items]) => (
|
||||
<section key={title}>
|
||||
<h2 className="mb-2 font-semibold">{title}</h2>
|
||||
<ul className="space-y-2">
|
||||
{items.map(([label, href]) => (
|
||||
<li key={label}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={withContext(href)}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
<p className="text-sm sm:col-span-2 lg:col-span-4">
|
||||
Filtros e vistas reutilizam os catálogos existentes.
|
||||
Comprar/vender continua no consumidor /negocios; não duplica
|
||||
anúncios nem unifica contagens. Selecionar um parque ou projeto
|
||||
específico usa os filtros existentes; a ficha relacionada não é
|
||||
uma oportunidade.
|
||||
</p>
|
||||
</nav>
|
||||
<details className="my-4 rounded-xl border bg-white p-4">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Catálogos relacionados
|
||||
</summary>
|
||||
<nav
|
||||
className="my-4 grid gap-3 rounded-xl border bg-white p-4 sm:grid-cols-2 lg:grid-cols-4"
|
||||
aria-label="Explorar dentro do catálogo"
|
||||
>
|
||||
{Object.entries(sections).map(([title, items]) => (
|
||||
<section key={title}>
|
||||
<h2 className="mb-2 font-semibold">{title}</h2>
|
||||
<ul className="space-y-2">
|
||||
{items.map(([label, href]) => (
|
||||
<li key={label}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={withContext(href)}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</nav>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { ContextReference } from '@/lib/investor-context';
|
||||
|
||||
export default function ContextDocuments({
|
||||
source,
|
||||
}: {
|
||||
source?: ContextReference;
|
||||
}) {
|
||||
if (!source) return null;
|
||||
return (
|
||||
<section
|
||||
aria-label="Fonte e documentos do contexto"
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h2 className="font-semibold">Fonte e documentos do contexto</h2>
|
||||
<p>
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>{' '}
|
||||
· versão da oportunidade {source.version ?? 'não indicada'} ·{' '}
|
||||
{source.visibility === 'private'
|
||||
? 'Preparação privada — não publicada'
|
||||
: 'Referência pública'}
|
||||
</p>
|
||||
{(source.documents ?? []).map((doc) => (
|
||||
<article
|
||||
key={doc.support_id}
|
||||
className="space-y-1 rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
{doc.title} · {doc.edition ?? 'Edição não indicada'} ·
|
||||
versão documental {doc.document_version} · metadados v
|
||||
{doc.metadata_version}
|
||||
</p>
|
||||
<p className="break-all">SHA256: {doc.sha256}</p>
|
||||
{doc.section && <p>Referência utilizada: {doc.section}</p>}
|
||||
<p>{doc.source_reference}</p>
|
||||
<a className="underline" href={doc.download_url}>
|
||||
Consultar original autorizado —{' '}
|
||||
{doc.edition ?? doc.title}
|
||||
</a>
|
||||
</article>
|
||||
))}
|
||||
{!source.documents?.length && (
|
||||
<p>Sem suporte da biblioteca associado nesta versão.</p>
|
||||
)}
|
||||
<p>
|
||||
Referência guardada nesta versão do dossier. A consulta do
|
||||
original continua sujeita às permissões actuais; esta ligação
|
||||
não publica nem concede acesso adicional.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -50,6 +50,14 @@ export default function CountrySelect({
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Pesquisar nome ou código do país"
|
||||
/>
|
||||
{search.trim() && (
|
||||
<p role="status" aria-live="polite">
|
||||
Países:{' '}
|
||||
{matches.length
|
||||
? `${matches.length} opções disponíveis`
|
||||
: 'Nenhuma opção encontrada'}
|
||||
</p>
|
||||
)}
|
||||
<select
|
||||
disabled={disabled}
|
||||
id={id ?? generatedId}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
// Imported from investidor/resources/js/modules/news/sections/about/AboutStory.tsx; original content preserved.
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Trans } from './source-text';
|
||||
|
||||
const aboutimgstory = '/assets/imgs/aboutimgstory.png';
|
||||
|
||||
interface CounterProps {
|
||||
end: number;
|
||||
suffix?: string;
|
||||
}
|
||||
|
||||
const Counter = ({ end, suffix = '' }: CounterProps) => {
|
||||
const [count, setCount] = useState<number>(0);
|
||||
const countRef = useRef<number>(0);
|
||||
|
||||
useEffect(() => {
|
||||
const duration = 2000;
|
||||
const increment = end / (duration / 16);
|
||||
|
||||
const timer = setInterval(() => {
|
||||
countRef.current += increment;
|
||||
if (countRef.current >= end) {
|
||||
clearInterval(timer);
|
||||
countRef.current = end;
|
||||
}
|
||||
setCount(Math.floor(countRef.current));
|
||||
}, 16);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [end]);
|
||||
|
||||
return (
|
||||
<span>
|
||||
{count}
|
||||
{suffix}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export const AboutStory = () => {
|
||||
const [isVisible, setIsVisible] = useState<boolean>(false);
|
||||
const [counted, setCounted] = useState<boolean>(false);
|
||||
const sectionRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsVisible(true);
|
||||
setCounted(true);
|
||||
}
|
||||
},
|
||||
{ threshold: 0.2 },
|
||||
);
|
||||
|
||||
if (sectionRef.current) {
|
||||
observer.observe(sectionRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (sectionRef.current) {
|
||||
observer.unobserve(sectionRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section
|
||||
ref={sectionRef}
|
||||
className={`bg-primary px-6 transition-all duration-1000 md:px-12 lg:px-20 ${
|
||||
isVisible
|
||||
? 'translate-y-0 opacity-100'
|
||||
: 'translate-y-10 opacity-0'
|
||||
}`}
|
||||
>
|
||||
<div className="mx-auto max-w-6xl">
|
||||
<div className="grid grid-cols-1 items-stretch gap-x-12 gap-y-2 lg:grid-cols-2">
|
||||
{/* Imagem */}
|
||||
<div
|
||||
className={`relative transition-all delay-200 duration-1000 ${
|
||||
isVisible
|
||||
? 'translate-x-0 opacity-100'
|
||||
: '-translate-x-12 opacity-0'
|
||||
}`}
|
||||
>
|
||||
<div className="group relative h-64 overflow-hidden rounded-2xl md:h-72">
|
||||
<img
|
||||
src={aboutimgstory}
|
||||
alt="Equipe Tempo"
|
||||
className="h-full w-full object-cover transition-transform duration-1000 group-hover:scale-110"
|
||||
onError={(e) => {
|
||||
e.currentTarget.src =
|
||||
'/assets/images/info.png';
|
||||
}}
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-0 bg-black/12" />
|
||||
|
||||
<div className="absolute right-4 bottom-4 left-4">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:gap-8">
|
||||
<div className="rounded-xl bg-black/20 p-3 backdrop-blur-sm transition-all sm:bg-transparent sm:p-0 sm:backdrop-blur-none">
|
||||
<div
|
||||
className="text-4xl font-black tracking-tighter text-white md:text-6xl"
|
||||
style={{
|
||||
textShadow:
|
||||
'0 4px 12px rgba(0,0,0,0.95), 0 2px 6px rgba(0,0,0,0.9)',
|
||||
}}
|
||||
>
|
||||
{counted ? (
|
||||
<Counter end={50} suffix="+" />
|
||||
) : (
|
||||
'50+'
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="mt-1 text-xs font-bold tracking-widest text-white uppercase opacity-90 md:text-lg"
|
||||
style={{
|
||||
textShadow:
|
||||
'0 3px 10px rgba(0,0,0,0.9), 0 1px 4px black',
|
||||
}}
|
||||
>
|
||||
<Trans>Anos de Experiência</Trans>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-xl bg-black/20 p-3 backdrop-blur-sm transition-all sm:bg-transparent sm:p-0 sm:backdrop-blur-none">
|
||||
<div
|
||||
className="text-4xl font-black tracking-tighter text-[#ED1C24] md:text-6xl"
|
||||
style={{
|
||||
textShadow:
|
||||
'0 4px 12px rgba(0,0,0,0.95), 0 2px 6px rgba(0,0,0,0.9)',
|
||||
}}
|
||||
>
|
||||
{counted ? (
|
||||
<Counter end={200} suffix="+" />
|
||||
) : (
|
||||
'200+'
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="mt-1 text-xs font-bold tracking-widest text-white uppercase opacity-90 md:text-lg"
|
||||
style={{
|
||||
textShadow:
|
||||
'0 3px 10px rgba(0,0,0,0.9), 0 1px 4px black',
|
||||
}}
|
||||
>
|
||||
<Trans>Projetos Realizados</Trans>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`absolute -right-6 -bottom-6 -z-10 h-32 w-32 rounded-2xl border-2 border-red-600/30 transition-all delay-500 duration-1000 ${
|
||||
isVisible
|
||||
? 'scale-100 opacity-100'
|
||||
: 'scale-0 opacity-0'
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Texto */}
|
||||
<div
|
||||
className={`flex flex-col justify-center space-y-4 transition-all delay-500 duration-1000 ${
|
||||
isVisible
|
||||
? 'translate-x-0 opacity-100'
|
||||
: '-translate-x-12 opacity-0'
|
||||
}`}
|
||||
>
|
||||
<p className="text-base leading-relaxed font-light text-white md:text-lg">
|
||||
<Trans>
|
||||
Somos detentores de um vasto património cultural
|
||||
e tecnológico, resultado da integração e da
|
||||
cooperação entre diversas empresas com ampla
|
||||
experiência nas áreas de Tecnologias de
|
||||
Informação e Comunicação, produção e
|
||||
disseminação de conteúdos informativos, educação
|
||||
vocacional e gestão empresarial.
|
||||
</Trans>
|
||||
</p>
|
||||
<p className="text-base leading-relaxed font-light text-white md:text-lg">
|
||||
<Trans>
|
||||
Dispomos de uma equipa qualificada, com sólida
|
||||
experiência na concepção e implementação de
|
||||
soluções de TI, de cibersegurança, de
|
||||
desenvolvimento institucional, de reengenharia
|
||||
de processos organizacionais e de formação
|
||||
profissional.
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default AboutStory;
|
||||
@@ -0,0 +1,156 @@
|
||||
// Imported from investidor; return destinations are restricted to this platform.
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { router } from '@inertiajs/react';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
import { Trans } from './source-text'; // Import Trans component
|
||||
|
||||
interface BackButtonProps {
|
||||
to?: string;
|
||||
label?: React.ReactNode; // Change type to React.ReactNode to accept <Trans> component
|
||||
className?: string;
|
||||
theme?: 'light' | 'dark';
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
const RETURN_URL_KEY = 'news:return-url';
|
||||
|
||||
function normalizeInternalUrl(value: string | null): string | null {
|
||||
if (!value || typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = value.startsWith('http')
|
||||
? new URL(value)
|
||||
: new URL(value, window.location.origin);
|
||||
|
||||
if (url.origin !== window.location.origin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = `${url.pathname}${url.search}${url.hash}`;
|
||||
const current = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||
|
||||
return normalized !== current ? normalized : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getStoredReturnUrl(): string | null {
|
||||
try {
|
||||
return normalizeInternalUrl(sessionStorage.getItem(RETURN_URL_KEY));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getReturnUrlFromPage(): string | null {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const fromParam = normalizeInternalUrl(params.get('from'));
|
||||
|
||||
if (fromParam) {
|
||||
return fromParam;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getInternalReferrerUrl(): string | null {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeInternalUrl(document.referrer);
|
||||
}
|
||||
|
||||
export const BackButton: React.FC<BackButtonProps> = ({
|
||||
to,
|
||||
label = <Trans>Voltar</Trans>, // Use Trans component for default label
|
||||
className = '',
|
||||
theme = 'light',
|
||||
onClick,
|
||||
}) => {
|
||||
const [showFloatingButton, setShowFloatingButton] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
setShowFloatingButton(window.scrollY > 220);
|
||||
};
|
||||
|
||||
handleScroll();
|
||||
window.addEventListener('scroll', handleScroll, { passive: true });
|
||||
|
||||
return () => window.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
const themeClasses =
|
||||
theme === 'dark'
|
||||
? 'border-white/20 bg-white/10 text-white shadow-lg backdrop-blur-md hover:bg-white/20'
|
||||
: 'border-red-100 bg-white text-[#ED1C24] shadow-sm hover:border-red-200 hover:bg-red-50';
|
||||
|
||||
const baseClasses =
|
||||
'inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-semibold transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-[#ED1C24]/25 active:scale-[0.98]';
|
||||
|
||||
const floatingClasses = [
|
||||
'fixed bottom-5 left-4 z-50 max-w-[calc(100vw-2rem)] sm:bottom-6 sm:left-6',
|
||||
'border-red-100 bg-white text-[#ED1C24] shadow-xl ring-1 ring-black/5 hover:border-red-200 hover:bg-red-50',
|
||||
showFloatingButton
|
||||
? 'pointer-events-auto translate-y-0 opacity-100'
|
||||
: 'pointer-events-none translate-y-3 opacity-0',
|
||||
].join(' ');
|
||||
|
||||
const renderContent = () => (
|
||||
<>
|
||||
<ArrowLeft size={16} aria-hidden="true" />
|
||||
<span className="truncate">{label}</span>
|
||||
</>
|
||||
);
|
||||
|
||||
const handleClick = () => {
|
||||
if (onClick) {
|
||||
onClick();
|
||||
return;
|
||||
}
|
||||
|
||||
const explicitReturnUrl = getReturnUrlFromPage();
|
||||
const storedReturnUrl = getStoredReturnUrl();
|
||||
|
||||
if (explicitReturnUrl) {
|
||||
router.visit(explicitReturnUrl);
|
||||
} else if (storedReturnUrl) {
|
||||
router.visit(storedReturnUrl);
|
||||
} else {
|
||||
router.visit(getInternalReferrerUrl() || to || '/');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
className={`${baseClasses} ${themeClasses} ${className}`}
|
||||
aria-label={typeof label === 'string' ? label : undefined} // aria-label should be a string
|
||||
>
|
||||
{renderContent()}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
className={`${baseClasses} ${floatingClasses}`}
|
||||
aria-label={typeof label === 'string' ? label : undefined} // aria-label should be a string
|
||||
aria-hidden={!showFloatingButton}
|
||||
tabIndex={showFloatingButton ? undefined : -1}
|
||||
>
|
||||
{renderContent()}
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default BackButton;
|
||||
@@ -0,0 +1,218 @@
|
||||
// Imported from investidor/resources/js/modules/news/sections/about/CompanyValues.tsx; original content preserved.
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Users, Lightbulb, Globe, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { Trans } from './source-text';
|
||||
|
||||
const img01 = '/assets/imgs/img01.jpg';
|
||||
const img02 = '/assets/imgs/img02.jpg';
|
||||
const img03 = '/assets/imgs/img03.jpg';
|
||||
const img04 = '/assets/imgs/img04.jpg';
|
||||
|
||||
interface CompanyValue {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string;
|
||||
image?: string;
|
||||
icon?: React.ReactNode;
|
||||
color?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export const CompanyValues = () => {
|
||||
const [hoveredId, setHoveredId] = useState<number | null>(null);
|
||||
const [isInView, setIsInView] = useState<boolean>(false);
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
if (sectionRef.current) {
|
||||
const rect = sectionRef.current.getBoundingClientRect();
|
||||
setIsInView(
|
||||
rect.top < window.innerHeight * 0.8 && rect.bottom > 100,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('scroll', handleScroll);
|
||||
handleScroll();
|
||||
|
||||
return () => window.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
const values: CompanyValue[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Diversidade & Inclusão',
|
||||
description:
|
||||
'Representando todas as vozes e realidades de Moçambique',
|
||||
image: img01,
|
||||
icon: <Users className="h-6 w-6" />,
|
||||
color: 'from-red-500 to-orange-500',
|
||||
label: 'Valor Central',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Inovação',
|
||||
description:
|
||||
'Soluções tecnológicas e sustentáveis que impulsionam o desenvolvimento',
|
||||
image: img02,
|
||||
icon: <Lightbulb className="h-6 w-6" />,
|
||||
color: 'from-red-600 to-red-700',
|
||||
label: 'Essencial',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Excelência',
|
||||
description:
|
||||
'Acreditamos que cada história merece ser contada com propósito. Combinamos visão criativa e conhecimento estratégico para dar vida às ideias.',
|
||||
image: img03,
|
||||
label: 'Somos mais que comunicação, somos transformação',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Impacto Positivo',
|
||||
description:
|
||||
'Criamos marcas que inspiram, conteúdo que conecta e experiências memoráveis. Transformamos visão em realidade com estratégia, criatividade e tecnologia.',
|
||||
image: img04,
|
||||
icon: <Globe className="h-6 w-6" />,
|
||||
color: 'from-red-600 to-red-700',
|
||||
label: 'Propósito',
|
||||
},
|
||||
];
|
||||
|
||||
const toggleExpand = (id: number) => {
|
||||
setExpandedId(expandedId === id ? null : id);
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
ref={sectionRef}
|
||||
className="bg-primary relative overflow-hidden py-4"
|
||||
>
|
||||
<div className="mx-auto mb-4 max-w-7xl space-y-2 px-6 text-center">
|
||||
<div
|
||||
className={`transition-all duration-1000 ${isInView ? 'translate-y-0 opacity-100' : 'translate-y-8 opacity-0'}`}
|
||||
>
|
||||
<h2 className="text-3xl font-semibold tracking-wide text-white md:text-3xl">
|
||||
<span
|
||||
className="font-bold italic not-italic"
|
||||
style={{ color: '#FFFFFF' }}
|
||||
>
|
||||
<Trans>Valores</Trans>
|
||||
</span>
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto max-w-7xl px-6">
|
||||
<div className="grid grid-cols-1 items-stretch gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
{values.map((value, i) => {
|
||||
const isExpanded = expandedId === value.id;
|
||||
const hasLongText = value.id === 3 || value.id === 4;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={value.id}
|
||||
onMouseEnter={() => setHoveredId(value.id)}
|
||||
onMouseLeave={() => setHoveredId(null)}
|
||||
className={`group relative transition-all duration-500 ${isInView ? 'translate-y-0 opacity-100' : 'translate-y-10 opacity-0'}`}
|
||||
style={{ transitionDelay: `${i * 100}ms` }}
|
||||
>
|
||||
<div
|
||||
className={`relative flex h-full flex-col overflow-hidden rounded-2xl border bg-white/5 backdrop-blur-xl transition-all duration-500 ${
|
||||
hoveredId === value.id
|
||||
? 'translate-y-[-6px] border-red-500/40 shadow-2xl shadow-red-600/20'
|
||||
: 'border-white/10'
|
||||
}`}
|
||||
>
|
||||
<div className="relative flex h-44 flex-1 flex-col overflow-hidden">
|
||||
<img
|
||||
src={value.image}
|
||||
alt={value.title}
|
||||
className={`h-full w-full object-cover transition-transform duration-700 ${
|
||||
hoveredId === value.id
|
||||
? 'scale-110'
|
||||
: 'scale-100'
|
||||
}`}
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/40" />
|
||||
|
||||
{value.icon && value.color && (
|
||||
<div
|
||||
className={`absolute top-4 left-4 h-11 w-11 rounded-xl bg-gradient-to-br ${value.color} flex items-center justify-center text-white shadow-lg transition-transform duration-500 ${
|
||||
hoveredId === value.id
|
||||
? 'scale-110 rotate-12'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
{value.icon}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{value.label && (
|
||||
<div className="absolute top-4 right-5 px-3 py-1 text-lg font-bold text-white drop-shadow-md md:text-xl">
|
||||
<Trans>{value.label}</Trans>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col bg-gradient-to-t from-black/60 via-black/30 to-transparent p-5">
|
||||
<h3 className="mb-2 text-2xl font-bold text-white drop-shadow-md md:text-3xl">
|
||||
<Trans>{value.title}</Trans>
|
||||
</h3>
|
||||
<p
|
||||
className={`text-sm leading-relaxed text-gray-100 drop-shadow-md md:text-base ${
|
||||
!isExpanded && hasLongText
|
||||
? 'line-clamp-2'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<Trans>{value.description}</Trans>
|
||||
</p>
|
||||
{hasLongText && (
|
||||
<button
|
||||
onClick={() =>
|
||||
toggleExpand(value.id)
|
||||
}
|
||||
className="mt-1 flex items-center gap-1 text-sm font-medium text-red-400 transition-colors hover:text-red-300"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<Trans>Ver menos</Trans>{' '}
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Trans>Ver mais</Trans>{' '}
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hoveredId === value.id && (
|
||||
<div className="pointer-events-none absolute inset-0 overflow-hidden rounded-2xl">
|
||||
<div className="animate-shimmer absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/10 to-transparent" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(100%); }
|
||||
}
|
||||
.animate-shimmer { animation: shimmer 1.5s ease-in-out infinite; }
|
||||
`}</style>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default CompanyValues;
|
||||
@@ -0,0 +1,124 @@
|
||||
// Imported from investidor/resources/js/modules/news/sections/about/MissionVision.tsx; original content preserved.
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Target, Eye } from 'lucide-react';
|
||||
import { Trans } from './source-text';
|
||||
|
||||
interface MissionVisionItem {
|
||||
id: number;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ReactNode;
|
||||
gradient: string;
|
||||
}
|
||||
|
||||
export const MissionVision = () => {
|
||||
const [hoveredId, setHoveredId] = useState<number | null>(null);
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
const [isInView, setIsInView] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => setIsInView(entry.isIntersecting),
|
||||
{ threshold: 0.1, rootMargin: '0px 0px -80px 0px' },
|
||||
);
|
||||
|
||||
if (sectionRef.current) {
|
||||
observer.observe(sectionRef.current);
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const items: MissionVisionItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Missão',
|
||||
description:
|
||||
'Fornecer soluções integradas e inovadoras em comércio, comunicação, tecnologia e informação, com excelência na intermediação comercial, na informação pública e em plataformas digitais promovendo crescimento sustentável e impacto positivo no mercado moçambicano.',
|
||||
icon: <Target className="h-7 w-7 sm:h-8 sm:w-8" />,
|
||||
gradient: 'from-red-500 to-red-600',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Visão',
|
||||
description:
|
||||
'Ser a referência líder em Moçambique, impulsionando o progresso do país através de soluções inovadoras e sustentáveis, para um futuro mais conectado, próspero e dinâmico.',
|
||||
icon: <Eye className="h-7 w-7 sm:h-8 sm:w-8" />,
|
||||
gradient: 'from-red-600 to-red-800',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<section ref={sectionRef} className="relative overflow-hidden py-6">
|
||||
<div className="relative mx-auto max-w-7xl px-5 sm:px-6 lg:px-8">
|
||||
<div className="grid grid-cols-1 gap-4 sm:gap-5 lg:grid-cols-2 lg:gap-6">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
onMouseEnter={() => setHoveredId(item.id)}
|
||||
onMouseLeave={() => setHoveredId(null)}
|
||||
className={`transition-all duration-1200 ease-in-out ${isInView ? 'translate-y-0 scale-100 opacity-100' : 'translate-y-6 scale-95 opacity-0'} `}
|
||||
style={{ transitionDelay: `${index * 200}ms` }}
|
||||
>
|
||||
<div
|
||||
className={`relative h-full rounded-2xl border bg-white/5 backdrop-blur-lg transition-all duration-700 ease-in-out sm:rounded-3xl ${
|
||||
hoveredId === item.id
|
||||
? '-translate-y-2 border-red-500/50 shadow-xl shadow-red-600/20 sm:-translate-y-3'
|
||||
: 'border-white/10 shadow-sm'
|
||||
} `}
|
||||
>
|
||||
<div className="p-5 sm:p-6 lg:p-8">
|
||||
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-6">
|
||||
<div
|
||||
className={`h-14 w-14 flex-shrink-0 rounded-xl bg-gradient-to-br sm:h-16 sm:w-16 sm:rounded-2xl ${item.gradient} flex items-center justify-center p-3 text-white shadow-lg transition-all duration-700 ease-in-out sm:p-3.5 ${
|
||||
hoveredId === item.id
|
||||
? 'scale-125 rotate-12 animate-pulse shadow-2xl'
|
||||
: 'animate-float scale-100 rotate-0'
|
||||
} `}
|
||||
>
|
||||
{item.icon}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 min-w-0 flex-1 text-center sm:mt-0 sm:text-left">
|
||||
<h3
|
||||
className={`mb-2 text-2xl font-light tracking-tight transition-colors duration-500 sm:mb-3 sm:text-3xl lg:text-4xl ${hoveredId === item.id ? 'text-red-400' : 'text-red-500'} `}
|
||||
>
|
||||
<Trans>{item.title}</Trans>
|
||||
</h3>
|
||||
<p className="text-sm leading-relaxed font-light text-[#ffffff] sm:text-base lg:text-lg">
|
||||
<Trans>
|
||||
{item.description}
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hoveredId === item.id && (
|
||||
<div className="pointer-events-none absolute inset-0 overflow-hidden rounded-2xl sm:rounded-3xl">
|
||||
<div className="animate-shimmer absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/10 to-transparent" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
@keyframes shimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(200%); }
|
||||
}
|
||||
.animate-shimmer { animation: shimmer 2.5s ease-in-out infinite; }
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-6px); }
|
||||
}
|
||||
.animate-float { animation: float 3s ease-in-out infinite; }
|
||||
`}</style>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default MissionVision;
|
||||
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
|
||||
const InstituitionalMaps = () => {
|
||||
// Google Maps EMBED – Prédio Revista Tempo (Maputo)
|
||||
const mapUrl =
|
||||
'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3586.601889886872!2d32.5840525!3d-25.9697003!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1ee69b0710fc41f7%3A0x4fa9cf4e964b7e50!2sPr%C3%A9dio%20Revista%20Tempo!5e0!3m2!1spt-PT!2smz!4v1733750000000';
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
{/* MAPA */}
|
||||
<iframe
|
||||
src={mapUrl}
|
||||
className="absolute inset-0 h-full w-full rounded-xl"
|
||||
style={{ border: 0 }}
|
||||
allowFullScreen
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer-when-downgrade"
|
||||
title="Localização - Prédio Revista Tempo, Maputo"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InstituitionalMaps;
|
||||
@@ -0,0 +1,36 @@
|
||||
// Empty-slot presentation copied from investidor's AdvertisementSlot.
|
||||
// Preserve the original reserved spaces without importing its advertising backend or tracking.
|
||||
export function AdvertisementSlot({
|
||||
position,
|
||||
className = '',
|
||||
}: {
|
||||
page: string;
|
||||
position: string;
|
||||
slot?: string;
|
||||
limit?: number;
|
||||
fallbackToUnslotted?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const placement = position === 'top' ? 'article.top' : 'article.bottom';
|
||||
return (
|
||||
<aside
|
||||
aria-label={`Espaço de publicidade ${placement}`}
|
||||
className={`mx-auto flex w-full items-center justify-center overflow-hidden border border-dashed border-slate-300 bg-slate-50/80 text-center ${className}`}
|
||||
style={{ aspectRatio: '970 / 250', maxWidth: '970px' }}
|
||||
data-ad-placement={placement}
|
||||
data-ad-state="empty"
|
||||
>
|
||||
<div className="px-4 py-6">
|
||||
<p className="text-[10px] font-semibold tracking-[0.2em] text-slate-400 uppercase">
|
||||
Publicidade
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
Espaço disponível para publicidade
|
||||
</p>
|
||||
<p className="mt-1 text-[10px] text-slate-400">
|
||||
970 × 250px · {placement}
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
// Bridge the original Trans calls to this platform's existing language context.
|
||||
export function Trans({ children }: { children: string }) {
|
||||
const { t } = useTempoUi();
|
||||
return <span>{t(children)}</span>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import SearchState from '@/components/search-state';
|
||||
import { useEffect, useState } from 'react';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import InteractiveInvestmentMap, {
|
||||
@@ -18,11 +19,14 @@ export default function InvestmentMapPanel({
|
||||
{ id: number; title: string; url: string }[]
|
||||
>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const params = new URLSearchParams(JSON.parse(key));
|
||||
setPoints(null);
|
||||
setError('');
|
||||
setMissing([]);
|
||||
setAreas([]);
|
||||
fetch(`/api/v1/investment/map?${params}`, {
|
||||
signal: controller.signal,
|
||||
@@ -43,14 +47,22 @@ export default function InvestmentMapPanel({
|
||||
: '',
|
||||
);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!controller.signal.aborted) setError(e.message);
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setError('Não foi possível concluir a pesquisa.');
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [key]);
|
||||
}, [key, retry]);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<SearchState
|
||||
scope="Registos consultados pelo mapa"
|
||||
countLabel="registos, incluindo os que não têm coordenadas"
|
||||
loading={points === null && !error}
|
||||
error={error}
|
||||
total={(points?.length ?? 0) + missing.length}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<InteractiveInvestmentMap points={points} areas={areas} />
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user