@@ -132,9 +132,11 @@ class InvestorGuidance
|
||||
$actions = ['opportunities' => '/oportunidades', 'locations' => '/oportunidades?view=map', 'partners' => '/parcerias',
|
||||
'documents' => '/documentos', 'plan' => $case->submission_id && (int) $case->user_id === $actor->id ? '/investidor/manifestacoes/'.$case->submission_id : '/balcao-virtual/dossiers/'.$id,
|
||||
'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id];
|
||||
// The simulator recovers its current owner-scoped draft; do not pass private payload in URLs.
|
||||
// Pin the linked owner-scoped draft instead of opening another project's current draft.
|
||||
// The receiving API still enforces ownership; no private payload is carried in the URL.
|
||||
if ($case->simulation_id && $context['financial_draft'] !== null) {
|
||||
$actions['plan'] = '/simulador-fiscal';
|
||||
$actions['simulator'] = '/simulador-fiscal?draft='.rawurlencode($case->simulation_id);
|
||||
$actions['plan'] = $actions['simulator'];
|
||||
}
|
||||
$phases = $this->rules->evaluate($context['facts'], $context['evidence']);
|
||||
foreach ($phases as &$phase) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class BusinessFormSchema
|
||||
@@ -13,7 +14,8 @@ final class BusinessFormSchema
|
||||
return [
|
||||
'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']],
|
||||
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
|
||||
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição (código ISO de duas letras)', 'en' => 'Country of origin or incorporation (two-letter ISO code)', 'type' => 'text', 'max' => 2],
|
||||
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição', 'en' => 'Country of origin or incorporation', 'type' => 'country', 'max' => 100],
|
||||
'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem declarado desta solicitação (opcional)', 'en' => 'Declared country of origin of this request (optional)', 'type' => 'country', 'max' => 2],
|
||||
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50],
|
||||
'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200],
|
||||
'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
|
||||
@@ -77,7 +79,7 @@ final class BusinessFormSchema
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<int,string>> */
|
||||
/** @return array<string, list<string|\Closure|In>> */
|
||||
public static function rules(): array
|
||||
{
|
||||
$rules = [];
|
||||
@@ -89,7 +91,8 @@ final class BusinessFormSchema
|
||||
}
|
||||
$rules['payload.contact_email'][] = 'nullable';
|
||||
$rules['payload.contact_email'][] = 'email';
|
||||
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/';
|
||||
$rules['payload.country'][] = app(CountryCatalogue::class)->legacyCountryRule();
|
||||
$rules['payload.declared_origin_country_code'][] = app(CountryCatalogue::class)->rule();
|
||||
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
|
||||
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
@@ -122,6 +125,8 @@ final class BusinessFormSchema
|
||||
$rules[$field] = ['required'];
|
||||
}
|
||||
$rules['sector_id'] = ['required'];
|
||||
$rules['country'] = ['required', 'string', app(CountryCatalogue::class)->rule()];
|
||||
$rules['declared_origin_country_code'] = ['nullable', 'string', app(CountryCatalogue::class)->rule()];
|
||||
$rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email'];
|
||||
$rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/'];
|
||||
$rules['legitimacy_declaration'] = ['required', 'in:yes'];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
|
||||
/** Shared ISO identifiers; independent of administrative territories and IP data. */
|
||||
final class CountryCatalogue
|
||||
@@ -28,8 +29,28 @@ final class CountryCatalogue
|
||||
return $countries;
|
||||
}
|
||||
|
||||
public function rule(): \Illuminate\Validation\Rules\In
|
||||
public function rule(): In
|
||||
{
|
||||
return Rule::in(array_column($this->all(), 'code'));
|
||||
}
|
||||
|
||||
/** Accept existing free-text integrations; validate ISO-shaped values without rewriting them. */
|
||||
public function legacyCountryRule(): \Closure
|
||||
{
|
||||
$codes = array_column($this->all(), 'code');
|
||||
|
||||
return static function (string $attribute, mixed $value, \Closure $fail) use ($codes): void {
|
||||
if (is_string($value) && preg_match('/^[a-zA-Z]{2}$/D', $value) && ! in_array($value, $codes, true)) {
|
||||
$fail('Seleccione um código ISO de país válido.');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** @return array{code:string|null,name:string} */
|
||||
public function describe(?string $code): array
|
||||
{
|
||||
$names = array_column($this->all(), 'name', 'code');
|
||||
|
||||
return isset($names[$code ?? '']) ? ['code' => $code, 'name' => $names[$code]] : ['code' => null, 'name' => 'Não informado'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
@@ -28,14 +29,23 @@ final class DeclaredOriginStatistics
|
||||
$desk[$key] = ($desk[$key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
$businesses = [];
|
||||
if (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 : '';
|
||||
$businesses[$key] = ($businesses[$key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
// Distinct request collections; summing them could count the same investor twice.
|
||||
if ($origin !== null && $origin !== '') {
|
||||
$key = $origin === 'unknown' ? '' : $origin;
|
||||
$groups = array_intersect_key($groups, [$key => true]);
|
||||
$desk = array_intersect_key($desk, [$key => true]);
|
||||
$businesses = array_intersect_key($businesses, [$key => true]);
|
||||
}
|
||||
|
||||
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names)];
|
||||
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names), 'businesses' => $this->format($businesses, $names)];
|
||||
}
|
||||
|
||||
/** @param array<string, int> $counts
|
||||
|
||||
@@ -81,7 +81,8 @@ final class ExistingBusinessIntake
|
||||
} elseif (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
Validator::make($business->payload, [
|
||||
'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'],
|
||||
'contact_email' => ['required', 'email'], 'country' => ['required', 'regex:/^[A-Z]{2}$/'],
|
||||
'contact_email' => ['required', 'email'], 'country' => ['required', app(CountryCatalogue::class)->rule()],
|
||||
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
|
||||
'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'],
|
||||
'legitimacy_declaration' => ['required', 'in:yes'],
|
||||
'mandate_reference' => ['required_if:acting_capacity,representative'],
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
final class InvestorPath
|
||||
{
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return (bool) config('investor-path.enabled') && $this->desk->installed()
|
||||
&& Schema::hasColumn('investor_journeys', 'path_definition_id') && Schema::hasColumn('journey_steps', 'path_detail');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function create(User $actor, array $input): string
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
|
||||
return DB::transaction(function () use ($actor, $input): string {
|
||||
$case = $this->desk->createCase($actor, $input);
|
||||
$this->initialize($actor, $case->id);
|
||||
|
||||
return $case->id;
|
||||
});
|
||||
}
|
||||
|
||||
public function initialize(User $actor, string $id): void
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
DB::transaction(function () use ($actor, $id): void {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
if ($case->journey_id) {
|
||||
$existing = DB::table('investor_journeys')->where('id', $case->journey_id)->firstOrFail();
|
||||
// Never convert or renumber a saved portfolio/legacy journey implicitly.
|
||||
abort_unless($existing->path_definition_id !== null, 409, 'O percurso existente foi preservado; a conversão exige uma correspondência explícita.');
|
||||
|
||||
return;
|
||||
}
|
||||
$version = DB::table('questionnaire_versions')->where('id', config('investor-path.definition_id'))
|
||||
->where('code', 'investor-path-19')->where('status', 'published')->firstOrFail();
|
||||
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
|
||||
InvestorPathDefinition::validate($definition);
|
||||
$journey = (string) Str::uuid();
|
||||
DB::table('investor_journeys')->insert(['id' => $journey, 'investor_id' => $case->investor_id, 'user_id' => $actor->id,
|
||||
'status' => 'started', 'path_definition_id' => $version->id, 'source_system' => 'investor-path', 'data_classification' => 'confidential']);
|
||||
foreach ($definition['steps'] as $step) {
|
||||
DB::table('journey_steps')->insert(['id' => (string) Str::uuid(), 'journey_id' => $journey, 'step_code' => $step['code'],
|
||||
'sequence_no' => $step['sequence'], 'status' => 'pending', 'source_system' => 'investor-path', 'data_classification' => 'confidential',
|
||||
'path_detail' => $this->desk->encode(['state' => 'not_started'])]);
|
||||
}
|
||||
DB::table('desk_cases')->where('id', $id)->update(['journey_id' => $journey, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'investor_path_started', ['journey_id' => $journey, 'definition_id' => $version->id, 'source_sha256' => $definition['source_sha256']]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function view(User $actor, string $id): array
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$case = $this->desk->case($actor, $id);
|
||||
$journey = DB::table('investor_journeys')->where('id', $case->journey_id)->whereNull('deleted_at')->firstOrFail();
|
||||
abort_unless($journey->path_definition_id !== null, 409, 'Este dossier conserva o seu roteiro original.');
|
||||
$version = DB::table('questionnaire_versions')->where('id', $journey->path_definition_id)->firstOrFail();
|
||||
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$path = $payload['investor_path'] ?? [];
|
||||
$facts = $path['facts'] ?? ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
|
||||
$records = DB::table('journey_steps')->where('journey_id', $journey->id)->whereNull('deleted_at')->get()->keyBy('step_code');
|
||||
$steps = [];
|
||||
foreach ($definition['steps'] as $step) {
|
||||
$row = $records->get($step['code']);
|
||||
abort_unless($row !== null, 409, 'Etapa em falta; reparar a instalação sem reconstruir o histórico.');
|
||||
$detail = $this->desk->decode($row->path_detail);
|
||||
$value = $step['branch'] ? ($facts[$step['branch']] ?? 'unknown') : 'yes';
|
||||
$applicable = $value === 'unknown' ? 'undetermined' : ($value === 'no' ? 'not_needed_for_preparation' : 'applicable');
|
||||
$state = $value === 'no' ? 'dispensed' : $detail['state'];
|
||||
$steps[] = [...$step, 'id' => $row->id, 'version' => $row->version_no, 'state' => $state, 'saved_state' => $detail['state'],
|
||||
'applicability' => $applicable, 'reason' => $value === 'no' ? ($path['fact_reasons'][$step['branch']] ?? '') : ($detail['reason'] ?? ''),
|
||||
'detail' => $detail, 'preparation_allowed' => $value !== 'no',
|
||||
'action_gaps' => []];
|
||||
}
|
||||
$byCode = collect($steps)->keyBy('code');
|
||||
foreach ($steps as &$step) {
|
||||
foreach ($step['dependencies'] as $action => $dependencies) {
|
||||
$step['action_gaps'][$action] = array_values(array_filter($dependencies, function ($code) use ($byCode) {
|
||||
$dependency = $byCode->get($code);
|
||||
|
||||
// Branch dispensation is not evidence of any legal permission.
|
||||
return ! in_array($dependency['state'], ['completed', 'approved'], true);
|
||||
}));
|
||||
}
|
||||
}
|
||||
unset($step);
|
||||
foreach ($steps as &$step) {
|
||||
if (in_array($step['state'], ['completed', 'submitted'], true)
|
||||
&& count(array_filter($step['action_gaps'])) > 0) {
|
||||
$step['state'] = 'correction_required';
|
||||
$step['reason'] = 'Uma dependência desta acção foi reaberta; reveja o avanço. O registo original foi preservado.';
|
||||
}
|
||||
}
|
||||
unset($step);
|
||||
$owner = $this->desk->owns($actor, $case);
|
||||
$manager = $actor->can('manage-portal');
|
||||
$requests = DB::table('desk_requests')->where('case_id', $id)
|
||||
->when(! $owner && ! $manager, fn ($q) => $q->where('analyst_id', $actor->id))
|
||||
->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'version']);
|
||||
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.case_id', $id)->whereNull('d.deleted_at')
|
||||
->when(! $owner && ! $manager, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', $requests->pluck('id'))))
|
||||
->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status']);
|
||||
// Only the private draft owner can receive the financial snapshot/result. Dossier access alone is insufficient.
|
||||
$results = (int) $case->user_id === $actor->id ? ($path['results'] ?? []) : [];
|
||||
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
|
||||
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $path['fact_reasons'] ?? [],
|
||||
'canWrite' => $owner && ! $case->closed_at, 'canReview' => $manager && (int) $case->user_id !== $actor->id && ! $case->closed_at,
|
||||
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => '#'.$next['code']] : null,
|
||||
'results' => $results, 'requests' => $requests, 'documents' => $documents,
|
||||
'tasks' => DB::table('tasks')->where('desk_case_id', $id)
|
||||
->whereNull('deleted_at')
|
||||
->when(! $owner && ! $manager, fn ($q) => $q->where('assignee_user_id', $actor->id))
|
||||
->get(['id', 'title', 'status', 'version_no', 'due_at', 'assignee_user_id']),
|
||||
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'definition'])
|
||||
->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title']]),
|
||||
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '') : null,
|
||||
'desk' => '/balcao-virtual/dossiers/'.$id, 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
|
||||
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function facts(User $actor, string $id, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1',
|
||||
'land_needed' => ['required', Rule::in(['yes', 'no', 'unknown'])], 'external_funding' => ['required', Rule::in(['yes', 'no', 'unknown'])],
|
||||
'viability' => ['required', Rule::in(['unknown', 'proceed', 'reformulate', 'archive'])],
|
||||
'reason' => 'required|string|min:3|max:3000'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data): void {
|
||||
$case = $this->writable($actor, $id, $data['version']);
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
foreach (['land_needed', 'external_funding', 'viability'] as $key) {
|
||||
$payload['investor_path']['facts'][$key] = $data[$key];
|
||||
$payload['investor_path']['fact_reasons'][$key] = $data['reason'];
|
||||
}
|
||||
$this->savePayload($case, $payload);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_applicability_declared', $data);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function stage(User $actor, string $id, string $code, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'state' => ['required', Rule::in(array_diff(InvestorPathDefinition::STATES, ['dispensed']))],
|
||||
'reason' => 'required|string|min:3|max:3000', 'action' => ['required', Rule::in(['prepare', 'submit', 'execute', 'operate', 'review', 'record_external'])],
|
||||
'document_id' => 'nullable|uuid', 'authority' => 'nullable|string|max:200', 'reference' => 'nullable|string|max:300',
|
||||
'decision_date' => 'nullable|date_format:Y-m-d|before_or_equal:today'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $code, $data): void {
|
||||
$case = $this->desk->case($actor, $id, false, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão actual.');
|
||||
$view = $this->view($actor, $id);
|
||||
$step = $this->findStep($view, $code);
|
||||
abort_unless($step !== null && $step['preparation_allowed'], 422, 'Etapa dispensada de preparação; altere os pressupostos com fundamento.');
|
||||
$state = $data['state'];
|
||||
$internal = in_array($state, ['reviewing', 'correction_required'], true);
|
||||
$external = in_array($state, ['approved', 'rejected', 'expired'], true);
|
||||
$scope = 'investor_preparation';
|
||||
if ($internal || $external) {
|
||||
abort_unless($view['canReview'], 403, 'A conferência interna exige um responsável distinto do promotor.');
|
||||
abort_unless($data['action'] === ($external ? 'record_external' : 'review'), 422);
|
||||
$scope = $external ? 'external_document_recorded' : 'internal_validation';
|
||||
} else {
|
||||
abort_unless($view['canWrite'], 403);
|
||||
abort_unless(! in_array($data['action'], ['review', 'record_external'], true), 422);
|
||||
if ($state === 'submitted') {
|
||||
abort_unless($data['action'] === 'submit' && ! empty($data['reference']), 422, 'Registe a referência da submissão; guardar não equivale a submeter.');
|
||||
}
|
||||
}
|
||||
if ($external || $data['action'] !== 'prepare') {
|
||||
abort_unless(empty($step['action_gaps'][$data['action']] ?? []), 422,
|
||||
'Dependências reais da acção: '.implode(', ', $step['action_gaps'][$data['action']] ?? []));
|
||||
}
|
||||
if ($external) {
|
||||
abort_unless(! empty($data['document_id']) && ! empty($data['authority']) && ! empty($data['reference']) && ! empty($data['decision_date']), 422, 'Registe documento, entidade, referência e data do acto externo.');
|
||||
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)
|
||||
->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256']);
|
||||
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento de decisão ainda não consultável.');
|
||||
}
|
||||
// Completion of a legal/finance/operation action requires the corresponding evidence; preparation can proceed independently.
|
||||
if ($state === 'completed' && in_array($code, ['S07', 'S08', 'S10', 'S11', 'S14', 'S15', 'S17', 'S18'], true)) {
|
||||
abort_unless(($step['saved_state'] ?? '') === 'approved' && in_array($data['action'], ['execute', 'operate'], true), 422, 'Conclusão operacional exige acto externo documentado; use preparação enquanto aguarda.');
|
||||
}
|
||||
$detail = [...$data, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
|
||||
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($detail),
|
||||
'status' => in_array($state, ['completed', 'approved'], true) ? 'completed' : ($state === 'not_started' ? 'pending' : 'active'),
|
||||
'version_no' => $step['version'] + 1, 'updated_at' => now()]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_stage_recorded', ['code' => $code, ...$detail]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function returnTool(Request $request, string $id, array $input): array
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'draft_id' => 'required|uuid', 'draft_version' => 'required|integer|min:1'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($request, $id, $data): array {
|
||||
$actor = $request->user();
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
abort_unless($case->simulation_id === $data['draft_id'] && (int) $case->user_id === $actor->id, 403, 'Ferramenta pertencente a outro contexto.');
|
||||
$draft = app(SimulationFormDrafts::class)->find($data['draft_id'], $request);
|
||||
abort_unless($draft->version_no === $data['draft_version'], 409, 'O rascunho mudou; aguarde a gravação e volte a recuperar o resultado.');
|
||||
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
$snapshot = $economic['financial_tools_snapshot'] ?? null;
|
||||
abort_unless(is_string($snapshot) && strlen($snapshot) <= 30000, 422, 'Guarde primeiro as entradas da ferramenta financeira.');
|
||||
$parsed = json_decode($snapshot, true);
|
||||
abort_unless(is_array($parsed) && ($parsed['version'] ?? null) === 1 && is_array($parsed['data'] ?? null), 422, 'Snapshot financeiro incompatível.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$resultKey = hash('sha256', $draft->id.':'.$draft->version_no.':'.$snapshot);
|
||||
foreach ($payload['investor_path']['results'] ?? [] as $result) {
|
||||
if ($result['source_key'] === $resultKey) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'Recupere a versão actual do dossier.');
|
||||
$result = ['id' => (string) Str::uuid(), 'source_key' => $resultKey, 'draft_id' => $draft->id, 'draft_version' => $draft->version_no,
|
||||
'snapshot_sha256' => $draft->snapshot_sha256, 'financial_snapshot' => $snapshot,
|
||||
'currency' => $economic['currency'] ?? null, 'engine' => 'financial-calculators:v1',
|
||||
'kind' => 'local_calculation_inputs', 'recorded_at' => now()->toIso8601String()];
|
||||
$payload['investor_path']['results'][] = $result;
|
||||
abort_unless(count($payload['investor_path']['results']) <= 100, 422, 'Limite de evidências financeiras deste dossier atingido.');
|
||||
$this->savePayload($case, $payload);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'tool_evidence_returned', array_diff_key($result, ['financial_snapshot' => true]));
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function contexts(User $actor): array
|
||||
{
|
||||
if (! $this->available()) {
|
||||
return [];
|
||||
}
|
||||
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
|
||||
|
||||
$contexts = DB::table('desk_cases as c')->join('investor_journeys as j', 'j.id', '=', 'c.journey_id')->whereNotNull('j.path_definition_id')
|
||||
->whereNull('j.deleted_at')->whereNull('c.closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('c.user_id', $actor->id)->whereNull('c.organization_id'))->orWhereIn('c.organization_id', $organizations))
|
||||
->orderByDesc('c.updated_at')->get(['c.id', 'c.title', 'c.version', 'c.updated_at'])
|
||||
->map(fn ($row) => ['id' => $row->id, 'title' => $row->title, 'version' => $row->version, 'updated_at' => $row->updated_at])->all();
|
||||
|
||||
return array_values($contexts);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function task(User $actor, string $id, array $input): string
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'code' => ['required', Rule::in(array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19)))],
|
||||
'title' => 'required|string|min:3|max:200', 'due_at' => 'required|date|after:now', 'consent' => 'accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data): string {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
$key = 'path:'.$data['code'];
|
||||
$existing = DB::table('tasks')->where('desk_case_id', $id)->where('guidance_key', $key)->first();
|
||||
if ($existing) {
|
||||
abort_unless($existing->title === $data['title'] && (int) $existing->accepted_by === $actor->id
|
||||
&& Carbon::parse($existing->due_at)->equalTo(Carbon::parse($data['due_at'])), 409, 'A tarefa desta etapa já existe com outros dados.');
|
||||
|
||||
return $existing->id;
|
||||
}
|
||||
$this->writable($actor, $id, $data['version']);
|
||||
$step = $this->findStep($this->view($actor, $id), $data['code']);
|
||||
abort_unless($step !== null && $step['preparation_allowed'], 422);
|
||||
$task = CrmTask::create(['desk_case_id' => $id, 'guidance_key' => $key, 'title' => $data['title'], 'due_at' => $data['due_at'],
|
||||
'status' => 'open', 'assignee_user_id' => $actor->id, 'accepted_by' => $actor->id, 'accepted_at' => now(),
|
||||
'external_sync_status' => 'pending_authorization', 'data_classification' => 'confidential', 'source_system' => 'investor-path']);
|
||||
$this->desk->event($case, $actor, 'path_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'scope' => 'internal_crm']);
|
||||
|
||||
return $task->id;
|
||||
});
|
||||
}
|
||||
|
||||
private function writable(User $actor, string $id, int $version): \stdClass
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
abort_unless((int) $case->version === $version, 409, 'Recupere a versão actual do dossier.');
|
||||
$this->view($actor, $id);
|
||||
|
||||
return $case;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $view
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function findStep(array $view, string $code): ?array
|
||||
{
|
||||
if (! is_array($view['steps'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
foreach ($view['steps'] as $step) {
|
||||
if (is_array($step) && ($step['code'] ?? null) === $code) {
|
||||
return $step;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
private function savePayload(\stdClass $case, array $payload): void
|
||||
{
|
||||
DB::table('desk_cases')->where('id', $case->id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
final class InvestorPathDefinition
|
||||
{
|
||||
public const STATES = ['not_started', 'preparing', 'ready_to_submit', 'submitted', 'reviewing', 'correction_required', 'waiting_external', 'approved', 'rejected', 'dispensed', 'completed', 'expired'];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function snapshot(): array
|
||||
{
|
||||
$titles = ['Sistematizar a ideia', 'Análise preliminar', 'Decisão sobre a viabilidade', 'Estruturar o investimento',
|
||||
'Constituição e registo', 'Preparar o dossier', 'Submeter quando aplicável', 'Licenciamento prévio',
|
||||
'Necessidade de terra', 'Regularização da terra', 'Confirmar regularização aplicável',
|
||||
'Necessidade e estrutura de financiamento', 'Diligência e negociação financeira', 'Decisão do financiador',
|
||||
'Fecho e desembolso', 'Implementação', 'Inspecções, testes e licença de operação', 'Início de operação', 'Acompanhamento recorrente'];
|
||||
$steps = [];
|
||||
foreach ($titles as $index => $title) {
|
||||
$n = $index + 1;
|
||||
$steps[] = ['code' => sprintf('S%02d', $n), 'sequence' => $n, 'title' => $title,
|
||||
'phase' => $n <= 4 ? 1 : ($n <= 7 ? 2 : ($n <= 11 ? 3 : ($n <= 15 ? 4 : 5))),
|
||||
'source_paragraph' => 21 + $n,
|
||||
'branch' => $n === 10 ? 'land_needed' : (in_array($n, [13, 14, 15], true) ? 'external_funding' : null),
|
||||
// Preparation has no dependencies. These only constrain the named consequential action.
|
||||
'dependencies' => match ($n) {
|
||||
7 => ['submit' => ['S06']],
|
||||
15 => ['execute' => ['S14']],
|
||||
18 => ['operate' => ['S17']],
|
||||
default => [],
|
||||
}];
|
||||
}
|
||||
|
||||
return ['kind' => 'investor-path', 'version' => 1,
|
||||
'source_sha256' => 'aa13c53138ec15cd808de43d9dc2fc6808da86943d09d3352c9dd0944bdae364',
|
||||
'phases' => [1 => 'Ideia e viabilidade', 2 => 'Formalização e dossier', 3 => 'Licenciamento e terra', 4 => 'Financiamento', 5 => 'Execução e acompanhamento'],
|
||||
'states' => self::STATES, 'steps' => $steps,
|
||||
'legacy_roadmaps' => ['virtual-desk:E0-E11', 'investor-guidance:7-phases', 'investment-roadmap:14-activities']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $definition */
|
||||
public static function validate(array $definition): void
|
||||
{
|
||||
$steps = $definition['steps'] ?? [];
|
||||
$expected = array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19));
|
||||
if (count($definition['phases'] ?? []) !== 5 || array_column($steps, 'code') !== $expected
|
||||
|| array_column($steps, 'sequence') !== range(1, 19)) {
|
||||
throw new \LogicException('The five phases and nineteen source stages must remain traceable.');
|
||||
}
|
||||
$edges = [];
|
||||
foreach ($steps as $step) {
|
||||
if (! in_array($step['phase'], range(1, 5), true)
|
||||
|| ! in_array($step['branch'], [null, 'land_needed', 'external_funding'], true)) {
|
||||
throw new \LogicException('Unknown phase or applicability field.');
|
||||
}
|
||||
$edges[$step['code']] = [];
|
||||
foreach ($step['dependencies'] as $action => $dependencies) {
|
||||
if (! in_array($action, ['submit', 'execute', 'operate'], true)
|
||||
|| array_diff($dependencies, $expected)) {
|
||||
throw new \LogicException('Unknown action/dependency; preparation cannot be blocked.');
|
||||
}
|
||||
$edges[$step['code']] = array_merge($edges[$step['code']], $dependencies);
|
||||
}
|
||||
}
|
||||
$visit = function (string $code, array $trail) use (&$visit, $edges): void {
|
||||
if (in_array($code, $trail, true)) {
|
||||
throw new \LogicException('Cyclic action dependencies.');
|
||||
}
|
||||
foreach ($edges[$code] as $next) {
|
||||
$visit($next, [...$trail, $code]);
|
||||
}
|
||||
};
|
||||
foreach ($expected as $code) {
|
||||
$visit($code, []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,17 @@ class OpportunityManagement
|
||||
|
||||
public const FIELDS = ['title', 'summary', 'description', 'sector_id', 'promoter_name', 'promoter_type', 'maturity_level', 'maturity_label', 'financing_modality', 'expected_impact', 'estimated_investment_amount', 'estimated_investment_currency', 'opportunity_category', 'primary_territory_id', 'province', 'district', 'geography_scope'];
|
||||
|
||||
public const MATURITY_FIELDS = ['maturity_level', 'maturity_label', 'maturity_stage', 'maturity_catalogue_version'];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function values(Opportunity $record): array
|
||||
{
|
||||
$base = $record->only(self::FIELDS);
|
||||
$draft = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::MATURITY_FIELDS)))];
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasColumn('opportunities', 'management_version');
|
||||
@@ -44,7 +55,9 @@ class OpportunityManagement
|
||||
'title' => ['nullable', 'string', 'max:150'], 'summary' => ['nullable', 'string', 'max:500'],
|
||||
'description' => ['nullable', 'string', 'max:50000'], 'promoter_name' => ['nullable', 'string', 'max:200'],
|
||||
'promoter_type' => ['nullable', Rule::in(['public', 'private', 'ppp', 'cooperative', 'association', 'community', 'other', $id ? Opportunity::withTrashed()->findOrFail($id)->promoter_type : null])],
|
||||
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
|
||||
'maturity_level' => ['nullable', 'integer', 'between:1,8'],
|
||||
'maturity_stage' => ['nullable', Rule::in(array_keys(OpportunityMaturity::STAGES))],
|
||||
'maturity_catalogue_version' => ['nullable', Rule::in([OpportunityMaturity::VERSION, OpportunityMaturity::LEGACY])],
|
||||
'financing_modality' => ['nullable', 'string', 'max:120'],
|
||||
'expected_impact' => ['nullable', 'string', 'max:10000'],
|
||||
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
@@ -54,12 +67,13 @@ class OpportunityManagement
|
||||
'reason' => ['required', 'string', 'min:20', 'max:1000'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
])->validate();
|
||||
$data = app(OpportunityMaturity::class)->normalize($data);
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $id) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
|
||||
if (! $id && ($existing = Opportunity::withTrashed()->where('management_creation_key', $data['creation_key'])->first())) {
|
||||
$snapshot = $existing->management_draft ? json_decode($existing->management_draft, true) : $existing->only(self::FIELDS);
|
||||
foreach (array_intersect_key($data, array_flip(self::FIELDS)) as $key => $value) {
|
||||
$snapshot = $this->values($existing);
|
||||
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS])) as $key => $value) {
|
||||
if (($snapshot[$key] ?? null) != $value) {
|
||||
throw ValidationException::withMessages(['creation_key' => 'Esta chave já foi utilizada com dados diferentes.']);
|
||||
}
|
||||
@@ -73,11 +87,7 @@ class OpportunityManagement
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
$before = $record->getAttributes();
|
||||
$changes = array_intersect_key($data, array_flip(self::FIELDS));
|
||||
if (array_key_exists('maturity_level', $changes)) {
|
||||
$labels = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
|
||||
$changes['maturity_label'] = $labels[$changes['maturity_level'] ?? 0] ?? null;
|
||||
}
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS]));
|
||||
if (array_intersect_key($data, InvestmentGeography::FIELDS) !== []) {
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$changes['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
@@ -101,8 +111,16 @@ class OpportunityManagement
|
||||
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
|
||||
} else {
|
||||
foreach ($changes as $key => $value) {
|
||||
if (in_array($key, ['maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
continue;
|
||||
}
|
||||
$record->{$key} = $value;
|
||||
}
|
||||
if (isset($changes['maturity_catalogue_version'])) {
|
||||
// The existing draft JSON holds the versioned catalogue; legacy columns stay intact.
|
||||
$previous = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::MATURITY_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
$record->save();
|
||||
$this->audit($record, $actor, $before, $id ? 'draft_updated' : 'draft_created', $data['reason']);
|
||||
|
||||
@@ -14,6 +14,8 @@ class OpportunityManagementInstallation
|
||||
{
|
||||
$files = [__FILE__, app_path('Models/Opportunity.php'), app_path('Services/OpportunityManagement.php'), app_path('Http/Controllers/OpportunityManagementController.php'), app_path('Http/Controllers/PortalManagementController.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunities.tsx')];
|
||||
|
||||
$files[] = app_path('Services/OpportunityMaturity.php');
|
||||
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Catalogue versions are not interchangeable: historical positions keep their meaning. */
|
||||
final class OpportunityMaturity
|
||||
{
|
||||
public const VERSION = 'spec-v2';
|
||||
|
||||
public const LEGACY = 'legacy-v1';
|
||||
|
||||
public const STAGES = [
|
||||
'idea' => 'Ideia',
|
||||
'concept' => 'Conceito',
|
||||
'prefeasibility' => 'Pré-viabilidade',
|
||||
'feasibility' => 'Viabilidade',
|
||||
'structured' => 'Estruturado',
|
||||
'investment_ready' => 'Pronto para investimento',
|
||||
'implementation' => 'Implementação',
|
||||
'operational' => 'Operacional',
|
||||
];
|
||||
|
||||
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'];
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @return array<string,mixed> */
|
||||
public function normalize(array $data): array
|
||||
{
|
||||
if (! array_key_exists('maturity_level', $data) && ! array_key_exists('maturity_stage', $data)) {
|
||||
if (isset($data['maturity_catalogue_version'])) {
|
||||
throw ValidationException::withMessages(['maturity_catalogue_version' => 'Seleccione também a etapa; mudar só a versão não converte o valor histórico.']);
|
||||
}
|
||||
unset($data['maturity_catalogue_version']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
$level = isset($data['maturity_level']) ? (int) $data['maturity_level'] : null;
|
||||
$version = $data['maturity_catalogue_version'] ?? ((isset($data['maturity_stage']) || ($level ?? 0) > 6) ? self::VERSION : self::LEGACY);
|
||||
if ($version === self::LEGACY) {
|
||||
if (($level ?? 0) > 6 || isset($data['maturity_stage'])) {
|
||||
throw ValidationException::withMessages(['maturity_level' => 'O catálogo histórico tem seis níveis; seleccione explicitamente o catálogo de oito etapas.']);
|
||||
}
|
||||
|
||||
return [...$data, 'maturity_catalogue_version' => self::LEGACY, 'maturity_stage' => null, 'maturity_label' => self::LEGACY_LABELS[$level ?? 0] ?? null];
|
||||
}
|
||||
$codes = array_keys(self::STAGES);
|
||||
$stage = $data['maturity_stage'] ?? ($level !== null ? $codes[$level - 1] : null);
|
||||
if ($stage !== null && $level !== null && $codes[$level - 1] !== $stage) {
|
||||
throw ValidationException::withMessages(['maturity_stage' => 'O código da etapa e a posição no catálogo não correspondem.']);
|
||||
}
|
||||
|
||||
return [...$data, 'maturity_catalogue_version' => self::VERSION, 'maturity_stage' => $stage,
|
||||
'maturity_level' => $stage !== null ? array_search($stage, $codes, true) + 1 : null,
|
||||
'maturity_label' => $stage !== null ? self::STAGES[$stage] : null];
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,20 @@ class OpportunityResourceInstallation
|
||||
|
||||
$files = [...$files, app_path('Services/CountryCatalogue.php'), app_path('Services/DeclaredOriginStatistics.php'), app_path('Services/VirtualDesk.php'), app_path('Http/Controllers/CrmController.php'), app_path('Http/Controllers/InvestmentWorkspaceController.php'), app_path('Http/Controllers/InvestmentSubmissionController.php'), app_path('Http/Controllers/InvestmentDiscoveryController.php'), app_path('Http/Controllers/VirtualDeskController.php'), resource_path('data/iso3166.tab'), resource_path('js/components/country-select.tsx'), resource_path('js/components/investment-territory.tsx'), resource_path('js/pages/investment/profile.tsx'), resource_path('js/pages/investment/submission.tsx'), resource_path('js/pages/investment/catalogue.tsx'), resource_path('js/pages/desk/request.tsx'), resource_path('js/pages/desk/panel.tsx'), resource_path('js/pages/crm/leads.tsx')];
|
||||
|
||||
$files = [...$files, app_path('Http/Controllers/PortalServicesController.php'), app_path('Http/Controllers/PublicPortalController.php'), app_path('Http/Controllers/InvestorWorkspaceController.php'), app_path('Http/Controllers/PublicBusinessOpportunityController.php'), app_path('Http/Controllers/Api/V1/InterestRequestController.php'), app_path('Http/Requests/StoreInterestRequestRequest.php'), resource_path('js/pages/portal/services.tsx'), resource_path('js/pages/PortalInvestidor.tsx'), resource_path('js/pages/portfolio/workspace.tsx'), resource_path('js/pages/investment/business-interest.tsx'), resource_path('js/lib/portal-api.ts')];
|
||||
|
||||
$files = [...$files, app_path('Http/Controllers/PortalManagementController.php'), resource_path('js/pages/management/interest.tsx')];
|
||||
$files = [...$files, app_path('Http/Controllers/Api/V1/ReferenceCatalogController.php'), base_path('routes/api.php'), resource_path('js/components/simulation-form.tsx')];
|
||||
$files[] = app_path('Http/Requests/StoreSimulationFormDraftRequest.php');
|
||||
$files = [...$files, app_path('Services/TerritoryGeometry.php'), app_path('Http/Controllers/InvestmentTerritoryController.php'), resource_path('js/components/territory-geometry-preview.tsx'), resource_path('js/components/interactive-investment-map.tsx'), resource_path('js/components/investment-map-panel.tsx')];
|
||||
$files = [...$files, app_path('Services/OpportunityManagement.php'), app_path('Services/OpportunityMaturity.php'), app_path('Services/BusinessFormSchema.php'), app_path('Http/Controllers/ExistingBusinessController.php'), app_path('Http/Controllers/LandAssistanceController.php'), app_path('Http/Requests/StoreLandAssistanceCaseRequest.php'), resource_path('js/pages/investment/business-wizard.tsx'), resource_path('js/pages/investment/businesses.tsx'), resource_path('js/pages/investment/business.tsx'), resource_path('js/pages/land-assistance/form.tsx'), resource_path('js/pages/management/interests.tsx')];
|
||||
$files = [...$files, app_path('Services/ExistingBusinessIntake.php'), resource_path('js/pages/land-assistance/case.tsx')];
|
||||
$files = [...$files, resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx')];
|
||||
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
|
||||
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
@@ -29,7 +43,7 @@ class OpportunityResourceInstallation
|
||||
$ready = ($proof['restore_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && ($proof['reversal_verified'] ?? false) && ($proof['qa_passed'] ?? false) && ($proof['code_hash'] ?? '') === $code && ($proof['target']['database'] ?? '') === $identity->database && (int) ($proof['target']['port'] ?? 0) === (int) $identity->port && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
|
||||
$installed = app(OpportunityResources::class)->installed();
|
||||
|
||||
return ['installed' => $installed, 'ready' => $ready, 'target' => $identity, 'code_hash' => $code, 'hash' => hash('sha256', json_encode([$identity, $code, $ready, $installed], JSON_THROW_ON_ERROR)), 'migration' => self::MIGRATION, 'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Recursos privados de preparação ligados às oportunidades existentes, documents e geo_locations; nenhum dado existente alterado.', 'Originais cifrados; scan pendente bloqueia acesso aos binários, não preparação de metadados/localizações.', 'Versões, exclusão lógica e restauro com auditoria; nenhuma publicação automática.', 'Pendentes: ClamD real, derivadas seguras/revisão/publicação e compatibilidade com limites oficiais onde ausentes.'], 'rollback' => 'Reversão apenas com tabelas vazias e sem documentos cifrados; após utilização, preservar e reconciliar versões antes de uma ação autorizada.'];
|
||||
return ['installed' => $installed, 'ready' => $ready, 'target' => $identity, 'code_hash' => $code, 'hash' => hash('sha256', json_encode([$identity, $code, $ready, $installed], JSON_THROW_ON_ERROR)), 'migration' => self::MIGRATION, 'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Recursos privados de preparação ligados às oportunidades existentes, documents e geo_locations; nenhum dado existente alterado.', 'Originais cifrados; scan pendente bloqueia acesso aos binários, não preparação de metadados/localizações.', 'Versões, exclusão lógica e restauro com auditoria; nenhuma publicação automática.', 'Scan de cada original/derivada, disponibilidade GD/WebP, revisão de divulgação e compatibilidade territorial têm critérios independentes; a instalação não os confirma. Consultar os estados por ficheiro e as evidências QA da revisão.'], 'rollback' => 'Reversão apenas com tabelas vazias e sem documentos cifrados; após utilização, preservar e reconciliar versões antes de uma ação autorizada.'];
|
||||
}
|
||||
|
||||
public function apply(User $actor, string $hash): void
|
||||
|
||||
@@ -23,13 +23,18 @@ final class SimulationFormDrafts
|
||||
public function create(array $data, Request $request, string $key): array
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
$caseId = $request->input('context');
|
||||
if ($caseId !== null) {
|
||||
abort_unless(config('investor-path.enabled') && is_string($caseId) && Str::isUuid($caseId), 422, 'Contexto de investimento indisponível.');
|
||||
abort_unless($request->user()?->hasVerifiedEmail(), 403);
|
||||
}
|
||||
$data = SimulationFormDraftPrivacyPolicy::apply($data, $actorId !== null);
|
||||
$scope = $actorId === null ? 'anonymous:'.$tokenHash : 'user:'.$actorId;
|
||||
$scope = ($actorId === null ? 'anonymous:'.$tokenHash : 'user:'.$actorId).($caseId ? ':case:'.$caseId : '');
|
||||
$keyHash = hash_hmac('sha256', strtolower($key), (string) config('app.key'));
|
||||
$canonicalPayload = json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
$payloadHash = hash('sha256', $canonicalPayload);
|
||||
|
||||
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $data): array {
|
||||
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $data, $caseId, $request): array {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
DB::select('select pg_advisory_xact_lock(261010, hashtext(?))', [$scope]);
|
||||
|
||||
@@ -39,7 +44,13 @@ final class SimulationFormDrafts
|
||||
->update(['deleted_at' => now()]);
|
||||
}
|
||||
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->first();
|
||||
$case = $caseId ? app(VirtualDesk::class)->case($request->user(), $caseId, true, true) : null;
|
||||
// Shared case access never grants ownership of a private simulator snapshot.
|
||||
abort_if($case && ((int) $case->user_id !== $actorId || $case->closed_at), 403);
|
||||
$query = $this->ownedQuery($actorId, $tokenHash);
|
||||
$draft = $case
|
||||
? ($case->simulation_id ? $query->whereKey($case->simulation_id)->lockForUpdate()->firstOrFail() : null)
|
||||
: $this->unscoped($query, $actorId)->lockForUpdate()->first();
|
||||
if ($draft) {
|
||||
if (hash_equals($draft->create_key_hash, $keyHash)) {
|
||||
abort_unless(hash_equals($draft->create_payload_hash, $payloadHash), 409, 'Idempotency-Key já foi utilizada com outros dados.');
|
||||
@@ -57,6 +68,11 @@ final class SimulationFormDrafts
|
||||
'expires_at' => $actorId === null ? now()->addDays(30) : null,
|
||||
]);
|
||||
|
||||
if ($case) {
|
||||
DB::table('desk_cases')->where('id', $case->id)->update(['simulation_id' => $draft->id, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
app(VirtualDesk::class)->event(app(VirtualDesk::class)->case($request->user(), $case->id), $request->user(), 'context_draft_created', ['draft_id' => $draft->id]);
|
||||
}
|
||||
|
||||
return ['draft' => $draft, 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
@@ -70,6 +86,7 @@ final class SimulationFormDrafts
|
||||
return DB::transaction(function () use ($id, $data, $request, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
|
||||
$this->checkContext($request, $draft);
|
||||
$this->requireMatch($request, $draft);
|
||||
$previousEconomic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
if (($data['economic_snapshot']['reuse_simulation'] ?? null) === 'no') {
|
||||
@@ -162,10 +179,19 @@ final class SimulationFormDrafts
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($actorId, $tokenHash): ?SimulationFormDraft {
|
||||
return DB::transaction(function () use ($actorId, $tokenHash, $request): ?SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$query = $this->ownedQuery($actorId, $tokenHash);
|
||||
if ($request->query('context') !== null) {
|
||||
$id = $request->query('context');
|
||||
abort_unless(config('investor-path.enabled') && $request->user()?->hasVerifiedEmail() && is_string($id) && Str::isUuid($id), 403);
|
||||
$case = app(VirtualDesk::class)->case($request->user(), $id, true);
|
||||
abort_unless((int) $case->user_id === $actorId, 403);
|
||||
|
||||
return $this->ownedQuery($actorId, $tokenHash)->orderByDesc('updated_at')->first();
|
||||
return $case->simulation_id ? $query->whereKey($case->simulation_id)->firstOrFail() : null;
|
||||
}
|
||||
|
||||
return $this->unscoped($query, $actorId)->orderByDesc('updated_at')->first();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -327,10 +353,12 @@ final class SimulationFormDrafts
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($id, $actorId, $tokenHash): SimulationFormDraft {
|
||||
return DB::transaction(function () use ($id, $actorId, $tokenHash, $request): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->findOrFail($id);
|
||||
$this->checkContext($request, $draft);
|
||||
|
||||
return $this->ownedQuery($actorId, $tokenHash)->findOrFail($id);
|
||||
return $draft;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -414,6 +442,31 @@ final class SimulationFormDrafts
|
||||
: $query->where('owner_user_id', $actorId)->whereNull('anonymous_token_hash');
|
||||
}
|
||||
|
||||
/** @param Builder<SimulationFormDraft> $query
|
||||
* @return Builder<SimulationFormDraft>
|
||||
*/
|
||||
private function unscoped(Builder $query, ?int $actorId): Builder
|
||||
{
|
||||
if ($actorId !== null && config('investor-path.enabled') && app(VirtualDesk::class)->installed()) {
|
||||
// The direct tool has its own current draft; context drafts are opened explicitly by ID/context.
|
||||
$query->whereNotExists(fn ($q) => $q->selectRaw('1')->from('desk_cases')
|
||||
->whereColumn('desk_cases.simulation_id', 'simulation_form_drafts.id'));
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function checkContext(Request $request, SimulationFormDraft $draft): void
|
||||
{
|
||||
$context = $request->input('context');
|
||||
if ($context === null) {
|
||||
return;
|
||||
}
|
||||
abort_unless(config('investor-path.enabled') && $request->user()?->hasVerifiedEmail() && is_string($context) && Str::isUuid($context), 403);
|
||||
$case = app(VirtualDesk::class)->case($request->user(), $context, true);
|
||||
abort_unless((int) $case->user_id === $request->user()->id && $case->simulation_id === $draft->id, 403, 'Rascunho pertencente a outro contexto.');
|
||||
}
|
||||
|
||||
/** @return array{id:string,title:string,updated_at:string|null,expires_at:string|null,version_no:int} */
|
||||
private function summary(SimulationFormDraft $draft): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Administrative context is never an investment site or a zone perimeter. */
|
||||
final class TerritoryGeometry
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function context(string $id, bool $management = false): array
|
||||
{
|
||||
$geography = app(InvestmentGeography::class);
|
||||
abort_unless($geography->references($management)->where('id', $id)->exists(), 404);
|
||||
$path = $geography->path($id, $management);
|
||||
$ids = array_map(fn ($node) => $node->id, $path);
|
||||
$rows = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id')
|
||||
->whereIn('g.geo_location_id', $ids)->whereNull('g.deleted_at')->whereNull('l.deleted_at')
|
||||
->whereIn('g.data_classification', $management ? ['internal', 'public'] : ['public'])
|
||||
->whereRaw("g.properties->>'purpose' = 'administrative_boundary'")
|
||||
->whereIn('g.geometry_type', ['polygon', 'multipolygon'])
|
||||
->whereRaw('ST_IsValid(g.geom) AND NOT ST_IsEmpty(g.geom) AND ST_SRID(g.geom)=4326')
|
||||
->orderBy('g.geo_location_id')->orderBy('g.id')->limit(101)
|
||||
->get(['g.id', 'g.geo_location_id', 'l.name', 'l.location_type', 'g.properties', 'g.data_classification',
|
||||
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry')]);
|
||||
$areas = $rows->take(100)->map(function ($row) use ($id) {
|
||||
$source = json_decode($row->properties, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return ['id' => $row->id, 'territory_id' => $row->geo_location_id, 'location_type' => $row->location_type,
|
||||
'selected_territory' => $row->geo_location_id === $id, 'geometry' => json_decode($row->geometry, true, 512, JSON_THROW_ON_ERROR),
|
||||
'title' => 'Limite administrativo: '.$row->name, 'purpose' => 'administrative_boundary',
|
||||
'source_reference' => $source['authority'] ?? null, 'source_date' => $source['source_version'] ?? null,
|
||||
'source_url' => $source['source_url'] ?? null, 'source_sha256' => $source['source_sha256'] ?? null,
|
||||
'data_classification' => $row->data_classification, 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
|
||||
})->all();
|
||||
|
||||
return ['territory_id' => $id, 'territory_registered' => true,
|
||||
'selected_geometry_available' => $rows->contains('geo_location_id', $id), 'context_geometry_count' => count($areas),
|
||||
'areas' => $areas, 'truncated' => $rows->count() > 100, 'investment_site' => false];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Imports only the retained, accepted INE edition. Publication is a separate action. */
|
||||
class TerritoryGeometryImport
|
||||
{
|
||||
public function fingerprint(): string
|
||||
{
|
||||
return hash('sha256', implode('', array_map(fn ($f) => hash_file('sha256', $f), [__FILE__, config_path('geometry-import.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), base_path('routes/web.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')])));
|
||||
}
|
||||
|
||||
private function guard(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless(config('geometry-import.enabled'), 503, 'Importação cartográfica não disponibilizada.');
|
||||
if (! $write) {
|
||||
return;
|
||||
}
|
||||
abort_unless($actor->two_factor_confirmed_at && $actor->two_factor_secret, 403, 'Confirme a autenticação de dois factores para aplicar ou reverter cartografia.');
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$qa = app()->environment('testing') && str_ends_with($target->database, '_test') && (int) $target->port === 55441 && config('database.connections.pgsql.host') === '127.0.0.1';
|
||||
if ($qa) {
|
||||
return;
|
||||
}
|
||||
$file = storage_path('app/private/investmoz-v2/geometry-import-activation-proof.json');
|
||||
$p = is_file($file) ? json_decode(file_get_contents($file), true) : [];
|
||||
abort_unless(($p['restore_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['ui_passed'] ?? false)
|
||||
&& ($p['code_hash'] ?? '') === $this->fingerprint() && ($p['target']['database'] ?? '') === $target->database
|
||||
&& (int) ($p['target']['port'] ?? 0) === (int) $target->port && strtotime($p['verified_at'] ?? '') >= time() - 86400
|
||||
&& is_file($p['dump_path'] ?? '') && hash_file('sha256', $p['dump_path']) === ($p['sha256'] ?? null)
|
||||
&& ($p['files_verified'] ?? false) && is_file($p['files_path'] ?? '') && hash_file('sha256', $p['files_path']) === ($p['files_sha256'] ?? null), 422, 'Backup/restauro e provas desta revisão e alvo necessários; preparação não autoriza ativação.');
|
||||
}
|
||||
|
||||
public function preview(User $actor, int $level): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
abort_unless(in_array($level, [1, 2, 3], true), 422);
|
||||
$directory = config('geometry-import.directory');
|
||||
$file = $directory.'/moz-adm'.$level.'-ine-20190607.geojson';
|
||||
$metadata = $directory.'/moz-adm'.$level.'-ine-metadata.html';
|
||||
abort_unless(is_file($file) && is_file($metadata), 422, 'Exemplar privado indisponível.');
|
||||
$text = file_get_contents($metadata);
|
||||
abort_unless(str_contains($text, 'Mozambique INE - Instituto Nacional de Estatistica') && str_contains($text, '2019-06-07'), 422, 'Metadados do exemplar divergentes.');
|
||||
$sourceHash = hash_file('sha256', $file);
|
||||
$source = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(($source['type'] ?? '') === 'FeatureCollection' && count($source['features'] ?? []) === [1 => 11, 2 => 159, 3 => 411][$level] && ! ($source['exceededTransferLimit'] ?? false), 422, 'Exemplar incompleto.');
|
||||
$locations = DB::table('geo_locations')->where('location_type', [1 => 'province', 2 => 'district', 3 => 'admin_post'][$level])->whereNull('deleted_at')->get(['id', 'name', 'parent_id']);
|
||||
$normalize = fn ($n) => strtolower(trim(Str::ascii($n)));
|
||||
$countryNames = array_map($normalize, [$source['features'][0]['properties']['ADM0_PT'], $source['features'][0]['properties']['ADM0_EN']]);
|
||||
$countries = DB::table('geo_locations')->where('location_type', 'country')->whereNull('deleted_at')->get(['id', 'name'])->filter(fn ($c) => in_array($normalize($c->name), $countryNames, true))->values();
|
||||
$countryId = count($countries) === 1 ? $countries[0]->id : null;
|
||||
$parentSourceHash = $level > 1 ? hash_file('sha256', $directory.'/moz-adm'.($level - 1).'-ine-20190607.geojson') : null;
|
||||
$rows = [];
|
||||
foreach ($source['features'] as $feature) {
|
||||
$p = $feature['properties'];
|
||||
abort_unless(($p['ADM0_PCODE'] ?? '') === 'MZ', 422, 'Âmbito territorial do exemplar divergente.');
|
||||
$external = '2019-06-07:adm'.$level.':'.$p['ADM'.$level.'_PCODE'];
|
||||
$parent = $level > 1 ? DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->where('external_id', '2019-06-07:adm'.($level - 1).':'.$p['ADM'.($level - 1).'_PCODE'])->where('properties->source_sha256', $parentSourceHash)->whereNull('deleted_at')->value('geo_location_id') : $countryId;
|
||||
$matches = $locations->filter(fn ($l) => $normalize($l->name) === $normalize($p['ADM'.$level.'_PT']) && $parent && $l->parent_id === $parent)->values();
|
||||
$row = ['external_id' => $external, 'name' => $p['ADM'.$level.'_PT'], 'parent_name' => $level > 1 ? $p['ADM'.($level - 1).'_PT'] : null,
|
||||
'parent_code' => $level > 1 ? $p['ADM'.($level - 1).'_PCODE'] : null, 'candidates' => $matches->all(), 'location_id' => count($matches) === 1 ? $matches[0]->id : null,
|
||||
'status' => count($matches) === 1 ? 'insert' : (! $parent ? 'parent_unresolved' : 'name_unresolved')];
|
||||
if ($row['location_id']) {
|
||||
$geometry = json_encode($feature['geometry'], JSON_THROW_ON_ERROR);
|
||||
$valid = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_NDims(g)=2 AND GeometryType(g) IN (\'POLYGON\',\'MULTIPOLYGON\') AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) q', [$geometry]);
|
||||
if (! $valid->valid) {
|
||||
$row['status'] = 'invalid_geometry';
|
||||
} else {
|
||||
$existing = DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->where('external_id', $external)->first();
|
||||
if ($existing) {
|
||||
$props = json_decode($existing->properties, true);
|
||||
$same = DB::selectOne('SELECT ST_Equals(geom,ST_SetSRID(ST_GeomFromGeoJSON(?),4326)) AS same FROM geo_geometries WHERE id=?', [$geometry, $existing->id])->same;
|
||||
$row['status'] = $same && $existing->geo_location_id === $row['location_id'] && ($props['source_sha256'] ?? null) === $sourceHash && ! $existing->deleted_at ? 'reuse' : 'identity_conflict';
|
||||
$row['geometry_id'] = $existing->id;
|
||||
$row['version'] = $existing->version_no;
|
||||
$row['classification'] = $existing->data_classification;
|
||||
} elseif (DB::table('geo_geometries')->where('geo_location_id', $row['location_id'])->where('geometry_type', strtolower($feature['geometry']['type']))->whereNull('deleted_at')->exists()) {
|
||||
$row['status'] = 'territory_geometry_conflict';
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows[] = $row;
|
||||
}
|
||||
$scanFile = $directory.'/geometry-source-scans.json';
|
||||
$scans = is_file($scanFile) ? json_decode(file_get_contents($scanFile), true) : [];
|
||||
$scan = null;
|
||||
foreach ($scans['files'] ?? [] as $s) {
|
||||
if ($s['file'] === basename($file) && $s['sha256'] === $sourceHash) {
|
||||
$scan = ($s['scan']['result'] ?? '') === 'clean' ? $s['scan'] : ($s['gis_scan'] ?? null);
|
||||
}
|
||||
}
|
||||
$scanReady = ($scan['result'] ?? '') === 'clean' && ($scan['engine'] ?? '') === 'ClamAV' && strtotime($scans['captured_at'] ?? '') >= time() - config('geometry-import.scan_max_age_seconds');
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$plan = ['level' => $level, 'target' => $target, 'edition' => '2019-06-07', 'source_sha256' => $sourceHash, 'metadata_sha256' => hash_file('sha256', $metadata), 'code_hash' => $this->fingerprint(),
|
||||
'expected' => count($rows), 'resolved' => count(array_filter($rows, fn ($r) => in_array($r['status'], ['insert', 'reuse'], true))), 'rows' => $rows, 'scan_ready' => $scanReady, 'scan' => $scan, 'scan_at' => $scans['captured_at'] ?? null, 'published' => false];
|
||||
$plan['pending'] = $plan['expected'] - $plan['resolved'];
|
||||
$plan['hash'] = hash_hmac('sha256', json_encode([$actor->id, $plan], JSON_THROW_ON_ERROR), config('app.key'));
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->guard($actor, true);
|
||||
$data = Validator::make($input, ['level' => 'required|integer|in:1,2,3', 'hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return $this->receipt($actor, 'geometry-import-apply', $data, function () use ($actor, $data) {
|
||||
$plan = $this->preview($actor, (int) $data['level']);
|
||||
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Correspondências, fonte ou estado alterados; repita a pré-visualização.');
|
||||
abort_unless($plan['scan_ready'], 423, 'Scan limpo atual ligado ao original necessário.');
|
||||
abort_if(count(array_filter($plan['rows'], fn ($r) => str_contains($r['status'], 'conflict') || $r['status'] === 'invalid_geometry')) > 0, 409, 'Conflito de identidade/geometria: nenhuma escrita aplicada.');
|
||||
$bytes = file_get_contents(config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-20190607.geojson');
|
||||
abort_unless(hash('sha256', $bytes) === $plan['source_sha256'], 409);
|
||||
$source = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
$metadata = config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-metadata.html';
|
||||
$metadataScan = app(MalwareScanner::class)->scan($metadata, filesize($metadata), storage_path('app/private'));
|
||||
abort_unless(($metadataScan['result'] ?? '') === 'clean', 423, 'Scan dos metadados do exemplar pendente ou inconclusivo.');
|
||||
abort_unless(hash_file('sha256', $metadata) === $plan['metadata_sha256'], 409, 'Metadados alterados durante o scan.');
|
||||
$metadataScan['signatures_at'] = $metadataScan['signatures_at']?->format(DATE_ATOM);
|
||||
$batch = (string) Str::uuid();
|
||||
$created = [];
|
||||
$reused = [];
|
||||
foreach ($plan['rows'] as $i => $row) {
|
||||
if ($row['status'] === 'reuse') {
|
||||
$reused[] = $row['geometry_id'];
|
||||
}
|
||||
if ($row['status'] !== 'insert') {
|
||||
continue;
|
||||
}
|
||||
$feature = $source['features'][$i];
|
||||
$id = (string) Str::uuid();
|
||||
$trace = ['authority' => 'Mozambique INE - Instituto Nacional de Estatistica', 'provider' => 'UNOCHA; exemplar hosted by World Bank', 'source_version' => $plan['edition'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'source_url' => 'https://services.arcgis.com/iQ1dY19aHwbSDYIF/arcgis/rest/services/Mozambique/FeatureServer/'.($data['level'] + 2), 'source_properties' => $feature['properties'], 'source_scan' => $plan['scan'], 'batch_id' => $batch, 'purpose' => 'administrative_boundary', 'investment_site' => false, 'legal_currentness' => 'not_determined', 'match_basis' => 'unique_exact_name_and_matched_parent_after_case_and_diacritics'];
|
||||
DB::insert('INSERT INTO geo_geometries(id,source_system,external_id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,?,?,?,ST_SetSRID(ST_GeomFromGeoJSON(?),4326),?::jsonb,?)', [$id, 'ine-cod-ab', $row['external_id'], $row['location_id'], strtolower($feature['geometry']['type']), json_encode($feature['geometry'], JSON_THROW_ON_ERROR), json_encode($trace, JSON_THROW_ON_ERROR), 'internal']);
|
||||
$created[] = ['id' => $id, 'checksum' => $this->snapshotHash($id)];
|
||||
}
|
||||
$result = ['batch_id' => $batch, 'level' => $data['level'], 'preview_hash' => $plan['hash'], 'expected' => $plan['expected'], 'resolved' => $plan['resolved'], 'created' => $created, 'inserted' => count($created), 'reused' => count($reused), 'reused_ids' => $reused, 'pending' => $plan['pending'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'metadata_scan' => $metadataScan, 'published' => false, 'reason' => $data['reason']];
|
||||
$this->audit($actor, $batch, 'geometry_import_applied', $result);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
public function reverse(User $actor, string $batch, array $input): array
|
||||
{
|
||||
$this->guard($actor, true);
|
||||
$data = Validator::make([...$input, 'batch_id' => $batch], ['batch_id' => 'required|uuid', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return $this->receipt($actor, 'geometry-import-reverse', $data, function () use ($actor, $data, $batch) {
|
||||
$event = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_applied')->first();
|
||||
abort_unless($event, 404);
|
||||
$old = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_reversed')->first();
|
||||
if ($old) {
|
||||
return json_decode($old->after_data, true);
|
||||
}
|
||||
$manifest = json_decode($event->after_data, true);
|
||||
foreach ($manifest['created'] as $row) {
|
||||
DB::table('geo_geometries')->where('id', $row['id'])->lockForUpdate()->first();
|
||||
abort_unless($this->snapshotHash($row['id']) === $row['checksum'], 409, 'Geometria alterada ou publicada; reversão recusada.');
|
||||
// Enumerate all real FKs, rather than assuming one consumer table.
|
||||
$references = DB::select("SELECT n.nspname AS schema,t.relname AS table_name,a.attname AS column_name FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace n ON n.oid=t.relnamespace JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=c.conkey[1] WHERE c.contype='f' AND c.confrelid='geo_geometries'::regclass");
|
||||
foreach ($references as $ref) {
|
||||
abort_if(DB::table($ref->schema.'.'.$ref->table_name)->where($ref->column_name, $row['id'])->exists(), 409, 'Geometria associada a um consumidor; preserve a relação.');
|
||||
}
|
||||
}
|
||||
foreach ($manifest['created'] as $row) {
|
||||
DB::table('geo_geometries')->where('id', $row['id'])->update(['deleted_at' => now(), 'updated_at' => now(), 'version_no' => DB::raw('version_no+1')]);
|
||||
}
|
||||
$result = ['batch_id' => $batch, 'reversed' => count($manifest['created']), 'reused_preserved' => $manifest['reused'], 'published' => false, 'reason' => $data['reason']];
|
||||
$this->audit($actor, $batch, 'geometry_import_reversed', $result);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
private function snapshotHash(string $id): string
|
||||
{
|
||||
$r = DB::selectOne('SELECT row_to_json(q)::text AS value FROM (SELECT *,encode(ST_AsEWKB(geom),\'hex\') AS binary_geometry FROM geo_geometries WHERE id=?) q', [$id]);
|
||||
|
||||
return hash('sha256', $r->value ?? 'missing');
|
||||
}
|
||||
|
||||
private function receipt(User $actor, string $scope, array $data, callable $operation): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $scope, $data, $operation) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(91026,20190607)');
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926,150000)');
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$receipt = DB::table('geo_write_receipts')->where('actor_id', $actor->id)->where('scope', $scope)->where('idempotency_key', $data['idempotency_key'])->first();
|
||||
if ($receipt) {
|
||||
abort_unless(hash_equals(trim($receipt->request_hash), $hash), 409, 'Chave reutilizada com outro pedido.');
|
||||
|
||||
return json_decode($receipt->response, true);
|
||||
}
|
||||
$result = $operation();
|
||||
DB::table('geo_write_receipts')->insert(['id' => (string) Str::uuid(), 'actor_id' => $actor->id, 'scope' => $scope, 'idempotency_key' => $data['idempotency_key'], 'request_hash' => $hash, 'response' => json_encode($result, JSON_THROW_ON_ERROR), 'http_status' => 200]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
private function audit(User $actor, string $batch, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'geometry-import', 'entity_type' => 'geo_geometries', 'entity_id' => $batch, 'correlation_id' => $batch, 'actor_user_id' => $actor->id, 'action' => $action, 'after_data' => json_encode($data, JSON_THROW_ON_ERROR), 'data_classification' => 'internal']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
|
||||
/** Authorization/publication stays with the consumer; originals share integrity and cipher handling. */
|
||||
class VerifiedDocumentBinary
|
||||
{
|
||||
public function respond(object $document, bool $inline = false): Response|BinaryFileResponse
|
||||
{
|
||||
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||
&& ($document->deleted_at ?? null) === null && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
|
||||
$disk = Storage::disk('local');
|
||||
$root = realpath($disk->path(''));
|
||||
$path = realpath($disk->path($document->storage_key));
|
||||
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
|
||||
$headers = ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store'];
|
||||
if ($inline) {
|
||||
$headers['Content-Type'] = $document->media_type;
|
||||
$headers['Content-Security-Policy'] = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
|
||||
}
|
||||
if (($document->storage_encryption ?? null) === 'laravel') {
|
||||
try {
|
||||
$bytes = Crypt::decryptString($disk->get($document->storage_key));
|
||||
} catch (DecryptException) {
|
||||
abort(404);
|
||||
}
|
||||
abort_unless(hash_equals(trim($document->sha256), hash('sha256', $bytes)), 404);
|
||||
$headers['Content-Type'] = $document->media_type;
|
||||
$headers['Content-Disposition'] = HeaderUtils::makeDisposition($inline ? 'inline' : 'attachment', basename($document->file_name), 'document');
|
||||
|
||||
return response($bytes, 200, $headers);
|
||||
}
|
||||
abort_unless(($document->storage_encryption ?? null) === null, 404);
|
||||
$checksum = hash_file('sha256', $path);
|
||||
abort_unless(is_string($checksum) && hash_equals(trim($document->sha256), $checksum), 404);
|
||||
|
||||
return $inline ? response()->file($path, $headers)->setContentDisposition('inline', basename($document->file_name)) : response()->download($path, basename($document->file_name), $headers);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ namespace App\Services;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Investor;
|
||||
use App\Models\InvestorJourney;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -186,6 +188,14 @@ class VirtualDesk
|
||||
$id = (string) Str::uuid();
|
||||
$base = $this->decode($case->payload);
|
||||
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
|
||||
if (config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$draftRequest = Request::create('/');
|
||||
$draftRequest->setUserResolver(fn () => $actor);
|
||||
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
|
||||
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
$payload['description'] = $economic['project_summary'] ?? $payload['description'];
|
||||
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
|
||||
}
|
||||
DB::table('desk_requests')->insert(['id' => $id, 'case_id' => $caseId, 'service_version_id' => $serviceId, 'client_key' => $clientKey, 'payload' => $this->encode($payload), 'created_at' => now(), 'updated_at' => now()]);
|
||||
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
|
||||
$this->event($case, $actor, 'draft_created', [], $request);
|
||||
@@ -205,7 +215,8 @@ class VirtualDesk
|
||||
* @return array<string,mixed> */
|
||||
public function validateFields(array $payload, array $definition, bool $submitting): array
|
||||
{
|
||||
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'declared_origin_country_code'])],
|
||||
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code'])],
|
||||
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
|
||||
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()]];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
$active = ! isset($field['when']) || ($payload[$field['when']['field']] ?? null) === $field['when']['equals'];
|
||||
@@ -219,8 +230,14 @@ class VirtualDesk
|
||||
$rules['payload.'.$key] = $rule;
|
||||
}
|
||||
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
if ($field['type'] === 'territory' && ! empty($validated[$key])) {
|
||||
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $validated[$key])->exists()) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione uma localização disponível no cadastro territorial.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($validated['territory_id'] ?? null) {
|
||||
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $validated['territory_id'])->exists(), 422, 'Localização indisponível.');
|
||||
if ($submitting && trim($validated['location_source'] ?? '') === '') {
|
||||
throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
|
||||
}
|
||||
@@ -320,7 +337,7 @@ class VirtualDesk
|
||||
}
|
||||
$editable = $data['editable_fields'] ?? [];
|
||||
abort_if($data['status'] === 'returned' && ! $editable, 422, 'Indique os campos autorizados para correção.');
|
||||
abort_if(array_diff($editable, array_keys($this->definition($request)['fields'])) !== [], 422);
|
||||
abort_if(array_diff($editable, [...array_keys($this->definition($request)['fields']), 'country', 'declared_origin_country_code']) !== [], 422);
|
||||
DB::table('desk_requests')->where('id', $id)->update(['status' => $data['status'], 'version' => $request->version + 1, 'editable_fields' => json_encode($editable), 'closed_at' => in_array($data['status'], ['closed', 'cancelled'], true) ? now() : null, 'updated_at' => now()]);
|
||||
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
|
||||
$this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
|
||||
|
||||
@@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class VirtualDeskInstallation
|
||||
{
|
||||
public const MIGRATIONS = ['2026_10_07_190000_create_internal_virtual_desk', '2026_10_08_120000_extend_desk_investor_guidance'];
|
||||
public const MIGRATIONS = ['2026_10_07_190000_create_internal_virtual_desk', '2026_10_08_120000_extend_desk_investor_guidance', '2026_10_09_190000_prepare_investor_path'];
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
@@ -20,6 +20,17 @@ class VirtualDeskInstallation
|
||||
resource_path('js/lib/business-financial-plan.ts'), resource_path('js/lib/financial-calculators.ts'), resource_path('js/lib/project-dossier.ts'),
|
||||
...array_map(fn ($name) => database_path('migrations/'.$name.'.php'), self::MIGRATIONS),
|
||||
...(glob(resource_path('js/pages/desk/*.tsx')) ?: []), resource_path('js/components/investor-guidance.tsx'), resource_path('js/components/journey-companion.tsx'), resource_path('js/components/desk-internal-operations.tsx'), resource_path('js/layouts/portal-navigation.tsx'), resource_path('js/layouts/app/app-sidebar-layout.tsx'), resource_path('js/pages/investment/shared.tsx'), resource_path('js/lib/investor-guidance-finance.ts')];
|
||||
$files = [...$files, app_path('Services/InvestorPath.php'), app_path('Services/InvestorPathDefinition.php'),
|
||||
app_path('Services/SimulationFormDrafts.php'), app_path('Http/Requests/StoreSimulationFormDraftRequest.php'),
|
||||
app_path('Http/Controllers/InvestorPathController.php'), app_path('Http/Controllers/DashboardController.php'),
|
||||
base_path('routes/investor-path.php'), base_path('routes/web.php'), config_path('investor-path.php'),
|
||||
resource_path('js/pages/dashboard.tsx'), resource_path('js/components/simulation-form.tsx'), resource_path('js/lib/investor-path.ts'),
|
||||
database_path('migrations/2026_10_01_000200_create_simulation_execution_core.php'),
|
||||
resource_path('js/components/investment-map-panel.tsx'), resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx'),
|
||||
...(glob(resource_path('js/pages/investor-path/*.tsx')) ?: [])];
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
|
||||
sort($files);
|
||||
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
@@ -57,20 +68,29 @@ class VirtualDeskInstallation
|
||||
foreach (['desk_cases', 'desk_requests', 'desk_documents', 'desk_messages', 'tasks', 'investor_accounts', 'investment_submissions'] as $table) {
|
||||
$counts[$table] = Schema::hasTable($table) ? DB::table($table)->count() : null;
|
||||
}
|
||||
$installed = app(VirtualDesk::class)->installed();
|
||||
$pathInstalled = Schema::hasColumn('investor_journeys', 'path_definition_id') && Schema::hasColumn('journey_steps', 'path_detail');
|
||||
$installed = app(VirtualDesk::class)->installed() && $pathInstalled
|
||||
&& DB::table('migrations')->where('migration', '2026_10_09_190000_prepare_investor_path')->exists();
|
||||
$pathQa = $read('investor-path-qa-evidence.json');
|
||||
$pathQaVerified = ($pathQa['code_hash'] ?? null) === $code && ($pathQa['api_persistence_passed'] ?? false)
|
||||
&& ($pathQa['integrated_ui_ab_passed'] ?? false) && str_ends_with($pathQa['database'] ?? '', '_test') && (int) ($pathQa['port'] ?? 0) === 55441;
|
||||
$privileges = DB::selectOne("select has_schema_privilege(current_user, 'public', 'CREATE') as can_create,
|
||||
pg_has_role(current_user, (select tableowner from pg_tables where schemaname='public' and tablename='tasks'), 'USAGE') as can_alter_tasks");
|
||||
$databaseReady = (bool) ($privileges->can_create && $privileges->can_alter_tasks);
|
||||
|
||||
return ['hash' => hash('sha256', json_encode([$identity, $code, $counts, $backupVerified, $qaVerified, $compatibilityVerified, $databaseReady], JSON_THROW_ON_ERROR)), 'code_hash' => $code,
|
||||
'installed' => $installed, 'target' => $identity, 'counts' => $counts, 'backupVerified' => $backupVerified, 'qaVerified' => $qaVerified,
|
||||
return ['hash' => hash('sha256', json_encode([$identity, $code, $counts, $backupVerified, $qaVerified, $compatibilityVerified, $databaseReady, $pathQaVerified, $pathInstalled, (bool) config('investor-path.enabled')], JSON_THROW_ON_ERROR)), 'code_hash' => $code,
|
||||
'installed' => $installed, 'baseDeskInstalled' => app(VirtualDesk::class)->installed(), 'pathInstalled' => $pathInstalled,
|
||||
'pathEnabled' => (bool) config('investor-path.enabled'), 'pathQaVerified' => $pathQaVerified,
|
||||
'target' => $identity, 'counts' => $counts, 'backupVerified' => $backupVerified, 'qaVerified' => $qaVerified,
|
||||
'compatibilityVerified' => $compatibilityVerified, 'backupDate' => $backup['verified_at'] ?? null,
|
||||
'databaseReady' => $databaseReady,
|
||||
'scanner' => app(MalwareScanner::class)->health(),
|
||||
'pendingMigrations' => array_values(array_filter(self::MIGRATIONS, fn ($name) => ! DB::table('migrations')->where('migration', $name)->exists())),
|
||||
'rollback' => 'Reversão vazia ensaiada em cópia isolada. Com dados novos, preservar/exportar pedidos e tarefas; o down recusa eliminar dados. Restauro integral só numa janela autorizada, após reconciliar alterações posteriores ao backup.',
|
||||
'changes' => ['Completar o Balcão Virtual existente, preservando pedidos anteriores.', 'Acrescentar associações opcionais ao investidor, projecto e percurso existentes.',
|
||||
'Reutilizar tasks do CRM para acções expressamente assumidas; sem envio externo.', 'Nenhuma publicação de serviço, documento ou candidatura automática.']];
|
||||
'Reutilizar tasks do CRM para acções expressamente assumidas; sem envio externo.', 'Nenhuma publicação de serviço, documento ou candidatura automática.',
|
||||
'Preparar duas colunas nas entidades existentes e uma versão publicada do percurso de 19 etapas. Não converter dossiers existentes.',
|
||||
'Não habilitar a navegação por instalação: configuração INVESTOR_PATH_ENABLED permanece uma acção separada.']];
|
||||
}
|
||||
|
||||
public function apply(string $hash, User $actor): void
|
||||
@@ -84,7 +104,9 @@ class VirtualDeskInstallation
|
||||
return;
|
||||
}
|
||||
abort_unless($preview['backupVerified'] && $preview['qaVerified'] && $preview['compatibilityVerified'] && $preview['databaseReady'], 422, 'Backup/restauro atualizado, compatibilidade/reversão, permissões da base e QA desta versão continuam necessários.');
|
||||
abort_unless($preview['pathQaVerified'], 422, 'Demonstração A/B na interface e evidência API/persistência desta versão ainda necessárias.');
|
||||
config(['virtual-desk.installation_authorized' => true]);
|
||||
config(['investor-path.authenticated_installation' => true]);
|
||||
try {
|
||||
foreach (self::MIGRATIONS as $name) {
|
||||
if (! DB::table('migrations')->where('migration', $name)->exists()) {
|
||||
@@ -94,6 +116,7 @@ class VirtualDeskInstallation
|
||||
}
|
||||
} finally {
|
||||
config(['virtual-desk.installation_authorized' => false]);
|
||||
config(['investor-path.authenticated_installation' => false]);
|
||||
}
|
||||
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_cases', 'actor_user_id' => $actor->id,
|
||||
'action' => 'desk_installed', 'after_data' => json_encode(['preview_hash' => $hash, 'code_hash' => $preview['code_hash'], 'prior_counts' => $preview['counts']])]);
|
||||
|
||||
Reference in New Issue
Block a user