Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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) {
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.');
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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.' }
|
||||
|
||||
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,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,7 @@ 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">{matches.length ? `${matches.length} resultados encontrados` : "Não foram encontrados resultados para esta pesquisa"}</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,12 @@ 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);
|
||||
setPoints(null); setError(''); setMissing([]);
|
||||
setAreas([]);
|
||||
fetch(`/api/v1/investment/map?${params}`, {
|
||||
signal: controller.signal,
|
||||
@@ -43,14 +45,14 @@ 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 loading={points === null && !error} error={error} total={(points?.length ?? 0) + missing.length} retry={() => setRetry(value => value + 1)} />
|
||||
<InteractiveInvestmentMap points={points} areas={areas} />
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import SearchState from '@/components/search-state';
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
@@ -110,12 +111,10 @@ export function ProvinceSelect({
|
||||
.then((data) => {
|
||||
if (!controller.signal.aborted) setOptions(data.data);
|
||||
})
|
||||
.catch((cause) => {
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
'Não foi possível concluir a pesquisa.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -131,6 +130,7 @@ export function ProvinceSelect({
|
||||
|
||||
return (
|
||||
<>
|
||||
<SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />
|
||||
<input
|
||||
className={className}
|
||||
aria-label={`Pesquisar ${label}`}
|
||||
@@ -162,17 +162,6 @@ export function ProvinceSelect({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{error && (
|
||||
<span role="alert" className="block text-sm">
|
||||
{error}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRetry((current) => current + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{geometryFeedback && <p role="status">{geometryFeedback}</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
@@ -309,10 +298,10 @@ export function TerritoryLevel({
|
||||
if (controller.signal.aborted) return;
|
||||
setOptions(data.data);
|
||||
setMore(Boolean(data.next_page_url));
|
||||
} catch (e) {
|
||||
} catch {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
e instanceof Error ? e.message : 'Erro de ligação.',
|
||||
'Não foi possível concluir a pesquisa.',
|
||||
);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
@@ -325,6 +314,7 @@ export function TerritoryLevel({
|
||||
}, [index, parent, page, enabled, endpoint, retry, search]);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{enabled && <SearchState loading={loading} error={error} total={options.length} retry={() => setRetry(value => value + 1)} />}
|
||||
<label htmlFor={id} className="font-medium">
|
||||
{labels[index]}
|
||||
</label>
|
||||
@@ -370,22 +360,11 @@ export function TerritoryLevel({
|
||||
))}
|
||||
</select>
|
||||
{loading && <p role="status">A carregar…</p>}
|
||||
{error && (
|
||||
<div role="alert">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={() => setRetry(retry + 1)}>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{fieldError && (
|
||||
<p id={`${id}-error`} role="alert">
|
||||
{fieldError}
|
||||
</p>
|
||||
)}
|
||||
{enabled && !loading && !error && options.length === 0 && (
|
||||
<p className="text-sm">Sem opções para esta pesquisa.</p>
|
||||
)}
|
||||
<div className="flex gap-3 text-sm">
|
||||
{page > 1 && (
|
||||
<button type="button" onClick={() => setPage(page - 1)}>
|
||||
|
||||
@@ -72,7 +72,7 @@ const labels: Record<string, string> = {
|
||||
location_mode: 'Uma ou várias localizações',
|
||||
geographic_scope: 'Âmbito geográfico',
|
||||
multi_district_rationale: 'Justificação territorial',
|
||||
locations: 'Localizações guardadas',
|
||||
locations: 'Onde se localiza — locais documentados',
|
||||
executive_summary: 'Resumo executivo',
|
||||
demand_statement: 'Necessidade e proposta',
|
||||
visibility: 'Visibilidade após publicação',
|
||||
@@ -632,6 +632,16 @@ export default function OpportunityCanonicalFields({
|
||||
disabled?: boolean;
|
||||
errors?: Record<string, string>;
|
||||
}) {
|
||||
const initiative = (value.initiative ?? {}) as Data;
|
||||
const isInitiative = category === 'investment_project' && ['program', 'portfolio'].includes(valueText(initiative.kind ?? ''));
|
||||
const applicability = (initiative.applicability ?? {}) as Record<string, string>;
|
||||
const groups: Record<string, { label: string; fields: string[] }> = {
|
||||
physical_site: { label: 'Implantação física, obra e licenças próprias', fields: ['location_mode', 'licenses', 'environmental_social'] },
|
||||
individual_business: { label: 'Empresa ou operação individual', fields: ['promoter_id', 'promoter_type', 'opportunity_type', 'investor_profiles', 'products', 'assets', 'inputs', 'markets', 'competitive_advantage', 'employment', 'impact_indicators', 'enterprise_size'] },
|
||||
unit_investment: { label: 'Investimento e financiamento por projecto', fields: ['total_investment', 'currency', 'investment_breakdown', 'secured_financing', 'funding_sought', 'financial_indicators'] },
|
||||
};
|
||||
const ignoredFields = isInitiative ? ['promoter_type', ...Object.entries(groups).flatMap(([key, group]) => applicability[key] === 'not_applicable' ? group.fields : [])] : [];
|
||||
const setInitiative = (key: string, next: unknown) => onChange({ ...value, opportunity_category: category, initiative: { ...initiative, [key]: next } });
|
||||
const set = (key: string, v: unknown) =>
|
||||
onChange({
|
||||
...value,
|
||||
@@ -642,7 +652,7 @@ export default function OpportunityCanonicalFields({
|
||||
? { economic_activity_id: null }
|
||||
: {}),
|
||||
opportunity_category: category,
|
||||
promoter_id: organization ?? actorId,
|
||||
...(isInitiative ? {} : { promoter_id: organization ?? actorId }),
|
||||
});
|
||||
const common = [
|
||||
'official_title',
|
||||
@@ -820,7 +830,49 @@ export default function OpportunityCanonicalFields({
|
||||
propostas não representam compromisso nem decisão externa.
|
||||
</p>
|
||||
)}
|
||||
{Array.from(new Set([...common, ...specialized])).map((key) => {
|
||||
{category === 'investment_project' && (
|
||||
<section aria-label="Enquadramento e aplicabilidade" className="space-y-4 rounded border p-4">
|
||||
<label className="block">Natureza da ficha
|
||||
<select className={control} aria-label="Natureza da ficha" value={valueText(initiative.kind ?? '')} onChange={(e) => {
|
||||
if (!e.target.value) { const next = { ...value }; delete next.initiative; onChange(next); }
|
||||
else setInitiative('kind', e.target.value);
|
||||
}}>
|
||||
<option value="">Projecto ou componente concreta</option>
|
||||
<option value="program">Programa ou iniciativa agregadora</option>
|
||||
<option value="portfolio">Carteira de oportunidades/PME</option>
|
||||
</select>
|
||||
</label>
|
||||
{isInitiative && <>
|
||||
<p>O responsável do programa/carteira não substitui os promotores das componentes. Abrangência não comprova implantação. A classificação não confirma financiamento, licenças ou disponibilidade.</p>
|
||||
<label className="block">Responsável do programa ou carteira
|
||||
<input className={control} aria-label="Responsável do programa ou carteira" value={valueText(initiative.responsible_name ?? '')} onChange={(e) => setInitiative('responsible_name', e.target.value || null)} />
|
||||
</label>
|
||||
<FieldErrors path="canonical.initiative.responsible_name" errors={errors} />
|
||||
<label className="block">Abrangência territorial documentada
|
||||
<textarea className={control} aria-label="Abrangência territorial documentada" value={valueText(initiative.coverage_statement ?? '')} onChange={(e) => setInitiative('coverage_statement', e.target.value || null)} />
|
||||
</label>
|
||||
<FieldErrors path="canonical.initiative.coverage_statement" errors={errors} />
|
||||
<label className="block">Orçamento agregado — fonte e situação, sem confirmação automática
|
||||
<textarea className={control} aria-label="Orçamento agregado" value={valueText(initiative.aggregate_budget_statement ?? '')} onChange={(e) => setInitiative('aggregate_budget_statement', e.target.value || null)} />
|
||||
</label>
|
||||
{Object.entries(groups).map(([key, group]) => <div key={key}>
|
||||
<label className="block">{group.label}
|
||||
<select className={control} aria-label={group.label} value={applicability[key] ?? 'missing'} onChange={(e) => setInitiative('applicability', { ...applicability, [key]: e.target.value })}>
|
||||
<option value="missing">Informação em falta — aplicabilidade por determinar</option>
|
||||
<option value="not_applicable">Não aplicável a esta ficha agregadora</option>
|
||||
<option value="applicable">Aplicável — preencher os dados próprios</option>
|
||||
</select>
|
||||
</label>
|
||||
<FieldErrors path={'canonical.initiative.applicability.' + key} errors={errors} />
|
||||
{applicability[key] === 'not_applicable' && <details><summary>Não aplicável — consultar dados anteriores preservados</summary><pre className="overflow-auto whitespace-pre-wrap">{JSON.stringify(Object.fromEntries(group.fields.filter((field) => field in value).map((field) => [field, value[field]])), null, 2)}</pre><p>Sem eliminação dos valores. As componentes concretas mantêm os seus requisitos.</p></details>}
|
||||
</div>)}
|
||||
<p>Os recursos territoriais abaixo documentam a abrangência quando a implantação não é aplicável. A informação em falta continua pendente; não é convertida em “não aplicável”.</p>
|
||||
</>}
|
||||
</section>
|
||||
)}
|
||||
{[...new Set([...common, ...specialized])].map((key) => {
|
||||
if (ignoredFields.includes(key)) return null;
|
||||
|
||||
if (key === 'relations' && options.classification) {
|
||||
const rows = (value.relations ??
|
||||
[]) as ClassificationRelation[];
|
||||
@@ -936,14 +988,40 @@ export default function OpportunityCanonicalFields({
|
||||
if (a.historical_only) return false;
|
||||
if (a.level) {
|
||||
return key === 'subsector_id'
|
||||
? a.level === 2 && a.code === '01' && a.sector_id === Number(value.sector_id)
|
||||
: a.level === 5 && a.code === '01120' && !!a.path?.some((p) => p.id === value.subsector_id);
|
||||
? a.level === 2 &&
|
||||
a.code === '01' &&
|
||||
a.sector_id ===
|
||||
Number(
|
||||
value.sector_id,
|
||||
)
|
||||
: a.level === 5 &&
|
||||
a.code === '01120' &&
|
||||
!!a.path?.some(
|
||||
(p) =>
|
||||
p.id ===
|
||||
value.subsector_id,
|
||||
);
|
||||
}
|
||||
return key === 'subsector_id'
|
||||
? options.activities.some((root) => root.sector_id === Number(value.sector_id) && a.parent_id === root.id)
|
||||
: a.parent_id === value.subsector_id;
|
||||
? options.activities.some(
|
||||
(root) =>
|
||||
root.sector_id ===
|
||||
Number(
|
||||
value.sector_id,
|
||||
) &&
|
||||
a.parent_id === root.id,
|
||||
)
|
||||
: a.parent_id ===
|
||||
value.subsector_id;
|
||||
})
|
||||
.map((a) => ({ id: a.id, label: (a.display_label ?? a.label_pt_mz) + (a.historical_only ? ' — histórico preservado' : '') }));
|
||||
.map((a) => ({
|
||||
id: a.id,
|
||||
label:
|
||||
(a.display_label ?? a.label_pt_mz) +
|
||||
(a.historical_only
|
||||
? ' — histórico preservado'
|
||||
: ''),
|
||||
}));
|
||||
return (
|
||||
<label key={key} className="block">
|
||||
{labels[key]}
|
||||
@@ -972,12 +1050,25 @@ export default function OpportunityCanonicalFields({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{key === 'economic_activity_id' && options.activities.find((a) => a.id === value[key])?.level && (
|
||||
<p className="mt-1 text-sm" data-economic-path="five-levels">
|
||||
{options.activities.find((a) => a.id === value[key])?.path?.map((p) => `${p.code} — ${p.label}`).join(' → ')}
|
||||
{' · Exemplar eBAU; edição normativa não determinada; divergência 600/579 aberta.'}
|
||||
</p>
|
||||
)}
|
||||
{key === 'economic_activity_id' &&
|
||||
options.activities.find(
|
||||
(a) => a.id === value[key],
|
||||
)?.level && (
|
||||
<p
|
||||
className="mt-1 text-sm"
|
||||
data-economic-path="five-levels"
|
||||
>
|
||||
{options.activities
|
||||
.find((a) => a.id === value[key])
|
||||
?.path?.map(
|
||||
(p) => `${p.code} — ${p.label}`,
|
||||
)
|
||||
.join(' → ')}
|
||||
{
|
||||
' · Exemplar eBAU; edição normativa não determinada; divergência 600/579 aberta.'
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -987,7 +1078,19 @@ export default function OpportunityCanonicalFields({
|
||||
: [];
|
||||
return (
|
||||
<fieldset key={key}>
|
||||
<legend>{labels[key]}</legend>
|
||||
<legend>{isInitiative && key === 'locations' ? 'Abrangência territorial — recursos guardados' : labels[key]}</legend>
|
||||
{key === 'locations' && (
|
||||
<p>
|
||||
Seleccione os locais já guardados em
|
||||
Recursos; não volte a introduzir a
|
||||
hierarquia. O local principal, os adicionais
|
||||
e a finalidade de cada um são definidos
|
||||
nesse registo. Abrangência, impacto e
|
||||
contexto não significam implantação. Pode
|
||||
guardar incompleto; a submissão conserva as
|
||||
verificações existentes.
|
||||
</p>
|
||||
)}
|
||||
<FieldErrors
|
||||
path={'canonical.' + key}
|
||||
errors={errors}
|
||||
|
||||
@@ -30,7 +30,18 @@ export type ClassificationOptions = {
|
||||
dimensions: Record<string, string>;
|
||||
types: Record<string, string>;
|
||||
purposes: Record<string, string>;
|
||||
targets: Record<string, { id: string | number; label: string; code?: string; level?: number | null; path?: { id: string; code: string; label: string }[]; source_version?: string | null; edition?: string | null }[]>;
|
||||
targets: Record<
|
||||
string,
|
||||
{
|
||||
id: string | number;
|
||||
label: string;
|
||||
code?: string;
|
||||
level?: number | null;
|
||||
path?: { id: string; code: string; label: string }[];
|
||||
source_version?: string | null;
|
||||
edition?: string | null;
|
||||
}[]
|
||||
>;
|
||||
externalStates: string[];
|
||||
};
|
||||
const typeLabels: Record<string, string> = {
|
||||
@@ -61,7 +72,7 @@ const externalLabels: Record<string, string> = {
|
||||
expired: 'Caducado',
|
||||
};
|
||||
const help =
|
||||
'Associação, publicação e ato externo têm estados separados. Localização ou proximidade não concedem licença, benefício, terreno ou capacidade. Dados ausentes permanecem por determinar. Os elos identificados como Modelo editorial não confirmam operadores, capacidade ou relações comerciais. O recorte CAE conserva cinco níveis; 600/579 permanece documentalmente aberto.';
|
||||
'Indique relações com corredores, clusters, projectos âncora, zonas, parques, cadeias e actividades, quando aplicáveis. Cada associação tem finalidade, fonte e estado próprios. A implantação, a abrangência e a proximidade são diferentes: estar num distrito não comprova pertença a um cluster, parque ou regime especial. Associação, publicação e acto externo são decisões separadas; dados ausentes permanecem por determinar.';
|
||||
|
||||
export function ClassificationEditor({
|
||||
rows,
|
||||
@@ -117,7 +128,16 @@ export function ClassificationEditor({
|
||||
className="space-y-4"
|
||||
aria-label="Classificação multidimensional"
|
||||
>
|
||||
<h3 className="font-semibold">Quatro dimensões da oportunidade</h3>
|
||||
<h3 className="font-semibold">
|
||||
Associações territoriais e produtivas
|
||||
</h3>
|
||||
<p>
|
||||
Inclui relações territoriais, produtivas, regulatórias e de
|
||||
actividade. Não repita aqui o endereço nem a hierarquia dos
|
||||
locais. Pode preparar relações preliminares; confirmação e
|
||||
publicação seguem as verificações já existentes de fonte,
|
||||
citação e revisão.
|
||||
</p>
|
||||
<p>{help}</p>
|
||||
{Object.entries(options.dimensions).map(([dimension, label]) => (
|
||||
<fieldset
|
||||
@@ -193,9 +213,25 @@ export function ClassificationEditor({
|
||||
<option value="">
|
||||
Selecionar referência
|
||||
</option>
|
||||
{row.related_id && !(options.targets[row.classification.target_type] ?? []).some((t) => String(t.id) === String(row.related_id)) && (
|
||||
<option value={row.related_id}>Referência guardada, atualmente indisponível — {row.related_id}</option>
|
||||
)}
|
||||
{row.related_id &&
|
||||
!(
|
||||
options.targets[
|
||||
row.classification
|
||||
.target_type
|
||||
] ?? []
|
||||
).some(
|
||||
(t) =>
|
||||
String(t.id) ===
|
||||
String(row.related_id),
|
||||
) && (
|
||||
<option
|
||||
value={row.related_id}
|
||||
>
|
||||
Referência guardada,
|
||||
atualmente indisponível
|
||||
— {row.related_id}
|
||||
</option>
|
||||
)}
|
||||
{(
|
||||
options.targets[
|
||||
row.classification
|
||||
@@ -210,9 +246,27 @@ export function ClassificationEditor({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{row.related_id && !(options.targets[row.classification.target_type] ?? []).some((t) => String(t.id) === String(row.related_id)) && (
|
||||
<span className="block text-sm">A referência deixou de estar disponível para novas escolhas. A relação histórica permanece guardada; não selecione outro valor para a recuperar.</span>
|
||||
)}
|
||||
{row.related_id &&
|
||||
!(
|
||||
options.targets[
|
||||
row.classification
|
||||
.target_type
|
||||
] ?? []
|
||||
).some(
|
||||
(t) =>
|
||||
String(t.id) ===
|
||||
String(row.related_id),
|
||||
) && (
|
||||
<span className="block text-sm">
|
||||
A referência deixou de estar
|
||||
disponível para novas
|
||||
escolhas. A relação
|
||||
histórica permanece
|
||||
guardada; não selecione
|
||||
outro valor para a
|
||||
recuperar.
|
||||
</span>
|
||||
)}
|
||||
{errors[
|
||||
`canonical.relations.${index}.related_id`
|
||||
] && (
|
||||
@@ -775,7 +829,7 @@ export function ClassificationSummary({
|
||||
aria-label="Quatro dimensões da oportunidade"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Classificação multidimensional
|
||||
Associações territoriais e produtivas
|
||||
</h2>
|
||||
<p>{help}</p>
|
||||
{Object.entries({
|
||||
@@ -792,12 +846,22 @@ export function ClassificationSummary({
|
||||
.map((r, i) => (
|
||||
<p key={i} className="break-words">
|
||||
{r.reference_path?.length
|
||||
? r.reference_path.map((n) => `${n.code} — ${n.label}`).join(' → ')
|
||||
: r.label} · {classificationStates[r.state]}{' '}
|
||||
? r.reference_path
|
||||
.map(
|
||||
(n) =>
|
||||
`${n.code} — ${n.label}`,
|
||||
)
|
||||
.join(' → ')
|
||||
: r.label}{' '}
|
||||
·{' '}
|
||||
{classificationStates[r.state] ??
|
||||
'Por determinar'}{' '}
|
||||
· {r.purpose_label ?? r.purpose} ·{' '}
|
||||
{r.source_reference || 'Fonte por indicar'}{' '}
|
||||
{r.citation} {r.production_stage} · Ato
|
||||
externo: {externalLabels[r.external_status]}
|
||||
externo:{' '}
|
||||
{externalLabels[r.external_status] ??
|
||||
'Não determinado'}
|
||||
. Benefício ou capacidade disponível: não
|
||||
inferido.
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { contextApi } from '@/lib/investor-context';
|
||||
|
||||
export type LibrarySource = {
|
||||
id: number;
|
||||
title: string;
|
||||
version_label: string | null;
|
||||
metadata_version: number;
|
||||
sha256: string;
|
||||
};
|
||||
export default function OpportunityLibraryReuse({
|
||||
sources,
|
||||
action,
|
||||
etag,
|
||||
}: {
|
||||
sources: LibrarySource[];
|
||||
action: string;
|
||||
etag: string;
|
||||
}) {
|
||||
const [selected, setSelected] = useState('');
|
||||
const [section, setSection] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [key, setKey] = useState(createOperationKey);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<section
|
||||
aria-label="Reutilizar original da biblioteca"
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Reutilizar original da biblioteca
|
||||
</h2>
|
||||
<p>
|
||||
O suporte aponta para os mesmos bytes e conserva edição, hash e
|
||||
histórico. Mantém-se privado; a ficha e o original têm
|
||||
permissões e publicação próprias.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Original da biblioteca
|
||||
<select
|
||||
aria-label="Original da biblioteca"
|
||||
className="w-full rounded border p-2"
|
||||
value={selected}
|
||||
onChange={(e) => setSelected(e.target.value)}
|
||||
>
|
||||
<option value="">Seleccionar original acessível</option>
|
||||
{sources.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title} · {s.version_label ?? 'sem edição'} ·
|
||||
metadados v{s.metadata_version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Secções utilizadas
|
||||
<input
|
||||
aria-label="Secções utilizadas"
|
||||
className="w-full rounded border p-2"
|
||||
value={section}
|
||||
maxLength={255}
|
||||
onChange={(e) => setSection(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Motivo da reutilização
|
||||
<textarea
|
||||
aria-label="Motivo da reutilização"
|
||||
className="w-full rounded border p-2"
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className="rounded border bg-emerald-800 px-4 py-2 text-white disabled:opacity-50"
|
||||
type="button"
|
||||
disabled={!selected || reason.length < 20 || busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const result = await contextApi<{ message: string }>(
|
||||
action,
|
||||
{
|
||||
resource_id: Number(selected),
|
||||
section: section || null,
|
||||
reason,
|
||||
etag,
|
||||
creation_key: key,
|
||||
},
|
||||
);
|
||||
setMessage(result.message);
|
||||
setKey(createOperationKey);
|
||||
router.reload();
|
||||
} catch (e) {
|
||||
setMessage(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível associar o original. Selecção preservada.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Associar original como suporte privado
|
||||
</button>
|
||||
<p role="status">
|
||||
{message ||
|
||||
(!sources.length
|
||||
? 'Não há originais acessíveis à conta neste âmbito.'
|
||||
: 'Seleccionar não grava nem divulga o original.')}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +1,13 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
export default function PartnershipSearchResults({ query }: { query: string }) {
|
||||
const [items, setItems] = useState<{ id: number; title: string }[]>([]);
|
||||
useEffect(() => {
|
||||
if (!query.trim()) {
|
||||
setItems([]);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
fetch('/api/v1/partnerships?q=' + encodeURIComponent(query), {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((data) => setItems(data?.data ?? []))
|
||||
.catch(() => {});
|
||||
return () => controller.abort();
|
||||
}, [query]);
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<section className="my-5 space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-bold">Parcerias nesta pesquisa</h2>
|
||||
{items.slice(0, 5).map((item) => (
|
||||
<p key={item.id}>
|
||||
<Link className="underline" href={'/parcerias/' + item.id}>
|
||||
{item.title}
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias?q=' + encodeURIComponent(query)}
|
||||
>
|
||||
Ver todas as parcerias correspondentes
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
import { usePortalQuery } from '@/hooks/use-portal-query';
|
||||
import SearchState from '@/components/search-state';
|
||||
export default function PartnershipSearchResults({query}: {query:string}) {
|
||||
const result = usePortalQuery<{data:{id:number;title:string}[]; total?:number}>('/api/v1/partnerships?q=' + encodeURIComponent(query), 250);
|
||||
const items = result.data?.data ?? [];
|
||||
if (!query.trim()) return null;
|
||||
return <section className="my-5 space-y-3 rounded border p-4"><h2 className="text-xl font-bold">Parcerias nesta pesquisa</h2>
|
||||
<SearchState loading={result.loading} error={result.error} total={result.data?.total ?? items.length} retry={result.retry}/>
|
||||
{!result.error && !result.loading && items.slice(0,5).map(item => <p key={item.id}><Link className="underline" href={'/parcerias/'+item.id}>{item.title}</Link></p>)}
|
||||
<Link className="underline" href={'/parcerias?q='+encodeURIComponent(query)}>Ver todas as parcerias correspondentes</Link>
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ export default function PasswordInput({
|
||||
type="button"
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute inset-y-0 right-0 flex items-center rounded-r-md px-3 focus-visible:ring-[3px] focus-visible:outline-none"
|
||||
aria-label={showPassword ? 'Hide password' : 'Show password'}
|
||||
aria-label={showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe'}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPassword ? (
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import PortalProductIdentity from '@/components/portal-product-identity';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import { ChevronDown, LogOut, UserRound } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
ChevronDown,
|
||||
ArrowUpRight,
|
||||
LogOut,
|
||||
Menu,
|
||||
UserRound,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { useNavigationContext } from '@/components/navigation-context';
|
||||
import { TempoSocialLinks, useTempoUi } from '@/components/tempo-brand';
|
||||
import {
|
||||
@@ -41,6 +49,7 @@ export function PortalGroupedMenu() {
|
||||
legacyContentEnabled?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
scopedAdministration?: {label:string;href:string}[];
|
||||
}>();
|
||||
const { t, language, requestCount } = useTempoUi();
|
||||
const navigation = useNavigationContext();
|
||||
@@ -58,9 +67,15 @@ export function PortalGroupedMenu() {
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
profileAccess: props.profileAccess,
|
||||
});
|
||||
if (props.scopedAdministration?.length) groups.push({id:'scoped-administration',label:'Administração',children:props.scopedAdministration.map((item,index)=>({id:`scoped-${index}`,label:item.label,href:item.href}))});
|
||||
const current = currentNavigationGroup(groups, url);
|
||||
const currentItem = currentNavigationItem(groups, url);
|
||||
const [loggingOut, setLoggingOut] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const institutionalId = useId();
|
||||
const toolsId = useId();
|
||||
const toggle = useRef<HTMLButtonElement>(null);
|
||||
useEffect(() => router.on('navigate', () => setExpanded(false)), []);
|
||||
const items = (children: PortalNavItem[]) =>
|
||||
children.map((item) =>
|
||||
item.children ? (
|
||||
@@ -97,157 +112,252 @@ export function PortalGroupedMenu() {
|
||||
!['home', 'discovery', 'realization', 'support'].includes(group.id),
|
||||
);
|
||||
return (
|
||||
<header className="tempo-header" lang={language}>
|
||||
<div className="tempo-header-inner mx-auto flex max-w-[1440px] flex-wrap items-center justify-between gap-x-3 gap-y-0 px-4 sm:px-6 xl:min-h-22">
|
||||
<Link
|
||||
href="/"
|
||||
aria-label="Tempo — início"
|
||||
className="tempo-logo-link my-4 shrink-0"
|
||||
>
|
||||
<img
|
||||
src="/images/logo/logo-vermelho.png"
|
||||
alt="Tempo"
|
||||
width="1787"
|
||||
height="564"
|
||||
className="h-9 w-auto object-contain sm:h-10"
|
||||
/>
|
||||
</Link>
|
||||
<nav
|
||||
aria-label="Áreas do portal"
|
||||
className="order-3 w-full border-t border-white/10 xl:order-none xl:w-auto xl:flex-1 xl:border-0"
|
||||
>
|
||||
<ul className="flex items-center justify-between gap-0 py-2 xl:justify-center xl:py-0">
|
||||
<li>
|
||||
<Link
|
||||
href="/"
|
||||
className="tempo-nav-trigger"
|
||||
aria-current={
|
||||
current === 'home' ? 'page' : undefined
|
||||
}
|
||||
data-current-group={
|
||||
current === 'home' || undefined
|
||||
}
|
||||
>
|
||||
{t('Início')}
|
||||
</Link>
|
||||
</li>
|
||||
{groups
|
||||
.filter((group) =>
|
||||
[
|
||||
'discovery',
|
||||
'realization',
|
||||
'support',
|
||||
].includes(group.id),
|
||||
)
|
||||
.map((group) => (
|
||||
<li key={group.id}>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger
|
||||
className="tempo-nav-trigger"
|
||||
data-current-group={
|
||||
current === group.id ||
|
||||
undefined
|
||||
}
|
||||
>
|
||||
{t(group.label)}
|
||||
<ChevronDown
|
||||
size={14}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{current === group.id && (
|
||||
<span className="sr-only">
|
||||
Grupo actual
|
||||
</span>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
sideOffset={12}
|
||||
collisionPadding={12}
|
||||
className="tempo-dropdown max-h-[min(75vh,36rem)] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto p-2"
|
||||
>
|
||||
{items(group.children ?? [])}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<header
|
||||
className="tempo-header"
|
||||
lang={language}
|
||||
data-expanded={expanded || undefined}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === 'Escape' &&
|
||||
expanded &&
|
||||
!event.defaultPrevented
|
||||
) {
|
||||
setExpanded(false);
|
||||
toggle.current?.focus();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="tempo-header-layout">
|
||||
<div className="tempo-header-inner">
|
||||
<Link
|
||||
href="/"
|
||||
aria-label="InvesteMoz — início"
|
||||
className="tempo-logo-link"
|
||||
>
|
||||
<PortalProductIdentity />
|
||||
</Link>
|
||||
<nav
|
||||
id={institutionalId}
|
||||
aria-label="Navegação institucional"
|
||||
className="tempo-primary-navigation"
|
||||
>
|
||||
<ul>
|
||||
<li>
|
||||
<Link
|
||||
href="/"
|
||||
className="tempo-nav-trigger"
|
||||
aria-current={
|
||||
url.split('?')[0] === '/'
|
||||
? 'page'
|
||||
: undefined
|
||||
}
|
||||
data-current-group={
|
||||
url.split('?')[0] === '/' || undefined
|
||||
}
|
||||
>
|
||||
{t('Início')}
|
||||
</Link>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
href="https://revista.tempo.co.mz/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="tempo-nav-trigger"
|
||||
aria-label={`${t('Revista Tempo')} — ${t('Abre num novo separador')}`}
|
||||
>
|
||||
{t('Revista Tempo')}
|
||||
<ArrowUpRight
|
||||
size={14}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</a>
|
||||
</li>
|
||||
{[
|
||||
['/sobre', 'Sobre nós'],
|
||||
['/contacto', 'Contacto'],
|
||||
].map(([href, label]) => (
|
||||
<li key={href}>
|
||||
<Link
|
||||
href={href}
|
||||
className="tempo-nav-trigger"
|
||||
aria-current={
|
||||
url.split('?')[0] === href
|
||||
? 'page'
|
||||
: undefined
|
||||
}
|
||||
data-current-group={
|
||||
url.split('?')[0] === href ||
|
||||
undefined
|
||||
}
|
||||
>
|
||||
{t(label)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<div className="tempo-panel-summary">
|
||||
<Link href="/investidor/manifestacoes">
|
||||
{t('O meu painel')}
|
||||
</Link>
|
||||
<span aria-live="polite" aria-atomic="true">
|
||||
{requestCount}{' '}
|
||||
{t(
|
||||
requestCount === 1
|
||||
? 'pedido recebido'
|
||||
: 'pedidos recebidos',
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="order-5 flex w-full items-center justify-between gap-2 border-t border-white/10 py-2 xl:order-none xl:w-auto xl:justify-end xl:border-0 xl:py-0">
|
||||
<div className="flex items-center gap-1 sm:gap-2">
|
||||
<TempoWeather />
|
||||
<TempoLanguageSelector />
|
||||
</ul>
|
||||
</nav>
|
||||
<div id={toolsId} className="tempo-header-extras">
|
||||
<div className="tempo-header-utilities">
|
||||
<div className="flex items-center gap-1">
|
||||
<TempoWeather />
|
||||
<TempoLanguageSelector />
|
||||
</div>
|
||||
<TempoSocialLinks />
|
||||
</div>
|
||||
</div>
|
||||
<TempoSocialLinks />
|
||||
</div>
|
||||
<div className="tempo-header-actions">
|
||||
{props.auth?.user ? (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="tempo-login-button">
|
||||
<UserRound size={16} aria-hidden="true" />
|
||||
<span className="max-w-24 truncate">
|
||||
{props.auth.user.name || t('A minha área')}
|
||||
</span>
|
||||
<ChevronDown size={12} aria-hidden="true" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
sideOffset={12}
|
||||
collisionPadding={12}
|
||||
className="tempo-dropdown max-h-[75vh] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto p-2"
|
||||
>
|
||||
<DropdownMenuLabel className="truncate text-xs text-slate-500">
|
||||
{props.auth.user.email}
|
||||
</DropdownMenuLabel>
|
||||
{items(accountGroups)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
asChild
|
||||
className="tempo-menu-item text-red-700"
|
||||
<div className="tempo-header-actions">
|
||||
{props.auth?.user ? (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="tempo-login-button">
|
||||
<UserRound size={16} aria-hidden="true" />
|
||||
<span className="max-w-24 truncate">
|
||||
{props.auth.user.name ||
|
||||
t('A minha área')}
|
||||
</span>
|
||||
<ChevronDown size={12} aria-hidden="true" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="end"
|
||||
sideOffset={12}
|
||||
collisionPadding={12}
|
||||
className="tempo-dropdown max-h-[75vh] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto p-2"
|
||||
>
|
||||
<Link
|
||||
href={logout()}
|
||||
as="button"
|
||||
type="button"
|
||||
disabled={loggingOut}
|
||||
data-test="portal-logout-button"
|
||||
onClick={() => router.flushAll()}
|
||||
onStart={() => setLoggingOut(true)}
|
||||
onFinish={() => setLoggingOut(false)}
|
||||
<DropdownMenuLabel className="truncate text-xs text-slate-500">
|
||||
{props.auth.user.email}
|
||||
</DropdownMenuLabel>
|
||||
{items(accountGroups)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
asChild
|
||||
className="tempo-menu-item text-red-700"
|
||||
>
|
||||
<LogOut size={16} aria-hidden="true" />
|
||||
{loggingOut
|
||||
? 'A terminar sessão…'
|
||||
: t('Terminar sessão')}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Link href="/login" className="tempo-login-button">
|
||||
<UserRound size={15} aria-hidden="true" />
|
||||
{t('Entrar')}
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href="/manifestar-interesse"
|
||||
className="tempo-interest-button"
|
||||
<Link
|
||||
href={logout()}
|
||||
as="button"
|
||||
type="button"
|
||||
disabled={loggingOut}
|
||||
data-test="portal-logout-button"
|
||||
onClick={() => router.flushAll()}
|
||||
onStart={() => setLoggingOut(true)}
|
||||
onFinish={() =>
|
||||
setLoggingOut(false)
|
||||
}
|
||||
>
|
||||
<LogOut
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{loggingOut
|
||||
? 'A terminar sessão…'
|
||||
: t('Terminar sessão')}
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Link href="/login" className="tempo-login-button">
|
||||
<UserRound size={15} aria-hidden="true" />
|
||||
{t('Entrar')}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
ref={toggle}
|
||||
type="button"
|
||||
className="tempo-header-toggle"
|
||||
aria-label={
|
||||
expanded
|
||||
? 'Fechar menu e ferramentas'
|
||||
: 'Abrir menu e ferramentas'
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={`${institutionalId} ${toolsId}`}
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
>
|
||||
{t('Manifestar interesse')}
|
||||
</Link>
|
||||
{expanded ? (
|
||||
<X size={22} aria-hidden="true" />
|
||||
) : (
|
||||
<Menu size={22} aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<div className="tempo-section-bar">
|
||||
<div className="tempo-section-inner">
|
||||
<Link
|
||||
href="/investidor/manifestacoes"
|
||||
className="tempo-panel-summary"
|
||||
>
|
||||
<span>{t('O meu painel')}</span>
|
||||
<span
|
||||
className="tempo-panel-count"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{requestCount}{' '}
|
||||
{t(
|
||||
requestCount === 1
|
||||
? 'pedido recebido'
|
||||
: 'pedidos recebidos',
|
||||
)}
|
||||
</span>
|
||||
</Link>
|
||||
<nav
|
||||
aria-label="Áreas do portal"
|
||||
className="tempo-section-navigation"
|
||||
>
|
||||
<ul>
|
||||
{groups
|
||||
.filter((group) =>
|
||||
[
|
||||
'discovery',
|
||||
'realization',
|
||||
'support',
|
||||
].includes(group.id),
|
||||
)
|
||||
.map((group) => (
|
||||
<li key={group.id}>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger
|
||||
className="tempo-nav-trigger"
|
||||
data-current-group={
|
||||
current === group.id ||
|
||||
undefined
|
||||
}
|
||||
>
|
||||
{t(group.label)}
|
||||
<ChevronDown
|
||||
size={14}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{current === group.id && (
|
||||
<span className="sr-only">
|
||||
Grupo actual
|
||||
</span>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
collisionPadding={12}
|
||||
className="tempo-dropdown max-h-[min(75vh,36rem)] w-72 max-w-[calc(100vw-1.5rem)] overflow-y-auto p-2"
|
||||
>
|
||||
{items(
|
||||
group.children ?? [],
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
<Link
|
||||
href="/manifestar-interesse"
|
||||
className="tempo-interest-button"
|
||||
>
|
||||
{t('Manifestar interesse')}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Product identity and ownership are distinct; reuse the existing owner logo. */
|
||||
export default function PortalProductIdentity() {
|
||||
return (
|
||||
<span className="flex flex-col items-start gap-1">
|
||||
<span className="text-xl font-semibold tracking-tight">InvesteMoz</span>
|
||||
<span className="flex items-center gap-1.5 text-[10px] font-normal">
|
||||
Propriedade da
|
||||
<img
|
||||
src="/images/logo/logo-vermelho.png"
|
||||
alt="Tempo, Lda."
|
||||
width="1787"
|
||||
height="564"
|
||||
className="h-3.5 w-auto object-contain"
|
||||
/>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { router, usePage } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
// Shared feedback for existing Inertia search consumers; form state is never reset.
|
||||
const collections = ['results','records','resources','partnerships','opportunities','interests','investors','leads','articles','services','items','entries','documents','requests','batches','users','assignments','zones','matches','businesses'];
|
||||
function count(props: Record<string, unknown>): number | null {
|
||||
if (props.demands && props.capacities) return Number((props.demands as {total:number}).total) + Number((props.capacities as {total:number}).total);
|
||||
if (props.plan && Array.isArray((props.plan as {rows:unknown[]}).rows)) return (props.plan as {rows:unknown[]}).rows.length;
|
||||
if (typeof props.total === 'number') return props.total;
|
||||
if (typeof props.match === 'boolean' && Array.isArray(props.articles)) return props.match ? props.articles.length : 0;
|
||||
for (const key of collections) {
|
||||
const value = props[key] as {total?:number; meta?:{total?:number}; data?:unknown[]} | unknown[] | undefined;
|
||||
if (!value) continue;
|
||||
if (Array.isArray(value)) return value.length;
|
||||
if (typeof value.total === 'number') return value.total;
|
||||
if (typeof value.meta?.total === 'number') return value.meta.total;
|
||||
if (Array.isArray(value.data)) return value.data.length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export default function SearchFeedback() {
|
||||
const page = usePage();
|
||||
const [state, setState] = useState<'idle'|'loading'|'error'>('idle');
|
||||
const latest = useRef<{url: string; data: Record<string, unknown>} | null>(null);
|
||||
const active = useRef(false);
|
||||
const searchable = page.props.filters !== undefined || ['portal/legacy','desk/catalogue','investment/zones','partnerships/catalogue','education/index','management/territory-geometry-import'].includes(page.component);
|
||||
const total = searchable ? count(page.props) : null;
|
||||
useEffect(() => {
|
||||
const off = [router.on('before', event => {
|
||||
const visit = event.detail.visit;
|
||||
if (visit.method !== 'get') { active.current = false; return; }
|
||||
const data = visit.data as Record<string, unknown>;
|
||||
const url = visit.url;
|
||||
const isSearch = total !== null || ['q','query','search','filter','status','sector'].some(key => key in data || url.searchParams.has(key));
|
||||
active.current = isSearch;
|
||||
if (isSearch) { latest.current = {url: url.toString(), data}; setState('loading'); }
|
||||
}), router.on('success', () => { if (active.current) { active.current = false; setState('idle'); } }),
|
||||
router.on('error', () => { if (active.current) setState('error'); }),
|
||||
router.on('httpException', event => { if (active.current) { event.preventDefault(); setState('error'); } }),
|
||||
router.on('networkError', event => { if (active.current) { event.preventDefault(); setState('error'); } })];
|
||||
return () => off.forEach(remove => remove());
|
||||
}, [total]);
|
||||
if (total === null && state === 'idle') return null;
|
||||
return <aside data-search-feedback role={state === 'error' ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="sticky top-0 z-50 border-b bg-white p-3 text-center text-slate-950 shadow">
|
||||
{state === 'loading' ? 'A pesquisar…' : state === 'error' ? <><span>Não foi possível concluir a pesquisa. Os resultados anteriores mantêm-se abaixo. </span><button type="button" className="underline" onClick={() => { const request = latest.current; if (request) router.get(request.url, request.data as never, {preserveState:true, preserveScroll:true}); }}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
|
||||
</aside>;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export default function SearchState({loading, error, total, retry}: {loading:boolean; error?:string; total:number; retry:()=>void}) {
|
||||
return <div role={error ? 'alert' : 'status'} aria-live="polite" aria-atomic="true" className="my-3 rounded border p-3">
|
||||
{loading ? 'A pesquisar…' : error ? <>Não foi possível concluir a pesquisa. <button type="button" className="underline" onClick={retry}>Tentar novamente</button></> : total === 0 ? 'Não foram encontrados resultados para esta pesquisa' : `${total} resultados encontrados`}
|
||||
</div>;
|
||||
}
|
||||
@@ -57,7 +57,7 @@ export type StructureGeography = {
|
||||
};
|
||||
|
||||
const roles: Record<string, string> = {
|
||||
opportunity: 'Implantação cadastrada da oportunidade',
|
||||
opportunity: 'Localização declarada da oportunidade',
|
||||
primary: 'Localização principal',
|
||||
secondary: 'Localização secundária',
|
||||
impact: 'Área de impacto',
|
||||
|
||||
@@ -30,6 +30,14 @@ export const tempoSocialLinks = [
|
||||
];
|
||||
|
||||
const menuTranslations = [
|
||||
['Sobre nós', 'About us', 'À propos', 'Sobre nosotros'],
|
||||
['Revista Tempo', 'Revista Tempo', 'Revista Tempo', 'Revista Tempo'],
|
||||
[
|
||||
'Abre num novo separador',
|
||||
'Opens in a new tab',
|
||||
'Ouvre un nouvel onglet',
|
||||
'Abre en una nueva pestaña',
|
||||
],
|
||||
['O meu painel', 'My dashboard', 'Mon espace', 'Mi panel'],
|
||||
[
|
||||
'Manifestar interesse',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user