Compare commits

...
Author SHA1 Message Date
nala 0d7b70459d fix: explain IVA query conditions and distinguish integration failures 2026-10-21 13:35:22 +02:00
nala bd5166bd11 docs: record authorised fiscal rule publication and consumer activation 2026-10-21 12:57:40 +02:00
nala 4a4d121275 fix: allow authorised fiscal maintenance by the same responsible person
tests / ci (push) Canceled after 0s
2026-10-21 12:39:07 +02:00
nala 226fd308dd feat: connect published IVA consumer to normal simulator in QA
tests / ci (push) Canceled after 0s
2026-10-21 11:59:50 +02:00
nala 2ced7b790c docs: delimit published IVA consumer and three rollout operations 2026-10-21 11:39:17 +02:00
nala d186f94206 feat: demonstrar percurso IVA QA e consolidar revisao 2026-10-21 09:40:49 +02:00
nala 83d2f97d82 feat: preparar lote IVA exacto em QA sem activacao 2026-10-21 09:22:11 +02:00
nala 37085b40c1 docs: fundamentar base IVA e delimitar lacuna de arredondamento 2026-10-21 09:03:01 +02:00
nala 325d58b694 docs: preparar ficha fiscal IVA v1 sem activacao 2026-10-21 08:57:56 +02:00
nala 0fafd348e7 docs: delimitar entrega de planeamento e propor primeiro lote fiscal 2026-10-21 08:47:07 +02:00
nala 13f68f1bd8 fix: concluir recuperacao de exportacoes e consolidar candidata QA
tests / ci (push) Canceled after 0s
2026-10-21 08:43:12 +02:00
nala c22003a3da fix: recover simulator cashflow and verify QA continuity and report assumptions 2026-10-20 22:00:48 +02:00
nala a690c665fb fix: validate simulator dates and reconcile QA calculations reports and language 2026-10-20 21:00:52 +02:00
nala 59ab4fe956 fix: validar datas fiscais e iniciar revisao integrada do simulador 2026-10-20 20:03:40 +02:00
nala e69ab1499f docs: comprovar guias na biblioteca QA existente
tests / ci (push) Canceled after 0s
2026-10-20 19:49:55 +02:00
nala 3258a25f76 feat: apresentar guias educativos com imagem resumo e contexto 2026-10-20 19:45:45 +02:00
nala 0e7d51f18f fix: concluir apresentacao publica dos negocios e zonas
tests / ci (push) Canceled after 0s
2026-10-20 19:00:32 +02:00
nala fd341b627e fix: harmonizar pesquisa e navegacao dos catalogos em QA 2026-10-20 18:53:41 +02:00
nala 1350b4df73 autenticacao 1
tests / ci (push) Canceled after 0s
2026-10-20 17:51:31 +02:00
nala 8cf820ef49 Reservar espaco minimo antes de compilar nova release
tests / ci (push) Canceled after 0s
2026-10-20 17:26:01 +02:00
nala 210b7d273b Clarificar comando de consulta para demonstrar entrega automatica 2026-10-20 17:25:29 +02:00
nala be49f4c39c Integrar navbar e sobre dos programadores preservando identidade e acessos 2026-10-20 17:23:45 +02:00
nala 9b3c20fc2a Registar resolucao do diagnostico e alinhar traducao financeira aceite 2026-10-20 17:23:20 +02:00
nala de061b81aa Conferir alteracoes durante CI e sinalizar falha ao systemd 2026-10-20 15:12:54 +02:00
nala 6e439def02 Reconciliar verificacoes com navegacao e relatorios aprovados 2026-10-20 15:12:17 +02:00
nala 74b081e93e Evitar migracao desnecessaria no teste unitario de exemplo 2026-10-20 15:09:51 +02:00
nala 9d148ca241 Preservar diagnostico mais recente dos programadores e isolar fixtures unitarias 2026-10-20 15:07:54 +02:00
nala 5be831ac44 Usar contrato QA existente e documentar operacao e reversao 2026-10-20 15:06:45 +02:00
nala f0e26e0d8a Preparar cadeia Git com verificacao isolada e releases reversiveis 2026-10-20 14:57:08 +02:00
nala 9ab721c97f Reconciliar fontes instaladas 423bd512d8c5 com main 2026-10-20 14:45:19 +02:00
236 changed files with 26847 additions and 11180 deletions
+5
View File
@@ -4,6 +4,11 @@ APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000
# Separate from publication. Bind only an explicitly authorised published rule version.
INVESTMOZ_IVA_CONSUMER_ENABLED=false
INVESTMOZ_IVA_CONSUMER_RULE_ID=
INVESTMOZ_IVA_CONSUMER_RULE_VERSION=0
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
@@ -0,0 +1,50 @@
<?php
namespace App\Console\Commands;
use App\Models\InvestmentLegalSource;
use App\Models\User;
use App\Services\SimulationTaxParameterResolver;
use App\Services\SimulationTaxRuleExpression;
use App\Services\SimulationTaxRuleGovernance;
use App\Support\IsolatedQaDatabase;
use Illuminate\Console\Command;
/** Explicit registration: never run during migration, deployment or document import. */
class RegisterFiscalQaDraft extends Command
{
protected $signature = 'fiscal:qa-register-iva {actor : Existing QA editor ID} {source : Existing accepted legal source UUID}';
protected $description = 'Cadastrar apenas o rascunho IVA do primeiro lote numa base QA isolada, sem publicação';
public function handle(SimulationTaxRuleGovernance $governance): int
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 403, 'O cadastro deste lote só é permitido na base QA isolada.');
$actor = User::findOrFail($this->argument('actor'));
$source = InvestmentLegalSource::findOrFail($this->argument('source'));
abort_unless($source->validation_status === 'validated' && $source->diploma === 'Lei 22/2022'
&& $source->article === 'Artigo 17(1)', 422, 'Seleccione a referência aceite da taxa geral, Lei 22/2022, artigo 17(1).');
$payload = json_decode(file_get_contents(database_path('qa/iva-general-net-v1.json')), true, flags: JSON_THROW_ON_ERROR);
$actualHash = hash_file('sha256', base_path('docs/investmoz/simulations/source-archive/Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf'));
abort_unless(hash_equals($payload['source_sha256'], $actualHash), 422, 'O exemplar não corresponde ao hash da ficha.');
$payload['legal_source_id'] = (string) $source->id;
app(SimulationTaxRuleExpression::class)->validate($payload['rule_definition']);
app(SimulationTaxParameterResolver::class)->validateParameters($payload['parameters']);
$existing = $governance->listing($actor, ['rule_code' => $payload['rule_code']])->getCollection()
->firstWhere('rule_version', 1);
if ($existing) {
foreach ($payload as $field => $value) {
$stored = $existing->attributesToArray()[$field] ?? null;
abort_unless($stored == $value, 409, 'O cadastro existente difere desta ficha; não será sobrescrito.');
}
abort_unless($existing->status === 'draft', 409, 'A versão existente já não é um rascunho.');
$this->line(json_encode(['id' => $existing->id, 'status' => 'draft', 'reused' => true], JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
$rule = $governance->create($actor, $payload);
$this->line(json_encode(['id' => $rule->id, 'status' => $rule->status, 'reused' => false], JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}
@@ -23,8 +23,9 @@ class InterestRequestController extends Controller
{
public function store(StoreInterestRequestRequest $request, InterestSubmission $submission): JsonResponse
{
$validated = $request->validated();
$validated = [...$request->validated(), '_actor_id' => $request->user()->id];
$key = $request->header('Idempotency-Key');
abort_unless(is_string($key), 422, 'Identificador do envio em falta.');
Validator::make(['idempotency_key' => $key], ['idempotency_key' => [$key === null ? 'nullable' : 'required', 'uuid']])->validate();
try {
@@ -53,7 +54,7 @@ class InterestRequestController extends Controller
'phone' => $validated['phone'] ?? null,
'investor_type' => $validated['investorType'],
'country' => $validated['country'],
'metadata' => ['declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
'metadata' => ['portal_user_id' => $request->user()->id, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
'sector_interest' => $validated['sectorInterest'],
'opportunity_reference' => $validated['opportunityReference'] ?? null,
'investment_range' => $validated['investmentRange'] ?? null,
@@ -77,6 +78,19 @@ class InterestRequestController extends Controller
}
}
$row = \App\Models\InvestmentSubmission::create([
'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id,
'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1,
'payload' => ['simple_participation' => true, 'opportunity_title' => $opportunity?->title ?? $business?->title, 'opportunity_reference' => $opportunity?->reference, 'phone' => $validated['phone'] ?? null, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null, 'full_name' => $validated['fullName'], 'email' => $validated['email'],
'objective' => $validated['message'], 'sector' => $validated['sectorInterest'],
'country' => $validated['country'], 'existing_business_id' => $business?->id,
'modality' => $validated['modality'] ?? null],
]);
\Illuminate\Support\Facades\DB::table('investment_submission_events')->insert([
'submission_id' => $row->id, 'actor_id' => $request->user()->id,
'action' => 'submitted', 'version' => 1, 'created_at' => now(),
]);
$interest->forceFill(['metadata' => [...$interest->metadata, 'submission_id' => $row->id]])->save();
return $interest;
});
@@ -85,7 +99,8 @@ class InterestRequestController extends Controller
'message' => 'Manifestação de interesse registada com sucesso.',
'data' => [
'reference' => $interestRequest->reference,
'status' => 'received',
'status' => $interestRequest->status,
'tracking_url' => '/investidor/manifestacoes',
],
], 201);
} catch (IdempotencyConflict) {
@@ -36,6 +36,7 @@ class OpportunityController extends Controller
$term = $validated['q'];
$query->where(fn ($q) => $q
->whereLike('title', "%{$term}%")
->orWhereLike('description', "%{$term}%")
->orWhereLike('summary', "%{$term}%")
->orWhereLike('reference', "%{$term}%")
->orWhereLike('province', "%{$term}%")
@@ -54,7 +55,7 @@ class OpportunityController extends Controller
}
if (! empty($validated['maturity_level'])) {
$query->where('maturity_level', $validated['maturity_level']);
\App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
}
$results = $query->orderByDesc('is_featured')
@@ -37,11 +37,17 @@ class SimulationController extends Controller
$token = $actorId === null ? $request->header('X-Simulation-Token') : null;
abort_if($actorId === null && (! is_string($token) || strlen($token) < 32 || strlen($token) > 256), 422, 'X-Simulation-Token opaco gerado pelo cliente é obrigatório para execução anónima.');
$validated = $request->validated();
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
'reduction' => (string) ($validated['reduction'] ?? '0'), 'organization_id' => $validated['organization_id'] ?? null];
$organizationId = $data['organization_id'] ?? null;
$organizationId = $validated['organization_id'] ?? null;
$execution->authorizeOrganization($actorId, $organizationId);
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
if (($validated['scenario_kind'] ?? null) === 'fiscal_rule_published') {
$input = array_intersect_key($validated, array_flip(['base', 'currency', 'reference_date', 'operation', 'scope_declared']));
$input['scope_declared'] = (bool) $input['scope_declared'];
$result = $execution->createPublishedFiscal($input, $actorId, $organizationId, $token, $key);
} else {
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
'reduction' => (string) ($validated['reduction'] ?? '0')];
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
}
$simulation = $result['simulation'];
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
if ($actorId === null) {
@@ -19,13 +19,15 @@ class SimulationTaxParameterController extends Controller
$input['period_start'],
$input['period_end'],
$input['context'] ?? [],
$input['component'] === 'IVA',
);
return response()->json([
'component' => $input['component'],
'period' => ['start' => $input['period_start'], 'end' => $input['period_end']],
'assumptions' => $input['context'] ?? [],
'parameters' => $data,
'parameters' => $input['component'] === 'IVA' ? $data['parameters'] : $data,
'diagnostics' => $input['component'] === 'IVA' ? $data['diagnostics'] : [],
])->header('Cache-Control', 'no-store');
}
}
@@ -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),
@@ -27,6 +27,7 @@ class InvestmentDiscoveryController extends Controller
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'guides' => app(\App\Services\SectorInvestment::class)->guides(\App\Models\Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
'territorial' => $this->territorial($filters)]);
@@ -53,7 +54,7 @@ class InvestmentDiscoveryController extends Controller
if (! empty($filters['geo_location_id'])) {
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, app(InvestmentGeography::class)->descendants($filters['geo_location_id']));
}
foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) {
foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation'] as $field) {
if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) {
return $query->whereRaw('false')->get();
}
@@ -75,9 +76,9 @@ class InvestmentDiscoveryController extends Controller
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString());
}
public function references(InvestmentCatalogue $catalogue): JsonResponse
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
{
return response()->json($catalogue->references());
return response()->json($catalogue->references(false, $catalogue->filters($request)));
}
public function detail(Request $request, string $slug, InvestmentCatalogue $catalogue): Response
@@ -106,6 +107,7 @@ class InvestmentDiscoveryController extends Controller
unset($returnFilters['zone_id'], $returnFilters['from_dossier']);
return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin,
'guides' => app(\App\Services\SectorInvestment::class)->guides($record->sector),
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]);
}
@@ -131,7 +133,7 @@ class InvestmentDiscoveryController extends Controller
{
$filters = $catalogue->filters($request);
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
$zoneFilters = $filters;
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
@@ -40,6 +40,7 @@ class InvestmentLegalSourceController extends Controller
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
return DB::transaction(function () use ($request, $id, $action, $data) {
DB::select('select pg_advisory_xact_lock(261022, hashtext(?))', [$id]);
$source = InvestmentLegalSource::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $source->version_no !== (int) $data['version_no'], 409, 'Versão alterada.');
if ($action === 'validate') {
@@ -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);
}
@@ -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',
@@ -0,0 +1,46 @@
<?php
namespace App\Http\Controllers;
use App\Models\InvestmentLegalSource;
use App\Services\SimulationTaxGovernanceAccess;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/** Explicit fiscal curation of an identified official source; not an independent legal opinion. */
final class SimulationFiscalSourceController extends Controller
{
public function store(Request $request): JsonResponse
{
SimulationTaxGovernanceAccess::requireRole($request->user(), 'editors');
$data = $request->validate([
'title' => ['required', 'string', 'max:255'], 'url' => ['required', 'url:https', 'max:2000'],
'diploma' => ['required', 'string', 'max:255'], 'article' => ['required', 'string', 'max:255'],
'competent_entity' => ['required', 'string', 'max:255'], 'valid_from' => ['required', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
'sha256' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
'citation' => ['required', 'string', 'min:10', 'max:2000'],
'official_origin' => ['required', 'string', 'min:10', 'max:2000'],
]);
return DB::transaction(function () use ($request, $data): JsonResponse {
$actor = $request->user();
$acceptance = ['scope' => 'fiscal_parameters', 'basis' => 'Tempo-official-sources-20261008',
'responsible_user_id' => $actor->id, 'sha256' => $data['sha256'], 'citation' => $data['citation'],
'official_origin' => $data['official_origin'], 'accepted_at' => now()->toISOString(),
'legal_opinion' => false, 'independent_review' => false];
unset($data['sha256'], $data['citation'], $data['official_origin']);
$source = InvestmentLegalSource::create([...$data, 'owner_id' => $actor->id, 'validator_id' => null,
'validation_status' => 'pending', 'validated_at' => null, 'version_no' => 1, 'fiscal_acceptance' => $acceptance]);
DB::table('audit_events')->insert(['source_system' => 'simulation-fiscal-maintenance',
'entity_type' => 'investment_legal_sources', 'entity_id' => $source->id, 'actor_user_id' => $actor->id,
'action' => 'official_source_acceptance', 'after_data' => json_encode([
'source' => $source->attributesToArray(), 'basis' => $acceptance,
'sha256' => hash('sha256', $source->toJson()),
], JSON_THROW_ON_ERROR)]);
return response()->json($source->fresh(), 201);
});
}
}
@@ -2,17 +2,51 @@
namespace App\Http\Controllers;
use App\Services\SimulationFiscalQaPreview;
use App\Services\SimulationTaxParameterResolver;
use App\Services\SimulationTaxRuleExpression;
use App\Services\SimulationTaxRuleGovernance;
use App\Support\IsolatedQaDatabase;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use InvalidArgumentException;
class SimulationTaxRuleGovernanceController extends Controller
{
public function qaReview(Request $request, string $id, SimulationTaxRuleGovernance $governance): Response
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
$rule = $governance->show($request->user(), $id);
abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422,
'Seleccione o rascunho do primeiro lote fiscal.');
return Inertia::render('management/fiscal-qa-review', ['rule' => [
'id' => $rule->id, 'code' => $rule->rule_code, 'version' => $rule->rule_version,
]]);
}
public function qaPreview(Request $request, string $id, SimulationFiscalQaPreview $preview): JsonResponse
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
$key = $request->header('Idempotency-Key');
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
$input = $request->validate([
'base' => ['required', 'string', 'max:40', 'regex:/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/D'],
'reference_date' => ['required', 'date_format:Y-m-d'],
'currency' => ['required', 'in:MZN'],
'operation' => ['required', 'in:internal_general_net'],
]);
$result = $preview->create($request->user(), $id, $input, $key);
$simulation = $result['simulation'];
return response()->json(['data' => $simulation, 'replayed' => $result['replayed']], $result['replayed'] ? 200 : 202)
->header('Location', url('/api/v1/simulations/'.$simulation->id));
}
public function index(Request $request, SimulationTaxRuleGovernance $governance): JsonResponse
{
$filters = $request->validate([
+24 -7
View File
@@ -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,39 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use App\Services\ScopedPortalAdministration;
use App\Services\SimulationTaxGovernanceAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
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/*');
// Fiscal maintenance reuses authorised administration; unrelated gates remain unchanged.
$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');
$fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*',
'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*');
$allowed = ($fiscal && SimulationTaxGovernanceAccess::maintainer($actor)) || ($interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor)));
abort_unless($allowed || ($actor->can('manage-portal') && ! app(PortalProfileAccess::class)->has($actor, 'auditor')), 403, 'Acesso reservado ao âmbito já designado.');
$response = $next($request);
if (! $request->isMethod('GET') && $response->getStatusCode() < 400) {
app(PortalProfileAccess::class)->audit($actor, 'scoped_administration', [
'method' => $request->method(), 'route' => $request->route()?->uri(), 'scope' => $fiscal ? 'fiscal-maintenance' : ($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);
}
}
@@ -21,7 +21,7 @@ class ResolveSimulationTaxParametersRequest extends FormRequest
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
'period_start' => ['required', 'date_format:Y-m-d'],
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
'context' => ['sometimes', 'array:fiscal_periodicity,fiscal_operation,fiscal_residency_assessment,fiscal_residency_country,fiscal_income_category,fiscal_establishments,fiscal_documentation,fiscal_customs_code,fiscal_vat_refund_state'],
'context' => ['sometimes', 'array:currency,fiscal_periodicity,fiscal_operation,fiscal_residency_assessment,fiscal_residency_country,fiscal_income_category,fiscal_establishments,fiscal_documentation,fiscal_customs_code,fiscal_vat_refund_state'],
'context.*' => ['string', 'max:160'],
];
}
@@ -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',
@@ -37,7 +37,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
'contact_province', 'contact_district', 'preferred_channel',
];
$economic = [
'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'cashflow_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'location_rationale', 'project_risk_responses_snapshot', 'project_questionnaire_version',
'customer_validation_status', 'cost_estimate_status', 'location_assessment_status', 'funding_status', 'receivables_timing_status',
'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date',
@@ -50,7 +50,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
'environmental_category', 'community_benefits', 'tax_calculation', 'fiscal_scenario_mode', 'base', 'rate', 'reduction',
'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs', 'non_deductible_costs',
'carried_losses', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'reference_date',
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment',
'fiscal_currency', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment',
'fiscal_operation', 'fiscal_activity', 'fiscal_establishments', 'fiscal_documentation',
'fiscal_customs_code', 'fiscal_vat_refund_state',
'offer_or_demand', 'opportunity_type', 'opportunity_type_other', 'opportunity_description',
@@ -71,6 +71,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
'economic_snapshot.detail_level' => ['nullable', 'in:simple,advanced'],
'economic_snapshot.business_plan_snapshot' => ['nullable', 'string', 'max:60000'],
'economic_snapshot.financial_tools_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.cashflow_snapshot' => ['nullable', 'string', 'max:20000'],
'economic_snapshot.project_team_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_execution_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_risk_responses_snapshot' => ['nullable', 'string', 'max:30000'],
@@ -278,7 +279,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'fiscal_scenario_mode', 'offer_or_demand',
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment', 'fiscal_operation',
'fiscal_currency', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment', 'fiscal_operation',
'fiscal_documentation', 'fiscal_vat_refund_state'],
'personal_snapshot.selection_labels' => ['person_type', 'investor_origin', 'tax_residency_country', 'fiscal_residency_country', 'entity_stage', 'legal_form', 'preferred_channel'],
];
@@ -11,10 +11,47 @@ class StoreSimulationRequest extends FormRequest
return true;
}
public function messages(): array
{
return [
'required' => 'Preencha o campo :attribute. As entradas foram preservadas.',
'string' => 'Indique :attribute em formato textual.',
'regex' => 'Indique uma base decimal positiva ou zero, com ponto decimal e sem separadores de milhares.',
'max' => 'O campo :attribute excede o tamanho permitido.',
'in' => 'A opção indicada em :attribute não pertence a este cálculo.',
'date_format' => 'Indique uma data de exigibilidade válida.',
'boolean' => 'Indique se declara o enquadramento da operação.',
'prohibited' => 'O campo :attribute não pode ser definido pelo cliente neste cálculo.',
];
}
public function attributes(): array
{
return ['base' => 'base tributável', 'currency' => 'moeda', 'reference_date' => 'data de exigibilidade',
'operation' => 'operação', 'scope_declared' => 'declaração de enquadramento', 'scenario_kind' => 'tipo de cálculo',
'rule_id' => 'regra', 'rule_version' => 'versão da regra', 'rate' => 'taxa', 'reduction' => 'redução'];
}
/** @return array<string, list<mixed>> */
public function rules(): array
{
if ($this->input('scenario_kind') === 'fiscal_rule_published') {
return [
'scenario_kind' => ['required', 'in:fiscal_rule_published'],
'base' => ['required', 'string', 'max:40', 'regex:/^\d+(?:\.\d+)?$/'],
'currency' => ['required', 'in:MZN'],
'reference_date' => ['required', 'date_format:Y-m-d'],
'operation' => ['required', 'in:internal_general_net'],
'scope_declared' => ['required', 'boolean'],
'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'],
'rate' => ['prohibited'], 'reduction' => ['prohibited'],
'rule_id' => ['prohibited'], 'rule_version' => ['prohibited'],
'fiscal_preview' => ['prohibited'],
];
}
return [
'scenario_kind' => ['sometimes', 'in:custom_planning'],
'base' => ['required', 'numeric', 'min:0'],
'rate' => ['required', 'numeric', 'between:0,100'],
'reduction' => ['required', 'numeric', 'between:0,100'],
+47 -22
View File
@@ -4,6 +4,7 @@ namespace App\Jobs;
use App\Models\Simulation;
use App\Services\SimulationExecution;
use App\Support\IsolatedQaDatabase;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -62,29 +63,39 @@ class RunSimulation implements ShouldQueue
throw new \RuntimeException('Simulation has no scenario.');
}
$input = json_decode($scenario->parameters, true, flags: JSON_THROW_ON_ERROR);
$row = DB::selectOne('select (CAST(? AS numeric) * CAST(? AS numeric) / 100 * (1 - CAST(? AS numeric) / 100))::text as value', [$input['base'], $input['rate'], $input['reduction']]);
$resultId = (string) Str::uuid();
$engineVersion = 'portal-arithmetic-v1+simulation-v'.$simulation->version_no;
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'scenario_kind' => 'custom_planning', 'indicative_total' => $row->value,
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
'contract_version' => 1,
'context' => [
'reference_date' => substr((string) $scenario->created_at, 0, 10),
'currency' => null,
'currency_fraction_digits' => null,
'scenario_id' => (string) $scenario->id,
'scenario_version' => (int) $scenario->version_no,
'engine_version' => $engineVersion,
'ruleset_version' => null,
],
'result' => [
'status' => 'calculated',
'value' => (string) $row->value,
'unit' => null,
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
'missing_inputs' => [],
'source_ids' => [],
]];
if (in_array($input['scenario_kind'] ?? null, ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true)) {
if ($input['scenario_kind'] === 'fiscal_rule_qa_preview') {
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
}
$result = $input['fiscal_preview'];
$engineVersion = $result['context']['engine_version'];
$result['context']['scenario_id'] = (string) $scenario->id;
$result['context']['scenario_version'] = (int) $scenario->version_no;
} else {
$row = DB::selectOne('select (CAST(? AS numeric) * CAST(? AS numeric) / 100 * (1 - CAST(? AS numeric) / 100))::text as value', [$input['base'], $input['rate'], $input['reduction']]);
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'scenario_kind' => 'custom_planning', 'indicative_total' => $row->value,
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
'contract_version' => 1,
'context' => [
'reference_date' => substr((string) $scenario->created_at, 0, 10),
'currency' => null,
'currency_fraction_digits' => null,
'scenario_id' => (string) $scenario->id,
'scenario_version' => (int) $scenario->version_no,
'engine_version' => $engineVersion,
'ruleset_version' => null,
],
'result' => [
'status' => 'calculated',
'value' => (string) $row->value,
'unit' => null,
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
'missing_inputs' => [],
'source_ids' => [],
]];
}
$json = json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
$resultHash = hash('sha256', $canonicalResult);
@@ -96,11 +107,25 @@ class RunSimulation implements ShouldQueue
DB::table('simulation_jobs')->where('id', $job->id)->update(['status' => 'succeeded', 'finished_at' => now(), 'updated_at' => now()]);
DB::table('simulation_reports')->insert(['id' => (string) Str::uuid(), 'simulation_id' => $simulation->id, 'version_no' => $scenario->version_no,
'status' => 'ready', 'report_snapshot' => $json, 'report_sha256' => $resultHash, 'created_at' => now(), 'updated_at' => now()]);
$sourceJson = json_encode($input, JSON_THROW_ON_ERROR);
$sourceJson = json_encode(isset($result['fiscal_provenance']) ? [
'base' => $result['base'], 'currency' => $result['currency'],
'reference_date' => $result['context']['reference_date'],
'context' => $result['fiscal_provenance']['context'], 'scope_status' => $result['fiscal_provenance']['scope_status'],
] : $input, JSON_THROW_ON_ERROR);
$canonicalSource = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$sourceJson])->canonical;
DB::table('simulation_result_sources')->insertOrIgnore(['id' => (string) Str::uuid(), 'result_id' => $resultId,
'source_type' => 'user_input', 'source_id' => $scenario->id, 'source_version' => (string) $scenario->version_no,
'source_snapshot' => $sourceJson, 'source_sha256' => hash('sha256', $canonicalSource), 'created_at' => now()]);
if (isset($result['fiscal_provenance'])) {
$provenance = $result['fiscal_provenance'];
$provenanceJson = json_encode($provenance, JSON_THROW_ON_ERROR);
$canonicalProvenance = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$provenanceJson])->canonical;
DB::table('simulation_result_sources')->insert([
'id' => (string) Str::uuid(), 'result_id' => $resultId, 'source_type' => $input['scenario_kind'] === 'fiscal_rule_published' ? 'tax_rule_published' : 'tax_rule_draft',
'source_id' => $provenance['rule']['id'], 'source_version' => (string) $provenance['rule']['rule_version'],
'source_snapshot' => $provenanceJson, 'source_sha256' => hash('sha256', $canonicalProvenance), 'created_at' => now(),
]);
}
DB::table('simulation_audit_events')->insert(['simulation_id' => $simulation->id, 'actor_user_id' => $simulation->owner_user_id,
'action' => 'simulation.completed', 'correlation_id' => $simulation->id, 'data' => json_encode(['result_sha256' => hash('sha256', $json), 'attempt' => $job->attempts + 1], JSON_THROW_ON_ERROR), 'occurred_at' => now()]);
}, 3);
+5
View File
@@ -16,4 +16,9 @@ class InvestmentLegalSource extends Model
use HasUuids;
protected $guarded = ['id'];
protected function casts(): array
{
return ['fiscal_acceptance' => 'array'];
}
}
+7 -6
View File
@@ -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;
}
}
+11 -4
View File
@@ -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 = [];
+6 -4
View File
@@ -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 : '';
+86
View File
@@ -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.');
+9 -1
View File
@@ -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;
}
}
+1
View File
@@ -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
+89 -11
View File
@@ -18,6 +18,7 @@ class InvestmentCatalogue
public function filters(Request $request): array
{
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
'opportunity_id' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
@@ -40,6 +41,17 @@ class InvestmentCatalogue
'publication_state' => ['nullable', 'in:published'],
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
app(InvestmentGeography::class)->selection($filters);
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
throw \Illuminate\Validation\ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
}
if (\Illuminate\Support\Str::isUuid($filters['association_target'])) {
$filters[$alias] = $filters['association_target'];
unset($filters['association_type'], $filters['association_target']);
}
}
return $filters;
}
@@ -51,6 +63,7 @@ class InvestmentCatalogue
public function query(array $filters): Builder
{
$query = Opportunity::published()->with('sector:id,name,slug');
$associated = $this->publicAssociatedIds($filters);
if (($filters['territory_basis'] ?? 'all') === 'direct') {
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
} elseif (($filters['territory_basis'] ?? 'all') === 'context') {
@@ -92,15 +105,17 @@ class InvestmentCatalogue
}
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) {
if (! empty($filters[$field])) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()
$legacy = app(InvestmentZones::class)->links()->where('zl.association_type', '<>', 'proximity')
->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $category)
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id'));
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id');
$query->where(fn ($matches) => $matches->whereIn('opportunities.id', $legacy)
->orWhereIn('opportunities.id', $associated[$field] ?? []));
}
}
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('description', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term))
->orWhereExists(fn ($g) => $g->selectRaw('1')->from('geo_locations as search_location')->whereNull('search_location.deleted_at')->where('search_location.data_classification', 'public')
->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
@@ -116,11 +131,21 @@ class InvestmentCatalogue
if (! empty($filters['sector'])) {
SectorOrganization::constrain($query, $filters['sector']);
}
foreach (['province', 'district', 'maturity_level'] as $field) {
foreach (['province', 'district'] as $field) {
if (! empty($filters[$field])) {
$query->where($field, $filters[$field]);
}
}
if (! empty($filters['preparation'])) {
OpportunityMaturity::constrainSearch($query, $filters['preparation']);
} elseif (! empty($filters['maturity_level'])) {
// Legacy links predate the eight-stage catalogue: retain their original meaning.
OpportunityMaturity::constrainSearch($query, match ((int) $filters['maturity_level']) {
7 => 'stage:implementation',
8 => 'stage:operational',
default => 'historical:'.$filters['maturity_level'],
});
}
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
if (! empty($filters[$foreign])) {
$locationIds = $relation === 'locations'
@@ -141,13 +166,15 @@ class InvestmentCatalogue
continue;
}
if (in_array($relation, ['clusters', 'corridors'], true)) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
$query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)));
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)))
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
} else {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
$query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)));
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)))
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
}
}
}
@@ -187,7 +214,9 @@ class InvestmentCatalogue
* @return array<string,mixed> */
public function references(bool $management = false, array $territoryFilters = []): array
{
$path = app(InvestmentGeography::class)->selection($territoryFilters);
$result = ['classification' => app(OpportunityClassification::class)->options(),
'preparationOptions' => OpportunityMaturity::searchOptions(),
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
'categories' => OpportunityManagement::CATEGORIES,
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
@@ -205,18 +234,67 @@ class InvestmentCatalogue
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
}
}
if (! $management && $path !== [] && $relation !== 'locations') {
$dossiers = InvestmentPortfolioController::visible();
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
$query->whereIn('id', $dossiers->whereNotNull($foreign)->select($foreign));
}
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
}
$zones = app(InvestmentZones::class)->visible();
if (! $management && $territoryFilters !== []) {
$zones = app(InvestmentZones::class)->search($territoryFilters);
// Opportunity words/modalities are not names/categories of zones.
$zones = app(InvestmentZones::class)->search(\Illuminate\Support\Arr::only($territoryFilters,
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
}
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
if (! $management && ($path !== [] || ! empty($territoryFilters['sector']))) {
$scope = \Illuminate\Support\Arr::only($territoryFilters, ['sector','province_id','district_id','admin_post_id','locality_id','include_national']);
$available = ['chain' => [], 'activity' => []];
$this->query($scope)->reorder()->chunkById(200, function ($records) use (&$available) {
foreach ($records as $record) {
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
if (isset($available[$row['target_type']])) $available[$row['target_type']][] = $row['target_id'];
}
foreach (['subsector_id','economic_activity_id'] as $key) {
$id = $record->workflow_context['publication']['taxonomy'][$key] ?? null;
if ($id) $available['activity'][] = $id;
}
}
}, 'opportunities.id', 'id');
foreach ($available as $kind => $ids) {
$result['classification']['targets'][$kind] = collect($result['classification']['targets'][$kind])->whereIn('id', $ids)->values();
}
}
return $result;
}
private function publicAssociatedIds(array $filters): array
{
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
$selected = array_filter(array_intersect_key($filters, $kinds));
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) unset($selected[$key]);
}
if ($selected === []) return [];
$ids = [];
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
foreach ($records as $record) {
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') continue;
foreach ($selected as $field => $target) {
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) $ids[$field][] = $record->id;
}
}
}
});
return $ids;
}
private function publicStructureIds(string $relation, string $foreign): \Illuminate\Database\Query\Builder
{
$table = self::RELATIONS[$relation][1];
@@ -329,11 +407,11 @@ class InvestmentCatalogue
DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'território declarado da oportunidade' ELSE 'contexto do projeto associado; implantação da oportunidade por confirmar' END AS basis")])
->map(fn ($area) => ['geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')',
'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null,
'url' => '/oportunidades/'.$area->slug])->all();
'url' => '/oportunidades/'.$area->slug.($filters === [] ? '' : '?'.http_build_query($filters))])->all();
$located = 0;
foreach ($records as $record) {
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug];
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
foreach ($relations as $relation => $groups) {
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
}
@@ -26,7 +26,7 @@ class InvestmentZoneOperationalDetailsInstallation
}
private function authorize(User $actor,bool $write=false): void
{
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
}
private function evidence(array $target,string $code): array
@@ -31,7 +31,7 @@ class InvestmentZoneProfileInstallation
}
private function authorize(User $actor,bool $write=false): void
{
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
}
private function evidence(array $target,string $code): array
+20 -4
View File
@@ -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'];
+69 -8
View File
@@ -35,12 +35,12 @@ final class LegacyContent
}
/** @return array<string, mixed> */
public function article(string $slug = 'agronegocio'): array
public function article(string $slug = 'agronegocio', bool $includeRelated = true): array
{
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();
@@ -80,13 +80,26 @@ final class LegacyContent
}
preg_match_all('~href="([^"]+)"~i', $localHtml, $existingLinks);
$alreadyLinked = array_map(fn ($href) => html_entity_decode($href, ENT_QUOTES | ENT_HTML5, 'UTF-8'), $existingLinks[1]);
$relatedArticles = array_values(array_filter($this->related($identity['group'], $slug), fn ($item) => !in_array($item['href'], $alreadyLinked, true)));
$relatedArticles = [];
if ($includeRelated) {
foreach ($this->related($identity['group'], $slug) as $item) {
if (in_array($item['href'], $alreadyLinked, true)) continue;
try {
$relatedArticles[] = $this->article($item['slug'], false);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $error) {
if ($error->getStatusCode() !== 404) throw $error;
}
}
}
return ['id' => (int) $row->resource_id, 'document_id' => $row->id, 'version' => (int) $row->metadata_version,
'sha256' => trim($row->sha256), 'title' => $source['title'], 'author' => $source['author'],
'legacy_id' => $source['legacy_id'], 'legacy_category' => $source['legacy_category'],
'published_at' => $source['published_at'], 'modified_at' => $source['modified_at'], 'source_url' => $source['source_url'],
'href' => '/'.$slug, 'html' => $localHtml,
'href' => '/'.$slug, 'html' => $localHtml, 'summary' => self::excerpt($localHtml),
'opportunities_href' => $sector ? '/oportunidades?sector='.rawurlencode($sector->slug) : null,
'opportunities_label' => $sector ? 'Ver oportunidades de '.$sector->name : null,
'has_opportunities' => count($opportunities) > 0,
'landing_href' => '/explorar/'.$identity['group'], 'start_href' => '/investimentos/a-partir-de/'.$slug,
'group' => config('legacy_content.groups.'.$identity['group']),
'related_articles' => $relatedArticles,
@@ -101,12 +114,28 @@ final class LegacyContent
'consultation_state' => 'public', 'legal_state' => 'not_applicable', 'calculation_use' => false];
}
/** An excerpt of the displayed edition, never a claim about returns or availability. */
public static function excerpt(string $html): string
{
$plain = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
if (str_contains($plain, 'Hotelaria e resorts') && str_contains($plain, 'Ecoturismo')
&& str_contains($plain, 'Infraestruturas turísticas') && str_contains($plain, 'Oportunidades Regionais')) {
return 'Conheça os temas de turismo e hospitalidade abordados no guia: hotelaria, ecoturismo, infraestruturas de apoio e referências regionais. Use este enquadramento para preparar a sua ideia de investimento.';
}
preg_match_all('~<p\b[^>]*>(.*?)</p>~isu', $html, $paragraphs);
foreach ([...($paragraphs[1] ?? []), $html] as $paragraph) {
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($paragraph), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
if (mb_strlen($text) >= 60) return \Illuminate\Support\Str::limit($text, 320);
}
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
}
/** Resolve a library identity, preserving the already stored source URLs and versions. */
/** @return array<string, mixed> */
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 +161,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 +175,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 +236,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')
+14 -5
View File
@@ -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.');
}
+24 -9
View File
@@ -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'));
+7 -2
View File
@@ -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.');
}
+1 -1
View File
@@ -383,7 +383,7 @@ class OpportunityClassification
$matches = $matches && collect($rows)->contains(fn ($r) => $r['authority_id'] === $filters['authority_id']);
}
if (! empty($filters['subsector_id'])) {
$matches = $matches && (($record->workflow_context['publication']['taxonomy']['subsector_id'] ?? '') === $filters['subsector_id'] || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
$matches = $matches && (in_array($filters['subsector_id'], array_intersect_key($record->workflow_context['publication']['taxonomy'] ?? [], array_flip(['subsector_id','economic_activity_id'])), true) || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
}
if ($matches) {
$ids[] = $record->id;
+1 -1
View File
@@ -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.';
}
}
}
}
+100
View File
@@ -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();
}
}
+26
View File
@@ -24,6 +24,32 @@ final class OpportunityMaturity
public const LEGACY_LABELS = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
/** Public selection is explicit; historical numbers never stand for current stages. */
public static function searchOptions(): array
{
$options = [];
foreach (self::STAGES as $code => $label) {
$options[] = ['value' => 'stage:'.$code, 'label' => $label, 'group' => 'Etapas de preparação'];
}
foreach (self::LEGACY_LABELS as $level => $label) {
$options[] = ['value' => 'historical:'.$level, 'label' => $label.' — registo histórico', 'group' => 'Classificações históricas'];
}
return $options;
}
public static function constrainSearch(\Illuminate\Database\Eloquent\Builder $query, string $selection): void
{
[$kind, $value] = explode(':', $selection, 2);
if ($kind === 'stage') {
$query->where('workflow_context->publication->maturity->catalogue_version', self::VERSION)
->where('workflow_context->publication->maturity->stage', $value);
} else {
$query->where(fn ($q) => $q->where('workflow_context->publication->maturity->catalogue_version', self::LEGACY)
->orWhere(fn ($old) => $old->whereNull('workflow_context->publication->maturity->catalogue_version')->whereNull('workflow_context->publication->maturity->stage')))
->where('maturity_level', (int) $value);
}
}
/** @param array<string,mixed> $data
* @return array<string,mixed> */
public function normalize(array $data): array
+9
View File
@@ -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];
}
}
+19 -5
View File
@@ -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());
}
}
+21 -13
View File
@@ -37,19 +37,7 @@ final class SectorInvestment
public function publicView(Sector $sector): array
{
$query = SectorOrganization::opportunities($sector);
$articles = [];
if (app(LegacyContent::class)->available()) {
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
try {
$a = app(LegacyContent::class)->article($slug);
$articles[] = ['title' => $a['title'], 'href' => $a['href'], 'image' => $a['image'], 'sha256' => $a['sha256'], 'scope' => $slug === 'tech-fintech' && $sector->slug !== 'fintech' ? 'Especialização Fintech; não representa todo o setor.' : 'Conteúdo educativo relacionado; não é uma oportunidade concreta.'];
} catch (HttpException $e) {
if ($e->getStatusCode() !== 404) {
throw $e;
}
}
}
}
$articles = $this->guides($sector);
$relations = [];
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $table => $foreign) {
$ids = DB::table('opportunity_'.$table)->whereIn('opportunity_id', (clone $query)->select('id'))->pluck($foreign);
@@ -74,6 +62,26 @@ final class SectorInvestment
'content_notice' => $sector->slug === 'mercado-financeiro' ? 'O artigo geral de Mercado Financeiro permanece vazio e não foi publicado. A preparação de negócios neste setor está disponível.' : null];
}
/** Published guides for an explicit sector; never inferred from proximity. */
public function guides(?Sector $sector): array
{
if (! $sector) return [];
$articles = [];
if (app(LegacyContent::class)->available()) {
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
try {
$a = app(LegacyContent::class)->article($slug, false);
$articles[] = \Illuminate\Support\Arr::only($a, ['title', 'href', 'image', 'sha256', 'summary', 'author', 'opportunities_href', 'opportunities_label', 'has_opportunities']);
} catch (HttpException $e) {
if ($e->getStatusCode() !== 404) {
throw $e;
}
}
}
}
return $articles;
}
public function attach(User $actor, string $id, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'sector_slug' => 'required|string|max:150'])->validate();
+39 -6
View File
@@ -4,6 +4,7 @@ namespace App\Services;
use App\Jobs\RunSimulation;
use App\Models\Simulation;
use App\Support\IsolatedQaDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -17,15 +18,39 @@ final class SimulationExecution
*/
public function create(array $data, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
{
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
$scope = $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous');
$scopeHash = hash('sha256', $scope);
$keyHash = hash('sha256', strtolower($key));
$payload = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction'], 'scenario_kind' => 'custom_planning', 'organization_id' => $organizationId];
return $this->createPayload($payload, $actorId, $organizationId, $token, $key);
}
public function createFiscalQaPreview(array $snapshot, int $actorId, string $key): array
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
abort_unless(($snapshot['scenario_kind'] ?? null) === 'fiscal_rule_qa_preview'
&& in_array($snapshot['result']['status'] ?? null, ['calculated', 'indeterminate'], true)
&& ($snapshot['presentation']['rounding_applied'] ?? null) === false, 422);
return $this->createPayload(['scenario_kind' => 'fiscal_rule_qa_preview', 'fiscal_preview' => $snapshot, 'organization_id' => null],
$actorId, null, null, $key);
}
public function createPublishedFiscal(array $input, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
{
$payload = ['scenario_kind' => 'fiscal_rule_published', 'fiscal_input' => $input, 'organization_id' => $organizationId];
return $this->createPayload($payload, $actorId, $organizationId, $token, $key,
fn (): array => app(SimulationPublishedFiscal::class)->admit($input));
}
private function createPayload(array $payload, ?int $actorId, ?string $organizationId, ?string $token, string $key, ?callable $admit = null): array
{
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
$scopeHash = hash('sha256', $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous'));
$keyHash = hash('sha256', strtolower($key));
ksort($payload);
$payloadHash = hash('sha256', json_encode($payload, JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actorId, $organizationId, $token, $tokenHash, $scopeHash, $keyHash, $payloadHash, $payload): array {
return DB::transaction(function () use ($actorId, $organizationId, $token, $tokenHash, $scopeHash, $keyHash, $payloadHash, $payload, $admit): array {
$this->setContext($actorId, $tokenHash);
DB::select('select pg_advisory_xact_lock(261001, hashtext(?))', [$scopeHash.$keyHash]);
$receipt = DB::table('simulation_idempotency')->where('scope_hash', $scopeHash)->where('key_hash', $keyHash)->first();
@@ -37,6 +62,10 @@ final class SimulationExecution
return ['simulation' => Simulation::with(['scenarios', 'reports'])->whereKey((string) $receipt->simulation_id)->firstOrFail(), 'token' => null, 'replayed' => true];
}
if ($admit !== null) {
$payload['fiscal_preview'] = $admit();
}
$plainToken = $actorId === null ? $token : null;
$tokenHash = $actorId === null ? hash_hmac('sha256', $plainToken, (string) config('app.key')) : null;
$this->setContext($actorId, $tokenHash);
@@ -44,7 +73,9 @@ final class SimulationExecution
$simulation = Simulation::create([
'id' => $id, 'questionnaire_version_id' => '61000100-0000-4000-8000-000000000001', 'owner_user_id' => $actorId, 'organization_id' => $organizationId,
'anonymous_token_hash' => $tokenHash, 'status' => 'queued', 'version_no' => 1,
'input_snapshot' => $payload, 'calculation_snapshot' => ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
'input_snapshot' => $payload, 'calculation_snapshot' => in_array($payload['scenario_kind'], ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true)
? ['engine' => $payload['fiscal_preview']['context']['engine_version'], 'mode' => $payload['fiscal_preview']['fiscal_provenance']['mode'], 'arithmetic' => 'exact_decimal_no_rounding']
: ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
]);
$scenarioId = (string) Str::uuid();
DB::table('simulation_scenarios')->insert([
@@ -85,6 +116,8 @@ final class SimulationExecution
return DB::transaction(function () use ($id, $scenarioId, $data, $request): Simulation {
$this->setContext($request->user()?->id, $this->tokenHash($request));
$simulation = Simulation::whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
abort_if(in_array($simulation->input_snapshot['scenario_kind'] ?? null, ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true), 422,
'Crie uma nova pré-visualização fiscal; este snapshot conserva a regra e as entradas originais.');
$this->requireMatch($request, $simulation);
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $id)->where('id', $scenarioId)->lockForUpdate()->first();
abort_if($scenario === null, 404);
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\InvestmentLegalSource;
use App\Models\User;
use App\Support\IsolatedQaDatabase;
use Illuminate\Support\Facades\DB;
/** Exact operation-level IVA calculation against an explicit QA draft; never a payment/return total. */
final class SimulationFiscalQaPreview
{
public function create(User $actor, string $ruleId, array $input, string $key): array
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
return DB::transaction(function () use ($actor, $ruleId, $input, $key): array {
$rule = app(SimulationTaxRuleGovernance::class)->show($actor, $ruleId);
abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422,
'Seleccione o rascunho do primeiro lote fiscal.');
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
'Este percurso preserva o valor exacto e não aplica arredondamento automático.');
$source = InvestmentLegalSource::findOrFail($rule->legal_source_id);
$version = $rule->attributesToArray();
$version['source'] = $source->attributesToArray();
$date = $input['reference_date'];
$context = ['operation' => $input['operation'], 'currency' => $input['currency']];
$missing = [];
$resolution = [];
$evaluation = null;
if ($date < '2026-01-01' || $date > '2026-12-31') {
$missing[] = 'demonstrated_coverage';
} else {
$resolution = app(SimulationTaxParameterResolver::class)->resolveDraftForQa([$version], 'IVA', $date, $date, $context);
$rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
if (($rate['status'] ?? null) !== 'resolved' || ($rate['unit'] ?? null) !== 'percent') {
$missing[] = 'eligible_parameter';
} else {
$evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition,
['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]);
}
}
$snapshot = app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing);
return app(SimulationExecution::class)->createFiscalQaPreview($snapshot, $actor->id, $key);
});
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Services;
use Brick\Math\BigRational;
/** Shared snapshot representation; eligibility is resolved by each admission adapter. */
final class SimulationFiscalSnapshot
{
public function build(array $version, array $input, array $resolution, ?array $evaluation, array $missing, bool $published = false): array
{
$date = $input['reference_date'];
$context = ['operation' => $input['operation'], 'currency' => $input['currency']];
$exact = ($evaluation['status'] ?? null) === 'determinate'
? (string) BigRational::of($evaluation['result'])->toBigDecimal()
: null;
if ($exact === null && $missing === []) {
$missing = $evaluation['missing'] ?? ['eligible_parameter'];
}
$snapshot = [
'contract_version' => 1, 'scenario_kind' => $published ? 'fiscal_rule_published' : 'fiscal_rule_qa_preview',
'base' => $input['base'], 'currency' => $input['currency'], 'indicative_total' => $exact,
'legal_interpretation' => false, 'formula_version' => 'investmoz.tax.v1',
'context' => [
'reference_date' => $date, 'currency' => $input['currency'], 'currency_fraction_digits' => 2,
'scenario_id' => null, 'scenario_version' => 1, 'engine_version' => $published ? 'fiscal-published-v1' : 'fiscal-draft-preview-v1',
'ruleset_version' => $version['rule_code'].':'.$version['rule_version'],
],
'result' => [
'status' => $exact === null ? 'indeterminate' : 'calculated', 'value' => $exact, 'unit' => 'MZN',
'explanation' => $exact === null
? 'IVA indeterminado: o contexto, a fonte ou o período não permitem resolver o parâmetro deste lote QA.'
: 'IVA calculado com precisão decimal exacta, sem arredondamento. Ensaio QA de regra em rascunho; enquadramento declarado, não validado. Não é saldo de declaração nem valor a pagar.',
'missing_inputs' => $missing, 'source_ids' => [(string) $version['legal_source_id']],
],
'presentation' => ['value' => $exact, 'currency' => $input['currency'], 'rounding_applied' => false, 'purpose' => 'operation_tax_not_payment'],
// Exact rational steps supplement the decimal result; no float conversion.
'intermediate' => $evaluation,
'fiscal_provenance' => [
'mode' => $published ? 'published_version' : 'qa_draft_only', 'scope_status' => ($input['scope_declared'] ?? true) ? 'user_declared' : 'undetermined', 'context' => $context,
'rounding_policy' => $version['rounding_policy'], 'resolution' => $resolution,
'rule' => $version, 'source_acceptance' => 'Fonte oficial aceite pela decisão Tempo de 08/10/2026; não constitui aprovação jurídica desta operação ou publicação da regra.',
],
];
if ($published) {
$snapshot['result']['explanation'] = $exact === null
? 'IVA indeterminado: falta contexto, fonte ou parâmetro elegível para esta operação.'
: 'IVA calculado pela versão publicada identificada, sem arredondamento. Enquadramento declarado, não validado. Não é saldo de declaração nem valor a pagar.';
$snapshot['fiscal_provenance']['admitted_at'] = now()->toISOString();
$snapshot['fiscal_provenance']['source_acceptance'] = 'Fonte oficial aceite pela Tempo em 08/10/2026; não constitui validação jurídica desta operação.';
}
return $snapshot;
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Services;
final class SimulationFiscalSourceAcceptance
{
public static function eligible(array $source, ?string $hash = null): bool
{
if (($source['validation_status'] ?? null) === 'validated') {
return true;
}
$basis = $source['fiscal_acceptance'] ?? null;
return ($source['validation_status'] ?? null) === 'pending' && is_array($basis)
&& ($basis['scope'] ?? null) === 'fiscal_parameters'
&& ($basis['basis'] ?? null) === 'Tempo-official-sources-20261008'
&& preg_match('/^[a-f0-9]{64}$/D', (string) ($basis['sha256'] ?? '')) === 1
&& ($hash === null || $basis['sha256'] === $hash);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Services;
/** Explains a failed selection; never changes answers, eligibility or calculation. */
final class SimulationIvaDiagnostics
{
public function explain(array $versions, string $start, string $end, array $context): array
{
$diagnostics = [];
foreach ($versions as $version) {
$parameter = $version['parameters']['IVA_GENERAL_RATE'] ?? null;
if (! is_array($parameter)) {
continue;
}
$issues = [];
$add = function (string $category, ?string $field, string $label, mixed $received, string $expected, string $message) use (&$issues): void {
$issues[] = compact('category', 'field', 'label', 'received', 'expected', 'message');
};
if ($start < $version['valid_from'] || ($version['valid_until'] !== null && $end > $version['valid_until'])) {
$add('period_unavailable', 'fiscal_period', 'Período', "$start a $end", $version['valid_from'].' a '.($version['valid_until'] ?? 'sem data final indicada'), 'Esta versão da regra não abrange todo o período seleccionado. Não altere a data real da operação para obter um resultado.');
}
foreach ($parameter['conditions'] ?? [] as $key => $expected) {
$received = $context[$key] ?? null;
if ($received === $expected) {
continue;
}
if ($key === 'currency') {
$category = $received === null || $received === '' ? 'missing_field' : (preg_match('/^[A-Z]{3}$/D', $received) ? 'out_of_scope' : 'invalid_value');
$add($category, 'fiscal_currency', 'Moeda', $received, $expected, $category === 'missing_field' ? 'Indique a moeda da operação.' : 'Esta versão aceita apenas '.$expected.'. Reveja a moeda ou utilize um cálculo adequado à operação; a resposta não foi alterada.');
} elseif ($key === 'operation' && ! array_key_exists('operation', $context) && $expected === 'internal_general_net' && in_array($context['fiscal_operation'] ?? null, ['import', 'export', 'non_resident', 'refund'], true)) {
$add('out_of_scope', 'fiscal_operation', 'Operação', $context['fiscal_operation'], 'Operação interna à taxa geral, sobre base líquida já apurada', 'A operação declarada está excluída desta versão. Utilize um cálculo adequado à operação; não altere a resposta para obter um resultado.');
} elseif ($key === 'operation' && ! array_key_exists('operation', $context)) {
$add('system_configuration', 'fiscal_operation', 'Operação', $context['fiscal_operation'] ?? null, $expected === 'internal_general_net' ? 'Operação interna à taxa geral, sobre base líquida já apurada' : $expected, 'Limitação de integração do sistema: esta consulta não comunica o enquadramento específico exigido pela versão. A resposta genérica não permite inferi-lo. Utilize o formulário IVA — taxa geral, com declaração explícita do âmbito; não altere respostas para forçar compatibilidade.');
} elseif ($key === 'operation') {
$add($received === null || $received === '' ? 'missing_field' : 'out_of_scope', 'fiscal_operation', 'Operação', $received, $expected === 'internal_general_net' ? 'Operação interna à taxa geral, sobre base líquida já apurada' : $expected, 'A operação não está abrangida por esta versão; utilize um cálculo adequado à operação declarada.');
} else {
$add('system_configuration', null, 'Configuração da regra', null, 'Condições publicadas ligadas a campos deste formulário', 'O sistema não consegue relacionar todas as condições desta versão com o formulário. Não é uma falha das suas respostas.');
}
}
if (! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|| ($version['source_version_no'] ?? null) !== ($version['source']['version_no'] ?? null)
|| ($version['rule_definition']['language'] ?? null) !== 'investmoz.tax.v1') {
$add('system_configuration', null, 'Regra', null, 'Versão publicada com fonte e configuração coerentes', 'A configuração ou a fonte da regra não permite resolver este parâmetro. Não altere as respostas; é necessária correcção do sistema.');
}
if ($issues !== []) {
$source = array_intersect_key($version['source'] ?? [], array_flip(['title', 'diploma', 'article', 'url']));
$diagnostics[] = ['label' => 'IVA — taxa geral', 'rule_version' => $version['rule_version'], 'validity' => ['start' => $version['valid_from'], 'end' => $version['valid_until']], 'source' => $source, 'issues' => $issues];
}
}
return $diagnostics;
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\InvestmentLegalSource;
use App\Models\SimulationTaxRuleVersion;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Admission freezes eligibility without granting the public consumer governance write access. */
final class SimulationPublishedFiscal
{
public function availability(): array
{
$enabled = (bool) config('simulation-fiscal-consumer.enabled');
$eligible = $enabled && $this->boundRule()->where('status', 'published')->exists();
return ['enabled' => $eligible, 'coverage_start' => '2026-01-01', 'coverage_end' => '2026-12-31',
'message' => $eligible ? 'IVA geral sobre base líquida disponível; enquadramento declarado.'
: 'O cálculo de IVA geral sobre base líquida está indisponível para novas execuções. Os históricos mantêm-se acessíveis.'];
}
private function boundRule(): Builder
{
if (! Str::isUuid((string) config('simulation-fiscal-consumer.rule_id')) || config('simulation-fiscal-consumer.rule_version') < 1) {
return SimulationTaxRuleVersion::query()->whereRaw('false');
}
return SimulationTaxRuleVersion::query()->whereKey(config('simulation-fiscal-consumer.rule_id'))
->where('rule_version', config('simulation-fiscal-consumer.rule_version'))
->where('rule_code', 'IVA-GERAL-BASE-LIQUIDA')->where('component', 'IVA')
->where('scope_key', 'mz.internal-general-net.mzn');
}
public function admit(array $input): array
{
// Called inside createPayload, after idempotent replay, never by the worker.
abort_unless(DB::transactionLevel() > 0, 500);
abort_unless(config('simulation-fiscal-consumer.enabled'), 503,
'O cálculo de IVA está temporariamente indisponível. Os dados e históricos foram preservados.');
DB::select('select pg_advisory_xact_lock_shared(261021, hashtext(?))', [(string) config('simulation-fiscal-consumer.rule_id')]);
$rule = $this->boundRule()->first();
abort_unless($rule && $rule->status === 'published', 503,
'A versão autorizada de IVA não está disponível para novas execuções. Os históricos foram preservados.');
abort_if($input['reference_date'] < '2026-01-01' || $input['reference_date'] > '2026-12-31', 422,
'Este cálculo abrange apenas exigibilidade em 2026. As entradas foram preservadas.');
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
'A versão seleccionada não é compatível com o cálculo exacto deste consumidor.');
DB::select('select pg_advisory_xact_lock_shared(261022, hashtext(?))', [(string) $rule->legal_source_id]);
$source = InvestmentLegalSource::whereKey($rule->legal_source_id)->firstOrFail();
// Publish calculation provenance, not private governance notes or staff identifiers.
$version = array_intersect_key($rule->attributesToArray(), array_flip([
'id', 'rule_code', 'rule_version', 'component', 'scope_key', 'status', 'valid_from', 'valid_until',
'legal_source_id', 'source_version_no', 'source_sha256', 'rule_definition', 'parameters', 'rounding_policy',
]));
$version['source'] = array_intersect_key($source->attributesToArray(), array_flip([
'id', 'title', 'url', 'diploma', 'article', 'competent_entity', 'valid_from', 'valid_until', 'validation_status', 'version_no',
]));
$resolution = app(SimulationTaxParameterResolver::class)->resolvePublishedForPeriod('IVA',
$input['reference_date'], $input['reference_date'], ['currency' => $input['currency'], 'operation' => $input['operation']]);
$rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
$missing = [];
$evaluation = null;
if (! ($input['scope_declared'] ?? false)) {
$missing[] = 'operation_scope';
}
if (($rate['status'] ?? null) !== 'resolved' || ($rate['unit'] ?? null) !== 'percent'
|| ($rate['rule_id'] ?? null) !== (string) $rule->id
|| (int) ($rate['rule_version'] ?? 0) !== (int) $rule->rule_version) {
$missing[] = 'eligible_parameter';
}
if ($missing === []) {
$evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition,
['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]);
}
return app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing, true);
}
}
+10 -1
View File
@@ -8,15 +8,24 @@ final class SimulationTaxGovernanceAccess
{
private const ROLES = ['editors', 'reviewers', 'approvers', 'publishers'];
public static function maintainer(User $user): bool
{
return $user->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($user, 'auditor') && ($user->can('manage-portal')
|| app(ScopedPortalAdministration::class)->administrative($user));
}
public static function requireRole(User $user, string $role): void
{
abort_unless(in_array($role, self::ROLES, true), 500, 'Função de governação desconhecida.');
abort_unless(in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true),
abort_unless(self::maintainer($user) || in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true),
403, 'O utilizador não está designado para esta função de governação fiscal.');
}
public static function requireAnyRole(User $user): void
{
if (self::maintainer($user)) {
return;
}
foreach (self::ROLES as $role) {
if (in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true)) {
return;
+44 -20
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Services;
use App\Support\IsolatedQaDatabase;
use Brick\Math\BigRational;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
@@ -16,32 +17,32 @@ final class SimulationTaxParameterResolver
public function validateParameters(array $parameters): void
{
if ($parameters === [] || count($parameters) > 100) {
throw new InvalidArgumentException('Provide between 1 and 100 versioned parameters.');
throw new InvalidArgumentException('Indique entre 1 e 100 parâmetros versionados.');
}
foreach ($parameters as $code => $parameter) {
if (! is_string($code) || ! preg_match('/^[A-Z][A-Z0-9._-]{1,63}$/', $code) || ! is_array($parameter)
|| array_diff(array_keys($parameter), ['value', 'unit', 'conditions']) !== []
|| array_diff(['value', 'unit', 'conditions'], array_keys($parameter)) !== []) {
throw new InvalidArgumentException('Each parameter requires only value, unit, and conditions.');
throw new InvalidArgumentException('Cada parâmetro deve conter apenas valor, unidade e condições.');
}
if ((! is_string($parameter['value']) && ! is_int($parameter['value'])) || (string) $parameter['value'] === ''
|| ! is_string($parameter['unit']) || ! preg_match('/^[a-z][a-z0-9._-]{0,31}$/', $parameter['unit'])
|| ! is_array($parameter['conditions'])) {
throw new InvalidArgumentException('Invalid parameter value, unit, or conditions.');
throw new InvalidArgumentException('Reveja o valor, a unidade e as condições do parâmetro.');
}
$isNumericValue = preg_match('/^-?\d+(?:\.\d+)?$/', (string) $parameter['value']) === 1;
if (in_array($parameter['unit'], ['percent', 'mzn', 'amount', 'days', 'count', 'mzn_per_unit', 'per_unit'], true) && ! $isNumericValue) {
throw new InvalidArgumentException('Numeric parameter units require a plain decimal value.');
throw new InvalidArgumentException('Esta unidade requer um valor numérico decimal.');
}
if ($isNumericValue) {
$value = BigRational::of((string) $parameter['value']);
if ($value->isNegative() || ($parameter['unit'] === 'percent' && $value->compareTo(100) > 0)) {
throw new InvalidArgumentException('Numeric parameters cannot be negative; percentages must be between 0 and 100.');
throw new InvalidArgumentException('Os valores não podem ser negativos; as percentagens devem estar entre 0 e 100.');
}
}
foreach ($parameter['conditions'] as $condition => $expected) {
if (! is_string($condition) || ! is_string($expected)) {
throw new InvalidArgumentException('Conditions must be a flat map of string assumptions.');
throw new InvalidArgumentException('Indique as condições numa lista simples de nomes e valores em texto.');
}
}
}
@@ -52,32 +53,34 @@ final class SimulationTaxParameterResolver
* never executes a tax formula and requires each parameter to declare context.
*
* @param array<string,string> $context
* @return list<array<string,mixed>>
* @return list<array<string,mixed>>|array{parameters:list<array<string,mixed>>,diagnostics:list<array<string,mixed>>}
*/
public function resolvePublishedForPeriod(string $component, string $periodStart, string $periodEnd, array $context): array
public function resolvePublishedForPeriod(string $component, string $periodStart, string $periodEnd, array $context, bool $diagnostics = false): array
{
$start = $this->date($periodStart);
$end = $this->date($periodEnd);
if ($end < $start || $start->diff($end)->days > 365) {
throw new InvalidArgumentException('Invalid effective period.');
throw new InvalidArgumentException('Reveja o período de aplicação indicado.');
}
$rows = DB::table('simulation_tax_rule_versions as rule')
->join('investment_legal_sources as source', 'source.id', '=', 'rule.legal_source_id')
->where('rule.component', $component)
->where('rule.status', 'published')
->whereDate('rule.valid_from', '<=', $periodEnd)
->where(fn ($query) => $query->whereNull('rule.valid_until')->orWhereDate('rule.valid_until', '>=', $periodStart))
->where('source.validation_status', 'validated')
->when(! $diagnostics, fn ($query) => $query->whereDate('rule.valid_from', '<=', $periodEnd)
->where(fn ($query) => $query->whereNull('rule.valid_until')->orWhereDate('rule.valid_until', '>=', $periodStart)))
->where(fn ($query) => $query->where('source.validation_status', 'validated')->orWhere(fn ($fiscal) => $fiscal->where('source.validation_status', 'pending')->where('source.fiscal_acceptance->scope', 'fiscal_parameters')
->where('source.fiscal_acceptance->basis', 'Tempo-official-sources-20261008')
->whereRaw("source.fiscal_acceptance->>'sha256'=rule.source_sha256")))
->whereColumn('source.version_no', 'rule.source_version_no')
->whereDate('source.valid_from', '<=', $periodStart)
->where(fn ($query) => $query->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', $periodEnd))
->when(! $diagnostics, fn ($query) => $query->whereDate('source.valid_from', '<=', $periodStart)
->where(fn ($query) => $query->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', $periodEnd)))
->select([
'rule.id', 'rule.rule_code', 'rule.rule_version', 'rule.component', 'rule.scope_key',
'rule.valid_from', 'rule.valid_until', 'rule.parameters', 'rule.rule_definition',
'rule.source_version_no', 'rule.source_sha256',
'source.title as source_title', 'source.diploma as source_diploma', 'source.article as source_article',
'source.url as source_url', 'source.validation_status as source_validation_status',
'source.url as source_url', 'source.validation_status as source_validation_status', 'source.fiscal_acceptance',
'source.version_no as source_current_version', 'source.valid_from as source_valid_from',
'source.valid_until as source_valid_until',
])
@@ -110,6 +113,7 @@ final class SimulationTaxParameterResolver
'article' => $row->source_article,
'url' => $row->source_url,
'validation_status' => $row->source_validation_status,
'fiscal_acceptance' => is_array($row->fiscal_acceptance) ? $row->fiscal_acceptance : json_decode($row->fiscal_acceptance ?? 'null', true),
'version_no' => (int) $row->source_current_version,
'valid_from' => (string) $row->source_valid_from,
'valid_until' => $row->source_valid_until === null ? null : (string) $row->source_valid_until,
@@ -117,7 +121,11 @@ final class SimulationTaxParameterResolver
];
})->all());
return $this->resolveAvailableParameters($versions, $component, $periodStart, $periodEnd, $context);
$parameters = $this->resolveAvailableParameters($versions, $component, $periodStart, $periodEnd, $context);
$resolvedIva = array_filter($parameters, fn (array $parameter): bool => $parameter['parameter_code'] === 'IVA_GENERAL_RATE' && $parameter['status'] === 'resolved');
return $diagnostics ? ['parameters' => $parameters, 'diagnostics' => $resolvedIva !== [] ? [] : (new SimulationIvaDiagnostics)->explain($versions, $periodStart, $periodEnd, $context)] : $parameters;
}
/**
@@ -126,15 +134,31 @@ final class SimulationTaxParameterResolver
* @return list<array<string,mixed>>
*/
public function resolveAvailableParameters(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
{
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'published');
}
/** Explicit draft preview. Never used by the published-parameter API. */
public function resolveDraftForQa(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
{
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'draft');
}
private function resolveWithStatus(array $versions, string $component, string $periodStart, string $periodEnd, array $context, string $requiredStatus): array
{
$start = $this->date($periodStart);
$end = $this->date($periodEnd);
if ($end < $start || $start->diff($end)->days > 365) {
throw new InvalidArgumentException('Reveja o período de aplicação indicado.');
}
$groups = [];
foreach ($versions as $version) {
if (($version['component'] ?? null) !== $component
|| ($version['status'] ?? null) !== 'published'
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|| ($version['status'] ?? null) !== $requiredStatus
|| ! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|| ! $this->overlaps($version, $start, $end)
|| ! $this->covers($version['source'], $start) || ! $this->covers($version['source'], $end)
@@ -232,7 +256,7 @@ final class SimulationTaxParameterResolver
|| ($version['component'] ?? null) !== $component
|| ($version['scope_key'] ?? null) !== $scopeKey
|| ! $this->covers($version, $date)
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|| ! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|| ! $this->covers($version['source'], $date)
|| ! preg_match('/^[a-f0-9]{64}$/D', (string) ($version['source_sha256'] ?? ''))) {
@@ -315,7 +339,7 @@ final class SimulationTaxParameterResolver
{
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
throw new InvalidArgumentException('Effective date must use YYYY-MM-DD.');
throw new InvalidArgumentException('Indique uma data de aplicação válida no formato ano-mês-dia.');
}
return $parsed;
+14 -14
View File
@@ -95,16 +95,16 @@ final class SimulationTaxRuleExpression
private function topologicalOrder(array $definition): array
{
if (($definition['language'] ?? null) !== self::LANGUAGE || ! is_array($definition['nodes'] ?? null) || ! is_string($definition['result'] ?? null)) {
throw new InvalidArgumentException('Unsupported expression definition.');
throw new InvalidArgumentException('O formato da expressão não é suportado.');
}
$nodes = $definition['nodes'];
if ($nodes === [] || count($nodes) > 100) {
throw new InvalidArgumentException('Expression must contain between 1 and 100 nodes.');
throw new InvalidArgumentException('A expressão deve conter entre 1 e 100 elementos.');
}
foreach ($nodes as $id => $node) {
if (! is_string($id) || ! preg_match('/^[a-z][a-z0-9_]{0,47}$/', $id) || ! is_array($node) || ! is_string($node['op'] ?? null)) {
throw new InvalidArgumentException('Invalid expression node.');
throw new InvalidArgumentException('Reveja o elemento indicado na expressão.');
}
$op = $node['op'];
$allowedFields = match ($op) {
@@ -112,40 +112,40 @@ final class SimulationTaxRuleExpression
'literal' => ['op', 'value'],
'add', 'subtract', 'multiply', 'divide', 'min', 'max' => ['op', 'args'],
'round' => ['op', 'args', 'scale', 'mode'],
default => throw new InvalidArgumentException('Expression operation is not allowed.'),
default => throw new InvalidArgumentException('Esta operação não é suportada na expressão.'),
};
if (array_diff(array_keys($node), $allowedFields) !== [] || array_diff($allowedFields, array_keys($node)) !== []) {
throw new InvalidArgumentException('Expression node has missing or unsupported fields.');
throw new InvalidArgumentException('Há campos em falta ou não suportados num elemento da expressão.');
}
if (in_array($op, ['input', 'parameter'], true) && (! is_string($node['key']) || ! preg_match('/^[a-z][a-z0-9_.-]{0,79}$/', $node['key']))) {
throw new InvalidArgumentException('Invalid input or parameter key.');
throw new InvalidArgumentException('Reveja o identificador da entrada ou do parâmetro.');
}
if ($op === 'literal') {
$this->number($node['value']);
}
if (isset($node['args'])) {
if (! is_array($node['args'])) {
throw new InvalidArgumentException('Invalid expression arguments.');
throw new InvalidArgumentException('Reveja os argumentos da expressão.');
}
$count = count($node['args']);
$validCount = $op === 'round' ? $count === 1 : ($op === 'subtract' || $op === 'divide' ? $count === 2 : $count >= 2 && $count <= 20);
if (! $validCount || count(array_filter($node['args'], 'is_string')) !== $count) {
throw new InvalidArgumentException('Invalid expression arguments.');
throw new InvalidArgumentException('Reveja os argumentos da expressão.');
}
}
if ($op === 'round' && (! is_int($node['scale']) || $node['scale'] < 0 || $node['scale'] > 12 || ! isset(self::ROUNDING[$node['mode']]))) {
throw new InvalidArgumentException('Invalid explicit rounding configuration.');
throw new InvalidArgumentException('Reveja a configuração de arredondamento.');
}
}
if (! array_key_exists($definition['result'], $nodes)) {
throw new InvalidArgumentException('Expression result references an unknown node.');
throw new InvalidArgumentException('O resultado da expressão refere um elemento inexistente.');
}
$state = [];
$order = [];
$visit = function (string $id) use (&$visit, &$state, &$order, $nodes): void {
if (($state[$id] ?? 0) === 1) {
throw new InvalidArgumentException('Expression dependency graph contains a cycle.');
throw new InvalidArgumentException('A expressão contém uma dependência circular.');
}
if (($state[$id] ?? 0) === 2) {
return;
@@ -153,7 +153,7 @@ final class SimulationTaxRuleExpression
$state[$id] = 1;
foreach ($nodes[$id]['args'] ?? [] as $dependency) {
if (! is_string($dependency) || ! array_key_exists($dependency, $nodes)) {
throw new InvalidArgumentException('Expression references an unknown node.');
throw new InvalidArgumentException('A expressão refere um elemento inexistente.');
}
$visit($dependency);
}
@@ -191,13 +191,13 @@ final class SimulationTaxRuleExpression
if ($op === 'min' || $op === 'max') {
return array_reduce(array_slice($args, 1), static fn (BigRational $carry, BigRational $value): BigRational => ($op === 'min' ? $carry->compareTo($value) <= 0 : $carry->compareTo($value) >= 0) ? $carry : $value, $args[0]);
}
throw new InvalidArgumentException('Expression operation is not allowed.');
throw new InvalidArgumentException('Esta operação não é suportada na expressão.');
}
private function number(mixed $value): BigRational
{
if ((! is_string($value) && ! is_int($value)) || ! preg_match('/^-?\d+(?:\.\d+)?$/', (string) $value)) {
throw new InvalidArgumentException('Numbers must be plain decimal strings or integers.');
throw new InvalidArgumentException('Introduza valores numéricos decimais ou inteiros.');
}
return BigRational::of((string) $value);
+9 -8
View File
@@ -65,6 +65,8 @@ final class SimulationTaxRuleGovernance
return DB::transaction(function () use ($actor, $id, $version, $action, $evidence): SimulationTaxRuleVersion {
$this->setContext($actor);
// Serialize public admission with publication/suspension, without widening RLS.
DB::select('select pg_advisory_xact_lock(261021, hashtext(?))', [$id]);
$rule = SimulationTaxRuleVersion::query()->lockForUpdate()->findOrFail($id);
$this->matchVersion($rule, $version);
$next = ['version_no' => $version + 1];
@@ -78,15 +80,12 @@ final class SimulationTaxRuleGovernance
break;
case 'review':
case 'reject':
abort_unless((int) $rule->author_id !== $actor->id, 403, 'O autor não pode rever a própria regra.');
abort_unless($rule->status === 'submitted', 422, 'A regra tem de estar submetida para revisão.');
$this->sourceStillValid($rule);
$next += ['status' => $action === 'review' ? 'reviewed' : 'rejected', 'reviewer_id' => $actor->id,
'review_evidence' => $evidence, 'reviewed_at' => now()];
break;
case 'approve':
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id, 403,
'Autor e revisor não podem aprovar a mesma regra.');
abort_unless($rule->status === 'reviewed', 422, 'A regra tem de estar revista antes da aprovação.');
$this->sourceStillValid($rule);
$next += ['status' => 'approved', 'approver_id' => $actor->id,
@@ -94,9 +93,6 @@ final class SimulationTaxRuleGovernance
break;
case 'publish':
abort_unless($rule->status === 'approved', 422, 'A regra tem de estar aprovada antes da publicação.');
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id
&& (int) $rule->approver_id !== $actor->id, 403,
'Autor, revisor e aprovador não podem publicar a mesma regra.');
$this->sourceStillValid($rule);
$this->assertNoPublishedOverlap($rule);
$next += ['status' => 'published', 'publisher_id' => $actor->id,
@@ -155,7 +151,11 @@ final class SimulationTaxRuleGovernance
$source = InvestmentLegalSource::query()->whereKey($data['legal_source_id'])->firstOrFail();
abort_unless(preg_match('/^[a-f0-9]{64}$/D', (string) $data['source_sha256']) === 1, 422,
'Indique o SHA-256 do exemplar oficial efectivamente revisto.');
abort_unless($source->validation_status === 'validated', 422, 'A fonte jurídica ainda não foi validada.');
abort_unless(SimulationFiscalSourceAcceptance::eligible($source->attributesToArray(), $data['source_sha256']), 422,
'A fonte ainda não está aceite para este cadastro fiscal.');
abort_if(is_array($source->fiscal_acceptance)
&& ($source->fiscal_acceptance['sha256'] ?? null) !== $data['source_sha256'], 422,
'O hash da regra deve corresponder ao exemplar registado na aceitação da fonte fiscal.');
abort_unless($source->valid_from <= $data['valid_from']
&& ($source->valid_until === null || ($data['valid_until'] !== null && $source->valid_until >= $data['valid_until']))
&& ($data['valid_until'] !== null || $source->valid_until === null), 422,
@@ -167,7 +167,8 @@ final class SimulationTaxRuleGovernance
private function sourceStillValid(SimulationTaxRuleVersion $rule): void
{
$source = InvestmentLegalSource::query()->lockForUpdate()->find($rule->legal_source_id);
abort_unless($source !== null && $source->validation_status === 'validated'
abort_unless($source !== null && SimulationFiscalSourceAcceptance::eligible($source->attributesToArray(), $rule->source_sha256)
&& (! is_array($source->fiscal_acceptance) || ($source->fiscal_acceptance['sha256'] ?? null) === $rule->source_sha256)
&& (int) $source->version_no === (int) $rule->source_version_no
&& $source->valid_from <= $rule->valid_from->format('Y-m-d')
&& ($source->valid_until === null || ($rule->valid_until !== null && $source->valid_until >= $rule->valid_until->format('Y-m-d')))
+2 -1
View File
@@ -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.
}
+3 -3
View File
@@ -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.');
+25 -5
View File
@@ -1,6 +1,7 @@
<?php
use App\Http\Middleware\AuditProfileDecision;
use App\Http\Middleware\EnsureHomologationAccess;
use App\Http\Middleware\EnsureSimulationRecoveryCookie;
use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
@@ -19,7 +20,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 +31,7 @@ $app = Application::configure(basePath: dirname(__DIR__))
$middleware->encryptCookies(except: ['appearance', 'sidebar_state', EnsureSimulationRecoveryCookie::NAME]);
$middleware->web(append: [
EnsureHomologationAccess::class,
PortalProfileSession::class,
ProtectPrivilegedIdentity::class,
AuditProfileDecision::class,
@@ -67,6 +69,28 @@ $app = Application::configure(basePath: dirname(__DIR__))
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
);
$exceptions->respond(function (Response $response, Throwable $exception, Request $request): Response {
if (($request->is('api/*') || $request->expectsJson()) && $response->getStatusCode() >= 400) {
$body = json_decode((string) $response->getContent(), true);
$genericMessages = [
'Not Found' => 'O registo não foi encontrado ou não está acessível nesta conta.',
'Not found.' => 'O registo não foi encontrado ou não está acessível nesta conta.',
'Forbidden' => 'Esta conta não tem acesso a esta operação.',
'Forbidden.' => 'Esta conta não tem acesso a esta operação.',
'Unauthenticated.' => 'Entre na sua conta para continuar esta operação.',
'CSRF token mismatch.' => 'A sessão expirou. Entre novamente antes de repetir a operação.',
'Too Many Attempts.' => 'Foram feitas várias tentativas. Aguarde um pouco e tente novamente.',
'Server Error' => 'Não foi possível concluir a operação. Tente novamente.',
];
if (is_array($body) && is_string($body['message'] ?? null) && isset($genericMessages[$body['message']])) {
$body['message'] = $genericMessages[$body['message']];
$response->setContent(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
} elseif (is_array($body) && is_string($body['message'] ?? null)
&& $response->getStatusCode() === 404 && str_starts_with($body['message'], 'The route ')
&& str_ends_with($body['message'], ' could not be found.')) {
$body['message'] = $genericMessages['Not Found'];
$response->setContent(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
}
if ($request->is('api/*')) {
$response->headers->set(
'X-Correlation-ID',
@@ -106,7 +130,3 @@ $app = Application::configure(basePath: dirname(__DIR__))
return $response;
});
})->create();
(require __DIR__.'/storage.php')($app->basePath(), $app->storagePath());
return $app;
+1 -1
View File
@@ -78,7 +78,7 @@ return [
|
*/
'locale' => env('APP_LOCALE', 'en'),
'locale' => env('APP_LOCALE', 'pt'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
+157
View File
@@ -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);
+127
View File
@@ -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);
+14
View File
@@ -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', '')),
+3
View File
@@ -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,
+1
View File
@@ -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
View File
@@ -0,0 +1,8 @@
<?php
return [
// Publication and consumer exposure are separate Tempo decisions.
'enabled' => env('INVESTMOZ_IVA_CONSUMER_ENABLED', false),
'rule_id' => env('INVESTMOZ_IVA_CONSUMER_RULE_ID'),
'rule_version' => (int) env('INVESTMOZ_IVA_CONSUMER_RULE_VERSION', 0),
];
+3 -2
View File
@@ -1,8 +1,9 @@
<?php
return [
// These lists are deliberately empty by default. A portal manager and MFA are
// also required; governance roles never activate rules in the calculation engine.
// Optional specific assignments. Existing authorised administration can maintain
// fiscal parameters with MFA, without four people or four email designations.
// Rule publication never activates the calculation consumer by itself.
'editors' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_EDITORS', '')))))),
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_REVIEWERS', '')))))),
'approvers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_APPROVERS', '')))))),
@@ -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,68 @@
<?php
use App\Support\IsolatedQaDatabase;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
throw new LogicException('Ensaie esta correcção apenas numa base QA isolada. A aplicação no destino exige decisão, backup/restauro e acção autenticada.');
}
// Only fiscal rule maintenance changes. Opportunity/zone workflow checks remain intact.
DB::statement('ALTER TABLE simulation_tax_rule_versions DROP CONSTRAINT tax_rule_stage_evidence_check, DROP CONSTRAINT tax_rule_approval_check, DROP CONSTRAINT tax_rule_publication_check');
DB::statement("ALTER TABLE simulation_tax_rule_versions
ADD CONSTRAINT tax_rule_stage_evidence_check CHECK(status NOT IN ('reviewed','rejected','approved','published','suspended','archived') OR (reviewer_id IS NOT NULL AND submitted_at IS NOT NULL AND reviewed_at IS NOT NULL AND length(trim(review_evidence))>=20)),
ADD CONSTRAINT tax_rule_approval_check CHECK(status NOT IN ('approved','published','suspended','archived') OR (approver_id IS NOT NULL AND approved_at IS NOT NULL AND length(trim(approval_evidence))>=20)),
ADD CONSTRAINT tax_rule_publication_check CHECK(status NOT IN ('published','suspended','archived') OR (publisher_id IS NOT NULL AND published_at IS NOT NULL AND length(trim(publication_evidence))>=20))");
DB::statement('ALTER TABLE investment_legal_sources ADD COLUMN fiscal_acceptance jsonb NULL');
DB::statement("ALTER TABLE investment_legal_sources ADD CONSTRAINT investment_legal_source_fiscal_acceptance_check CHECK (
fiscal_acceptance IS NULL OR COALESCE((
fiscal_acceptance->>'scope'='fiscal_parameters' AND
fiscal_acceptance->>'basis'='Tempo-official-sources-20261008' AND
fiscal_acceptance->>'responsible_user_id'=owner_id::text AND
fiscal_acceptance->>'sha256' ~ '^[a-f0-9]{64}$' AND
fiscal_acceptance->>'legal_opinion'='false' AND fiscal_acceptance->>'independent_review'='false' AND
length(trim(fiscal_acceptance->>'citation'))>=10 AND
length(trim(fiscal_acceptance->>'official_origin'))>=10
), false))");
DB::statement('DROP POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions');
DB::statement("CREATE POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions FOR SELECT USING (
status='published' AND EXISTS (SELECT 1 FROM investment_legal_sources source
WHERE source.id=simulation_tax_rule_versions.legal_source_id
AND (source.validation_status='validated' OR (source.validation_status='pending'
AND source.fiscal_acceptance->>'scope'='fiscal_parameters'
AND source.fiscal_acceptance->>'basis'='Tempo-official-sources-20261008'
AND source.fiscal_acceptance->>'sha256'=simulation_tax_rule_versions.source_sha256))
AND source.version_no=simulation_tax_rule_versions.source_version_no
AND source.valid_from<=simulation_tax_rule_versions.valid_from
AND (source.valid_until IS NULL OR (simulation_tax_rule_versions.valid_until IS NOT NULL AND source.valid_until>=simulation_tax_rule_versions.valid_until))
AND (simulation_tax_rule_versions.valid_until IS NOT NULL OR source.valid_until IS NULL)))");
}
public function down(): void
{
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
throw new LogicException('Reversão permitida apenas em QA isolado.');
}
$used = DB::table('investment_legal_sources')->whereNotNull('fiscal_acceptance')->exists()
|| DB::table('simulation_tax_rule_versions')->whereRaw('reviewer_id=author_id OR approver_id=author_id OR approver_id=reviewer_id OR publisher_id=author_id OR publisher_id=reviewer_id OR publisher_id=approver_id')->exists();
if ($used) {
throw new LogicException('Reversão recusada: conservar os cadastros e históricos legítimos; desactivar novas execuções em vez de apagar registos.');
}
DB::statement('ALTER TABLE simulation_tax_rule_versions DROP CONSTRAINT tax_rule_stage_evidence_check, DROP CONSTRAINT tax_rule_approval_check, DROP CONSTRAINT tax_rule_publication_check');
DB::statement("ALTER TABLE simulation_tax_rule_versions
ADD CONSTRAINT tax_rule_stage_evidence_check CHECK(status NOT IN ('reviewed','rejected','approved','published','suspended','archived') OR (reviewer_id IS NOT NULL AND reviewer_id<>author_id AND submitted_at IS NOT NULL AND reviewed_at IS NOT NULL AND length(trim(review_evidence))>=20)),
ADD CONSTRAINT tax_rule_approval_check CHECK(status NOT IN ('approved','published','suspended','archived') OR (approver_id IS NOT NULL AND approver_id<>author_id AND approver_id<>reviewer_id AND approved_at IS NOT NULL AND length(trim(approval_evidence))>=20)),
ADD CONSTRAINT tax_rule_publication_check CHECK(status NOT IN ('published','suspended','archived') OR (publisher_id IS NOT NULL AND publisher_id<>author_id AND publisher_id<>reviewer_id AND publisher_id<>approver_id AND published_at IS NOT NULL AND length(trim(publication_evidence))>=20))");
DB::statement('DROP POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions');
(require __DIR__.'/2026_10_03_190000_allow_public_read_of_published_tax_parameters.php')->up();
DB::statement('ALTER TABLE investment_legal_sources DROP CONSTRAINT investment_legal_source_fiscal_acceptance_check');
DB::statement('ALTER TABLE investment_legal_sources DROP COLUMN fiscal_acceptance');
}
};
+38
View File
@@ -0,0 +1,38 @@
{
"rule_code": "IVA-GERAL-BASE-LIQUIDA",
"rule_version": 1,
"component": "IVA",
"scope_key": "mz.internal-general-net.mzn",
"valid_from": "2023-01-01",
"valid_until": null,
"source_sha256": "ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53",
"rule_definition": {
"language": "investmoz.tax.v1",
"nodes": {
"base": {"op": "input", "key": "base_tributavel"},
"rate": {"op": "parameter", "key": "iva_general_rate"},
"hundred": {"op": "literal", "value": "100"},
"product": {"op": "multiply", "args": ["base", "rate"]},
"intermediate": {"op": "divide", "args": ["product", "hundred"]}
},
"result": "intermediate"
},
"parameters": {
"IVA_GENERAL_RATE": {
"value": "16",
"unit": "percent",
"conditions": {"operation": "internal_general_net", "currency": "MZN"}
}
},
"rounding_policy": {
"status": "not_applied",
"precision": "exact_decimal",
"method": "none",
"ties": "not_applicable_without_rounding",
"aggregation": "single_declared_taxable_base",
"purpose": "operation_tax_not_payment",
"evidence": "Orientação expressa Tempo: calcular este lote IVA sem arredondamento automático; ficha v1.2",
"coverage_start": "2026-01-01",
"coverage_end": "2026-12-31"
}
}
+1
View File
@@ -0,0 +1 @@
__pycache__/
+44
View File
@@ -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.
+17
View File
@@ -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"
}
+342
View File
@@ -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()
+446
View File
@@ -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"
}
]
}
+108
View File
@@ -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()
+41
View File
@@ -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
+41
View File
@@ -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]);
@@ -0,0 +1,100 @@
# IVA-GERAL-BASE-LIQUIDA — ficha documental v1.2
21/10/2026. AUD-SIM-INT02 na matriz existente. Proposta inicial `0fafd348`; v1 em `325d58b6`, v1.1 em `37085b40`. Essas versões ficam preservadas em Git. Esta versão aplica a orientação posterior expressa da Tempo: **prosseguir neste lote IVA com precisão decimal exacta, sem introduzir arredondamento automático; separar valor calculado de apresentação monetária**. Retira a falta de uma política genérica de arredondamento como condição bloqueante do cálculo. Não estende a decisão a todos os impostos.
**Estado:** cadastro e cálculo experimental em QA, regra em rascunho, sem publicação/activação ou integração em `main`. Não equivale a conclusão do simulador fiscal, emissão de factura, declaração ou determinação de saldo a pagar. A Tempo declarou não ter conferido a ficha local nem validado juridicamente as conclusões transcritas; não se lhe atribui essa validação.
## Âmbito e contrato
Um único percurso: base tributável líquida já identificada × taxa geral /100, em MZN explícito, para operação interna abrangida pela taxa geral. Janela demonstrada do lote:01/01/2026–31/12/2026, delimitação técnica que não cria caducidade legal em31/12. Não decide automaticamente incidência, sujeito passivo, localização, isenção ou regime especial. Contexto declarado é rotulado como tal; uma rubrica orçamental não se transforma automaticamente em base fiscal.
Excluídos: extracção de preço com IVA incluído, taxas reduzidas, isenções/listas, importações, digital/não residentes, dedução/crédito/reembolso, incentivos e outros impostos. Permanecem no inventário documental existente, sem omissão nem alegação de cobertura deste lote.
| Campo | Estado actual |
|---|---|
| Regra | `IVA-GERAL-BASE-LIQUIDA`, versão1, estado `draft`; cadastro explícito apenas em QA. |
| Taxa / unidade | `16` / `percent`, vínculo Lei22/2022, art.17(1), exemplar/hash abaixo. |
| Vigência cadastrada | Desde01/01/2023, sem termo artificial; cobertura ensaiada2026 separada da vigência. |
| Entradas | Base decimal como texto, MZN explícito, data de exigibilidade declarada, contexto `internal_general_net`. Zero explícito é válido; ausência não é zero. |
| Valor calculado | Decimal exacto obtido pelo avaliador racional existente; sem conversão para float, truncagem ou redução para duas casas. |
| Apresentação | Valor decimal preservado como texto e moeda separados. Duas casas da unidade monetária não impõem arredondamento ao cálculo. Ecrã/CSV/dossier reproduzem o valor guardado. |
| Arredondamento | `not_applied`; nenhum nó `round` neste percurso. Não se inventa precisão, empate ou método fiscal. |
| Indeterminação efectiva | Fonte/versão/contexto incompatível, parâmetro ausente ou pedido fora da cobertura demonstrada. A falta de arredondamento não torna indeterminado o resultado deste percurso. |
| Limites do resultado | Cálculo QA sobre regra em rascunho e enquadramento declarado; não é obrigação validada nem saldo a pagar. |
## Fontes reutilizadas e disposições documentadas
Fontes oficiais aceites pela decisão Tempo de08/10/2026; sem nova certificação genérica de proveniência. A identificação de âmbito, período e dispositivo é aplicação da fonte aceite. Reutilizar [análise primária](primary-text-review-2025-2026.md), [registo de fontes](official-source-register.md) e [reforma fiscal](fiscal-reform-2026-review.md). A aceitação da fonte não activa regra nem valida juridicamente uma operação concreta.
| Exemplar | Identificação e integridade |
|---|---|
| [Lei13/2016 / CIVA republicado](source-archive/Lei-13-2016-CIVA-BR-156-10-suplemento.pdf) | BR156,10.º suplemento,30/12/2016;32páginas,2.127.554bytes; SHA256 `B90DC7C14ECEA2E378C4A62E8E5A47D54A5644C457BAEB8B8053B92FD2A5710B`. Leitura visual dirigida PDF6–8,13–14,17–18; entrada em vigor no art.4/PDF5. Não se afirma análise integral de anexos. |
| [Lei22/2022 republicada](source-archive/Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf) | BR250,2.º suplemento;18páginas,1.834.284bytes; SHA256 `EA1B0DC6F5CF6E595F6D9A19E7042F398999E0087CAEF1785F6E8FAC571B5F53`. Art.17(1),PDF3/BR2252-(27), taxa16%; art.6 da Lei,PDF4, eficácia01/01/2023. |
| [BR248, suplemento1/2025](source-archive/BR-248-I-Suplemento-1-2025.pdf) |21páginas,440.018bytes; SHA256 `CCF2A8DEECA820F2DD076B4B2141B1EFE3F6A806568C3A587CA59A8E92F4C251`. Lei10/2025,PDF12–15; eficácia01/01/2026. |
| [BR16/2008 / Decreto7/2008](source-archive/BR-16-I-Serie-2008-04-16.pdf) |16/04/2008;28páginas,2.267.865bytes; SHA256 `FC373FF5637EDF75EC6A9595DEC8763A8503D4EE786E3B7D8F1C742EAE9D80EE`. Regulamento IVA,PDF1–2; página2 conferida visualmente. O BR inclui outros impostos, que não são fundamento deste lote. |
| [BR89/2017 / rectificação CIVA](source-archive/BR-89-I-Serie-2017-06-08.pdf) | Aviso relativo a art.6(5)c/d,14(2)c e anexos de isenção; análise anterior reutilizada. Não encerra consolidação das listas de isenção. |
| Disposição exacta | Conteúdo documentado / consequência |
|---|---|
| CIVA art.1(1)(a), PDF6, BR1426-(264) | Transmissões de bens e prestações de serviços onerosas no território nacional, nos termos do art.6, por sujeito passivo nessa qualidade. Exigir identificação desse contexto; importações ficam fora. |
| Art.2(1)(a), PDF6 | Qualidade do sujeito passivo ligada às condições de residência/estabelecimento e actividade independente previstas. Perfil de investidor não prova sujeição. |
| Arts.3(1),4(1), PDF6–7 | Transferência onerosa de bens corpóreos e noção geral de serviço. Casos assimilados/especiais não entram implicitamente na fórmula. |
| Art.6(1), PDF7, BR1426-(265) | Para bens, localização no início do transporte/expedição ou quando postos à disposição, sem transporte. Serviços seguem art.6(3) e excepções subsequentes; não basta localização do prestador para todos os serviços. |
| Art.15(1), PDF13, BR1426-(271) | Base geral: contraprestação obtida ou a obter, sem prejuízo das bases especiais do n.º2. Não equivale a qualquer receita de planeamento. |
| Art.15(5)(a)/(b), PDF14, BR1426-(272) | Inclusão de outros impostos/direitos/taxas, excepto o próprio IVA, e despesas acessórias debitadas, nas condições previstas. |
| Art.15(6)(a)–(d), PDF14 | Exclusões condicionadas: indemnizações judiciais indicadas, descontos/abatimentos/bónus, pagamentos em nome/conta de terceiros registados adequadamente e embalagens retornáveis. Não classificar só pelo nome da rubrica. |
| Art.17(2), PDF14; art.7(1)(a)/(b), PDF8 | Taxa vigente na exigibilidade; facto gerador/exigibilidade diferem por operação e condições. A criação da simulação não substitui a data fiscal. Adiantamentos e prestações continuadas requerem enquadramento próprio. |
| Art.27(5)(c)/(d), PDF17, BR1426-(275) | Separação do preço líquido/elementos da base, taxa e montante do imposto. Lei10/2025 preserva essas alíneas com «[…]», alterando o n.º10. |
| Regulamento, arts.4/5, Decreto7/2008,PDF1–2 | Remete matéria colectável para arts.15/16 e apuramento devido para arts.18–22 do Código. IVA da operação não equivale ao saldo após deduções. |
Cadeia temporal documentada: Lei13/2016 efectiva em01/01/2017; a taxa histórica17% do exemplar não é usada para2026. Lei22/2022 altera art.17(1) para16% desde01/01/2023 e acrescenta art.15(10) para taxa reduzida, mantendo os números gerais consultados. Lei10/2025, efectiva01/01/2026, não lista arts.15/17 entre os alterados. Esta conclusão documental não é atribuída como validação jurídica ao utilizador e não certifica todos os regimes/excepções.
## Precisão do cálculo e exigências contextuais
Art.34 do CIVA, Lei10/2025/PDF14, regula extracção de base de valores com imposto incluído, com divisor116 e arredondamento para unidade mais próxima. Art.9(1)(b) do regulamento/Decreto7/2008,PDF2/p.100, trata do valor do meio de pagamento por cheque ou vale de correio e arredondamento por excesso para meticais nesse exemplar histórico. **Nenhum é aplicado como regra geral de arredondamento deste cálculo sobre base líquida.** A vigência consolidada e exigências de formatos de pagamento/declaração serão determinadas quando esses consumidores forem abrangidos.
A [comunicação oficial de30/09/2026](https://portaldogoverno.gov.mz/governo-introduz-alteracoes-nos-regulamentos-fiscais-para-reforcar-eficiencia-tributaria/) anuncia alterações regulamentares; não fornece articulado publicado e eficácia por disposição. A pesquisa dirigida em fontes oficiais não identificou uma exigência geral que obrigue a arredondar este percurso. Ausência de correspondência não prova inexistência de instruções específicas. Não há questão pendente à Tempo como pré-condição deste cálculo. Se um futuro formato exigir precisão, apresentar uma única questão contextual, identificando o formato, precisão, método, empates e agregação; não generalizar a outros cálculos.
Nota de rastreabilidade, sem reabrir pontos: o exemplar BR54 de06/04/2017 consultado anteriormente não continha a alteração regulamentar procurada. O [catálogo INM](https://www.inm.gov.mz/pt-br/produtos?page=124) identifica Decreto8/2017 no BR50 de30/03/2017. O articulado e alterações pertinentes continuam a ser correspondências documentais a completar quando necessárias ao consumidor; não são bloqueio genérico do cálculo exacto deste lote.
## Exemplos e provas dirigidas
Pressupostos explícitos: operação interna onerosa à taxa geral, base já apurada, sem isenção/redução/base especial, data coberta2026 e MZN. Não são classificações jurídicas de operações reais.
| Base | IVA calculado exacto | Apresentação / significado |
|---|---|---|
|100|16|`16` e moeda `MZN`, separados; não é saldo a pagar. |
|0,03|0,0048|Conservar todas as casas no armazenamento, ecrã e exportação. Não substituir por0,00. |
|0|0|Zero explicitamente declarado, distinto de entrada ausente. |
|9007199254740993,0003|1441151880758558,880048|Preservar sem converter para float JavaScript/PHP. |
|100 + transporte10 − desconto5|16,8 sobre base105|Apenas se verificadas as condições de inclusão/exclusão do art.15. |
Os testes do novo consumidor cobrem registo repetido sem duplicação, rascunho excluído da API publicada, resultado exacto, snapshot/relatório conservados após edição da regra e recuperação noutra sessão de autenticação, acesso negado a outra conta, moeda obrigatória, incompatibilidade da fonte, cobertura e recusa fora de QA. A nova sessão provada é API/autenticação, não alegação de novo ensaio browser. A conta PostgreSQL QA ultrapassa RLS: recusas demonstram a política da aplicação, não nova prova de RLS.
## Implementação, limites e integração
Reutilizados `SimulationTaxRuleGovernance`, `SimulationTaxParameterResolver`, `SimulationTaxRuleExpression` e o armazenamento existente de simulações, fontes, histórico e relatórios. Não há motor novo, migration ou alteração da base activa. `fiscal:qa-register-iva` exige alvo QA isolado, editor e referência de fonte já existente; confere hash e cadastra apenas rascunho, de forma idempotente. Não corre em deploy/importação. O artefacto versionado é `database/qa/iva-general-net-v1.json`.
Pré-visualização administrativa `POST /api/v2/investment/admin/tax-rules/{id}/qa-preview`, com `Idempotency-Key`, exige os controlos administrativos existentes e alvo QA isolado. Não muda a API de parâmetros publicados para aceitar rascunhos. O snapshot congela regra, fonte/versão/hash, contexto declarado, data, passos racionais, decimal calculado, apresentação sem arredondamento e limitações. Alteração da regra não reescreve o histórico. Uma nova entrada produz nova execução; um snapshot fiscal não é convertido por edição numa simulação de planeamento.
O cadastro persistido usa clone `simulator_fiscal_delta_20261021_test` e referência/actores sintéticos explicitamente identificados; não representa revisão jurídica por uma pessoa real nem atribuição persistente de papéis da Tempo. O recibo privado regista IDs, estado draft, zero regras publicadas e hash do relatório. A conta técnica e os ficheiros de prova privados não são material de deploy.
Planeamento personalizado mantém identificação própria. O resultado deste lote é apresentado como cálculo QA com regra em rascunho, não estimativa percentual introduzida pelo utilizador nem regra fiscal activada. As provas aceites de13f68f1b/valores/CSV/paginação não são repetidas. A entrega anterior permanece independente e concluída; não integra esta branch automaticamente.
## Estimativa e revisão
As15–26h anteriores eram condicionais e incluíam o trabalho de cadastro e integração que agora avançou em QA. O esclarecimento de uma política genérica de arredondamento deixa de integrar o caminho crítico deste lote. O saldo deve usar os resultados técnicos registados na adenda do manual existente, distinguindo trabalho já executado, revisão e qualquer consumidor futuro de pagamento/declaração. Não são horas medidas, promessa de activação nem estimativa do simulador fiscal integral. Publicação, activação e integração em `main` continuam separadas e não foram executadas.
## Revisão consolidada de83d2f97d
**Controlo de manutenção corrigido emQA,21/10/2026:** por decisão expressa da Tempo, a mesma administração autorizada pode cadastrar a fonte e concluir as etapas da regra, comMFA, responsável, evidência e histórico. A obrigação técnica de quatro pessoas não tinha fundamento aprovado identificado para este cadastro fiscal. Foi retirada apenas deste fluxo; o novo fundamento de aceitação da fonte oficial não é parecer jurídico nem revisão independente. Âmbito, exclusões, pressupostos e identificação do resultado como estimativa sobre base declarada mantêm-se. O manual consolidado contém a origem da condição, as6provas dirigidas/86asserções e o procedimento actualizado; não se reensaiou o cálculo nem se publicou ou activou a regra real nesta correcçãoQA.
**Actualização técnica de21/10/2026 — delta2ced7b79 implementado em QA:** o consumidor por versão publicada está ligado ao simulador normal, com activação desligada por omissão, selecção da regra no servidor e gravação/recuperação/relatório pelo histórico existente. O mesmo manual regista a demonstração pelo Edge, indeterminação sem declaração de âmbito, repetição sem duplicação, suspensão antes do processamento da fila, conclusão com versão congelada e recusa de novas execuções. Oito testes dirigidos/75asserções e dois testes frontend novos passaram, além deTypeScript/build/Pint. Mantêm-se integralmente o âmbito2026, exclusões, fontes e precisão desta ficha; não se repete a fundamentação jurídica nem se lhe atribui validação da Tempo. O procedimento único foi actualizado para integração, publicação da versão real e activação, decisões ainda não executadas na homologação. A fixture publicada exclusivamente no clone QA foi suspensa após o ensaio; os históricos foram preservados. As notas abaixo sobre ausência do consumidor descrevem o estado anterior à implementação deste delta.
**Disponibilização no simulador existente:** a proposta única «Consumidor IVA no simulador da homologação», no mesmo manual, delimita o código ainda necessário e as três operações distintas: integração com consumidor desligado, publicação da versão pela governação existente e activação da ligação à versão autorizada. O percurso QA aceite não equivale a esse consumidor público. Mantêm-se âmbito2026, exclusões, precisão exacta e históricos; suspensão impede novas admissões e preserva execuções já admitidas. Esta proposta não executa nenhuma das três operações nem amplia a cobertura fiscal.
O [mesmo manual de rastreabilidade](../unification/traceability-and-manual.md) consolida âmbito/período, operações excluídas/indeterminadas e os procedimentos concretos de integração, publicação, activação e desactivação, preservando históricos. Identifica também que83d2f97d não contém um consumidor fiscal público: a publicação torna parâmetros elegíveis na API existente, mas não transforma o percurso QA em cálculo público activado.
A única lacuna adicional encontrada foi o percurso completo pela interface. Acrescentou-se a páginaQA protegida `/management/investment/tax-rules/{id}/qa-review`, ligada às APIs existentes de cálculo/gravação, recuperação e relatório imutável. **Exemplo observado no Edge:** base1000,03MZN e exigibilidade declarada21/10/2026 → IVA calculado160,0048 → execução`fa6d17f2-5f47-4cb6-b8cb-40850c12505f` gravada → recarga da página → recuperação do mesmoID no histórico → relatório`d13e2ad5-3ba8-4d01-9d30-5815496da774`, mesmo valor/contexto/proveniência e hash igual ao resultado guardado. Uma execução persistida; regra continua emdraft, zero publicadas. Não prova aplicabilidade fiscal a qualquer operação nem saldo a pagar.
A ferramenta perdeu inicialmente a ligação ao navegador e permaneceu sem inventário apesar das reactivações; essa limitação ficou registada, sem a atribuir ao simulador. A ligação foi depois restabelecida e concluiu-se apenas a parte não observada, com autenticação/segundo factor normais, sem contornar guardas. As provas aceites de83d2f97d são reutilizadas;1teste novo de rota/17asserções,TypeScript/build e a observação browser cobrem o delta. Não se atribui ao utilizador conferência local ou validação jurídica. Não há nova preparação genérica identificada para este recorte; integração e activação continuam separadas.
@@ -0,0 +1,281 @@
{
"base": "59ab4fe95635",
"branch": "codex/simulator-integrated-review",
"scope": "QA only; no main merge or remote change",
"source_files": [
{
"path": "config/app.php",
"sha256": "a01f552093570f8744f7b874392824c15b5a6b49d61759273a658e8660a1d240"
},
{
"path": "docs/investmoz/unification/traceability-and-manual.md",
"sha256": "347c340bcc4f5adc7965bd66cef1f357d98b6c271fdcd35206a3a086e59ad34d"
},
{
"path": "docs/investmoz/v2/auditoria-portal/backlog-priorizado.csv",
"sha256": "a3473a391634c32fa8c53ecb2528b4de08f145ec0284b50f3bbf89aa97e5cf24"
},
{
"path": "docs/investmoz/v2/auditoria-portal/backlog.md",
"sha256": "1294586bfd452e6430aa1fcb71a512cbf64177e529a416ac28dfab954839664b"
},
{
"path": "docs/investmoz/v2/auditoria-portal/matriz-requisitos.csv",
"sha256": "f57861a36e310a892d55a16be6d06fecd48763defe11011036df8a3a33a57d6d"
},
{
"path": "lang/pt.json",
"sha256": "c21fa0b63a3729e001f7d4ba891a23890bcfcfd718137d99a7c6c18d3be1a235"
},
{
"path": "lang/pt/auth.php",
"sha256": "d32cc31b75d4056ef561baf501d9cbf71ec136c7f63bef635c0c3e31b9a2357d"
},
{
"path": "lang/pt/validation.php",
"sha256": "bb95fe0f683cd6d8a6d0475dc322c71bce58197b952220e70ac74f5e97cdcf60"
},
{
"path": "resources/js/components/appearance-tabs.tsx",
"sha256": "d53f48b0883713bf786fdf4b7877e03638bcf2e707b64ea6b8559501bfc8c4c7"
},
{
"path": "resources/js/components/delete-user.tsx",
"sha256": "2f94b4dc6edf20bf9e00940d4d7e7b5da31bdf560f26b84efd65672bcee585b8"
},
{
"path": "resources/js/components/manage-passkeys.tsx",
"sha256": "8f3e8970d3b82deba721ac27e57718e2e7dcecc67b1e78cb6404c475c9f9c62e"
},
{
"path": "resources/js/components/manage-two-factor.tsx",
"sha256": "35fea615cf3a0454448057b0ef3137e24c21df4de30a58fce04cb847eb89eba1"
},
{
"path": "resources/js/components/passkey-item.tsx",
"sha256": "a307c5ef209e24f3f913f77e355a4d04a1433f59f520ad45ad40112111ab4677"
},
{
"path": "resources/js/components/passkey-register.tsx",
"sha256": "e7cb9d853eb943fd0899bc8530378eddbf941f9334a77bcbb7693d2e29d99470"
},
{
"path": "resources/js/components/passkey-verify.tsx",
"sha256": "6db387920437ab39cd734a2af9bec7e64ae6469c0f1b368d536b275e57cbea37"
},
{
"path": "resources/js/components/simulation-fiscal-status.tsx",
"sha256": "540dc6addbec0be79114526f7d27f53942291b0c7be05a2608a515498970d3e0"
},
{
"path": "resources/js/components/simulation-form.tsx",
"sha256": "1b2d3a917e354eef7ccdb47201fb7e515ea646d45099beb9b15798c80e1dd2db"
},
{
"path": "resources/js/components/two-factor-recovery-codes.tsx",
"sha256": "9384ae3987a58ae89018f2a997dec7faebec4f51f516ebbdc2b337c8e757f00f"
},
{
"path": "resources/js/components/two-factor-setup-modal.tsx",
"sha256": "8586833e10310dbca8a097df80b86f40638f874170b7668fa476f0d7017a311b"
},
{
"path": "resources/js/components/ui/dialog.tsx",
"sha256": "abeb6df2254f0bf5f73de1c9b5aeb4e667afe8ac0319e8b9aa099a612cc70b8d"
},
{
"path": "resources/js/components/ui/sheet.tsx",
"sha256": "a525cc98beaf974e0dfe6cda1c5da1101798b6843ea355a758b3c5df5235f506"
},
{
"path": "resources/js/components/user-menu-content.tsx",
"sha256": "9cb79c2a999bb363bd9d4fc1869b672c474b088eff23fca6e9f588ecae00d3ce"
},
{
"path": "resources/js/hooks/use-two-factor-auth.ts",
"sha256": "16d9434379531f1994096e4d1fcfd778b2c829602cce5731d602a25ea9c0073f"
},
{
"path": "resources/js/layouts/settings/layout.tsx",
"sha256": "78ea66c1eb6cad907e23de9c81a4d309a127f251355f04771f72eb5689609a4e"
},
{
"path": "resources/js/lib/project-dossier-document.ts",
"sha256": "d0a66ca759e8710c1a3900bcd27cc7f0506587c782ab798c49703396c1fb31d6"
},
{
"path": "resources/js/lib/project-dossier-report.ts",
"sha256": "6c5f52362a6218048f321b41211bfd328fa1e19ea4ab45fd1424932130482c8d"
},
{
"path": "resources/js/lib/simulation-form.ts",
"sha256": "40df1a9b6939b1910d12045835e981d6e47d4c1d534775631ac2f6b655a5e2bd"
},
{
"path": "resources/js/pages/auth/forgot-password.tsx",
"sha256": "6cdedca491d5a05dad0083fb637cd618d0b290bd6b48b98e7c6163dc0d740166"
},
{
"path": "resources/js/pages/auth/login.tsx",
"sha256": "8468308dacd26bd94ee41683684dcb7719386a1a53196ed90496ca406b1b94da"
},
{
"path": "resources/js/pages/auth/reset-password.tsx",
"sha256": "f3561726ae5d7ee682d968a295bbf60ec9f8cbabba1721c33f48bafd80d1b20a"
},
{
"path": "resources/js/pages/auth/two-factor-challenge.tsx",
"sha256": "0fd14dff2f0a572f4b99905d0fb152baa476eaa55a221998b67da85fa4787610"
},
{
"path": "resources/js/pages/auth/verify-email.tsx",
"sha256": "ffc3220d0ee6cc243e8e08ea46f8b1637794626fa45d7aeaa77f54203692864d"
},
{
"path": "resources/js/pages/portal/services.tsx",
"sha256": "9369add7c012c1e8a9e217b46be55e2927382bb8f18b90973d3b1f4199442d9b"
},
{
"path": "resources/js/pages/settings/appearance.tsx",
"sha256": "638367104837b028aeeb49b4cad1d2c9a44a92d1b9aebe71c31995605e0479b4"
},
{
"path": "resources/js/pages/settings/profile.tsx",
"sha256": "c599b1ca523ece69c3f5d3fe480a9f2ce4c323e97afb42095f61f2ddb7d4ba7b"
},
{
"path": "resources/js/pages/settings/security.tsx",
"sha256": "39264620329657af975f990a50d657c42186ead57458cd83040aa07f9cd78444"
},
{
"path": "tests/frontend/project-dossier-report.test.mjs",
"sha256": "fcdcabfc659f2f4ca0d5a51e592719d53d51420271c7cbe350176b48cef3fc97"
},
{
"path": "tests/frontend/simulation-form.test.mjs",
"sha256": "294a1b996d8131771ebaca85d2ff0e44bb6afd62e460073b7535486f13ae3a6b"
}
],
"evidence": [
{
"path": "outputs/simulator-integrated-review/effective-parameter-inventory.json",
"sha256": "aeec1251ef5dbbf7ae547af9f1ebcd2575aaa6c251ef65b37c6c31b8cf371acc"
},
{
"path": "outputs/simulator-integrated-review/independent-controls-proof.json",
"sha256": "47ad49b2136fd74c801b7a5d057c891732d820fb6a5002ccf08c71a2ffabf575"
},
{
"path": "outputs/simulator-integrated-review/visible-language-inventory.json",
"sha256": "5f1f50236ae492c8428a9528af350900e4f2c44c387fe8f23ebce0e4f1b14b3a"
},
{
"path": "outputs/simulator-integrated-review/dynamic-language-inventory.json",
"sha256": "fe3246f570c333c2c59e9fe2acb0ec01078a158a46e53d37087ec59d419578a5"
},
{
"path": "outputs/simulator-integrated-review/portuguese-validation-proof.json",
"sha256": "b7a454cdc1e934faada40b683ff2b7a6edce73aebfd22ba34e5da17a1854b0a1"
},
{
"path": "outputs/simulator-integrated-review/http-reports-proof.json",
"sha256": "9d37fbee89f7dc556ff9496f6b0980e1c9626790eb50a41a499cf23e2f27fe5f"
},
{
"path": "outputs/simulator-integrated-review/date-field-error.jpg",
"sha256": "6a792c09c61857a0a064a56d3d61b47fc2adc1d6c8bcf627161f6fa77c7b099d"
},
{
"path": "outputs/simulator-integrated-review/stale-result.jpg",
"sha256": "84b37c41ba47d44f52979e83dbc3426184f5cbfee6d38e7c7d4caa3be225320b"
},
{
"path": "outputs/simulator-integrated-review/tax-lookup-error.jpg",
"sha256": "d3f366690fa3acbda45bc021ade90dc003cea7dc0517c4d2932935548dbb40d0"
},
{
"path": "outputs/simulator-integrated-review/positivo.docx",
"sha256": "61b1ea80476922aa1be8c29f9a757b389c3ecc8f0e75f414a29eddd5b37ecefd"
},
{
"path": "outputs/simulator-integrated-review/positivo-model.json",
"sha256": "fc8df79e7ce81e4a475b99f5ea07763c1cee140bc9dcb24550ed26ce412e4e0d"
},
{
"path": "outputs/simulator-integrated-review/checked-positivo/positivo.pdf",
"sha256": "60d655b33fcc27dbbaae40a0739c1ebeb9b366df9b00621a6536feecd60da452"
},
{
"path": "outputs/simulator-integrated-review/negativo.docx",
"sha256": "f266cff1a1f9f63449703cc5ef51a7f4d2d7bf94230be70ae382bc89af8139bd"
},
{
"path": "outputs/simulator-integrated-review/negativo-model.json",
"sha256": "6aff37f66695e1d2a7441bf7b361f7980bc10f6951f915713f55a01e5b00da48"
},
{
"path": "outputs/simulator-integrated-review/checked-negativo/negativo.pdf",
"sha256": "3a2577194bc6c9e7234b650e69f3795f6cef6aef41d62658839c0790989a8f5c"
},
{
"path": "outputs/simulator-integrated-review/nulo.docx",
"sha256": "efb83aa9044e35515880e40641d6bea52c6ea6f81289c3abc9d3bdbc76a9ba26"
},
{
"path": "outputs/simulator-integrated-review/nulo-model.json",
"sha256": "94bbc6cf72cc613ebcd5ab9e9c074220b2f50dfb5b03959e92a7c84032a86750"
},
{
"path": "outputs/simulator-integrated-review/checked-nulo/nulo.pdf",
"sha256": "c93e989a7af230e56f5d01766a4e386161e6fbbfa99341d5bfa0569bafe9e18e"
},
{
"path": "outputs/simulator-integrated-review/incompleto.docx",
"sha256": "026f0ff1877ed5f23359d220e3223a319c213e742ff9704d81812fc2ed3ae20e"
},
{
"path": "outputs/simulator-integrated-review/incompleto-model.json",
"sha256": "748b9cecde2acc99d7e2bbfd16188bf9f9ac0ab411ad850ba687c6e1f2e36cf5"
},
{
"path": "outputs/simulator-integrated-review/checked-incompleto/incompleto.pdf",
"sha256": "0daac41c80ae131df6d66b7b542353a61a804d02d2e77769b9e5cc2bc9cfbc88"
},
{
"path": "outputs/simulator-integrated-review/completed-calculation.jpg",
"sha256": "7180ff0f536e2e377c2a28b85574ec7c7fefcce5eed28ed08f07628b16870293"
}
],
"checks": {
"targeted_frontend": 34,
"typescript": "passed",
"php_lint": "passed",
"build": "passed",
"reports_pages": {
"positivo": 6,
"negativo": 6,
"nulo": 6,
"incompleto": 5
},
"tax_lookup_retry": "503 then successful lookup; IVA; 2026-01-01 through 2026-12-31; indeterminate parameters",
"arithmetic_ui": "100*16/100*(1-25/100)=12; base change removes result",
"build_manifest_sha256": "af96a5f5682dad7a741d0ee8b302d8dc7f4d08a1806bc000265bd2602e5bfc61",
"terminal_status_ui": "200*16/100*(1-25/100)=24; completed notice visible; awaiting-calculation notice absent"
},
"remaining_hours": [
6,
10
],
"limitations": [
"No published fiscal rule versions in QA; no legal tax validation",
"Authenticated cross-dossier and new-session frontend delta still pending",
"Parameter-version change and additional business-plan/cash-flow controls pending",
"PDF examples are DOCX rendering; native Edge print and final UI download comparison pending",
"Dynamic backend/catalogue messages and directed save/export error checks remain open"
],
"deployment": {
"authorised_now": false,
"migrations": [],
"locale_on_future_deploy": "APP_LOCALE=pt; preserve existing secrets"
}
}
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,15 @@
# Governação de versões de regras fiscais
## Correcção de controlo — decisão expressa da Tempo,21/10/2026
A manutenção dos parâmetros fiscais reutiliza a administração já autorizada, com autenticação/MFA, fonte, versão, responsável e histórico. Uma mesma pessoa pode concluir `submit` → `review` → `approve` → `publish`; esses estados preservam o percurso técnico e os eventos, sem afirmar independência pessoal ou parecer jurídico. As quatro listas específicas de permissões permanecem opcionais. A utilização do simulador pelo investidor conserva as permissões e os limites próprios, separados da manutenção.
A obrigação de actores distintos foi encontrada no serviço fiscal e nosCHECKs da migration de03/10/2026, incorporados em `e65cb269` (06/10/2026), e descrita como implementação em `simulator-evolution-progress.md`. Não foi localizada uma decisão expressa da Tempo ou requisito aplicável que a imponha ao cadastro fiscal. A origem identificada é escolha de implementação; a autoria ou integração do commit não demonstra aprovação dessa regra organizacional. A decisão actual da Tempo manda removê-la neste fluxo, sem alterar a independência acordada nas oportunidades, perfis ou outros processos.
A correcçãoQA retira apenas as comparações de identidade entre autor/revisor/aprovador/publicador dos controlos fiscais; mantém campos obrigatórios, evidência, datas, etapas, versão optimista, fonte, bloqueios, RLS e eventos imutáveis. Para cadastrar uma fonte oficial neste percurso existe `POST /api/v2/investment/admin/tax-rule-sources`, sob a mesma administração autenticada. Recebe os metadados existentes mais `sha256`, `citation` e `official_origin`; regista a aceitação da fonte oficial segundo a decisão Tempo de08/10/2026, o responsável real e a indicação explícita de que não é parecer jurídico nem revisão independente. O hash da regra tem de coincidir com o exemplar cadastrado. A fonte permanece pending no estado geral: a aceitação fiscal não a valida para outros módulos. A projecção pública e o resolvedor fiscal reconhecem esse fundamento e o hash correspondente, sem alterar a fórmula. A fonte não activa nem publica uma regra automaticamente. A validação normal de fontes para os outros processos mantém o seu controlo; não se alteraram os workflows de oportunidades/zonas/perfis.
Migration de correcção: `2026_10_21_130000_correct_fiscal_maintenance_actor_constraints.php`, protegida contra execução fora deQA isolado. Acrescenta metadados de aceitação fiscal à fonte e corrige osCHECKs que impediam o actor único. Foi ensaiada apenas emQA, com6testes/86asserções do controlo alterado, sem cálculo, build ou repetição dos testes aritméticos/exportadores. O manual consolidado regista provas e procedimento actualizado das três operações. Os estados históricos abaixo descrevem o incremento original e não reabrem as provas já aceites da candidata226fd308.
## Âmbito deste incremento
Foi criado um fluxo administrativo para registar uma versão declarativa de regra e a sua referência jurídica. O fluxo existe separado do motor de cálculo. Nenhum endpoint de simulação consulta `simulation_tax_rule_versions`; `published` significa apenas publicada no registo interno de governação, não activa no produto nem aprovada para aconselhamento fiscal.

Some files were not shown because too many files have changed in this diff Show More