Integrate mining and energy references into sector and dossier journeys
This commit is contained in:
@@ -8,7 +8,9 @@ use App\Services\InvestmentGuides;
|
||||
use App\Services\InvestmentZonePathContext;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\SectorResourceReferences;
|
||||
use App\Services\SectorInvestment;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -32,6 +34,9 @@ class InvestorPathController extends Controller
|
||||
{
|
||||
abort_unless($path->available(), 404);
|
||||
$data = ['contexts' => $path->contexts($request->user()), 'sectorSource' => app(SectorInvestment::class)->context($sectorSlug)];
|
||||
if (isset(SectorResourceReferences::SOURCES[$sectorSlug]) && $request->filled('resource_area')) {
|
||||
$data['resourceSource'] = app(SectorResourceReferences::class)->selection($sectorSlug, ['area_id' => $request->query('resource_area'), 'location_label' => $request->query('resource_location'), 'group_id' => $request->query('resource_group'), 'source_sha256' => $request->query('resource_source')]);
|
||||
}
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
|
||||
}
|
||||
@@ -73,14 +78,28 @@ class InvestorPathController extends Controller
|
||||
if ($sector !== null) {
|
||||
app(SectorInvestment::class)->context($sector);
|
||||
}
|
||||
$reference = $request->input('sector_reference');
|
||||
if ($reference !== null) {
|
||||
abort_unless(isset(SectorResourceReferences::SOURCES[$sector]) && is_array($reference), 422);
|
||||
app(SectorResourceReferences::class)->selection($sector, $reference);
|
||||
}
|
||||
$source = $request->input('content_resource_id');
|
||||
if ($source !== null) {
|
||||
$resourceId = filter_var($source, FILTER_VALIDATE_INT);
|
||||
abort_unless(is_int($resourceId) && $resourceId !== 0, 422);
|
||||
app(LegacyContent::class)->articleForResource($resourceId);
|
||||
}
|
||||
$id = DB::transaction(function () use ($path, $request, $source, $sector, $zone): string {
|
||||
$id = DB::transaction(function () use ($path, $request, $source, $sector, $zone, $reference): string {
|
||||
if ($reference !== null) {
|
||||
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->first();
|
||||
}
|
||||
$existingReferenceCase = $reference !== null ? DB::table('desk_cases')->where('user_id', $request->user()->id)->where('client_key', $request->input('client_key'))->first() : null;
|
||||
$id = $path->create($request->user(), $request->all());
|
||||
if ($existingReferenceCase) {
|
||||
$selection = app(SectorResourceReferences::class)->selection($sector, $reference);
|
||||
$oldPayload = app(VirtualDesk::class)->decode($existingReferenceCase->payload);
|
||||
abort_unless(array_any($oldPayload['investor_path']['sector_references'] ?? [], fn ($row) => $row['key'] === $selection['key']), 409, 'A chave de criação já foi usada com outra referência sectorial; recupere o dossier existente.');
|
||||
}
|
||||
if ($source !== null) {
|
||||
$case = $path->view($request->user(), $id)['case'];
|
||||
app(LegacyContent::class)->attach($request->user(), $id, ['version' => $case['version'], 'resource_id' => (int) $source]);
|
||||
@@ -88,7 +107,7 @@ class InvestorPathController extends Controller
|
||||
|
||||
if ($sector !== null) {
|
||||
$case = $path->view($request->user(), $id)['case'];
|
||||
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector]);
|
||||
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector, 'sector_reference' => $reference]);
|
||||
}
|
||||
|
||||
if ($zone) {
|
||||
|
||||
@@ -127,6 +127,10 @@ final class InvestmentPreparationWorkspace
|
||||
{
|
||||
$objects = [['key' => 'investment:'.$case->id, 'label' => $case->title, 'kind' => 'investment']];
|
||||
$evidence = [];
|
||||
foreach ($context['sector_references'] ?? [] as $reference) {
|
||||
$current = hash_equals((SectorResourceReferences::SOURCES[$reference['sector_slug']] ?? ''), $reference['source_sha256'] ?? '') ? $reference : ['unavailable' => true, 'source_sha256' => (SectorResourceReferences::SOURCES[$reference['sector_slug']] ?? '')];
|
||||
$evidence['sector-resource:'.$reference['key']] = ['key' => 'sector-resource:'.$reference['key'], 'label' => $reference['title'], 'consulted' => $reference, 'current' => $current, 'notice' => 'Referência sectorial e de cadeia de valor; não certifica direitos, licenças nem disponibilidade de projecto.'];
|
||||
}
|
||||
$refs = array_values($context['selection'] ?? []);
|
||||
foreach ($context['opportunity_choices'] ?? [] as $choice) {
|
||||
$refs[] = $choice['opportunity'];
|
||||
|
||||
@@ -142,6 +142,9 @@ final class InvestorContext
|
||||
$zone = $context['selection']['park'] ?? null;
|
||||
$context['fields']['investment_regime'] = $zone['fields']['investment_regime'] ?? 'general';
|
||||
$context['fields']['special_zone_id'] = $zone['id'] ?? '';
|
||||
if (! empty($payload['investor_path']['sector_references'])) {
|
||||
$context['sector_references'] = $payload['investor_path']['sector_references'];
|
||||
}
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
@@ -173,6 +173,7 @@ final class InvestorPath
|
||||
'results' => $results, 'requests' => $requests, 'documents' => $documents,
|
||||
'zone_contexts' => ($owner || $manager) ? ($path['zone_contexts'] ?? []) : [],
|
||||
'sector_contexts' => ($owner || $manager) ? ($path['sector_contexts'] ?? []) : [],
|
||||
'sector_references' => ($owner || $manager) ? ($path['sector_references'] ?? []) : [],
|
||||
'content_sources' => ($owner || $manager) ? ($path['content_sources'] ?? []) : [],
|
||||
'tasks' => DB::table('tasks')->where('desk_case_id', $id)
|
||||
->whereNull('deleted_at')
|
||||
|
||||
@@ -74,7 +74,7 @@ final class SectorInvestment
|
||||
}
|
||||
}
|
||||
|
||||
return ['articles' => $articles, 'relations' => collect($relations)->unique('id')->values()->all(), 'locations' => $locations,
|
||||
return ['resource_reference' => isset(SectorResourceReferences::SOURCES[$sector->slug]) ? app(SectorResourceReferences::class)->view($sector->slug) : null, 'articles' => $articles, 'relations' => collect($relations)->unique('id')->values()->all(), 'locations' => $locations,
|
||||
'start_href' => app(InvestorPath::class)->available() ? '/investimentos/a-partir-do-setor/'.$sector->slug : null,
|
||||
'start_notice' => app(InvestorPath::class)->available() ? null : 'O percurso para guardar a ideia está temporariamente indisponível. A consulta e o apoio continuam disponíveis.',
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? ($creation ? $creation.'?sector_id='.$sector->id : '/perfil/promotor') : null,
|
||||
@@ -114,24 +114,31 @@ final class SectorInvestment
|
||||
*/
|
||||
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();
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'sector_slug' => 'required|string|max:150', 'sector_reference' => 'nullable|array'])->validate();
|
||||
$context = $this->context($data['sector_slug']);
|
||||
abort_if(! empty($data['sector_reference']) && ! isset(SectorResourceReferences::SOURCES[$context['slug']]), 422);
|
||||
$reference = isset($data['sector_reference']) ? app(SectorResourceReferences::class)->selection($context['slug'], $data['sector_reference']) : null;
|
||||
abort_unless(app(InvestorPath::class)->available(), 404);
|
||||
DB::transaction(function () use ($actor, $id, $data, $context) {
|
||||
DB::transaction(function () use ($actor, $id, $data, $context, $reference) {
|
||||
$desk = app(VirtualDesk::class);
|
||||
$case = $desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409, 'O dossier está encerrado.');
|
||||
abort_unless(DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(), 409, 'Este dossier conserva outro roteiro.');
|
||||
$payload = $desk->decode($case->payload);
|
||||
foreach ($payload['investor_path']['sector_contexts'] ?? [] as $existing) {
|
||||
if ($existing['id'] === $context['id']) {
|
||||
return;
|
||||
}
|
||||
$hasSector = array_any($payload['investor_path']['sector_contexts'] ?? [], fn ($row) => $row['id'] === $context['id']);
|
||||
$hasReference = $reference !== null && array_any($payload['investor_path']['sector_references'] ?? [], fn ($row) => $row['key'] === $reference['key']);
|
||||
if ($hasSector && ($reference === null || $hasReference)) {
|
||||
return;
|
||||
}
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi alterado; recupere a versão atual.');
|
||||
$payload['investor_path']['sector_contexts'][] = [...$context, 'actor_id' => $actor->id, 'saved_at' => now()->toIso8601String()];
|
||||
if (! $hasSector) {
|
||||
$payload['investor_path']['sector_contexts'][] = [...$context, 'actor_id' => $actor->id, 'saved_at' => now()->toIso8601String()];
|
||||
}
|
||||
if ($reference !== null && ! $hasReference) {
|
||||
$payload['investor_path']['sector_references'][] = [...$reference, 'actor_id' => $actor->id, 'saved_at' => now()->toIso8601String()];
|
||||
}
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($desk->case($actor, $id), $actor, 'sector_context_referenced', ['sector_id' => $context['id'], 'sector_slug' => $context['slug']]);
|
||||
$desk->event($desk->case($actor, $id), $actor, 'sector_context_referenced', ['sector_id' => $context['id'], 'sector_slug' => $context['slug'], 'sector_reference_key' => $reference['key'] ?? null]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** Versioned reference content over existing sector pages and private dossiers. */
|
||||
final class SectorResourceReferences
|
||||
{
|
||||
public const SOURCES = [
|
||||
'mineracao' => '7202fb5986b40e62347867c653770030683ffec2701a2921e84342f15e9f3d8a',
|
||||
'energia-especifica' => '2d9d94ac70115ade43c4093a4d5b302aaa93623a149f936615c38ba67b1e2bd2',
|
||||
];
|
||||
|
||||
// Generated data are checked independently from the unchanged Word originals.
|
||||
public const DATA = [
|
||||
'mineracao' => ['file' => 'mining-reference-20261111.json', 'hash' => '173c1fda9e20997436704d0e8e3a9a6d1be9b0dba4eb8b5f3d4c1e5fbb1020b8'],
|
||||
'energia-especifica' => ['file' => 'energy-reference-20261111.json', 'hash' => '3c1c33e68a710c65114f5db232eceb732f8894a1825baa52683e70a6e5a1f2bf'],
|
||||
];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function data(string $sector): array
|
||||
{
|
||||
abort_unless(isset(self::DATA[$sector]), 404);
|
||||
$path = database_path('data/'.self::DATA[$sector]['file']);
|
||||
abort_unless(hash_equals(self::DATA[$sector]['hash'], CheckedFile::sha256($path)), 503, 'A versão das referências sectoriais mudou.');
|
||||
$data = json_decode(CheckedFile::read($path), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(($data['source_sha256'] ?? null) === self::SOURCES[$sector], 503, 'Reconciliar a versão da referência antes de usar.');
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function view(string $sector): array
|
||||
{
|
||||
$data = $this->data($sector);
|
||||
$mining = $sector === 'mineracao';
|
||||
$groups = $mining ? $data['minerals'] : $data['groups'];
|
||||
$risks = $data['risks'];
|
||||
if ($mining) {
|
||||
$start = array_find_key($risks, fn ($text) => str_starts_with($text, 'Riscos e pontos'));
|
||||
$end = array_find_key($risks, fn ($text) => str_starts_with($text, 'Próximos passos'));
|
||||
$risks = $start !== null && $end !== null ? array_slice($risks, $start + 1, $end - $start - 1) : [];
|
||||
}
|
||||
|
||||
return ['sector_slug' => $sector, 'title' => $mining ? 'Mineração e cadeias de valor' : 'Energia e cadeias de valor',
|
||||
'introduction' => $mining ? 'Explore recursos minerais por localização e possibilidades de fornecimento, logística, energia e transformação. São referências para preparar o investimento; uma ocorrência não identifica uma concessão ou um projecto disponível.' : 'Explore gás natural, electricidade, renováveis e as actividades da cadeia de valor. Distinga projectos de referência, propostas, previsões e possibilidades de fornecimento ao preparar o investimento.',
|
||||
'group_label' => $mining ? 'Grupo mineral' : 'Segmento energético',
|
||||
'resource_heading' => $mining ? 'Recursos e localização' : 'Segmentos e âmbito territorial',
|
||||
'resource_notice' => $mining ? 'A localização é a indicada para o grupo de minérios. Quando a fonte não discrimina a distribuição de cada minério, não se presume que todos ocorram em todos os locais.' : 'Bacias, localidades, corredores e províncias conservam o âmbito indicado na fonte. Uma localização não delimitada fica por definir no investimento; uma referência não significa concurso aberto ou projecto disponível.',
|
||||
'source_sha256' => self::SOURCES[$sector], 'reference_date' => $data['reference_date'],
|
||||
'groups' => array_map(fn ($group) => [...array_diff_key($group, ['province_names' => true]), 'location_labels' => $group['location_labels'] ?? $group['province_names']], $groups),
|
||||
'areas' => array_map(fn ($area) => [...array_diff_key($area, ['source_fields' => true, 'province_names' => true, 'mineral_ids' => true]), 'location_labels' => $area['location_labels'] ?? $area['province_names'], 'group_ids' => $area['group_ids'] ?? $area['mineral_ids']], $data['areas']),
|
||||
'projects' => $data['projects'], 'indicators' => array_map(fn ($row) => ['label' => $row['mineral'], 'value' => $row['value'], 'source' => $row['source']], $data['indicators']),
|
||||
'risks' => $risks, 'sources' => $data['sources'], 'source_links' => $data['source_links'] ?? [], 'background' => $data['background'] ?? []];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function selection(string $sector, array $input): array
|
||||
{
|
||||
abort_unless(isset(self::SOURCES[$sector]), 422);
|
||||
$input = Validator::make($input, ['area_id' => 'required|string', 'source_sha256' => 'required|string|size:64', 'location_label' => 'nullable|string|max:150', 'group_id' => 'nullable|string'])->validate();
|
||||
abort_unless(hash_equals(self::SOURCES[$sector], $input['source_sha256']), 409, 'A referência foi actualizada; recupere a selecção actual.');
|
||||
$data = $this->view($sector);
|
||||
$area = array_find($data['areas'], fn ($row) => $row['id'] === $input['area_id']);
|
||||
abort_unless($area, 422, 'Escolha uma área de referência existente.');
|
||||
$group = isset($input['group_id']) ? array_find($data['groups'], fn ($row) => $row['id'] === $input['group_id']) : null;
|
||||
abort_if(isset($input['group_id']) && (! $group || ! in_array($group['id'], $area['group_ids'], true)), 422, 'O grupo escolhido não corresponde à cadeia de valor.');
|
||||
$location = $input['location_label'] ?? null;
|
||||
abort_if($location !== null && ! in_array($location, $area['location_labels'], true), 422, 'A localização escolhida não consta desta área de referência.');
|
||||
$snapshot = ['sector_slug' => $sector, 'source_sha256' => self::SOURCES[$sector], 'reference_date' => $data['reference_date'],
|
||||
'group_id' => $group['id'] ?? null, 'group_name' => $group['name'] ?? null, 'area_id' => $area['id'], 'title' => $area['title'], 'location_label' => $location,
|
||||
'locations_text' => $area['locations_text'], 'indicative_location' => $area['indicative_location'], 'value_chain' => $area['value_chain'], 'market_evidence' => $area['market_evidence'],
|
||||
'source_row' => $area['source_row'], 'source_state' => $area['source_state'], 'coordinates' => null, 'promotion_ready' => false,
|
||||
'territory_precision' => $location === null ? 'source_area_reference' : ($location === 'Maputo' ? 'province_or_city_unspecified' : 'source_location_reference'),
|
||||
'href' => '/sectores/'.$sector.'?'.http_build_query(['resource_area' => $area['id'], 'resource_location' => $location, 'resource_group' => $group['id'] ?? null])];
|
||||
|
||||
return ['key' => hash('sha256', json_encode([$sector, self::SOURCES[$sector], $area['id'], $location, $group['id'] ?? null], JSON_THROW_ON_ERROR)), ...$snapshot];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user