Compare commits
123
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a045162773 | ||
|
|
f059c226d2 | ||
|
|
d9f088587b | ||
|
|
2bad72c042 | ||
|
|
39bddad091 | ||
|
|
42b9324acb | ||
|
|
7e7bd4fde3 | ||
|
|
1263b4f6b7 | ||
|
|
2f1ef2fdfc | ||
|
|
61b4d9f1f9 | ||
|
|
1d52c3d8f4 | ||
|
|
0f79d0d54c | ||
|
|
d325b72fad | ||
|
|
8854b2928c | ||
|
|
f53a308327 | ||
|
|
723ce2a0a4 | ||
|
|
07182c7c73 | ||
|
|
bb6824d75d | ||
|
|
095280e29d | ||
|
|
e92519dd75 | ||
|
|
4988ca89dc | ||
|
|
258c8bd28b | ||
|
|
df543a4414 | ||
|
|
291a1c420f | ||
|
|
b20068d04b | ||
|
|
eab09dd61e | ||
|
|
71f2fcbb84 | ||
|
|
f6c1b60612 | ||
|
|
880e12890c | ||
|
|
f276781876 | ||
|
|
542ac2ff2c | ||
|
|
4971f8935b | ||
|
|
6d3bf2937e | ||
|
|
eca6719135 | ||
|
|
a400802b63 | ||
|
|
1b8b9f414a | ||
|
|
70423474d2 | ||
|
|
ee23a2cc2c | ||
|
|
a59142caa2 | ||
|
|
8ebe734d0d | ||
|
|
8f295f0551 | ||
|
|
a2033dd4a0 | ||
|
|
a708f079b3 | ||
|
|
aae79c712d | ||
|
|
bcbbe51c2f | ||
|
|
e549003e5d | ||
|
|
fbff2660f2 | ||
|
|
192a7e35e5 | ||
|
|
6805b606a1 | ||
|
|
bbc3c1c9bc | ||
|
|
9c067d6ae8 | ||
|
|
67cd583b94 | ||
|
|
0f280d2d6d | ||
|
|
0e8da995e0 | ||
|
|
ff293940a6 | ||
|
|
4f3dbcf864 | ||
|
|
d830fbca50 | ||
|
|
ef24cbdc92 | ||
|
|
5a5cc9e815 | ||
|
|
5ff9402fd0 | ||
|
|
c8e0a7ee39 | ||
|
|
1c75a30a60 | ||
|
|
c790159250 | ||
|
|
37854d0231 | ||
|
|
7476dc3430 | ||
|
|
d216830b06 | ||
|
|
d5cb41b111 | ||
|
|
89e6d72c1e | ||
|
|
7c8d4726e9 | ||
|
|
b10b35f308 | ||
|
|
60b52fc8c7 | ||
|
|
ac67f9c13a | ||
|
|
c359364de3 | ||
|
|
ff726e577f | ||
|
|
03bcaf38cd | ||
|
|
659c039b27 | ||
|
|
6734441855 | ||
|
|
95def7f75e | ||
|
|
786d5f78d1 | ||
|
|
5e00f1ee9e | ||
|
|
252f38bb0a | ||
|
|
7f13149723 | ||
|
|
dcecd25102 | ||
|
|
4e07557cb1 | ||
|
|
4e61480272 | ||
|
|
377c40a21a | ||
|
|
2209b83820 | ||
|
|
67aa015b4c | ||
|
|
4f630b9f2a | ||
|
|
5859a9810e | ||
|
|
dab85aee96 | ||
|
|
12cecd061b | ||
|
|
705dc69d68 | ||
|
|
6da444ae2e | ||
|
|
7e351348af | ||
|
|
c5756c0282 | ||
|
|
3f50f66633 | ||
|
|
a9241ff26b | ||
|
|
21ebad73e7 | ||
|
|
bbc05f1df6 | ||
|
|
6dde36b5ca | ||
|
|
dc0bbd74d5 | ||
|
|
66a5dbf311 | ||
|
|
f17e807ce1 | ||
|
|
4a881252fc | ||
|
|
36c8cadb49 | ||
|
|
bf2c054943 | ||
|
|
f3455432cf | ||
|
|
1da273f1f3 | ||
|
|
4b3c7e161f | ||
|
|
3a3aba5026 | ||
|
|
8ddfa93f45 | ||
|
|
87b74f0c2a | ||
|
|
ed96fd10b9 | ||
|
|
fa2ece10de | ||
|
|
26f6a0d348 | ||
|
|
a10dd83d8d | ||
|
|
181a9883b3 | ||
|
|
d662e63469 | ||
|
|
fb9a363e9e | ||
|
|
4f72751b8b | ||
|
|
8a8204eb53 | ||
|
|
996b5b08cd |
@@ -119,3 +119,8 @@ INVESTMOZ_TAX_RULE_APPROVERS=
|
||||
INVESTMOZ_TAX_RULE_PUBLISHERS=
|
||||
|
||||
INVESTMOZ_ZONE_TERRITORY_REVIEWERS=
|
||||
|
||||
# Local LibreTranslate service and installed language models.
|
||||
LIBRETRANSLATE_URL=http://127.0.0.1:5000
|
||||
LIBRETRANSLATE_TIMEOUT=60
|
||||
LIBRETRANSLATE_API_KEY=
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
## Uniformização pública e menu — decisão expressa do proprietário,11/11/2026
|
||||
|
||||
Lista e detalhe das instituições financeiras devem usar a mesma apresentação:descrição única,categoria/tipo sem repetição,produtos/serviços,contactos e moradas úteis apenas quando disponíveis. Não apresentar secções vazias,avisos genéricos repetidos,notas de publicação/importação,preços antigos por reconfirmar ou a mesma informação várias vezes. Deduplicar apenas a apresentação,conservando dados e fontes no editor. Usar Quorus e Moza Banco como exemplos de conferência.
|
||||
Menu principal:Início,Descoberta,Realização,Suporte,Sobre nós,Mais. Descoberta:Concursos e anúncios,Localizações,Instituições financeiras,Catálogos relacionados. Realização:Iniciar investimento,Licenciamento,Acesso à terra. Suporte:Biblioteca,Legislação,Serviços ao investidor,Acompanhamento do projecto,Apoio ao investidor. Preservar conteúdo deSobre nós/Mais,contexto dos dossiers e permissões. Escolha de apresentação:acessos de trabalho antes no nível principal passam paraMais,sem novas concessões.
|
||||
|
||||
## Comunicação pública — orientação expressa do proprietário,11/11/2026
|
||||
|
||||
Apresentar conteúdos públicos com linguagem profissional,clara e apelativa,centrada na entidade,oportunidade,produtos e serviços úteis ao investidor. Não usar descrições de importação,cadastro,fichas,ficheiros ou documentos geradores como apresentação comercial. Preservar as fontes,versões e rastreabilidade no cadastro/editor;ligações institucionais e datas úteis podem ser consultadas separadamente. Não inventar ofertas,condições,disponibilidade,cobertura ou garantias para preencher lacunas. Esta orientação aplica-se transversalmente aos conteúdos do portal.
|
||||
|
||||
## Simulação de viabilidade — clarificação expressa do proprietário,11/11/2026
|
||||
|
||||
O InvesteMoz simula impostos para avaliar a viabilidade do negócio; não actua como entidade que executa pagamentos. Apresentar PPC/PEC e distribuição por meses como estimativas fiscais e projecções de tesouraria,com fontes e pressupostos. Montantes já pagos,quando fornecidos,são dados documentais para o cálculo. Não confundir uma hipótese de caixa com pagamento efectuado,declaração submetida ou cumprimento fiscal certificado. Preservar os cálculos,históricos e dados aceites; não criar serviços de cobrança/execução de pagamentos como requisito de conclusão deste simulador.
|
||||
|
||||
# Instruções permanentes do projeto InvesteMoz
|
||||
|
||||
## Encerramento e reabertura do dossier — decisão do proprietário, 03/11/2026
|
||||
|
||||
O proprietário definiu expressamente: «o dossier tem um dono, esse é que deve executar essa acção», em resposta a quem pode encerrar e reabrir o dossier completo. Usar o dono registado no dossier e conservar a verificação do acesso efectivo existente, incluindo a representação actual quando pertence a uma organização. A condição de gestor, analista ou outro representante não substitui por inferência esse dono. Registar a decisão, motivo, versão e histórico. Encerrar ou reabrir o dossier não equivale a decidir/aprovar pedidos, conferir pagamentos ou alterar em cascata estados de documentos e tarefas.
|
||||
|
||||
## Percurso adaptativo — decisão expressa da Tempo, 23/10/2026
|
||||
|
||||
Carteira/projectos âncora e percurso adaptativo têm diagnósticos distintos, mas fazem parte da mesma experiência e responsabilidade de correcção. Separar o diagnóstico não autoriza adiamento, desligamento do percurso ou perda de contexto entre corredor/localização, oportunidades, associações documentadas a âncoras/clusters, dossier e simulador. A reposição prioritária só se considera demonstrada com causa delimitada e disponibilidade recuperada, reutilizando o inventário e os recibos existentes; melhorias noutro ponto não a comprovam. Consultar os registos de reposição antes de voltar a declarar causa desconhecida ou registos desaparecidos.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
final class DispatchInvestmentAlerts extends Command
|
||||
{
|
||||
protected $signature = 'investmoz:dispatch-opportunity-alerts';
|
||||
|
||||
protected $description = 'Generate due opt-in alerts from public catalogues, without external messages';
|
||||
|
||||
public function handle(InvestmentOpportunityAlerts $alerts): int
|
||||
{
|
||||
if (! $alerts->installed()) {
|
||||
$this->warn('Opportunity alerts schema is not installed.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$this->info('Matched public catalogue items: '.$alerts->dispatchDue());
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class OpportunityWorkflowUnavailable extends RuntimeException
|
||||
{
|
||||
public function __construct(public readonly string $reference, public readonly bool $recorded, Throwable $previous)
|
||||
{
|
||||
parent::__construct('Opportunity operation result requires verification.', 0, $previous);
|
||||
}
|
||||
|
||||
public function render(): JsonResponse
|
||||
{
|
||||
return response()->json(['message' => 'Não foi possível confirmar o resultado. Consulte o estado da oportunidade e dos recursos antes de repetir. '.($this->recorded ? 'Incidente técnico registado. ' : 'Não foi possível guardar o incidente; conserve esta referência. ').'Referência: '.$this->reference,
|
||||
'reference' => $this->reference, 'incident_recorded' => $this->recorded], 503)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
class TranslationApiController extends Controller
|
||||
{
|
||||
public function languages(): JsonResponse
|
||||
{
|
||||
try {
|
||||
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->get($this->url().'/languages');
|
||||
if ($response->successful() && is_array($response->json())) {
|
||||
return response()->json($response->json())->header('Cache-Control', 'no-store');
|
||||
}
|
||||
} catch (Throwable) {
|
||||
}
|
||||
|
||||
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503);
|
||||
}
|
||||
|
||||
public function translate(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'text' => is_array($request->input('text'))
|
||||
? 'required|array|min:1|max:8'
|
||||
: 'required|string|max:10000',
|
||||
'text.*' => 'required|string|max:10000',
|
||||
'source_lang' => 'required|string|max:20',
|
||||
'target_lang' => 'required|string|max:20',
|
||||
'is_html' => 'boolean',
|
||||
]);
|
||||
|
||||
$isBatch = is_array($data['text']);
|
||||
if ($isBatch && mb_strlen(implode('', $data['text'])) > 10000) {
|
||||
return response()->json(['message' => 'O lote de tradução excede o limite permitido.'], 422);
|
||||
}
|
||||
|
||||
if ($data['source_lang'] === $data['target_lang']) {
|
||||
return response()->json([
|
||||
'original_text' => $data['text'],
|
||||
'translated_text' => $data['text'],
|
||||
'source_lang' => $data['source_lang'],
|
||||
'target_lang' => $data['target_lang'],
|
||||
])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
$payload = ['q' => $data['text'], 'source' => $data['source_lang'], 'target' => $data['target_lang'], 'format' => ($data['is_html'] ?? false) ? 'html' : 'text'];
|
||||
if (config('services.translation.api_key')) {
|
||||
$payload['api_key'] = config('services.translation.api_key');
|
||||
}
|
||||
try {
|
||||
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->post($this->url().'/translate', $payload);
|
||||
$translated = $response->json('translatedText');
|
||||
$validTranslation = $isBatch
|
||||
? is_array($translated)
|
||||
&& count($translated) === count($data['text'])
|
||||
&& ! array_filter($translated, fn ($text) => ! is_string($text) || $text === '')
|
||||
: is_string($translated) && $translated !== '';
|
||||
|
||||
if ($response->successful() && $validTranslation) {
|
||||
return response()->json([
|
||||
'original_text' => $data['text'],
|
||||
'translated_text' => $translated,
|
||||
'source_lang' => $data['source_lang'],
|
||||
'target_lang' => $data['target_lang'],
|
||||
])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
} catch (Throwable) {
|
||||
}
|
||||
|
||||
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503)->header('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
private function url(): string
|
||||
{
|
||||
return rtrim((string) config('services.translation.url'), '/');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\SectorOrganization;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -20,8 +21,9 @@ class HomeController extends Controller
|
||||
|
||||
$locale = $validated['locale'] ?? 'pt';
|
||||
|
||||
$data = Cache::remember("portal_home_sector_organization_v1_{$locale}", now()->addMinutes(10), function () {
|
||||
$data = Cache::remember("portal_home_territorial_v2_{$locale}", now()->addMinutes(10), function () {
|
||||
$sectors = SectorOrganization::catalog();
|
||||
$statistics = app(InvestmentGeography::class)->opportunityStatistics();
|
||||
|
||||
$featured = Opportunity::with('sector:id,name,slug')
|
||||
->published()->where('is_featured', true)
|
||||
@@ -48,9 +50,9 @@ class HomeController extends Controller
|
||||
'url' => "/oportunidades/{$o->slug}",
|
||||
])->values()->all(),
|
||||
'stats' => [
|
||||
'opportunities' => Opportunity::published()->count(),
|
||||
'opportunities' => $statistics['opportunities'],
|
||||
'sectors' => $sectors->count(),
|
||||
'provinces' => Opportunity::published()->distinct('province')->count('province'),
|
||||
'provinces' => $statistics['provinces'],
|
||||
],
|
||||
];
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ use App\Http\Controllers\Controller;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\OpportunityTextSearch;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\SectorOrganization;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -41,16 +43,7 @@ class OpportunityController extends Controller
|
||||
}
|
||||
|
||||
if (! empty($validated['q'])) {
|
||||
$term = $validated['q'];
|
||||
$query->where(fn ($q) => $q
|
||||
->whereLike('title', "%{$term}%")
|
||||
->orWhereLike('description', "%{$term}%")
|
||||
->orWhereLike('summary', "%{$term}%")
|
||||
->orWhereLike('reference', "%{$term}%")
|
||||
->orWhereLike('province', "%{$term}%")
|
||||
->orWhereHas('sector', fn ($sectorQuery) => $sectorQuery
|
||||
->whereLike('name', "%{$term}%")
|
||||
->orWhereLike('slug', "%{$term}%")));
|
||||
app(OpportunityTextSearch::class)->constrain($query, $validated['q']);
|
||||
}
|
||||
|
||||
if (! empty($validated['sector'])) {
|
||||
@@ -71,6 +64,7 @@ class OpportunityController extends Controller
|
||||
$results = $query->orderByDesc('is_featured')
|
||||
->orderByDesc('published_at')
|
||||
->paginate($validated['per_page'] ?? 12);
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'opportunities_api', $results->total(), $validated);
|
||||
|
||||
return response()->json($results->withQueryString()->through(fn ($record) => app(InvestmentCatalogue::class)->presentLocation($record)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\CompanyComparison;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class CompanyComparisonController extends Controller
|
||||
{
|
||||
public function index(Request $request, CompanyComparison $service): Response|JsonResponse
|
||||
{
|
||||
$answers = $service->answers($request->all());
|
||||
$data = ['definition' => $service->definition(), 'answers' => $answers, 'result' => $service->evaluate($answers),
|
||||
'case' => null, 'saved' => null, 'canWrite' => false, 'history' => [], 'historyNext' => null, 'historical' => false, 'workingCopy' => false];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-comparison', $data);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, CompanyComparison $service): Response|JsonResponse
|
||||
{
|
||||
$data = ['definition' => $service->definition(), ...$service->view($request->user(), $id, $request->all())];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-comparison', $data);
|
||||
}
|
||||
|
||||
public function save(Request $request, string $id, CompanyComparison $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->save($request->user(), $id, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\CompanyPreparation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class CompanyPreparationController extends Controller
|
||||
{
|
||||
public function show(Request $request, string $id, CompanyPreparation $service): Response|JsonResponse
|
||||
{
|
||||
$data = $service->view($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-preparation', $data);
|
||||
}
|
||||
|
||||
public function save(Request $request, string $id, CompanyPreparation $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->save($request->user(), $id, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,14 @@ use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use App\Services\ConvertInterestToLead;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\CrmNextAction;
|
||||
use App\Services\CrmTaskCreation;
|
||||
use App\Services\CrmTaskPreparations;
|
||||
use App\Services\DeclaredOriginStatistics;
|
||||
use App\Services\PortalAudit;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -23,6 +28,12 @@ use Inertia\Response;
|
||||
|
||||
class CrmController extends Controller
|
||||
{
|
||||
private const VERSION_MESSAGES = [
|
||||
'version.required' => 'Actualize os dados para recuperar a versão deste registo antes de gravar. As suas edições foram conservadas.',
|
||||
'version.integer' => 'A versão do registo não foi reconhecida. Recupere os dados actuais.',
|
||||
'version.min' => 'A versão do registo não foi reconhecida. Recupere os dados actuais.',
|
||||
];
|
||||
|
||||
public function investors(Request $request): Response
|
||||
{
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:150']]);
|
||||
@@ -43,10 +54,12 @@ class CrmController extends Controller
|
||||
|
||||
public function saveInvestor(Request $request, Investor $investor): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['legal_name' => ['required', 'string', 'max:200'],
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'legal_name' => ['required', 'string', 'max:200'],
|
||||
'investor_type' => ['required', Rule::in(['domestic', 'foreign', 'institutional', 'individual'])],
|
||||
'status' => ['required', Rule::in(['prospect', 'active', 'inactive'])]]);
|
||||
PortalAudit::save($investor, $data, $request->user()->id);
|
||||
'status' => ['required', Rule::in(['prospect', 'active', 'inactive'])]], self::VERSION_MESSAGES);
|
||||
$version = (int) $data['version'];
|
||||
unset($data['version']);
|
||||
PortalAudit::save($investor, $data, $request->user()->id, $version);
|
||||
|
||||
return back()->with('success', 'Investidor actualizado.');
|
||||
}
|
||||
@@ -54,15 +67,17 @@ class CrmController extends Controller
|
||||
public function saveContact(Request $request, Investor $investor, Contact $contact): RedirectResponse
|
||||
{
|
||||
abort_unless(DB::table('investor_contacts')->where('investor_id', $investor->id)->where('contact_id', $contact->id)->exists(), 404);
|
||||
$data = $request->validate(['full_name' => ['required', 'string', 'max:150'],
|
||||
'email' => ['required', 'email:rfc', 'max:150'], 'phone' => ['nullable', 'string', 'max:30']]);
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'full_name' => ['required', 'string', 'max:150'],
|
||||
'email' => ['required', 'email:rfc', 'max:150'], 'phone' => ['nullable', 'string', 'max:30']], self::VERSION_MESSAGES);
|
||||
$data['email'] = strtolower(trim($data['email']));
|
||||
DB::transaction(function () use ($contact, $data, $request) {
|
||||
$version = (int) $data['version'];
|
||||
unset($data['version']);
|
||||
DB::transaction(function () use ($contact, $data, $request, $version) {
|
||||
DB::select('select pg_advisory_xact_lock(170925, hashtext(?))', [$data['email']]);
|
||||
if (Contact::where('id', '!=', $contact->id)->whereRaw('lower(trim(email)) = ?', [$data['email']])->exists()) {
|
||||
throw ValidationException::withMessages(['email' => 'Já existe outro contacto com este email. Reveja os registos antes de os fundir.']);
|
||||
}
|
||||
PortalAudit::save($contact, $data, $request->user()->id);
|
||||
PortalAudit::save($contact, $data, $request->user()->id, $version);
|
||||
});
|
||||
|
||||
return back()->with('success', 'Contacto actualizado.');
|
||||
@@ -82,7 +97,7 @@ class CrmController extends Controller
|
||||
'owner_user_id' => ['nullable', 'integer', 'exists:users,id'],
|
||||
'origin' => ['nullable', Rule::in(['unknown', ...array_column(app(CountryCatalogue::class)->all(), 'code')])]]);
|
||||
$query = Lead::with(['investor:id,legal_name', 'owner:id,name'])
|
||||
->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())]);
|
||||
->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->availableForWork()->where('due_at', '<', now())]);
|
||||
if ($term = $filters['q'] ?? null) {
|
||||
$query->where(fn ($q) => $q->whereLike('title', "%{$term}%")
|
||||
->orWhereHas('investor', fn ($investor) => $investor->whereLike('legal_name', "%{$term}%")));
|
||||
@@ -127,29 +142,37 @@ class CrmController extends Controller
|
||||
return redirect('/management/crm/leads/'.$lead->id)->with('success', 'Pedido convertido em lead com responsável e próxima acção.');
|
||||
}
|
||||
|
||||
public function show(Lead $lead): Response
|
||||
public function show(Request $request, Lead $lead): Response
|
||||
{
|
||||
$lead->load(['investor', 'owner:id,name', 'tasks' => fn ($q) => $q->orderBy('due_at')]);
|
||||
$caseIds = $lead->tasks->pluck('desk_case_id')->filter();
|
||||
$closedCases = $caseIds->isEmpty() ? [] : DB::table('desk_cases')->whereIn('id', $caseIds)->whereNotNull('closed_at')->pluck('id')->all();
|
||||
foreach ($lead->tasks as $task) {
|
||||
$task->setAttribute('can_update', ! in_array($task->getAttribute('desk_case_id'), $closedCases, true));
|
||||
}
|
||||
$contacts = DB::table('investor_contacts')->join('contacts', 'contacts.id', '=', 'investor_contacts.contact_id')
|
||||
->where('investor_id', $lead->investor_id)->whereNull('contacts.deleted_at')->get(['contacts.id', 'full_name', 'email', 'phone']);
|
||||
|
||||
return Inertia::render('crm/lead', ['lead' => $lead, 'contacts' => $contacts, 'owners' => $this->owners()]);
|
||||
return Inertia::render('crm/lead', ['lead' => $lead, 'contacts' => $contacts, 'owners' => $this->owners(), 'taskCreation' => app(CrmTaskCreation::class)->context($request->user(), $lead),
|
||||
'nextAction' => ['future_tasks' => app(CrmNextAction::class)->future($lead)->count()]]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Lead $lead): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['owner_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))],
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'owner_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))],
|
||||
'status' => ['required', Rule::in(['new', 'qualified', 'disqualified'])],
|
||||
'qualification_reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
DB::transaction(function () use ($lead, $data, $request) {
|
||||
'qualification_reason' => ['required', 'string', 'min:10', 'max:2000']], self::VERSION_MESSAGES);
|
||||
$version = (int) $data['version'];
|
||||
unset($data['version']);
|
||||
DB::transaction(function () use ($lead, $data, $request, $version) {
|
||||
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
|
||||
if ($lead->status === 'converted') {
|
||||
throw ValidationException::withMessages(['status' => 'O lead já foi convertido numa negociação.']);
|
||||
}
|
||||
if ($data['status'] !== 'disqualified' && ! $lead->tasks()->whereIn('status', ['open', 'in_progress'])->where('due_at', '>', now())->exists()) {
|
||||
if ($data['status'] !== 'disqualified' && ! app(CrmNextAction::class)->future($lead)->exists()) {
|
||||
throw ValidationException::withMessages(['status' => 'Registe uma próxima acção com prazo futuro antes de activar ou qualificar o lead.']);
|
||||
}
|
||||
PortalAudit::save($lead, $data, $request->user()->id);
|
||||
PortalAudit::save($lead, $data, $request->user()->id, $version);
|
||||
});
|
||||
|
||||
return back()->with('success', 'Lead actualizado.');
|
||||
@@ -157,24 +180,39 @@ class CrmController extends Controller
|
||||
|
||||
public function task(Request $request, Lead $lead): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['title' => ['required', 'string', 'max:200'], 'due_at' => ['required', 'date', 'after:now'],
|
||||
'assignee_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))]]);
|
||||
PortalAudit::save(new CrmTask, [...$data, 'lead_id' => $lead->id, 'status' => 'open'], $request->user()->id);
|
||||
$result = app(CrmTaskCreation::class)->create($request->user(), $lead, $request->all(), $this->owners()->pluck('id')->all());
|
||||
|
||||
return back()->with('success', 'Tarefa criada.');
|
||||
return redirect('/management/crm/leads/'.$lead->id)->with('success', $result['replayed'] ? 'A tarefa já tinha sido registada. A criação não foi repetida.' : 'Tarefa criada.');
|
||||
}
|
||||
|
||||
public function taskPreparation(Request $request, Lead $lead): JsonResponse
|
||||
{
|
||||
// Preserve the user's partial text; business validation still occurs only on task creation.
|
||||
$input = json_decode($request->getContent(), true);
|
||||
if (! is_array($input)) {
|
||||
throw ValidationException::withMessages(['snapshot' => 'A preparação deve ser enviada em JSON.']);
|
||||
}
|
||||
|
||||
return response()->json(app(CrmTaskPreparations::class)->save($request->user(), $lead, $input));
|
||||
}
|
||||
|
||||
public function updateTask(Request $request, Lead $lead, CrmTask $task): RedirectResponse
|
||||
{
|
||||
abort_unless($task->lead_id === $lead->id, 404);
|
||||
$data = $request->validate(['status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])]]);
|
||||
DB::transaction(function () use ($lead, $task, $data, $request) {
|
||||
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
|
||||
if (in_array($lead->status, ['new', 'qualified'], true) && in_array($data['status'], ['done', 'cancelled'], true)
|
||||
&& ! $lead->tasks()->where('id', '!=', $task->id)->whereIn('status', ['open', 'in_progress'])->where('due_at', '>', now())->exists()) {
|
||||
throw ValidationException::withMessages(['status' => 'Crie a próxima acção antes de encerrar a última tarefa de um lead activo.']);
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])]], self::VERSION_MESSAGES);
|
||||
$version = (int) $data['version'];
|
||||
unset($data['version']);
|
||||
DB::transaction(function () use ($lead, $task, $data, $request, $version) {
|
||||
if ($task->getAttribute('desk_case_id')) {
|
||||
$case = DB::table('desk_cases')->where('id', $task->getAttribute('desk_case_id'))->lockForUpdate()->first();
|
||||
abort_unless($case !== null, 404);
|
||||
app(VirtualDesk::class)->assertOpen($case);
|
||||
}
|
||||
PortalAudit::save($task, $data, $request->user()->id);
|
||||
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
|
||||
$task = CrmTask::lockForUpdate()->findOrFail($task->id);
|
||||
abort_unless($task->lead_id === $lead->id, 404);
|
||||
app(CrmNextAction::class)->assertMayFinish($lead, $task, $data['status']);
|
||||
PortalAudit::save($task, $data, $request->user()->id, $version);
|
||||
});
|
||||
|
||||
return back()->with('success', 'Tarefa actualizada.');
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\DashboardWorkQueue;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -16,12 +17,18 @@ class DashboardController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request): Response
|
||||
{
|
||||
if (! $request->user()->can('manage-portal')) {
|
||||
$validated = $request->validate(['interests_page' => 'sometimes|integer|min:1', 'desk_page' => 'sometimes|integer|min:1', 'crm_tasks_page' => 'sometimes|integer|min:1']);
|
||||
$pages = [];
|
||||
foreach (['interests_page', 'desk_page', 'crm_tasks_page'] as $key) {
|
||||
$pages[$key] = (int) ($validated[$key] ?? 1);
|
||||
}
|
||||
$workQueue = app(DashboardWorkQueue::class)->forActor($request->user(), $pages);
|
||||
if (! $request->user()->can('manage-portal') || app(PortalProfileAccess::class)->has($request->user(), 'auditor')) {
|
||||
$path = app(InvestorPath::class);
|
||||
$contexts = $path->contexts($request->user());
|
||||
$current = $contexts ? $path->view($request->user(), $contexts[0]['id']) : null;
|
||||
|
||||
return Inertia::render('dashboard', ['summary' => null, 'investorPath' => $path->available() ? [
|
||||
return Inertia::render('dashboard', ['summary' => null, 'workQueue' => $workQueue, 'investorPath' => $path->available() ? [
|
||||
'contexts' => $contexts,
|
||||
'current' => $current ? ['id' => $current['case']['id'], 'next' => $current['next'],
|
||||
'pending' => count(array_filter($current['steps'], fn ($step) => ! in_array($step['state'], ['completed', 'approved', 'dispensed'], true))),
|
||||
@@ -36,7 +43,7 @@ class DashboardController extends Controller
|
||||
$drafts = app(PortalProfileAccess::class)->scope($drafts, $request->user());
|
||||
}
|
||||
|
||||
return Inertia::render('dashboard', ['summary' => [
|
||||
return Inertia::render('dashboard', ['workQueue' => $workQueue, 'summary' => [
|
||||
'canCreateOpportunity' => app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
|
||||
'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed'])
|
||||
->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]),
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\DemographicEvidence;
|
||||
use App\Services\DemographicImport;
|
||||
use App\Services\DemographicInstallation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class DemographyController extends Controller
|
||||
{
|
||||
public function index(Request $request, DemographicEvidence $service): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['territories' => 'nullable|array|max:4', 'territories.*' => 'required|uuid|distinct',
|
||||
'start_year' => 'nullable|integer|between:1900,2100', 'end_year' => 'nullable|integer|between:1900,2100|gte:start_year',
|
||||
'sector' => 'nullable|in:'.implode(',', array_keys(DemographicEvidence::sectors())), 'edition' => 'nullable|uuid']);
|
||||
$start = (int) ($data['start_year'] ?? date('Y'));
|
||||
$end = (int) ($data['end_year'] ?? $start);
|
||||
abort_unless($end >= $start && $end - $start <= 50, 422, 'Escolha um horizonte até 50 anos.');
|
||||
$evidence = $service->analyse($data['territories'] ?? [], $start, $end, $data['sector'] ?? 'general', $data['edition'] ?? null);
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json($evidence);
|
||||
}
|
||||
$territories = $service->territories()->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']);
|
||||
|
||||
return Inertia::render('investment/demography', ['evidence' => $evidence, 'filters' => $data, 'territories' => $territories, 'sectors' => DemographicEvidence::sectors()]);
|
||||
}
|
||||
|
||||
public function management(Request $request, DemographicImport $service): Response|RedirectResponse
|
||||
{
|
||||
if (! Schema::hasTable('demographic_imports')) {
|
||||
return redirect('/management/demography/install');
|
||||
}
|
||||
$service->authorize($request->user());
|
||||
$data = $request->validate(['batch' => 'nullable|uuid']);
|
||||
|
||||
return Inertia::render('management/demography', ['qa' => ! app(DemographicInstallation::class)->activeTarget(), 'batches' => DB::table('demographic_imports')->orderByDesc('created_at')->get(['id', 'file_name', 'publication_version', 'status', 'created_at']),
|
||||
'preview' => isset($data['batch']) ? $service->preview($request->user(), $data['batch']) : null]);
|
||||
}
|
||||
|
||||
public function installation(Request $request, DemographicInstallation $service): Response
|
||||
{
|
||||
return Inertia::render('management/demography-install', ['plan' => $service->preview($request->user())]);
|
||||
}
|
||||
|
||||
public function install(Request $request, DemographicInstallation $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->apply($request->user(), $request->all()));
|
||||
}
|
||||
|
||||
public function prepare(Request $request, DemographicImport $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['file' => 'required|file|mimes:xlsx|max:19531', 'publication_version' => 'required|string|max:255', 'baseline_year' => 'nullable|integer|between:1900,2100']);
|
||||
$file = $request->file('file');
|
||||
|
||||
return response()->json($service->prepare($request->user(), $file->getRealPath(), $file->getClientOriginalName(), $data['publication_version'], isset($data['baseline_year']) ? (int) $data['baseline_year'] : null));
|
||||
}
|
||||
|
||||
public function confirm(Request $request, string $id, DemographicImport $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['sha256' => 'required|string|size:64', 'mapping' => 'present|array', 'mapping.*' => 'required|uuid', 'reason' => 'required|string|min:10|max:2000']);
|
||||
|
||||
return response()->json($service->confirm($request->user(), $id, $data['sha256'], $data['mapping'], $data['reason']));
|
||||
}
|
||||
|
||||
public function transition(Request $request, string $id, DemographicImport $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['action' => 'required|in:approved,disabled', 'reason' => 'required|string|min:10|max:2000']);
|
||||
$service->transition($request->user(), $id, $data['action'], $data['reason']);
|
||||
|
||||
return response()->json(['id' => $id, 'status' => $data['action']]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\DeskRequestCheckpoints;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class DeskRequestCheckpointController extends Controller
|
||||
{
|
||||
public function show(Request $request, string $id, DeskRequestCheckpoints $checkpoints): JsonResponse
|
||||
{
|
||||
return response()->json($checkpoints->show($request->user(), $id));
|
||||
}
|
||||
|
||||
public function save(Request $request, string $id, DeskRequestCheckpoints $checkpoints): JsonResponse
|
||||
{
|
||||
return response()->json($checkpoints->save($request->user(), $id, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\DeskServiceAvailability;
|
||||
use App\Services\DeskServiceEditor;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class DeskServiceEditorController extends Controller
|
||||
{
|
||||
public function index(Request $request, DeskServiceEditor $editor): Response|JsonResponse
|
||||
{
|
||||
$data = ['services' => $editor->listing(), 'schedulingAvailable' => app(DeskServiceAvailability::class)->scheduled(), 'today' => now()->toDateString(), 'calendarTimezone' => config('app.timezone')];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/service-editor', $data);
|
||||
}
|
||||
|
||||
public function publish(Request $request, DeskServiceEditor $editor, string $code): JsonResponse|RedirectResponse
|
||||
{
|
||||
$row = $editor->publish($request->user(), $code, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version, 'effective_from' => $row->effective_from ?? null], 201)
|
||||
: back()->with('success', 'Versão publicada'.(($row->effective_from ?? null) ? ' com entrada em vigor em '.$row->effective_from : '').'. Os pedidos existentes conservam a sua versão.');
|
||||
}
|
||||
|
||||
public function history(Request $request, DeskServiceEditor $editor, string $code): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['page' => ['nullable', 'integer', 'min:1']]);
|
||||
|
||||
return response()->json($editor->history($code, (int) ($data['page'] ?? 1)));
|
||||
}
|
||||
}
|
||||
@@ -2,28 +2,28 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use App\Services\Malware\DocumentScanRetry;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class DocumentMalwareController extends Controller
|
||||
{
|
||||
public function retry(Request $request, string $id): RedirectResponse
|
||||
public function retry(Request $request, string $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
DB::transaction(function () use ($id, $request): void {
|
||||
$document = app(DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
|
||||
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
|
||||
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
|
||||
$result = app(DocumentScanRetry::class)->request($request->user(), $id);
|
||||
$message = match ($result['outcome']) {
|
||||
'accepted' => 'Pedido de análise aceite pelo serviço de envio. Acompanhe o estado do ficheiro até haver resultado.',
|
||||
'duplicate' => 'Já existe uma reserva de análise para este ficheiro. Não foi enviado outro pedido. Acompanhe o estado antes de repetir.',
|
||||
'stale' => 'O ficheiro ou o seu acesso mudou. Actualize a página para consultar o estado antes de repetir.',
|
||||
'unconfirmed' => 'Não foi possível confirmar o envio da análise. Consulte o estado antes de repetir. Referência: '.$result['reference'],
|
||||
default => 'Pedido preparado para envio após a confirmação da gravação. Acompanhe o estado do ficheiro.',
|
||||
};
|
||||
|
||||
DB::table('documents')->where('id', $id)->update([
|
||||
'status' => 'quarantined', 'malware_scan_status' => 'pending', 'malware_failure_reason' => null, 'updated_at' => now(),
|
||||
]);
|
||||
ScanDocumentForMalware::dispatch($id)->afterCommit();
|
||||
});
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json([...$result, 'message' => $message], $result['outcome'] === 'unconfirmed' ? 503 : 200)->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Nova análise colocada na fila. O ficheiro permanece privado até haver resultado.');
|
||||
return back()->with($result['outcome'] === 'accepted' ? 'success' : 'warning', $message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,28 +11,45 @@ use App\Models\Sector;
|
||||
use App\Models\Skill;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\TrainingProvider;
|
||||
use App\Models\User;
|
||||
use App\Services\EducationAccess;
|
||||
use App\Services\EducationDeclarationDrafts;
|
||||
use App\Services\EducationDeclarationRules;
|
||||
use App\Services\EducationGapCalculator;
|
||||
use App\Services\EducationReviews;
|
||||
use App\Services\EducationWorkQueue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\PortalAudit;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class EducationController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
public function index(Request $request): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:150'],
|
||||
'status' => ['nullable', Rule::in(['submitted', 'reviewed', 'rejected', 'expired'])],
|
||||
'geo_location_id' => ['nullable', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
'demand_page' => ['nullable', 'integer', 'min:1'],
|
||||
'capacity_page' => ['nullable', 'integer', 'min:1'],
|
||||
]);
|
||||
app(EducationAccess::class)->authorize($request->user());
|
||||
$filters = $this->filters($request);
|
||||
if (($filters['scope'] ?? 'all') === 'review') {
|
||||
unset($filters['status']);
|
||||
}
|
||||
$draftService = app(EducationDeclarationDrafts::class);
|
||||
$draftsAvailable = $draftService->installed();
|
||||
$selectedDraft = null;
|
||||
if (! empty($filters['draft'])) {
|
||||
abort_unless($draftsAvailable, 404);
|
||||
$kind = DB::table('education_declaration_drafts')->where('id', $filters['draft'])->where('owner_user_id', $request->user()->id)->value('kind');
|
||||
abort_unless($kind !== null, 404);
|
||||
$selectedDraft = $draftService->show($request->user(), $kind, $filters['draft']);
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
$demands = LabourDemand::query();
|
||||
$capacities = TrainingCapacity::query();
|
||||
$territoryIds = [];
|
||||
@@ -53,20 +70,36 @@ class EducationController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
// Viewing one's work must not remove existing territorial catalogue evidence.
|
||||
$territorialCapacities = clone $capacities;
|
||||
foreach ([$demands, $capacities] as $query) {
|
||||
if (($filters['scope'] ?? 'all') === 'mine') {
|
||||
$query->where('submitted_by', $request->user()->id);
|
||||
} elseif (($filters['scope'] ?? 'all') === 'review') {
|
||||
$query->where('submitted_by', '<>', $request->user()->id)->where('status', 'submitted')->where('valid_until', '>=', now()->toDateString());
|
||||
}
|
||||
}
|
||||
$providers = TrainingProvider::where('status', '!=', 'inactive');
|
||||
$courses = Course::where('status', '!=', 'retired')
|
||||
->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'));
|
||||
if ($territoryIds !== []) {
|
||||
// Provider and course location is evidenced by their submitted training capacity.
|
||||
// Do not infer locations from provider names, addresses, or unrelated records.
|
||||
$courses->whereIn('id', $territorialCapacities->select('course_id'));
|
||||
$providers->whereIn('id', (clone $courses)->select('provider_id'));
|
||||
}
|
||||
|
||||
return Inertia::render('education/index', [
|
||||
'demands' => $demands->latest()->orderBy('id')->paginate(20, ['*'], 'demand_page')->withQueryString(),
|
||||
'capacities' => $capacities->latest()->orderBy('id')->paginate(20, ['*'], 'capacity_page')->withQueryString(),
|
||||
return tap(Inertia::render('education/index', [
|
||||
'workQueue' => app(EducationWorkQueue::class)->summary($request->user()),
|
||||
'draftsAvailable' => $draftsAvailable, 'selectedDraft' => $selectedDraft,
|
||||
'ownDrafts' => $draftsAvailable ? DB::table('education_declaration_drafts')->where('owner_user_id', $request->user()->id)
|
||||
->orderByDesc('updated_at')->orderBy('id')->paginate(20, ['id', 'kind', 'version_no', 'state', 'updated_at', 'payload'], 'draft_page')->withQueryString()
|
||||
->through(function ($row) {
|
||||
$payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return ['id' => $row->id, 'kind' => $row->kind, 'version_no' => (int) $row->version_no, 'state' => $row->state,
|
||||
'updated_at' => CarbonImmutable::parse($row->updated_at)->toIso8601String(), 'label' => $payload['qualification'] ?? null];
|
||||
}) : null,
|
||||
'demands' => $demands->latest()->orderBy('id')->paginate(20, ['*'], 'demand_page')->withQueryString()->through(fn (LabourDemand $row) => $this->listing($row, 'demands', $request, $filters)),
|
||||
'capacities' => $capacities->latest()->orderBy('id')->paginate(20, ['*'], 'capacity_page')->withQueryString()->through(fn (TrainingCapacity $row) => $this->listing($row, 'capacities', $request, $filters)),
|
||||
'filters' => $filters,
|
||||
'indicators' => [
|
||||
'demand_records' => LabourDemand::count(),
|
||||
@@ -83,9 +116,63 @@ class EducationController extends Controller
|
||||
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
|
||||
->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']),
|
||||
'today' => now()->toDateString(),
|
||||
])->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:150'],
|
||||
'status' => ['nullable', Rule::in(['submitted', 'reviewed', 'rejected', 'expired'])],
|
||||
'geo_location_id' => ['nullable', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
'demand_page' => ['nullable', 'integer', 'min:1'],
|
||||
'capacity_page' => ['nullable', 'integer', 'min:1'],
|
||||
'draft' => ['nullable', 'uuid'], 'draft_page' => ['nullable', 'integer', 'min:1'],
|
||||
'scope' => ['nullable', Rule::in(['all', 'mine', 'review'])],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters
|
||||
* @return array<string,mixed> */
|
||||
private function listing(LabourDemand|TrainingCapacity $record, string $kind, Request $request, array $filters): array
|
||||
{
|
||||
$unavailable = $record->getAttribute('valid_until') < now()->toDateString() ? 'expired' : ((int) $record->getAttribute('submitted_by') === $request->user()->id ? 'self' : null);
|
||||
|
||||
return [...$record->toArray(), 'can_review' => $unavailable === null, 'review_unavailable' => $unavailable,
|
||||
'details_url' => route('management.education.declaration', ['kind' => $kind, 'id' => $record->id, ...$filters], false)];
|
||||
}
|
||||
|
||||
public function declaration(Request $request, string $kind, string $id): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
app(EducationAccess::class)->authorize($request->user());
|
||||
$model = match ($kind) {
|
||||
'demands' => LabourDemand::class,'capacities' => TrainingCapacity::class,default => abort(404)
|
||||
};
|
||||
$record = $model::findOrFail($id);
|
||||
$filters = $this->filters($request);
|
||||
$request->validate(['history_page' => ['nullable', 'integer', 'min:1']]);
|
||||
$row = $this->listing($record, $kind, $request, $filters);
|
||||
$row['review_context'] = app(EducationReviews::class)->context($request->user(), $record);
|
||||
$row['submitted_by_name'] = User::whereKey($record->getAttribute('submitted_by'))->value('name');
|
||||
$row['reviewed_by_name'] = $record->getAttribute('reviewed_by') ? User::whereKey($record->getAttribute('reviewed_by'))->value('name') : null;
|
||||
$references = ['occupation' => Occupation::whereKey($record->getAttribute('occupation_id'))->value('name'),
|
||||
'skill' => Skill::whereKey($record->getAttribute('skill_id'))->value('name'),
|
||||
'location' => collect(app(InvestmentGeography::class)->path($record->getAttribute('geo_location_id'), true))->pluck('name')->implode(' › ')];
|
||||
if ($kind === 'demands') {
|
||||
$references['project'] = Project::whereKey($record->getAttribute('project_id'))->value('name');
|
||||
} else {
|
||||
$references['course'] = Course::whereKey($record->getAttribute('course_id'))->value('title');
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return tap(Inertia::render('education/declaration', ['declaration' => $row, 'kind' => $kind, 'actorId' => $request->user()->id, 'today' => now()->toDateString(),
|
||||
'preparation' => app(EducationReviews::class)->preparation($request->user(), $record),
|
||||
'history' => app(EducationReviews::class)->history($request->user(), $record),
|
||||
'backUrl' => route('management.education.index', $filters, false), 'references' => $references])->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function catalog(Request $request, string $kind): RedirectResponse
|
||||
{
|
||||
$model = match ($kind) {
|
||||
@@ -112,45 +199,41 @@ class EducationController extends Controller
|
||||
public function store(Request $request, string $kind): RedirectResponse
|
||||
{
|
||||
$demand = $kind === 'demands';
|
||||
$data = $request->validate([
|
||||
'occupation_id' => ['required', 'uuid', Rule::exists('occupations', 'id')->whereNull('deleted_at')],
|
||||
'skill_id' => ['required', 'uuid', Rule::exists('skills', 'id')->whereNull('deleted_at')],
|
||||
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')
|
||||
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])],
|
||||
$demand ? 'project_id' : 'course_id' => ['required', 'uuid', $demand
|
||||
? Rule::exists('projects', 'id')->whereNull('deleted_at')
|
||||
: Rule::exists('courses', 'id')->whereNull('deleted_at')->whereNot('status', 'retired')
|
||||
->where(fn ($query) => $query->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id')))],
|
||||
'employer' => [$demand ? 'required' : 'exclude', 'string', 'max:200'],
|
||||
'qualification' => ['required', 'string', 'max:150'],
|
||||
'quantity' => ['required', 'integer', 'min:1', 'max:10000000'],
|
||||
'period_start' => ['required', 'date_format:Y-m-d'],
|
||||
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
|
||||
'source' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
'reference_date' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'],
|
||||
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:reference_date'],
|
||||
]);
|
||||
$data = $request->validate(EducationDeclarationRules::forKind($kind));
|
||||
PortalAudit::save($demand ? new LabourDemand : new TrainingCapacity,
|
||||
[...$data, 'submitted_by' => $request->user()->id, 'status' => 'submitted'], $request->user()->id);
|
||||
|
||||
return back()->with('success', 'Declaração registada para revisão independente.');
|
||||
}
|
||||
|
||||
public function reviewPreparation(Request $request, string $kind, string $id): JsonResponse
|
||||
{
|
||||
$service = app(EducationReviews::class);
|
||||
app(EducationAccess::class)->authorize($request->user());
|
||||
if ($request->isMethod('POST')) {
|
||||
// Like CRM preparations, retain partial text before business validation.
|
||||
$input = json_decode($request->getContent(), true);
|
||||
if (! is_array($input)) {
|
||||
throw ValidationException::withMessages(['snapshot' => 'A preparação deve ser enviada em JSON.']);
|
||||
}
|
||||
$view = $service->savePreparation($request->user(), $kind, $id, $input);
|
||||
} else {
|
||||
$expected = $request->validate(['actor_id' => 'sometimes|required|integer|min:1']);
|
||||
abort_if(isset($expected['actor_id']) && (int) $expected['actor_id'] !== $request->user()->id, 409, 'A conta mudou. Actualize a entrada antes de recuperar.');
|
||||
$record = match ($kind) {
|
||||
'demands' => LabourDemand::findOrFail($id), 'capacities' => TrainingCapacity::findOrFail($id), default => abort(404)
|
||||
};
|
||||
$view = $service->preparation($request->user(), $record);
|
||||
}
|
||||
|
||||
return response()->json($view)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function review(Request $request, string $kind, string $id): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'],
|
||||
'status' => ['required', 'in:reviewed,rejected'], 'review_reason' => ['required', 'string', 'min:15', 'max:3000']]);
|
||||
$model = $kind === 'demands' ? LabourDemand::class : TrainingCapacity::class;
|
||||
DB::transaction(function () use ($model, $id, $data, $request) {
|
||||
$record = $model::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if((int) $record->getAttribute('submitted_by') === $request->user()->id, 403, 'Outro gestor deve efectuar a revisão.');
|
||||
abort_if((int) $record->getAttribute('version_no') !== $data['version_no'], 409, 'A versão foi alterada. Recarregue antes de decidir.');
|
||||
abort_if($record->getAttribute('valid_until') < now()->toDateString(), 422, 'A fonte expirou.');
|
||||
PortalAudit::save($record, [...$data, 'version_no' => $data['version_no'] + 1,
|
||||
'reviewed_by' => $request->user()->id], $request->user()->id);
|
||||
});
|
||||
$result = app(EducationReviews::class)->decide($request->user(), $kind, $id, $request->all());
|
||||
|
||||
return back()->with('success', 'Revisão interna registada; não substitui decisão institucional.');
|
||||
return back()->with('success', $result['replayed'] ? 'A revisão já tinha sido registada.' : 'Revisão interna registada; não substitui decisão institucional.');
|
||||
}
|
||||
|
||||
public function analysis(string $id, EducationGapCalculator $calculator): Response
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\EducationDeclarationDrafts;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class EducationDeclarationDraftController extends Controller
|
||||
{
|
||||
public function index(Request $request, string $kind, EducationDeclarationDrafts $drafts): JsonResponse
|
||||
{
|
||||
$drafts->guard($request->user(), $kind);
|
||||
|
||||
return response()->json(DB::table('education_declaration_drafts')->where('owner_user_id', $request->user()->id)->where('kind', $kind)
|
||||
->orderByDesc('updated_at')->orderBy('id')->paginate(20, ['id', 'kind', 'version_no', 'state', 'updated_at']))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function show(Request $request, string $kind, string $id, EducationDeclarationDrafts $drafts): JsonResponse
|
||||
{
|
||||
return response()->json($drafts->show($request->user(), $kind, $id))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function save(Request $request, string $kind, EducationDeclarationDrafts $drafts, ?string $id = null): JsonResponse
|
||||
{
|
||||
return response()->json($drafts->save($request->user(), $kind, $id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function submit(Request $request, string $kind, string $id, EducationDeclarationDrafts $drafts): JsonResponse
|
||||
{
|
||||
return response()->json($drafts->submit($request->user(), $kind, $id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Models\ExistingBusinessObject;
|
||||
use App\Models\Sector;
|
||||
use App\Policies\ExistingBusinessPolicy;
|
||||
use App\Services\BusinessFormSchema;
|
||||
use App\Services\BusinessPointPublication;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use App\Services\ExistingBusinessIntake;
|
||||
@@ -69,6 +70,7 @@ class ExistingBusinessController extends Controller
|
||||
Gate::authorize('view', $business);
|
||||
app(CompatibilityShadow::class)->schedule($id);
|
||||
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'modalityFormType' => ExistingBusinessProfileCategory::formType($business->modality), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
'pointPublicationAvailable' => app(BusinessPointPublication::class)->available(), 'registeredLocation' => app(BusinessPointPublication::class)->registered($business),
|
||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||
'canTriage' => $request->user()->can('triage', $business),
|
||||
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use App\Services\FundingDossierPreparation;
|
||||
use App\Services\FundingInstitutionClassification;
|
||||
use App\Services\FundingInstitutionDetails;
|
||||
use App\Services\FundingProgrammeReferences;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestorContext;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\Procurement;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
final class FundingProgrammeController extends Controller
|
||||
{
|
||||
public function reference(Request $request, string $code, FundingProgrammeReferences $references): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$plan = $references->preview($request->user(), $code);
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json($plan)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
return tap(Inertia::render('funding/reference', ['reference' => $plan])->toResponse($request),
|
||||
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function prepareReference(Request $request, string $code, FundingProgrammeReferences $references): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['hash' => 'required|string|size:64']);
|
||||
$result = $references->prepare($request->user(), $code, $data['hash']);
|
||||
if ($request->expectsJson()) {
|
||||
$reference = $references->preview($request->user(), $code);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$matches = $service->matchesReference($request->user(), $result['id'], $reference['draft']);
|
||||
$publication = $matches ? $service->preview($request->user(), $result['id']) : null;
|
||||
|
||||
return response()->json([...$result, 'matches_reference' => $matches, 'publication' => $publication ? ['version' => $publication['version'], 'hash' => $publication['hash']] : null])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
return redirect('/management/fundos/'.$result['id'])->with('success', $result['created']
|
||||
? 'Rascunho preparado com as fontes indicadas. Ainda não está publicado.'
|
||||
: 'Esta referência já tem ficha. Aberta a versão existente, sem substituir alterações ou acrescentar chamadas.');
|
||||
}
|
||||
|
||||
public function assisted(Request $request, FundingProgrammeReferences $references): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
return tap(Inertia::render('funding/assisted', ['batch' => $references->assisted($request->user())])->toResponse($request), static fn ($response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function manage(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$service->guard($request->user());
|
||||
$items = DB::table('funding_programmes')->orderByDesc('updated_at')->paginate(20);
|
||||
$items->through(fn ($row) => ['id' => $row->id, 'title' => json_decode($row->draft, true)['title'] ?? 'Rascunho sem título',
|
||||
'version' => (int) $row->version, 'published' => $row->published_version_id !== null]);
|
||||
|
||||
return tap(Inertia::render('funding/manage', ['items' => $items, 'references' => app(FundingProgrammeReferences::class)->choices($request->user())])->toResponse($request),
|
||||
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function edit(Request $request, FundingProgrammes $service, ?string $id = null): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$service->guard($request->user());
|
||||
$row = $id ? DB::table('funding_programmes')->where('id', $id)->firstOrFail() : null;
|
||||
$editable = app(DocumentManagementAccess::class)->documents($request->user())->select('id');
|
||||
$references = ['organizations' => DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->get(['id', 'name']),
|
||||
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name']),
|
||||
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name']),
|
||||
'documents' => DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->whereNull('d.deleted_at')->where(fn ($q) => $q->whereIn('d.id', $editable)
|
||||
->orWhereIn('r.id', app(Procurement::class)->publicDocuments()->select('r.id')))
|
||||
->orderBy('r.title')->get(['r.id', 'r.title'])];
|
||||
|
||||
return tap(Inertia::render('funding/edit', ['record' => $row ? ['id' => $row->id, 'code' => $row->code, 'version' => (int) $row->version,
|
||||
'draft' => json_decode($row->draft, true), 'published' => $row->published_version_id !== null] : null,
|
||||
'references' => Arr::only($references, ['organizations', 'sectors', 'territories', 'documents']),
|
||||
'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'institutionNatures' => FundingInstitutionDetails::NATURES, 'needs' => FundingInstitutionDetails::NEEDS,
|
||||
'kinds' => FundingProgrammes::KINDS, 'windowModes' => FundingProgrammes::WINDOWS,
|
||||
'history' => $id ? DB::table('funding_programme_versions')->where('programme_id', $id)->orderByDesc('version')->get(['version', 'reason', 'published_at']) : []])->toResponse($request),
|
||||
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function save(Request $request, FundingProgrammes $service, ?string $id = null): RedirectResponse
|
||||
{
|
||||
$id = $service->save($request->user(), $id, $request->all());
|
||||
|
||||
return redirect('/management/fundos/'.$id)->with('success', 'Rascunho guardado. Confira a prévia antes de publicar.');
|
||||
}
|
||||
|
||||
public function preview(Request $request, string $id, FundingProgrammes $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->preview($request->user(), $id))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function publish(Request $request, string $id, FundingProgrammes $service): RedirectResponse|JsonResponse
|
||||
{
|
||||
$versionId = $service->publish($request->user(), $id, $request->all());
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['id' => $id, 'version_id' => $versionId, 'published' => true])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
return back()->with('success', 'Nova versão publicada. Os interesses anteriores conservam a versão guardada.');
|
||||
}
|
||||
|
||||
public function withdraw(Request $request, string $id, FundingProgrammes $service): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:20|max:2000']);
|
||||
$service->withdraw($request->user(), $id, $data['version'], $data['reason']);
|
||||
|
||||
return back()->with('success', 'Publicação retirada. Versões e interesses preservados.');
|
||||
}
|
||||
|
||||
public function saved(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
abort_unless($service->installed(), 404);
|
||||
$items = DB::table('funding_programme_interests as i')
|
||||
->join('funding_programme_versions as v', fn ($join) => $join->on('v.id', '=', 'i.version_id')->on('v.programme_id', '=', 'i.programme_id'))
|
||||
->join('funding_programmes as p', 'p.id', '=', 'i.programme_id')
|
||||
->where('i.user_id', $request->user()->id)->whereNull('i.removed_at')
|
||||
->orderByDesc('i.saved_at')->orderBy('i.programme_id')
|
||||
->paginate(20, ['i.programme_id', 'i.saved_at', 'v.version', 'v.payload', 'p.published_version_id'])->withQueryString();
|
||||
$items->through(function ($row) use ($service) {
|
||||
$current = $service->publicQuery()->where('p.id', $row->programme_id)->first(['v.version']);
|
||||
$snapshot = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return ['id' => $row->programme_id, 'title' => $snapshot['title'], 'saved_version' => (int) $row->version,
|
||||
'saved_at' => $row->saved_at, 'available' => $current !== null, 'current_version' => $current ? (int) $current->version : null];
|
||||
});
|
||||
|
||||
return tap(Inertia::render('funding/saved', ['items' => $items])->toResponse($request),
|
||||
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function index(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'kind' => 'nullable|in:institution,fund,programme,incentive',
|
||||
'category' => ['nullable', Rule::in(array_keys(FundingInstitutionClassification::CATEGORIES))], 'institution_type' => ['nullable', Rule::in(array_keys(FundingInstitutionClassification::TYPES))], 'location_mode' => 'nullable|in:physical,coverage', 'include_historical' => 'nullable|boolean',
|
||||
'need' => ['nullable', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))],
|
||||
'context' => 'nullable|uuid', 'opportunity' => 'nullable|string|max:150',
|
||||
'territory' => ['nullable', 'uuid', Rule::in(app(InvestmentGeography::class)->publicReferences()->pluck('id')->all())],
|
||||
'sector' => ['nullable', 'integer', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())],
|
||||
'certainty' => 'nullable|in:include_unknown,documented', 'state' => 'nullable|in:open,closed,upcoming,unknown']);
|
||||
$filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
|
||||
$dossier = $request->user() && ! empty($filters['context']) ? app(FundingDossierPreparation::class)->context($request->user(), $filters['context'], $filters['opportunity'] ?? null) : null;
|
||||
if ($dossier && empty($filters['territory']) && $dossier['territory']) {
|
||||
$filters['territory'] = $dossier['territory'];
|
||||
}
|
||||
$query = $service->catalogueQuery($filters);
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['q']).'%';
|
||||
$query->where(fn ($q) => $q->whereRaw("v.payload->>'title' ilike ?", [$term])->orWhereRaw("v.payload->>'summary' ilike ?", [$term])->orWhereRaw("(v.payload->'aliases')::text ilike ?", [$term])->orWhereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) l WHERE l->>'label' ilike ? OR l->>'address' ilike ? OR l->>'location_text' ilike ?)", [$term, $term, $term]));
|
||||
}
|
||||
if (! empty($filters['kind'])) {
|
||||
$query->whereRaw("v.payload->>'kind' = ?", [$filters['kind']]);
|
||||
}
|
||||
$items = $query->orderByDesc('v.published_at')->orderBy('p.id')->paginate(20, ['p.id', 'p.code', 'v.id as version_id', 'v.version', 'v.payload', 'v.published_at'])->withQueryString();
|
||||
$items->through(function ($row) use ($service, $filters) {
|
||||
$record = $service->present($row);
|
||||
|
||||
return [...$record, 'filter_explanation' => $service->filterExplanation($record, $filters)];
|
||||
});
|
||||
|
||||
return tap(Inertia::render('funding/index', ['items' => $items, 'filters' => $filters, 'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'kinds' => FundingProgrammes::KINDS, 'needs' => FundingInstitutionDetails::NEEDS, 'dossier' => $dossier,
|
||||
'options' => ['territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name']),
|
||||
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name'])], 'management' => $service->access($request->user())])
|
||||
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$request->validate(['context' => 'nullable|uuid', 'opportunity' => 'nullable|string|max:150', 'need' => ['nullable', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))], 'territory' => 'nullable|uuid', 'category' => 'nullable|string|max:80', 'institution_type' => 'nullable|string|max:80', 'location_mode' => 'nullable|in:physical,coverage']);
|
||||
$dossier = $request->user() && $request->filled('context') ? app(FundingDossierPreparation::class)->context($request->user(), $request->string('context')->toString(), $request->query('opportunity')) : null;
|
||||
if ($dossier && ! $request->filled('territory') && $dossier['territory']) {
|
||||
$request->merge(['territory' => $dossier['territory']]);
|
||||
}
|
||||
$record = $service->published($id);
|
||||
$destinations = [];
|
||||
if ($request->user()) {
|
||||
foreach (app(InvestorPath::class)->contexts($request->user()) as $item) {
|
||||
$case = app(VirtualDesk::class)->case($request->user(), $item['id']);
|
||||
$state = app(InvestorContext::class)->state($case);
|
||||
$choices = $state['opportunity_choices'] ?? [];
|
||||
if ($choices === []) {
|
||||
$destinations[] = ['id' => $item['id'], 'opportunity' => null, 'title' => $item['title']];
|
||||
}
|
||||
foreach ($choices as $choice) {
|
||||
$destinations[] = ['id' => $item['id'], 'opportunity' => $choice['opportunity']['key'], 'title' => $item['title'].' — '.$choice['opportunity']['title']];
|
||||
}
|
||||
}
|
||||
}
|
||||
$saved = $request->user() ? DB::table('funding_programme_interests as i')->join('funding_programme_versions as v', 'v.id', '=', 'i.version_id')
|
||||
->where('i.programme_id', $id)->where('i.user_id', $request->user()->id)->whereNull('i.removed_at')->first(['v.version', 'i.saved_at']) : null;
|
||||
|
||||
return tap(Inertia::render('funding/show', ['record' => $record, 'saved' => $saved, 'authenticated' => $request->user() !== null, 'dossier' => $dossier, 'selection' => [...$request->only(['need', 'territory', 'context', 'opportunity', 'category', 'institution_type', 'location_mode']), 'territory_label' => app(InvestmentGeography::class)->publicReferences()->where('id', $request->query('territory'))->value('name') ?? 'Local por seleccionar'], 'needs' => FundingInstitutionDetails::NEEDS, 'destinations' => $destinations])
|
||||
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function dossier(Request $request, string $id, FundingDossierPreparation $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->save($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function assess(Request $request, string $id, FundingProgrammes $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->assess($id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function saveInterest(Request $request, string $id, FundingProgrammes $service): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version_id' => 'required|uuid', 'consent' => 'required|accepted']);
|
||||
$service->saveInterest($request->user(), $id, $data['version_id'], true);
|
||||
|
||||
return back()->with('success', 'Programa guardado na sua área privada. Consulte a versão indicada na ficha.');
|
||||
}
|
||||
|
||||
public function removeInterest(Request $request, string $id, FundingProgrammes $service): RedirectResponse
|
||||
{
|
||||
abort_unless($service->installed(), 404);
|
||||
$service->removeInterest($request->user(), $id);
|
||||
|
||||
return back()->with('success', 'Interesse removido da sua lista.');
|
||||
}
|
||||
|
||||
public function download(string $id, string $version, int $resource, FundingProgrammes $service): Response|BinaryFileResponse
|
||||
{
|
||||
return $service->download($id, $version, $resource);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\EditorialReading;
|
||||
use App\Services\FederatedSearch;
|
||||
use App\Services\FundingInstitutionDetails;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\SearchTerms;
|
||||
use App\Services\SectorOrganization;
|
||||
use App\Services\SectorResourceReferences;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
class GlobalSearchController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, InvestmentCatalogue $catalogue, SearchTerms $search, FederatedSearch $federated): Response
|
||||
{
|
||||
$input = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'], 'category' => ['nullable', 'in:all,physical,financial']]);
|
||||
$original = trim($input['q'] ?? '');
|
||||
$intent = $search->requestIntent($original);
|
||||
if (isset($input['category']) && ($intent === null || $intent['type'] === 'products')) {
|
||||
$intent = ['type' => 'products', 'label' => 'Produtos e localização', 'kind' => null,
|
||||
'filter' => $intent['filter'] ?? $original,
|
||||
'category' => match ($input['category']) {
|
||||
'physical' => 'Produtos e localizações', 'financial' => 'Produtos financeiros', default => null,
|
||||
}];
|
||||
}
|
||||
$term = $intent['filter'] ?? $original;
|
||||
$tokens = $search->tokens($term);
|
||||
$results = ['data' => [], 'total' => 0, 'current_page' => 1, 'last_page' => 1, 'per_page' => 5, 'unavailable' => []];
|
||||
if ($tokens !== [] || $intent !== null) {
|
||||
$factories = [
|
||||
'Produtos e localizações' => function () use ($search, $tokens, $term) {
|
||||
try {
|
||||
return $this->productReferences($search, $tokens, $term);
|
||||
} catch (\RuntimeException $exception) {
|
||||
throw new HttpException(503, 'Referências de produtos temporariamente indisponíveis.', $exception);
|
||||
}
|
||||
},
|
||||
'Produtos financeiros' => function () use ($search, $tokens, $term) {
|
||||
$service = app(FundingProgrammes::class);
|
||||
if (! $service->installed()) {
|
||||
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
|
||||
}
|
||||
$query = $service->catalogueQuery([])->select('p.id', 'v.payload')->selectRaw("v.payload->>'title' AS title");
|
||||
foreach ($tokens as $token) {
|
||||
$query->where(function ($match) use ($search, $token) {
|
||||
$search->orFields($match, ["(v.payload->>'title')",
|
||||
"(SELECT string_agg(product->>'title', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product)",
|
||||
"(SELECT string_agg(place->>'location_text', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) place)",
|
||||
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.locations[*].territory_path[*]') node)",
|
||||
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.products[*].territory_paths[*][*]') node)"], $token);
|
||||
foreach (FundingInstitutionDetails::NEEDS as $code => $label) {
|
||||
$text = in_array($code, ['investment', 'working_capital'], true) ? 'Financiamento '.$label : $label;
|
||||
if ($search->matches($text, [$token])) {
|
||||
$match->orWhereJsonContains('v.payload->institution_services', $code)->orWhereJsonContains('v.payload->funding_needs', $code)
|
||||
->orWhereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product WHERE product->'needs' @> ?::jsonb)", [json_encode([$code], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
foreach (FundingInstitutionDetails::NATURES as $code => $label) {
|
||||
if ($search->matches($label, [$token])) {
|
||||
$match->orWhere('v.payload->institution_nature', $code);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, "(v.payload->>'title')", 'p.id', function ($row) {
|
||||
$p = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
$products = array_values(array_unique(array_filter(array_column($p['products'] ?? [], 'title'))));
|
||||
$services = array_values(array_intersect_key(FundingInstitutionDetails::NEEDS, array_flip($p['institution_services'] ?? [])));
|
||||
$places = [];
|
||||
foreach ($p['locations'] ?? [] as $location) {
|
||||
if (! empty($location['location_text'])) {
|
||||
$places[] = $location['location_text'];
|
||||
}
|
||||
foreach ($location['territory_path'] ?? [] as $node) {
|
||||
if ($node['type'] !== 'country') {
|
||||
$places[] = $node['name'];
|
||||
}
|
||||
}
|
||||
}
|
||||
$national = array_any($p['products'] ?? [], fn ($product) => ($product['coverage'] ?? '') === 'national');
|
||||
|
||||
return ['title' => $row->title, 'description' => implode(' · ', $products ?: $services) ?: 'Instituição financeira.',
|
||||
'location' => $places === [] ? null : 'Presença física: '.implode(' · ', array_unique($places)),
|
||||
'coverage' => $national ? 'Existe produto com cobertura nacional indicada; consulte as condições.' : 'Cobertura financeira: consultar cada produto.',
|
||||
'url' => '/fundos/'.$row->id];
|
||||
});
|
||||
},
|
||||
'Páginas e serviços' => function () use ($search, $tokens, $term) {
|
||||
$pages = array_values(array_filter($this->pages(), fn ($page) => $search->matches(implode(' ', $page), $tokens)));
|
||||
usort($pages, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens)
|
||||
?: strcmp($a['title'], $b['title']) ?: strcmp($a['url'], $b['url']));
|
||||
|
||||
return ['count' => count($pages), 'fetch' => fn ($offset, $limit) => array_slice($pages, $offset, $limit)];
|
||||
},
|
||||
'Oportunidades' => function () use ($catalogue, $search, $tokens, $term) {
|
||||
$query = $catalogue->query(['include_national' => true]);
|
||||
foreach ($tokens as $token) {
|
||||
$query->where(function ($match) use ($catalogue, $search, $token) {
|
||||
$search->orFields($match, ['opportunities.title', 'opportunities.summary', 'opportunities.description', 'opportunities.reference', 'opportunities.province'], $token);
|
||||
$match->orWhereHas('sector', fn ($sector) => $search->constrain($sector, ['name'], [$token]));
|
||||
$match->orWhereExists(fn ($location) => $location->selectRaw('1')->from('geo_locations as search_location')
|
||||
->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
|
||||
->where(fn ($name) => $search->orFields($name, ['search_location.name'], $token))
|
||||
->where(fn ($direct) => $direct->whereColumn('search_location.id', 'opportunities.primary_territory_id')
|
||||
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations as search_link')
|
||||
->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereColumn('search_link.geo_location_id', 'search_location.id'))));
|
||||
if (preg_match('/^[a-z0-9]+$/', $token)) {
|
||||
$match->orWhereIn('opportunities.id', $catalogue->query(['q' => $token, 'include_national' => true])->reorder()->select('opportunities.id'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'opportunities.title', 'opportunities.id',
|
||||
fn ($r) => ['title' => $r->title, 'description' => $r->summary, 'url' => '/oportunidades/'.rawurlencode($r->slug)]);
|
||||
},
|
||||
'Negócios' => function () use ($search, $tokens, $term) {
|
||||
$query = ExistingBusiness::query()->published();
|
||||
$search->constrain($query, ['public_title', 'activity_code', 'objective'], $tokens);
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'public_title', 'existing_businesses.id',
|
||||
fn ($r) => ['title' => $r->public_title, 'description' => $r->objective, 'url' => '/negocios/'.rawurlencode($r->public_slug)]);
|
||||
},
|
||||
'Carteira: projectos, clusters e corredores' => function () use ($search, $tokens, $term, $intent) {
|
||||
$query = InvestmentPortfolioController::visible();
|
||||
$search->constrain($query, ['investment_dossiers.title', 'investment_dossiers.content'], $tokens);
|
||||
if ($intent !== null && $intent['kind'] !== null) {
|
||||
[$column, $table] = ['corridor' => ['corridor_id', 'development_corridors'], 'cluster' => ['cluster_id', 'economic_clusters'], 'project' => ['project_id', 'projects']][$intent['kind']];
|
||||
$query->whereNotNull($column)->whereExists(fn ($entity) => $entity->selectRaw('1')->from($table)
|
||||
->whereColumn($table.'.id', 'investment_dossiers.'.$column)->whereNull($table.'.deleted_at'));
|
||||
// The existing unique entity key already prevents duplicate dossiers.
|
||||
}
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'investment_dossiers.title', 'investment_dossiers.id',
|
||||
fn ($r) => ['title' => $r->title, 'description' => $r->corridor_id ? 'Corredor' : ($r->cluster_id ? 'Cluster' : 'Projecto âncora'), 'url' => '/carteira/'.$r->id]);
|
||||
},
|
||||
'Documentos e legislação' => function () use ($search, $tokens, $term) {
|
||||
$query = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->where('r.published', true)->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
|
||||
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256');
|
||||
$search->constrain($query, ['r.title', 'r.description', 'r.document_number', 'd.issuer', 'r.source_reference', 'r.category', 'r.topic'], $tokens);
|
||||
$query->select('r.id', 'r.title', 'r.description');
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
|
||||
fn ($r) => ['title' => $r->title, 'description' => $r->description, 'url' => '/documentos/'.$r->id]);
|
||||
},
|
||||
'Artigos' => function () use ($search, $tokens, $term) {
|
||||
if (! Schema::hasColumn('portal_resources', 'editorial_content')) {
|
||||
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
|
||||
}
|
||||
$query = app(EditorialReading::class)->publicResources()
|
||||
->whereRaw("nullif(btrim(r.editorial_content->>'body'), '') is not null");
|
||||
$search->constrain($query, ['r.title', "(r.editorial_content->>'body')"], $tokens);
|
||||
$query->select('r.id', 'r.title')->selectRaw("r.editorial_content->>'body' as body");
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
|
||||
fn ($r) => ['title' => $r->title, 'description' => Str::limit(trim(strip_tags($r->body)), 220), 'url' => '/artigos/'.$r->id]);
|
||||
},
|
||||
'Sectores' => function () use ($search, $tokens, $term) {
|
||||
$query = Sector::query()->where('is_active', true)->whereNotNull('published_at');
|
||||
$search->constrain($query, ['name', 'description', 'short_description'], $tokens);
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'name', 'sectors.id',
|
||||
fn ($r) => ['title' => $r->name, 'description' => $r->short_description, 'url' => SectorOrganization::href($r->slug)]);
|
||||
},
|
||||
'Localizações' => function () use ($search, $tokens, $term) {
|
||||
$query = app(InvestmentGeography::class)->publicReferences()
|
||||
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality']);
|
||||
$search->constrain($query, ['geo_locations.name', 'geo_locations.source_code'], $tokens);
|
||||
$query->select('geo_locations.id', 'geo_locations.name', 'geo_locations.location_type');
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'geo_locations.name', 'geo_locations.id',
|
||||
fn ($r) => ['title' => $r->name, 'description' => ['province' => 'Província', 'district' => 'Distrito', 'admin_post' => 'Posto administrativo', 'locality' => 'Localidade'][$r->location_type],
|
||||
'url' => '/oportunidades?'.http_build_query([$r->location_type.'_id' => $r->id])]);
|
||||
},
|
||||
'Zonas de investimento' => function () use ($search, $tokens, $term) {
|
||||
$query = app(InvestmentZones::class)->visible();
|
||||
$search->constrain($query, ['name', 'code'], $tokens);
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'name', 'investment_zones.id',
|
||||
fn ($r) => ['title' => $r->name, 'description' => $r->code, 'url' => '/zonas/'.$r->id]);
|
||||
},
|
||||
'Parcerias' => function () use ($search, $tokens, $term) {
|
||||
$query = DB::table('portal_partnerships as p')->where('p.status', 'published');
|
||||
$search->constrain($query, ['p.title', 'p.sector', 'p.province'], $tokens);
|
||||
$query->select('p.id', 'p.title', 'p.sector', 'p.province');
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, 'p.title', 'p.id',
|
||||
fn ($r) => ['title' => $r->title, 'description' => implode(' · ', array_filter([$r->sector, $r->province])), 'url' => '/parcerias/'.$r->id]);
|
||||
},
|
||||
];
|
||||
if ($intent !== null) {
|
||||
$categories = $intent['category'] === null ? ['Produtos e localizações', 'Produtos financeiros'] : [$intent['category']];
|
||||
$factories = array_intersect_key($factories, array_flip($categories));
|
||||
}
|
||||
$results = $federated->page($factories, (int) ($input['page'] ?? 1), 5,
|
||||
fn ($item) => $search->score($item['title'], $term, $tokens));
|
||||
}
|
||||
|
||||
$answer = $intent === null ? null : ['type' => $intent['type'], 'label' => $intent['label'], 'filter' => $term,
|
||||
'count' => $results['unavailable'] === [] ? $results['total'] : null];
|
||||
|
||||
if ($answer !== null && $intent['type'] === 'products') {
|
||||
$answer['category'] = match ($intent['category']) {
|
||||
'Produtos e localizações' => 'physical', 'Produtos financeiros' => 'financial', default => 'all',
|
||||
};
|
||||
}
|
||||
|
||||
return Inertia::render('portal/search', ['query' => $original, 'results' => $results, 'answer' => $answer]);
|
||||
}
|
||||
|
||||
/** @param list<string> $tokens
|
||||
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
|
||||
*/
|
||||
private function productReferences(SearchTerms $search, array $tokens, string $term): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach (['mineracao', 'energia-especifica'] as $sector) {
|
||||
if (! Sector::where('slug', $sector)->where('is_active', true)->whereNotNull('published_at')->exists()) {
|
||||
continue;
|
||||
}
|
||||
$data = app(SectorResourceReferences::class)->view($sector);
|
||||
foreach ($data['groups'] as $group) {
|
||||
$locations = array_values(array_filter($group['location_labels'], fn ($name) => $search->matches($term, $search->tokens($name))));
|
||||
$rows[] = ['title' => $group['name'], 'description' => $sector === 'mineracao' ? 'Referência mineral; não identifica uma concessão ou produção disponível.' : 'Segmento energético e cadeia de valor.',
|
||||
'location' => $group['locations_text'], 'url' => '/sectores/'.$sector.'?'.http_build_query(['resource_group' => $group['id'],
|
||||
...(count($locations) === 1 ? ['resource_location' => $locations[0]] : [])])];
|
||||
}
|
||||
}
|
||||
if (app(LegacyContent::class)->available() && Sector::where('slug', 'agronegocio')->where('is_active', true)->whereNotNull('published_at')->exists()) {
|
||||
try {
|
||||
app(LegacyContent::class)->article('agronegocio', false);
|
||||
$entries = app(CorridorAgribusinessOpportunities::class)->entries();
|
||||
$published = Opportunity::published()->whereIn('management_creation_key', array_column($entries, 'key'))->pluck('slug', 'management_creation_key');
|
||||
foreach ($entries as $entry) {
|
||||
if (! isset($published[$entry['key']])) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['title' => $entry['chain'], 'description' => 'Cadeia agrícola: '.$entry['summary'], 'location' => 'Enquadramento territorial: '.$entry['corridor'],
|
||||
'url' => '/oportunidades/'.rawurlencode($published[$entry['key']])];
|
||||
}
|
||||
} catch (HttpException $exception) {
|
||||
if ($exception->getStatusCode() !== 404) {
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows = array_values(array_filter($rows, fn ($row) => $search->matches(implode(' ', $row), $tokens)));
|
||||
usort($rows, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens) ?: strcmp($a['title'], $b['title']));
|
||||
|
||||
return ['count' => count($rows), 'fetch' => fn ($offset, $limit) => array_slice($rows, $offset, $limit)];
|
||||
}
|
||||
|
||||
/** @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
|
||||
* @param list<string> $tokens
|
||||
* @param callable(mixed):array<string,mixed> $present
|
||||
* @param literal-string $title
|
||||
* @param literal-string $id
|
||||
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
|
||||
*/
|
||||
private function source($query, SearchTerms $search, string $term, array $tokens, string $title, string $id, callable $present): array
|
||||
{
|
||||
$count = (clone $query)->reorder()->count();
|
||||
$query->reorder();
|
||||
$search->orderByRelevance($query, $title, $term, $tokens, $id);
|
||||
|
||||
return ['count' => $count, 'fetch' => fn ($offset, $limit) => (clone $query)->offset($offset)->limit($limit)->get()->map($present)->all()];
|
||||
}
|
||||
|
||||
/** Public service entry points and terms used to find them.
|
||||
* @return list<array{title:string,description:string,url:string}>
|
||||
*/
|
||||
private function pages(): array
|
||||
{
|
||||
return [
|
||||
['title' => 'Licenciamento da empresa', 'description' => 'Roteiro de constituição e licenciamento conforme a actividade e localização.', 'url' => '/como-investir#planeamento'],
|
||||
['title' => 'Preparar licenciamento no dossier', 'description' => 'Continuar a preparação na etapa de licenciamento prévio.', 'url' => '/investimentos/iniciar?step=S08'],
|
||||
['title' => 'Como investir em Moçambique', 'description' => 'Procedimentos e etapas para investir', 'url' => '/como-investir'],
|
||||
['title' => 'Iniciar ou continuar investimento', 'description' => 'Preparar uma ideia e dossier de investimento', 'url' => '/investimentos/iniciar'],
|
||||
['title' => 'Oportunidades de investimento', 'description' => 'Pesquisar por sector, localização e maturidade', 'url' => '/oportunidades'],
|
||||
['title' => 'Carteira de investimento', 'description' => 'Projectos âncora, clusters e corredores', 'url' => '/carteira'],
|
||||
['title' => 'Negócios existentes', 'description' => 'Compra, venda e participação em negócios', 'url' => '/negocios'],
|
||||
['title' => 'Sectores de investimento', 'description' => 'Actividades económicas e sectores prioritários', 'url' => '/sectores'],
|
||||
['title' => 'Zonas de investimento', 'description' => 'Zonas económicas especiais, ZEE, ZFI e parques industriais', 'url' => '/zonas'],
|
||||
['title' => 'Contextos de investimento', 'description' => 'Formas de iniciar e preparar um investimento', 'url' => '/contextos-de-investimento'],
|
||||
['title' => 'Documentos e formulários', 'description' => 'Acervo documental e formulários para investidores e empresas', 'url' => '/documentos'],
|
||||
['title' => 'Formulário do investidor', 'description' => 'Dados e contacto para investir', 'url' => '/formularios/investidor'],
|
||||
['title' => 'Formulário de empresa', 'description' => 'Dados e contacto para empresas', 'url' => '/formularios/empresa'],
|
||||
['title' => 'Legislação e incentivos', 'description' => 'Leis, decretos, benefícios e enquadramento legal', 'url' => '/legislacao'],
|
||||
['title' => 'Simulador fiscal', 'description' => 'Simular impostos e cenários fiscais de investimento', 'url' => '/simulador-fiscal'],
|
||||
['title' => 'Formulários fiscais', 'description' => 'Preparação dos formulários IVA e IRPC', 'url' => '/formularios/fiscais'],
|
||||
['title' => 'Terra e DUAT', 'description' => 'Apoio ao uso e aproveitamento da terra', 'url' => '/terra-duat'],
|
||||
['title' => 'Bolsa de parcerias', 'description' => 'Encontrar parceiros e propostas', 'url' => '/parcerias'],
|
||||
['title' => 'Apoio ao investidor', 'description' => 'Contactos e pedido de apoio', 'url' => '/apoio'],
|
||||
['title' => 'Educação para investimento', 'description' => 'Conteúdos educativos e orientação', 'url' => '/educacao'],
|
||||
['title' => 'Sobre o InvesteMoz', 'description' => 'Informação institucional do portal', 'url' => '/sobre'],
|
||||
['title' => 'Contacto', 'description' => 'Contactar o portal InvesteMoz', 'url' => '/contacto'],
|
||||
['title' => 'Política de privacidade', 'description' => 'Privacidade e tratamento de dados pessoais', 'url' => '/politica-de-privacidade'],
|
||||
['title' => 'Termos de uso', 'description' => 'Condições de utilização do portal', 'url' => '/termos-de-uso'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class InvestmentAlertPreferencesController extends Controller
|
||||
{
|
||||
public function save(Request $request, InvestmentOpportunityAlerts $alerts): JsonResponse|RedirectResponse
|
||||
{
|
||||
$preferences = $alerts->save($request->user(), $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($preferences) : back()->with('success', $preferences['enabled']
|
||||
? 'Preferências guardadas. O acompanhamento considera novas disponibilizações nos catálogos escolhidos.'
|
||||
: 'Alertas dos catálogos cancelados. As notificações anteriores foram conservadas.');
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,12 @@ use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentComplements;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentMapIndicators;
|
||||
use App\Services\InvestmentZoneOperationalDetails;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\OpportunityCorridorExplorer;
|
||||
use App\Services\OpportunityTextSearch;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\SectorInvestment;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -29,12 +33,21 @@ class InvestmentDiscoveryController extends Controller
|
||||
if ($request->routeIs('investment.education')) {
|
||||
$filters['education'] = true;
|
||||
}
|
||||
$results = $catalogue->query($filters)->paginate(12)->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record));
|
||||
$relatedQuery = $results->total() === 0 ? app(OpportunityTextSearch::class)->relatedQuery($filters['q'] ?? '') : null;
|
||||
$relatedFilters = [...Arr::except($filters, ['page', 'q']), 'q' => $relatedQuery];
|
||||
$related = $relatedQuery === null ? null : [
|
||||
'query' => $filters['q'], 'subject' => $relatedQuery,
|
||||
'href' => ($request->routeIs('investment.education') ? '/educacao' : '/oportunidades').'?'.http_build_query($relatedFilters),
|
||||
'items' => $catalogue->query($relatedFilters)->limit(6)->get()->map(fn ($record) => $catalogue->presentLocation($record)),
|
||||
];
|
||||
app(PublicSearchMetrics::class)->candidate($request, $request->routeIs('investment.education') ? 'education_page' : 'opportunities_page', $results->total(), $request->routeIs('investment.education') ? Arr::except($filters, ['education']) : $filters);
|
||||
|
||||
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
|
||||
'corridorGroups' => ($filters['view'] ?? '') === 'corridors' ? app(OpportunityCorridorExplorer::class)->groups($filters) : [],
|
||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||
'guides' => app(SectorInvestment::class)->guides(Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)),
|
||||
'results' => $results, 'relatedSearch' => $related,
|
||||
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
|
||||
'territorial' => $this->territorial($filters)]);
|
||||
}
|
||||
@@ -79,7 +92,11 @@ class InvestmentDiscoveryController extends Controller
|
||||
|
||||
public function search(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)));
|
||||
$filters = $catalogue->filters($request);
|
||||
$results = $catalogue->query($filters)->paginate($request->integer('per_page', 12))->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record));
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'opportunities_api', $results->total(), $filters);
|
||||
|
||||
return response()->json($results);
|
||||
}
|
||||
|
||||
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
@@ -140,6 +157,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
$filters = $catalogue->filters($request);
|
||||
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
|
||||
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
|
||||
$quantitative = ['state' => 'not_included', 'records' => [], 'truncated' => false];
|
||||
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
|
||||
$zoneFilters = $filters;
|
||||
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
|
||||
@@ -151,10 +169,12 @@ class InvestmentDiscoveryController extends Controller
|
||||
$zones->where('id', $filters[$key]);
|
||||
}
|
||||
}
|
||||
$context = $context->concat($zones->orderBy('name')->limit(30)->get(['id', 'name', 'category'])->map(fn ($z) => ['id' => 'zone:'.$z->id, 'title' => $z->name, 'kind' => ['zee' => 'ZEE', 'zfi' => 'ZFI', 'industrial_park' => 'Parque industrial'][$z->category] ?? $z->category, 'url' => '/zonas/'.$z->id]));
|
||||
$zoneRows = $zones->orderBy('name')->orderBy('id')->limit(31)->get(['id', 'name', 'category', 'version_no', ...(app(InvestmentZoneOperationalDetails::class)->installed() ? ['operational_details'] : [])]);
|
||||
$quantitative = app(InvestmentMapIndicators::class)->forZones($zoneRows->take(30)->values(), $zoneRows->count() > 30);
|
||||
$context = $context->concat($zoneRows->take(30)->map(fn ($z) => ['id' => 'zone:'.$z->id, 'title' => $z->name, 'kind' => ['zee' => 'ZEE', 'zfi' => 'ZFI', 'industrial_park' => 'Parque industrial'][$z->category] ?? $z->category, 'url' => '/zonas/'.$z->id]));
|
||||
}
|
||||
|
||||
return response()->json([...$catalogue->map($filters), 'territorial_context' => $context->values(), 'context_limit_per_collection' => 30]);
|
||||
return response()->json([...$catalogue->map($filters), 'territorial_context' => $context->values(), 'quantitative_context' => $quantitative, 'context_limit_per_collection' => 30]);
|
||||
}
|
||||
|
||||
public function compare(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
@@ -184,15 +204,16 @@ class InvestmentDiscoveryController extends Controller
|
||||
{
|
||||
$records = $catalogue->query($catalogue->filters($request))->limit(1000)->get();
|
||||
|
||||
return response()->streamDownload(function () use ($records) {
|
||||
return response()->streamDownload(function () use ($records, $catalogue) {
|
||||
$stream = fopen('php://output', 'w');
|
||||
if ($stream === false) {
|
||||
return;
|
||||
}
|
||||
fwrite($stream, "\xEF\xBB\xBF");
|
||||
fputcsv($stream, ['Referência', 'Título', 'Sector', 'Província', 'Montante', 'Moeda', 'Maturidade', 'URL'], ';', '"', '');
|
||||
fputcsv($stream, ['Referência', 'Título', 'Sector', 'Província', 'Montante', 'Moeda', 'Maturidade', 'URL', 'Localização e âmbito'], ';', '"', '');
|
||||
foreach ($records as $r) {
|
||||
$fields = [$r->reference, $r->title, $r->sector?->name, $r->province, $r->estimated_investment_amount, $r->estimated_investment_currency, $r->maturity_label, url('/oportunidades/'.$r->slug)];
|
||||
$location = $catalogue->locationPresentation($r);
|
||||
$fields = [$r->reference, $r->title, $r->sector?->name, implode(' / ', $location['provinces']), $r->estimated_investment_amount, $r->estimated_investment_currency, $r->maturity_label, url('/oportunidades/'.$r->slug), $location['summary']];
|
||||
fputcsv($stream, array_map(fn ($v) => preg_match('/^[\s]*[=+@-]/u', (string) $v) ? "'".$v : $v, $fields), ';', '"', '');
|
||||
}
|
||||
fclose($stream);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentGuides;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class InvestmentGuideController extends Controller
|
||||
{
|
||||
public function index(Request $request, string $slug, InvestmentGuides $guides): Response|JsonResponse
|
||||
{
|
||||
$data = $guides->publicView($slug, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/guide', $data);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, string $slug, InvestmentGuides $guides): Response|JsonResponse
|
||||
{
|
||||
$data = $guides->view($request->user(), $id, $slug, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/guide', $data);
|
||||
}
|
||||
|
||||
public function save(Request $request, string $id, string $slug, InvestmentGuides $guides): JsonResponse
|
||||
{
|
||||
return response()->json($guides->save($request->user(), $id, $slug, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentRelations;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\PortalAudit;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
@@ -85,7 +86,12 @@ class InvestmentPortfolioController extends Controller
|
||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, $territoryIds);
|
||||
}
|
||||
|
||||
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(),
|
||||
$results = $query->orderBy('title')->paginate(30)->withQueryString();
|
||||
if (! $management) {
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'portfolio', $results->total(), $filters);
|
||||
}
|
||||
|
||||
return Inertia::render('portfolio/index', ['records' => $results,
|
||||
'management' => $management, 'filters' => $filters, 'sectors' => $sectorOptions, 'territorySelection' => $territorySelection]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentPreparationWorkspace;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class InvestmentPreparationController extends Controller
|
||||
{
|
||||
public function show(Request $request, string $id, InvestmentPreparationWorkspace $workspace): JsonResponse|Response
|
||||
{
|
||||
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier', 'history_before' => 'nullable|integer|min:1']);
|
||||
$data = $workspace->view($request->user(), $id, $request->query('opportunity'), $request->filled('history_before') ? $request->integer('history_before') : null, $request->query('history_scope') === 'dossier');
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/preparation', ['workspace' => $data]);
|
||||
}
|
||||
|
||||
public function change(Request $request, string $id, InvestmentPreparationWorkspace $workspace): JsonResponse
|
||||
{
|
||||
return response()->json($workspace->change($request->user(), $id, $request->all()));
|
||||
}
|
||||
|
||||
public function preview(Request $request, string $id, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
|
||||
{
|
||||
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier']);
|
||||
$data = $workspace->view($request->user(), $id, $request->query('opportunity'), null, $request->query('history_scope') === 'dossier');
|
||||
|
||||
return response()->view('investments.preparation-index', ['workspace' => $data, 'manifest' => null])->header('Content-Security-Policy', "sandbox; default-src 'none'; style-src 'unsafe-inline'")->header('X-Content-Type-Options', 'nosniff');
|
||||
}
|
||||
|
||||
public function download(Request $request, string $id, string $exportId, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
|
||||
{
|
||||
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier']);
|
||||
$bundle = $workspace->bundle($request->user(), $id, $request->query('opportunity'), $exportId, $request->query('history_scope') === 'dossier');
|
||||
|
||||
return response($bundle['bytes'], 200, ['Content-Type' => 'application/zip', 'Content-Disposition' => 'attachment; filename="preparacao-apiex-'.$id.'.zip"', 'X-Export-Id' => $exportId, 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
public function export(Request $request, string $id, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
|
||||
{
|
||||
$body = [...$request->all(), 'action' => 'apiex_export'];
|
||||
$state = $workspace->change($request->user(), $id, $body);
|
||||
$bundle = $workspace->bundle($request->user(), $id, $state['opportunity'], $body['operation_key']);
|
||||
|
||||
return response($bundle['bytes'], 200, ['Content-Type' => 'application/zip', 'Content-Disposition' => 'attachment; filename="preparacao-apiex-'.$id.'.zip"', 'X-Export-Id' => $bundle['export_id'], 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ class InvestmentTerritoryController extends Controller
|
||||
{
|
||||
public function geometries(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
||||
$data = $request->validate(['territory_id' => ['required', 'uuid'], 'include_children' => ['sometimes', 'boolean']]);
|
||||
$profile = $request->is('minhas-oportunidades/*');
|
||||
$management = $request->is('management/*') || $profile;
|
||||
$actor = $request->user();
|
||||
@@ -31,7 +31,7 @@ class InvestmentTerritoryController extends Controller
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
...app(TerritoryGeometry::class)->context($data['territory_id'], $internal),
|
||||
...app(TerritoryGeometry::class)->context($data['territory_id'], $internal, $request->boolean('include_children')),
|
||||
'geometry_scope' => $internal ? 'authorized_internal' : 'public',
|
||||
])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
@@ -3,10 +3,18 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use App\Services\InvestmentProfileCommands;
|
||||
use App\Services\InvestmentWorkspace;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OrganizationCountry;
|
||||
use App\Services\Procurement;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -18,9 +26,9 @@ use Inertia\Response;
|
||||
|
||||
class InvestmentWorkspaceController extends Controller
|
||||
{
|
||||
public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse
|
||||
public function profile(Request $request, InvestmentWorkspace $workspace): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$data = ['organizationCountryAvailable' => app(OrganizationCountry::class)->available(), 'organizations' => app(OrganizationCountry::class)->represented($request->user()), 'countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
|
||||
$data = ['actorId' => $request->user()->id, 'organizationCountryAvailable' => app(OrganizationCountry::class)->available(), 'organizations' => app(OrganizationCountry::class)->represented($request->user()), 'countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
|
||||
->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) {
|
||||
$company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
|
||||
$company->countrySource = $company->payload['organization_country_snapshot'] ?? null;
|
||||
@@ -28,12 +36,17 @@ class InvestmentWorkspaceController extends Controller
|
||||
return $company;
|
||||
})];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/profile', $data);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
$response = $request->expectsJson() ? response()->json($data) : Inertia::render('investment/profile', $data)->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'no-store, private');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function saveProfile(Request $request): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'],
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'operation_key' => ['sometimes', 'required', 'uuid'],
|
||||
'payload' => ['required', 'array:phone,country,residence_country_code,sector,experience,investment_capacity'],
|
||||
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'],
|
||||
@@ -41,12 +54,19 @@ class InvestmentWorkspaceController extends Controller
|
||||
'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]);
|
||||
$version = DB::transaction(function () use ($request, $data) {
|
||||
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
|
||||
$commands = app(InvestmentProfileCommands::class);
|
||||
$command = ['kind' => 'account', 'target_id' => null, 'version' => (int) $data['version'], 'payload' => $data['payload']];
|
||||
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
|
||||
if ($replay !== null) {
|
||||
return $replay['version'];
|
||||
}
|
||||
$row = DB::table('investment_accounts')->where('user_id', $request->user()->id)->first();
|
||||
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Perfil alterado. Recarregue.');
|
||||
$version = (int) $data['version'] + 1;
|
||||
DB::table('investment_accounts')->updateOrInsert(['user_id' => $request->user()->id], ['version' => $version,
|
||||
'payload' => Crypt::encryptString(json_encode($data['payload'], JSON_THROW_ON_ERROR)), 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
|
||||
$this->audit($request, 'profile_saved', 'investment_accounts', null, ['version' => $version]);
|
||||
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['version' => $version]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
@@ -56,7 +76,7 @@ class InvestmentWorkspaceController extends Controller
|
||||
|
||||
public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'],
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'operation_key' => ['sometimes', 'required', 'uuid'],
|
||||
'payload' => ['required', 'array:name,country,incorporation_country_code,registration,sector,role,description'],
|
||||
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required_without:payload.incorporation_country_code', 'nullable', 'string', 'max:100'],
|
||||
@@ -66,6 +86,12 @@ class InvestmentWorkspaceController extends Controller
|
||||
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
|
||||
$row = $id ? DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->first() : null;
|
||||
abort_if($id && ! $row, 404);
|
||||
$commands = app(InvestmentProfileCommands::class);
|
||||
$command = ['kind' => 'company', 'target_id' => $id, 'version' => (int) $data['version'], 'payload' => $data['payload']];
|
||||
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
|
||||
if ($replay !== null) {
|
||||
return $replay;
|
||||
}
|
||||
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Declaração alterada. Recarregue.');
|
||||
abort_if(! $id && DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->count() >= 20, 422, 'Máximo de vinte empresas declaradas.');
|
||||
$id ??= (string) Str::uuid();
|
||||
@@ -79,6 +105,7 @@ class InvestmentWorkspaceController extends Controller
|
||||
DB::table('investment_company_declarations')->updateOrInsert(['id' => $id], ['user_id' => $request->user()->id, 'version' => $version,
|
||||
'payload' => $encrypted, 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
|
||||
$this->audit($request, 'company_declared', 'investment_company_declarations', $id, ['version' => $version, 'before_payload' => $row?->payload, 'after_payload' => $encrypted]);
|
||||
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['id' => $id, 'version' => $version]);
|
||||
|
||||
return ['id' => $id, 'version' => $version];
|
||||
});
|
||||
@@ -95,13 +122,25 @@ class InvestmentWorkspaceController extends Controller
|
||||
|
||||
public function reuseOrganizationCountry(Request $request, string $id, OrganizationCountry $service): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'organization_id' => 'required|uuid', 'organization_version' => 'required|integer|min:1']);
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'organization_id' => 'required|uuid', 'organization_version' => 'required|integer|min:1', 'operation_key' => ['sometimes', 'required', 'uuid']]);
|
||||
$result = DB::transaction(function () use ($request, $id, $data, $service) {
|
||||
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
|
||||
$row = DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
$snapshot = $service->readableSnapshot($request->user(), $data['organization_id']);
|
||||
$commands = app(InvestmentProfileCommands::class);
|
||||
$command = ['kind' => 'organization_country_reuse', 'target_id' => $row->id, 'version' => (int) $data['version'], 'payload' => ['organization_id' => $snapshot['organization_id'], 'organization_version' => (int) $data['organization_version']]];
|
||||
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
|
||||
if ($replay !== null) {
|
||||
if (! isset($replay['country'])) {
|
||||
throw new \LogicException('Stored country reuse receipt unavailable.');
|
||||
}
|
||||
|
||||
return ['version' => $replay['version'], 'country' => $replay['country']];
|
||||
}
|
||||
abort_unless((int) $row->version === (int) $data['version'], 409, 'Declaração alterada. Recarregue.');
|
||||
$snapshot = $service->snapshot($request->user(), $data['organization_id']);
|
||||
abort_unless((int) $snapshot['organization_version'] === (int) $data['organization_version'], 409, 'País mestre alterado. Recarregue.');
|
||||
abort_unless($snapshot['country'] !== null, 422, 'País de constituição não informado no cadastro mestre.');
|
||||
$payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
|
||||
$payload['incorporation_country_code'] = $snapshot['country'];
|
||||
$payload['organization_country_snapshot'] = $snapshot;
|
||||
@@ -109,24 +148,49 @@ class InvestmentWorkspaceController extends Controller
|
||||
DB::table('investment_company_declarations')->where('id', $id)->update(['payload' => $encrypted, 'version' => $row->version + 1, 'updated_at' => now()]);
|
||||
$this->audit($request, 'organization_country_reused', 'investment_company_declarations', $id, ['version' => $row->version + 1,
|
||||
'before_payload' => $row->payload, 'after_payload' => $encrypted, 'organization_id' => $data['organization_id'], 'organization_version' => $snapshot['organization_version']]);
|
||||
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['version' => $row->version + 1, 'country' => $snapshot['country']]);
|
||||
|
||||
return ['version' => $row->version + 1, 'country' => $snapshot['country']];
|
||||
});
|
||||
|
||||
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'País mestre reutilizado nesta declaração; manifestações anteriores não alteradas.');
|
||||
return $request->expectsJson() ? response()->json($result)->header('Cache-Control', 'no-store, private') : back()->with('success', 'País mestre reutilizado nesta declaração; manifestações anteriores não alteradas.');
|
||||
}
|
||||
|
||||
public function notifications(Request $request): Response|JsonResponse
|
||||
{
|
||||
$query = DB::table('investment_notifications')->where('user_id', $request->user()->id);
|
||||
if (! $request->user()->can('manage-portal')) {
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$available = $alerts->installed();
|
||||
if ($available) {
|
||||
$query->where(function ($sources) use ($request, $alerts) {
|
||||
$sources->whereIn('opportunity_id', Opportunity::published()->select('id'))
|
||||
->orWhere(function ($legacy) use ($request) {
|
||||
$legacy->whereNotNull('submission_id');
|
||||
if (! $request->user()->can('manage-portal')) {
|
||||
$legacy->whereIn('submission_id', InvestmentSubmission::where('user_id', $request->user()->id)->select('id'));
|
||||
}
|
||||
});
|
||||
if ($alerts->tendersAvailable()) {
|
||||
$sources->orWhereIn('tender_version_id', app(Procurement::class)->readableVersions()->select('id'));
|
||||
}
|
||||
if ($alerts->fundingAvailable()) {
|
||||
$sources->orWhereIn('funding_version_id', app(FundingProgrammes::class)->readableVersions()->select('id'));
|
||||
}
|
||||
});
|
||||
} elseif (! $request->user()->can('manage-portal')) {
|
||||
$query->whereIn('submission_id', InvestmentSubmission::where('user_id', $request->user()->id)->select('id'));
|
||||
}
|
||||
$data = ['unread' => (clone $query)->whereNull('read_at')->count(), 'notifications' => $query->orderByDesc('created_at')->paginate(20)->through(function ($row) {
|
||||
$row->payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
|
||||
$data = ['alertPreferences' => $available ? $alerts->preferences($request->user()->id) : null,
|
||||
'alertOptions' => $available ? ['frequencies' => InvestmentOpportunityAlerts::FREQUENCIES,
|
||||
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['slug', 'name']),
|
||||
'provinces' => app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->orderBy('name')->get(['id', 'name']),
|
||||
'categories' => OpportunityManagement::CATEGORIES, 'tendersAvailable' => $alerts->tendersAvailable(), 'fundingAvailable' => $alerts->fundingAvailable(),
|
||||
'tenderRegimes' => config('procurement.regimes'), 'tenderActs' => config('procurement.acts')] : null,
|
||||
'unread' => (clone $query)->whereNull('read_at')->count(), 'notifications' => $query->orderByDesc('created_at')->orderByDesc('id')->paginate(20)->through(function ($row) {
|
||||
$row->payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return $row;
|
||||
})];
|
||||
return $row;
|
||||
})];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/notifications', $data);
|
||||
}
|
||||
@@ -135,7 +199,17 @@ class InvestmentWorkspaceController extends Controller
|
||||
{
|
||||
$row = DB::table('investment_notifications')->where('id', $id)->where('user_id', $request->user()->id)->first();
|
||||
abort_unless($row !== null, 404);
|
||||
$this->submission($request, $row->submission_id);
|
||||
if ($row->opportunity_id ?? null) {
|
||||
abort_unless(Opportunity::published()->whereKey($row->opportunity_id)->exists(), 404);
|
||||
} elseif ($row->tender_version_id ?? null) {
|
||||
abort_unless(app(InvestmentOpportunityAlerts::class)->tendersAvailable()
|
||||
&& app(Procurement::class)->readableVersions()->where('id', $row->tender_version_id)->exists(), 404);
|
||||
} elseif ($row->funding_version_id ?? null) {
|
||||
abort_unless(app(InvestmentOpportunityAlerts::class)->fundingAvailable()
|
||||
&& app(FundingProgrammes::class)->readableVersions()->where('id', $row->funding_version_id)->exists(), 404);
|
||||
} else {
|
||||
$this->submission($request, $row->submission_id);
|
||||
}
|
||||
DB::table('investment_notifications')->where('id', $id)->whereNull('read_at')->update(['read_at' => now()]);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['read' => true]) : back();
|
||||
|
||||
@@ -16,6 +16,7 @@ use App\Services\InvestmentZoneOperationalProfile;
|
||||
use App\Services\InvestmentZonePathContext;
|
||||
use App\Services\InvestmentZoneProfileInstallation;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -108,6 +109,9 @@ class InvestmentZoneController extends Controller
|
||||
$publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
|
||||
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
|
||||
->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString();
|
||||
if (! $management) {
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'zones', $rows->total(), $filters);
|
||||
}
|
||||
$rows->getCollection()->transform(function (InvestmentZone $zone) use ($management) {
|
||||
$territoryPath = app(InvestmentGeography::class)->path($zone->primary_territory_id, $management);
|
||||
$zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province);
|
||||
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\CompanyComparison;
|
||||
use App\Services\FintechInvestment;
|
||||
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;
|
||||
@@ -16,10 +20,22 @@ use Inertia\Response;
|
||||
|
||||
class InvestorPathController extends Controller
|
||||
{
|
||||
public function fiscalReport(Request $request, string $id, string $reportId, \App\Services\SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
abort_unless(app(InvestorPath::class)->available(), 404);
|
||||
$request->validate(['opportunity' => 'nullable|string|max:150']);
|
||||
$data = $drafts->dossierReport($request->user(), $id, $reportId, $request->query('opportunity'));
|
||||
|
||||
return response()->json($data)->header('Content-Disposition', 'attachment; filename="relatorio-fiscal-'.$reportId.'.json"')
|
||||
->header('X-Content-Type-Options', 'nosniff');
|
||||
}
|
||||
|
||||
public function index(Request $request, InvestorPath $path): JsonResponse|Response
|
||||
{
|
||||
abort_unless($path->available(), 404);
|
||||
$data = ['contexts' => $path->contexts($request->user())];
|
||||
$data = ['contexts' => $path->contexts($request->user()),
|
||||
'companyComparisonAnswers' => $request->has('company_comparison') ? app(CompanyComparison::class)->answers(['answers' => $request->input('company_comparison')]) : null,
|
||||
'guideSelection' => $request->has('investment_guide') ? app(InvestmentGuides::class)->selection($request->array('investment_guide')) : null];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
|
||||
}
|
||||
@@ -28,6 +44,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);
|
||||
}
|
||||
@@ -57,6 +76,9 @@ class InvestorPathController extends Controller
|
||||
|
||||
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
|
||||
{
|
||||
$comparison = $request->has('company_comparison') ? app(CompanyComparison::class)->answers(['answers' => $request->input('company_comparison')]) : null;
|
||||
$guide = $request->has('investment_guide') ? app(InvestmentGuides::class)->selection($request->array('investment_guide')) : null;
|
||||
abort_if($comparison !== null && $guide !== null, 422, 'Escolha o contexto de preparação que pretende continuar.');
|
||||
$zone = $request->has('zone_id') ? app(InvestmentZonePathContext::class)->input($request->all()) : null;
|
||||
if ($zone) {
|
||||
$request->validate(['confirm' => 'required|accepted']);
|
||||
@@ -66,14 +88,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]);
|
||||
@@ -81,7 +117,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) {
|
||||
@@ -92,7 +128,12 @@ class InvestorPathController extends Controller
|
||||
return $id;
|
||||
});
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $id], 201) : redirect('/investimentos/'.$id)->with('success', 'Investimento guardado no seu dossier.');
|
||||
$href = $comparison === null ? '/investimentos/'.$id : '/investimentos/'.$id.'/forma-juridica?'.http_build_query(['answers' => $comparison]);
|
||||
if ($guide !== null) {
|
||||
$href = '/investimentos/'.$id.'/guias/'.$guide['slug'].'?'.http_build_query(['current' => 1, 'selection' => 1, 'sha256' => $guide['sha256'], 'instruments' => $guide['instruments']]);
|
||||
}
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $id, ...($comparison !== null ? ['comparison_href' => $href] : []), ...($guide !== null ? ['guide_href' => $href] : [])], 201) : redirect($href)->with('success', 'Investimento guardado no seu dossier.');
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
@@ -24,6 +25,7 @@ class LegacyContentController extends Controller
|
||||
$articles = array_values(array_filter($articles, fn ($item) => $q === ''
|
||||
|| str_contains(mb_strtolower(strip_tags($item['html'].' '.$item['title'])), mb_strtolower($q))));
|
||||
$match = $articles !== [];
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'sector_content', count($articles), ['q' => $q]);
|
||||
|
||||
return Inertia::render('portal/legacy', ['article' => $article, 'articles' => $articles, 'view' => 'landing', 'query' => $q, 'match' => $match]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\OpportunityCuration;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class OpportunityCurationController extends Controller
|
||||
{
|
||||
public function show(Request $request, int $id, OpportunityCuration $service): Response
|
||||
{
|
||||
$base = str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities';
|
||||
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
|
||||
return Inertia::render('management/opportunity-curation', [...$service->state($request->user(), $id, (int) ($filters['page'] ?? 1)), 'basePath' => $base]);
|
||||
}
|
||||
|
||||
public function preview(Request $request, int $id, OpportunityCuration $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->preview($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function confirm(Request $request, int $id, OpportunityCuration $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->confirm($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,14 @@ use App\Models\Sector;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityCanonicalResponse;
|
||||
use App\Services\OpportunityCuration;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityManagementInstallation;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\OpportunityPromotion;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\OpportunityWorkflowTasks;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\ProactiveInvestment;
|
||||
@@ -129,6 +131,8 @@ class OpportunityManagementController extends Controller
|
||||
$access->authorize($request->user(), 'view', $record);
|
||||
}
|
||||
Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities',
|
||||
'curationHref' => $record && app(OpportunityCuration::class)->allowed($request->user(), $record)
|
||||
? (str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades/' : '/management/opportunities/').$record->id.'/destaque' : null,
|
||||
'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null,
|
||||
'workflowState' => $record ? $access->state($record) : null,
|
||||
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
|
||||
@@ -139,6 +143,7 @@ class OpportunityManagementController extends Controller
|
||||
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
||||
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
|
||||
'workflowTasks' => $record && $record->owner_user_id !== null ? app(OpportunityWorkflowTasks::class)->listing($record) : [],
|
||||
'workflowIncidents' => $record && $record->owner_user_id !== null ? app(OpportunityTechnicalIncidents::class)->recent($request->user(), $record) : [],
|
||||
'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'),
|
||||
'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]);
|
||||
$values = $record ? $service->values($record) : [];
|
||||
|
||||
@@ -10,6 +10,8 @@ use App\Services\OpportunityLibrarySupport;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityResourceInstallation;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\OpportunityTechnicalExecution;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use App\Services\OpportunityTerritorialPresentation;
|
||||
use App\Services\OrganizationCountryInstallation;
|
||||
use App\Services\PortalProfileAccess;
|
||||
@@ -75,7 +77,7 @@ class OpportunityResourceController extends Controller
|
||||
return hash('sha256', json_encode([$request->user()->getAuthIdentifier(), $plan['target'], $plan['migration'], $plan['code_hash']], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function index(int $id, OpportunityResources $service): Response
|
||||
public function index(int $id, OpportunityResources $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$opportunity = Opportunity::withTrashed()->findOrFail($id);
|
||||
app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
|
||||
@@ -100,7 +102,9 @@ class OpportunityResourceController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'librarySources' => ! app(PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)]);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return tap(Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'technicalIncidents' => app(OpportunityTechnicalIncidents::class)->recent(request()->user(), $opportunity), 'librarySources' => ! app(PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)])->toResponse(request()), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function reuseLibrary(Request $request, int $id): JsonResponse
|
||||
@@ -116,9 +120,18 @@ class OpportunityResourceController extends Controller
|
||||
if (is_string($input['payload'] ?? null)) {
|
||||
$input['payload'] = json_decode($input['payload'], true);
|
||||
}
|
||||
$record = $service->save($request->user(), $id, $kind, $input, $request->file('file'), $resourceId);
|
||||
$operation = function () use ($request, $id, $kind, $input, $resourceId, $service) {
|
||||
$record = $service->save($request->user(), $id, $kind, $input, $request->file('file'), $resourceId);
|
||||
|
||||
return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201);
|
||||
return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201);
|
||||
};
|
||||
if (! $request->hasFile('file') || ! in_array($kind, ['documents', 'images'], true)) {
|
||||
return $operation();
|
||||
}
|
||||
$before = Opportunity::withTrashed()->findOrFail($id);
|
||||
app(PortalProfileAccess::class)->authorize($request->user(), 'edit', $before);
|
||||
|
||||
return app(OpportunityTechnicalExecution::class)->run($request->user(), $before, $kind === 'images' ? 'upload_image' : 'upload_document', $input, $operation);
|
||||
}
|
||||
|
||||
public function lifecycle(Request $request, int $id, string $kind, string $resourceId, OpportunityResources $service): JsonResponse
|
||||
@@ -130,9 +143,14 @@ class OpportunityResourceController extends Controller
|
||||
|
||||
public function prepareImage(Request $request, int $id, string $resourceId, OpportunityImageProcessor $service): JsonResponse
|
||||
{
|
||||
$service->prepare($request->user(), $id, $resourceId, $request->all());
|
||||
$before = Opportunity::withTrashed()->findOrFail($id);
|
||||
app(PortalProfileAccess::class)->authorize($request->user(), 'edit', $before);
|
||||
|
||||
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']);
|
||||
return app(OpportunityTechnicalExecution::class)->run($request->user(), $before, 'prepare_image', $request->all(), function () use ($request, $id, $resourceId, $service) {
|
||||
$service->prepare($request->user(), $id, $resourceId, $request->all());
|
||||
|
||||
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']);
|
||||
});
|
||||
}
|
||||
|
||||
public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response|BinaryFileResponse
|
||||
|
||||
@@ -2,26 +2,35 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentRelations;
|
||||
use App\Services\PartnershipAgreementHistory;
|
||||
use App\Services\PartnershipAgreementProjection;
|
||||
use App\Services\PartnershipAgreements;
|
||||
use App\Services\PartnershipCandidacies;
|
||||
use App\Services\PartnershipCandidacyHistory;
|
||||
use App\Services\PartnershipDraftSaves;
|
||||
use App\Services\PartnershipExchange;
|
||||
use App\Services\PartnershipMatching;
|
||||
use App\Services\PartnershipMilestones;
|
||||
use App\Services\PartnershipNotifications;
|
||||
use App\Services\PartnershipPublication;
|
||||
use App\Services\PartnershipPublicationHistory;
|
||||
use App\Services\PartnershipRoomUploads;
|
||||
use App\Services\PartnershipSources;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\SectorOrganization;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
@@ -82,6 +91,7 @@ class PartnershipExchangeController extends Controller
|
||||
}
|
||||
$results = $query->orderByDesc('p.id')->select(['p.id', 'p.title', 'p.sector', 'p.province', 'p.kind', 'p.partnership_type', 'p.sector_id', 'p.deadline', 'p.published_at'])
|
||||
->selectRaw("p.payload->>'summary' as summary")->paginate(12)->withQueryString();
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'partnerships', $results->total(), $filters);
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json($results);
|
||||
}
|
||||
@@ -119,16 +129,23 @@ class PartnershipExchangeController extends Controller
|
||||
public function dashboard(Request $request): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
|
||||
$exchange = app(PartnershipExchange::class);
|
||||
$organizations = $exchange->readableOrganizations($actor);
|
||||
$mine = DB::table('portal_partnerships')->where(fn ($q) => $q->where(fn ($own) => $own->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->latest()->limit(100)->get();
|
||||
$interests = DB::table('partnership_interests as i')->join('portal_partnerships as p', 'p.id', '=', 'i.partnership_id')
|
||||
->leftJoin('partnership_rooms as room', 'room.interest_id', '=', 'i.id')
|
||||
->where(fn ($q) => $q->where(fn ($own) => $own->where('i.user_id', $actor->id)->whereNull('i.organization_id'))->orWhereIn('i.organization_id', $organizations))
|
||||
->select(['i.id', 'i.partnership_id', 'i.status', 'i.decision_reason', 'p.title', 'room.id as room_id'])->orderByDesc('i.id')->limit(100)->get();
|
||||
->select(['i.id', 'i.partnership_id', 'i.status', 'i.decision_reason', 'p.title', 'p.status as partnership_status', 'p.user_id', 'p.organization_id', 'room.id as room_id'])->orderByDesc('i.id')->limit(100)->get()
|
||||
->map(function ($interest) use ($actor, $exchange) {
|
||||
$canRead = $interest->partnership_status === 'published' || $exchange->owns($actor, $interest, false) || Gate::forUser($actor)->allows('manage-portal');
|
||||
|
||||
return ['id' => $interest->id, 'partnership_id' => $interest->partnership_id, 'status' => $interest->status, 'decision_reason' => $interest->decision_reason,
|
||||
'title' => $canRead ? $interest->title : null, 'partnership_href' => $canRead ? '/parcerias/'.$interest->partnership_id : null, 'room_id' => $interest->room_id];
|
||||
});
|
||||
$moderation = Gate::forUser($actor)->allows('manage-portal') ? DB::table('portal_partnerships')->whereIn('status', ['submitted', 'pending'])->orderBy('updated_at')->get(['id', 'title', 'status', 'version']) : [];
|
||||
|
||||
return Inertia::render('partnerships/dashboard', ['mine' => $mine->map(fn ($p) => ['id' => $p->id, 'title' => $p->title, 'status' => $p->status, 'version' => $p->version]), 'interests' => $interests, 'moderation' => $moderation,
|
||||
'notifications' => DB::table('partnership_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(50)->get()]);
|
||||
'notifications' => app(PartnershipNotifications::class)->forUser($actor)]);
|
||||
}
|
||||
|
||||
public function edit(Request $request, ?int $id = null): Response
|
||||
@@ -141,7 +158,10 @@ class PartnershipExchangeController extends Controller
|
||||
$origins = [['type' => $source['type'], 'target_id' => $source['target_id']]];
|
||||
}
|
||||
|
||||
return Inertia::render('partnerships/editor', ['record' => $record ? [...(array) $record, 'payload' => json_decode($record->payload, true)] : null, 'origins' => $origins,
|
||||
$payload = $record ? json_decode($record->payload, true) : [];
|
||||
unset($payload['_creation_hash']);
|
||||
|
||||
return Inertia::render('partnerships/editor', ['editorActorId' => $request->user()->id, 'saveCommands' => $record ? app(PartnershipDraftSaves::class)->commands($request->user(), $record) : [], 'record' => $record ? [...(array) $record, 'payload' => $payload] : null, 'origins' => $origins,
|
||||
'locations' => $record ? DB::table('partnership_locations')->where('partnership_id', $id)->get() : [], ...$this->catalogues($request)]);
|
||||
}
|
||||
|
||||
@@ -149,7 +169,7 @@ class PartnershipExchangeController extends Controller
|
||||
{
|
||||
$record = app(PartnershipExchange::class)->save($request->user(), $request->all(), $id);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $record->id, 'version' => $record->version, 'status' => $record->status]) : redirect('/parcerias/'.$record->id.'/editar')->with('success', 'Rascunho guardado.');
|
||||
return $request->expectsJson() ? response()->json(['id' => $record->id, 'version' => $record->version, 'status' => $record->status, 'replayed' => (bool) ($record->command_replayed ?? false), 'saved_version' => $record->command_saved_version ?? null]) : redirect('/parcerias/'.$record->id.'/editar')->with('success', 'Rascunho guardado.');
|
||||
}
|
||||
|
||||
public function show(Request $request, int $id): Response|JsonResponse
|
||||
@@ -163,17 +183,23 @@ class PartnershipExchangeController extends Controller
|
||||
$privateDetails = ($payload['confidentiality'] ?? 'public') === 'private' && ! $owner && ! $moderator;
|
||||
$mine = $request->user() ? DB::table('partnership_interests')->where('partnership_id', $id)->get()->filter(fn ($i) => app(PartnershipExchange::class)->owns($request->user(), $i, false))->values() : collect();
|
||||
$interests = $owner ? DB::table('partnership_interests')->where('partnership_id', $id)->orderBy('id')->get() : $mine;
|
||||
$interestData = $interests->map(function ($interest) use ($record) {
|
||||
$commands = $request->user() ? app(PartnershipCandidacies::class)->commands($request->user(), $id) : [];
|
||||
$interestData = $interests->map(function ($interest) use ($record, $request, $commands) {
|
||||
return [...(array) $interest, 'payload' => json_decode($interest->payload, true), 'assessment' => json_decode($interest->assessment, true),
|
||||
'can_edit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $interest), 'commands' => $commands[(int) $interest->id] ?? [],
|
||||
'match' => app(PartnershipMatching::class)->explain($record, $interest), 'room_id' => DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id')];
|
||||
});
|
||||
$props = ['record' => ['id' => $record->id, 'title' => $record->title, 'status' => $record->status, 'version' => $record->version, 'kind' => $record->kind,
|
||||
'partnership_type' => $record->partnership_type, 'sector' => $record->sector, 'province' => $record->province, 'sector_id' => $record->sector_id, 'deadline' => $record->deadline,
|
||||
'offer' => $privateDetails ? null : $record->offer, 'seeking' => $privateDetails ? null : $record->seeking, 'payload' => $privateDetails ? ['summary' => $payload['summary'] ?? '', 'confidentiality' => 'private'] : $payload],
|
||||
'owner' => (bool) $owner, 'canEdit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $record), 'moderator' => (bool) $moderator,
|
||||
'acceptingInterests' => app(PartnershipCandidacies::class)->accepting($record),
|
||||
'canStartInterest' => $request->user() && ! $owner && ! DB::table('partnership_interests')->where('partnership_id', $id)->where('user_id', $request->user()->id)->exists(),
|
||||
'origins' => app(PartnershipSources::class)->forPartnership($id, $owner ? $request->user() : null), 'interests' => $interestData,
|
||||
'locations' => app(InvestmentRelations::class)->locations(array_values(DB::table('partnership_locations')->where('partnership_id', $id)->get()->map(fn ($l) => ['id' => $l->geo_location_id, 'role' => $l->role, 'source_reference' => $l->source_reference])->all())),
|
||||
'history' => ($owner || $moderator) ? DB::table('partnership_events')->where('partnership_id', $id)->where('event_type', 'like', 'partnership_opportunity.%')->orderBy('occurred_at')->get(['event_type', 'actor_id', 'occurred_at', 'payload']) : [],
|
||||
'historySummary' => ($owner || $moderator) ? app(PartnershipPublicationHistory::class)->summary($request->user(), $id) : null,
|
||||
'publicationActions' => app(PartnershipPublication::class)->actions($request->user(), $record),
|
||||
'publicationCommands' => app(PartnershipPublication::class)->commands($request->user(), $record),
|
||||
...$this->catalogues($request)];
|
||||
if ($request->user()) {
|
||||
Inertia::encryptHistory();
|
||||
@@ -182,39 +208,74 @@ class PartnershipExchangeController extends Controller
|
||||
return $request->expectsJson() ? response()->json($props)->header('Cache-Control', 'private, no-store') : Inertia::render('partnerships/detail', $props);
|
||||
}
|
||||
|
||||
public function publicationHistory(Request $request, int $id): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['before' => 'nullable|string|max:4000']);
|
||||
$history = app(PartnershipPublicationHistory::class)->page($request->user(), $id, $data['before'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/publication-history', $history);
|
||||
}
|
||||
|
||||
public function transition(Request $request, int $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000']);
|
||||
$record = app(PartnershipExchange::class)->transition($request->user(), $id, $data['version'], $data['action'], $data['reason']);
|
||||
$data = $request->validate(['client_key' => 'nullable|uuid', 'version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000']);
|
||||
$record = app(PartnershipExchange::class)->transition($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['client_key'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['status' => $record->status, 'version' => $record->version]) : back()->with('success', 'Decisão registada.');
|
||||
return $request->expectsJson() ? response()->json(['id' => $record->id, 'status' => $record->status, 'version' => $record->version, 'replayed' => (bool) ($record->command_replayed ?? false)]) : back()->with('success', 'Decisão registada.');
|
||||
}
|
||||
|
||||
public function interest(Request $request, int $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
$interest = app(PartnershipExchange::class)->interest($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $interest->id, 'version' => $interest->version]) : back()->with('success', 'Interesse guardado.');
|
||||
return $request->expectsJson() ? response()->json(['id' => $interest->id, 'version' => $interest->version, 'replayed' => (bool) ($interest->command_replayed ?? false)]) : back()->with('success', 'Interesse guardado.');
|
||||
}
|
||||
|
||||
public function decide(Request $request, int $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000', 'assessment' => 'array|max:7']);
|
||||
$interest = app(PartnershipExchange::class)->decideInterest($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['assessment'] ?? []);
|
||||
$data = $request->validate(['client_key' => 'nullable|uuid', 'partnership_version' => 'nullable|integer|min:1', 'weights_hash' => 'nullable|string|regex:/^[a-f0-9]{64}$/', 'version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000', 'assessment' => 'array|max:7']);
|
||||
$interest = app(PartnershipExchange::class)->decideInterest($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['assessment'] ?? [], $data['partnership_version'] ?? null, $data['weights_hash'] ?? null, $data['client_key'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['status' => $interest->status, 'version' => $interest->version]) : back()->with('success', 'Candidatura atualizada.');
|
||||
return $request->expectsJson() ? response()->json(['status' => $interest->status, 'version' => $interest->version, 'replayed' => (bool) ($interest->command_replayed ?? false)]) : back()->with('success', 'Candidatura atualizada.');
|
||||
}
|
||||
|
||||
public function candidacyHistory(Request $request, int $id): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['before' => 'nullable|string|max:4000']);
|
||||
$history = app(PartnershipCandidacyHistory::class)->page($request->user(), $id, $data['before'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/interest-history', $history);
|
||||
}
|
||||
|
||||
public function agreementHistory(Request $request, int $id): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['before' => 'nullable|string|max:4000']);
|
||||
$history = app(PartnershipAgreementHistory::class)->page($request->user(), $id, $data['before'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/agreement-history', $history);
|
||||
}
|
||||
|
||||
public function room(Request $request, int $id): Response|JsonResponse
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id);
|
||||
$props = [...$context, 'room' => [...(array) $context['room'], 'agreement' => $context['room']->agreement ? json_decode($context['room']->agreement, true) : null],
|
||||
'messages' => DB::table('partnership_messages as m')->join('users as u', 'u.id', '=', 'm.author_id')->where('room_id', $id)->orderBy('m.id')->get(['m.id', 'm.body', 'm.created_at', 'm.author_id', 'u.name']),
|
||||
$participants = app(PartnershipExchange::class)->participants($context['partnership'], $context['interest']);
|
||||
$participantIds = array_column($participants, 'id');
|
||||
$canWrite = app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest']);
|
||||
$canAssign = $canWrite && in_array($context['room']->status, ['agreement_recorded', 'agreed', 'execution'], true);
|
||||
$creationKeys = app(PartnershipMilestones::class)->creationKeys($request->user(), (int) $context['partnership']->id, $id);
|
||||
$partnership = (array) $context['partnership'];
|
||||
$payload = json_decode($partnership['payload'], true, 512, JSON_THROW_ON_ERROR);
|
||||
unset($payload['_creation_hash']);
|
||||
$partnership['payload'] = json_encode($payload, JSON_THROW_ON_ERROR);
|
||||
$props = [...$context, 'partnership' => $partnership, 'room' => [...(array) $context['room'], 'agreement' => app(PartnershipAgreementProjection::class)->current($context['room']->agreement)],
|
||||
'messages' => DB::table('partnership_messages as m')->join('users as u', 'u.id', '=', 'm.author_id')->where('room_id', $id)->orderBy('m.id')->get(['m.id', 'm.body', 'm.created_at', 'm.author_id', 'm.client_key', 'u.name'])
|
||||
->map(fn ($message) => [...(array) $message, 'client_key' => (int) $message->author_id === $request->user()->id ? $message->client_key : null]),
|
||||
'documents' => DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('room_id', $id)
|
||||
->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))
|
||||
->get(['link.id', 'link.shared', 'link.owner_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.id as document_id']),
|
||||
'milestones' => DB::table('partnership_milestones')->where('room_id', $id)->orderBy('id')->get(),
|
||||
'canWrite' => app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest'])];
|
||||
'milestones' => DB::table('partnership_milestones as m')->leftJoin('users as responsible', 'responsible.id', '=', 'm.responsible_id')->where('m.room_id', $id)->orderBy('m.id')
|
||||
->get(['m.*', 'responsible.name as responsible_name'])->map(fn ($milestone) => [...(array) $milestone, 'responsible_is_participant' => in_array((int) $milestone->responsible_id, $participantIds, true), 'client_key' => $creationKeys[(int) $milestone->id] ?? null]),
|
||||
'agreementActorId' => $request->user()->id, 'agreementParty' => app(PartnershipAgreements::class)->party($request->user(), $context), 'agreementCommands' => app(PartnershipAgreements::class)->commands($request->user(), $context), 'participants' => $canAssign ? $participants : [], 'canWrite' => $canWrite];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('partnerships/room', $props);
|
||||
}
|
||||
@@ -223,9 +284,10 @@ class PartnershipExchangeController extends Controller
|
||||
{
|
||||
$data = $request->validate(['client_key' => 'required|uuid', 'body' => 'required|string|max:15000']);
|
||||
DB::transaction(function () use ($request, $id, $data) {
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id);
|
||||
abort_unless(app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest']), 403);
|
||||
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.');
|
||||
abort_unless($locked !== null, 404);
|
||||
$key = ['room_id' => $id, 'author_id' => $request->user()->id, 'client_key' => $data['client_key']];
|
||||
$existing = DB::table('partnership_messages')->where($key)->first();
|
||||
if ($existing) {
|
||||
@@ -233,6 +295,7 @@ class PartnershipExchangeController extends Controller
|
||||
|
||||
return;
|
||||
}
|
||||
abort_if(in_array($locked->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.');
|
||||
DB::table('partnership_messages')->insert([...$key, 'body' => $data['body']]);
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.message_created.v1', ['room_id' => $id], 'Nova mensagem privada', [$context['partnership']->user_id, $context['interest']->user_id]);
|
||||
});
|
||||
@@ -242,100 +305,31 @@ class PartnershipExchangeController extends Controller
|
||||
|
||||
public function agreement(Request $request, int $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|in:record,confirm,start,complete,cancel,renew', 'title' => 'required_if:action,record|nullable|string|max:200',
|
||||
'terms' => 'required_if:action,record|nullable|string|max:20000', 'reason' => 'required|string|max:2000']);
|
||||
DB::transaction(function () use ($request, $id, $data) {
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
|
||||
$room = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless((int) $room->version === (int) $data['version'], 409, 'Acordo alterado.');
|
||||
$agreement = $room->agreement ? json_decode($room->agreement, true) : null;
|
||||
$status = $room->status;
|
||||
if ($data['action'] === 'record') {
|
||||
abort_unless(in_array($status, ['negotiation', 'agreement_recorded'], true), 409);
|
||||
$previous = $agreement['previous_versions'] ?? [];
|
||||
if ($agreement) {
|
||||
$previous[] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations'], 'recorded_at' => $agreement['recorded_at']];
|
||||
}
|
||||
$agreement = ['title' => $data['title'], 'terms' => $data['terms'], 'recorded_by' => $request->user()->id, 'recorded_at' => now()->toIso8601String(), 'confirmations' => [],
|
||||
'parties' => [$context['partnership']->user_id, $context['interest']->user_id], 'legal_signature_status' => 'not_verified', 'previous_versions' => $previous];
|
||||
$status = 'agreement_recorded';
|
||||
} elseif ($data['action'] === 'confirm') {
|
||||
abort_unless($status === 'agreement_recorded' && $agreement, 409);
|
||||
$party = app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) ? 'proponent' : 'candidate';
|
||||
$agreement['confirmations'][$party] = ['actor_id' => $request->user()->id, 'date' => now()->toIso8601String(), 'reason' => $data['reason']];
|
||||
if (count($agreement['confirmations']) === 2) {
|
||||
$status = 'agreed';
|
||||
}
|
||||
} else {
|
||||
$allowed = ['start' => ['agreed'], 'complete' => ['execution'], 'cancel' => ['negotiation', 'agreement_recorded', 'agreed', 'execution'], 'renew' => ['agreed', 'execution']];
|
||||
abort_unless(in_array($status, $allowed[$data['action']] ?? [], true), 409);
|
||||
if ($data['action'] === 'complete') {
|
||||
abort_if(DB::table('partnership_milestones')->where('room_id', $id)->where('status', '!=', 'completed')->exists(), 409, 'Existem marcos pendentes.');
|
||||
}
|
||||
$status = ['start' => 'execution', 'complete' => 'closed', 'cancel' => 'cancelled', 'renew' => 'negotiation'][$data['action']];
|
||||
if ($data['action'] === 'renew') {
|
||||
$agreement['previous_versions'][] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations']];
|
||||
$agreement['confirmations'] = [];
|
||||
}
|
||||
}
|
||||
DB::table('partnership_rooms')->where('id', $id)->update(['agreement' => $agreement ? json_encode($agreement) : null, 'status' => $status, 'version' => $room->version + 1, 'updated_at' => now()]);
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_agreement.changed.v1', ['room_id' => $id, 'status' => $status, 'version' => $room->version + 1, 'reason' => $data['reason']], 'Acordo: '.$status, [$context['partnership']->user_id, $context['interest']->user_id]);
|
||||
});
|
||||
$result = app(PartnershipAgreements::class)->act($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json(['recorded' => true]) : back()->with('success', 'Acordo atualizado; assinatura jurídica não verificada.');
|
||||
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Acordo atualizado; assinatura jurídica não verificada.');
|
||||
}
|
||||
|
||||
public function milestone(Request $request, int $id, ?int $milestone = null): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['title' => 'required|string|max:200', 'responsible_id' => 'required|integer', 'due_date' => 'nullable|date_format:Y-m-d', 'status' => 'required|in:pending,progress,completed',
|
||||
$data = $request->validate(['client_key' => 'nullable|uuid', 'title' => 'required|string|max:200', 'responsible_id' => 'required|integer', 'due_date' => 'nullable|date_format:Y-m-d', 'status' => 'required|in:pending,progress,completed',
|
||||
'evidence' => 'required_if:status,completed|nullable|string|max:10000', 'version' => ($milestone ? 'required' : 'nullable').'|integer|min:1']);
|
||||
DB::transaction(function () use ($request, $id, $milestone, $data) {
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
|
||||
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($locked !== null && in_array($locked->status, ['agreement_recorded', 'agreed', 'execution'], true), 409);
|
||||
$responsible = User::query()->whereKey($data['responsible_id'])->first();
|
||||
abort_unless($responsible !== null && (app(PartnershipExchange::class)->owns($responsible, $context['partnership']) || app(PartnershipExchange::class)->owns($responsible, $context['interest'])), 422, 'Responsável deve ser participante identificado.');
|
||||
if ($milestone) {
|
||||
$existing = DB::table('partnership_milestones')->where('room_id', $id)->where('id', $milestone)->lockForUpdate()->first();
|
||||
abort_unless($existing !== null, 404);
|
||||
abort_unless((int) $existing->version === (int) $data['version'], 409);
|
||||
DB::table('partnership_milestones')->where('id', $milestone)->update([...$data, 'version' => $existing->version + 1, 'updated_at' => now()]);
|
||||
} else {
|
||||
unset($data['version']);
|
||||
$milestone = DB::table('partnership_milestones')->insertGetId([...$data, 'room_id' => $id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_milestone.changed.v1', ['milestone_id' => $milestone, 'status' => $data['status']], 'Marco atualizado', [$context['partnership']->user_id, $context['interest']->user_id]);
|
||||
});
|
||||
if (isset($data['client_key'])) {
|
||||
$data['client_key'] = strtolower($data['client_key']);
|
||||
}
|
||||
$result = app(PartnershipMilestones::class)->save($request->user(), $id, $data, $milestone);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['saved' => true]) : back()->with('success', 'Marco guardado.');
|
||||
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Marco guardado.');
|
||||
}
|
||||
|
||||
public function upload(Request $request, int $id): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', 'shared' => 'required|boolean']);
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
|
||||
$data = $request->validate(['client_key' => 'nullable|uuid', 'file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', 'shared' => 'required|boolean']);
|
||||
$file = $request->file('file');
|
||||
$documentId = (string) Str::uuid();
|
||||
$stored = $file->storeAs('partnerships/'.$id, $documentId, 'local');
|
||||
abort_unless(is_string($stored) && $stored !== '', 503);
|
||||
try {
|
||||
DB::transaction(function () use ($request, $id, $data, $file, $documentId, $stored, $context) {
|
||||
app(PartnershipExchange::class)->room($request->user(), $id, true);
|
||||
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409);
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'partnership-exchange', 'data_classification' => 'restricted',
|
||||
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored,
|
||||
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined', 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id]);
|
||||
DB::table('partnership_documents')->insert(['room_id' => $id, 'document_id' => $documentId, 'owner_id' => $request->user()->id, 'shared' => $data['shared']]);
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_added.v1', ['room_id' => $id, 'document_id' => $documentId, 'shared' => $data['shared']], 'Documento privado anexado');
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
Storage::disk('local')->delete($stored);
|
||||
throw $e;
|
||||
}
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
abort_unless($file instanceof UploadedFile, 422);
|
||||
$result = app(PartnershipRoomUploads::class)->save($request->user(), $id, $file, (bool) $data['shared'], isset($data['client_key']) ? strtolower($data['client_key']) : null);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['uploaded' => true]) : back()->with('success', 'Documento privado guardado; análise antimalware pendente.');
|
||||
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Envio reconciliado com o documento privado. Consulte o estado da análise na lista.')->with('uploaded_document_id', $result['document_id']);
|
||||
}
|
||||
|
||||
public function download(Request $request, int $id, int $attachment): \Illuminate\Http\Response|BinaryFileResponse
|
||||
@@ -367,7 +361,7 @@ class PartnershipExchangeController extends Controller
|
||||
|
||||
public function notification(Request $request, int $id): RedirectResponse
|
||||
{
|
||||
abort_unless(DB::table('partnership_notifications')->where('id', $id)->where('user_id', $request->user()->id)->update(['read_at' => now()]) > 0, 404);
|
||||
app(PartnershipNotifications::class)->markRead($request->user(), $id);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Exceptions\OpportunityWorkflowUnavailable;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityContacts;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\OpportunityTechnicalSupport;
|
||||
use App\Services\OpportunityWorkflowExecution;
|
||||
use App\Services\PortalInternalDesignation;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
@@ -49,13 +51,15 @@ class PortalProfileController extends Controller
|
||||
{
|
||||
$service->administrative($request->user());
|
||||
|
||||
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(),
|
||||
return Inertia::render('profiles/administration', ['technicalSupportAvailable' => app(OpportunityTechnicalSupport::class)->installed(), 'requests' => DB::table('portal_profile_requests')->latest()->get(),
|
||||
'assignments' => DB::table('portal_role_assignments')->get(), 'pair' => DB::table('portal_superuser_pair')->first(),
|
||||
'operatorOrganizations' => app(PortalInternalDesignation::class)->organizations(),
|
||||
'staffAccounts' => User::query()->orderBy('name')->get(['id', 'name', 'email', 'email_verified_at', 'two_factor_confirmed_at'])->map(fn (User $user) => [
|
||||
'id' => $user->id, 'name' => $user->name, 'email' => $user->email,
|
||||
'verified' => $user->email_verified_at !== null, 'mfa' => $user->two_factor_confirmed_at !== null,
|
||||
]),
|
||||
'staffAccounts' => User::query()->select(['id', 'name', 'email', 'email_verified_at'])
|
||||
->selectRaw('CASE WHEN two_factor_secret IS NOT NULL AND two_factor_confirmed_at IS NOT NULL THEN 1 ELSE 0 END AS mfa_enrolled')
|
||||
->withCasts(['mfa_enrolled' => 'boolean'])->orderBy('name')->get()->map(fn (User $user) => [
|
||||
'id' => $user->id, 'name' => $user->name, 'email' => $user->email,
|
||||
'verified' => $user->email_verified_at !== null, 'mfa' => $user->getAttribute('mfa_enrolled'),
|
||||
]),
|
||||
'internalTypes' => OpportunityCanonicalContract::BASE_CATEGORIES,
|
||||
'actorId' => $request->user()->id, 'types' => OpportunityManagement::CATEGORIES,
|
||||
'organizations' => DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']),
|
||||
@@ -148,9 +152,14 @@ class PortalProfileController extends Controller
|
||||
return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id);
|
||||
}
|
||||
|
||||
public function workflow(Request $request, int $id, OpportunityProfileWorkflow $service): JsonResponse
|
||||
public function workflow(Request $request, int $id, OpportunityWorkflowExecution $service): JsonResponse
|
||||
{
|
||||
$record = $service->transition($request->user(), $id, $request->all());
|
||||
try {
|
||||
$record = $service->transition($request->user(), $id, $request->all());
|
||||
} catch (OpportunityWorkflowUnavailable $failure) {
|
||||
return response()->json(['message' => 'Não foi possível confirmar o resultado. Consulte o estado da oportunidade antes de repetir. '.($failure->recorded ? 'Incidente técnico registado. ' : 'Não foi possível guardar o incidente; conserve esta referência. ').'Referência: '.$failure->reference,
|
||||
'reference' => $failure->reference, 'incident_recorded' => $failure->recorded], 503)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
return response()->json(['id' => $id, 'status' => app(PortalProfileAccess::class)->state($record), 'publication_status' => $record->status, 'etag' => app(OpportunityManagement::class)->etag($record), 'message' => 'Ação interna registada; não representa decisão externa.']);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response as HttpResponse;
|
||||
|
||||
class PortalProfileInstallationController extends Controller
|
||||
{
|
||||
@@ -22,6 +23,19 @@ class PortalProfileInstallationController extends Controller
|
||||
return response()->json($installation->apply($request->user(), $request->all()));
|
||||
}
|
||||
|
||||
public function supportPreview(Request $request, PortalProfileInstallation $installation): HttpResponse
|
||||
{
|
||||
$plan = $installation->supportPreview($request->user());
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return tap($request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/support-installation', $plan)->toResponse($request), static fn (HttpResponse $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function applySupport(Request $request, PortalProfileInstallation $installation): JsonResponse
|
||||
{
|
||||
return response()->json($installation->applySupport($request->user(), $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function bootstrap(Request $request, PortalProfileInstallation $installation): JsonResponse
|
||||
{
|
||||
return response()->json($installation->bootstrap($request->user(), $request->all()));
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Services\LegacyContent;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PublicDocumentPresentation;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\SectorOrganization;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use App\Services\VirtualDesk;
|
||||
@@ -127,6 +128,7 @@ class PortalServicesController extends Controller
|
||||
])->paginate(20)->withQueryString();
|
||||
$pageResult->getCollection()->transform(fn ($resource) => app(PublicDocumentPresentation::class)->resource($resource));
|
||||
$props['resources'] = $pageResult;
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'documents', $pageResult->total(), $filters);
|
||||
$props['documentTypes'] = (clone $this->resources())->distinct()->orderBy('r.document_type')->pluck('r.document_type');
|
||||
$props['languages'] = (clone $this->resources())->distinct()->orderBy('r.language')->pluck('r.language');
|
||||
$props['issuers'] = (clone $this->resources())->whereNotNull('d.issuer')->distinct()->orderBy('d.issuer')->pluck('d.issuer');
|
||||
@@ -153,6 +155,7 @@ class PortalServicesController extends Controller
|
||||
$query->where('title', 'ilike', '%'.$filters['q'].'%');
|
||||
}
|
||||
$props['partnerships'] = $query->orderByDesc('id')->select(['id', 'title', 'sector', 'province', 'offer', 'seeking'])->paginate(20)->withQueryString();
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'partnerships', $props['partnerships']->total(), $filters);
|
||||
}
|
||||
if ($page === 'desk') {
|
||||
if (app(VirtualDesk::class)->installed()) {
|
||||
|
||||
@@ -6,11 +6,26 @@ use App\Models\Opportunity;
|
||||
use App\Services\ProactiveSupply;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class ProactiveSupplyController extends Controller
|
||||
{
|
||||
public function review(Request $request, ProactiveSupply $service): JsonResponse|Response
|
||||
{
|
||||
$service->authorize($request->user());
|
||||
$v = $request->validate(['record_id' => 'nullable|integer|min:1']);
|
||||
$record = isset($v['record_id']) ? Opportunity::whereKey($v['record_id'])->firstOrFail() : null;
|
||||
$data = $service->review($request->user(), $request->all(), $record);
|
||||
$data['recordId'] = isset($v['record_id']) ? (int) $v['record_id'] : null;
|
||||
|
||||
return $request->expectsJson() ? response()->json($data)->header('Cache-Control', 'private, no-store')
|
||||
: Inertia::render('management/proactive-supply-review', $data);
|
||||
}
|
||||
|
||||
public function index(Request $request, ProactiveSupply $service): JsonResponse
|
||||
{
|
||||
$service->authorize($request->user());
|
||||
$v = $request->validate(['record_id' => 'nullable|integer|min:1']);
|
||||
$record = isset($v['record_id']) ? Opportunity::whereKey($v['record_id'])->firstOrFail() : null;
|
||||
|
||||
|
||||
@@ -13,37 +13,16 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ProcurementController extends Controller
|
||||
{
|
||||
private const STATE_SQL = "CASE WHEN v.payload->>'procedural_state' IN ('cancelled','results') THEN v.payload->>'procedural_state' WHEN ((v.payload->>'deadline')::timestamp AT TIME ZONE (v.payload->>'timezone'))<=CURRENT_TIMESTAMP THEN 'deadline_ended' WHEN v.payload->>'extended'='true' THEN 'extended' ELSE 'open' END";
|
||||
|
||||
private function query(Procurement $service): Builder
|
||||
{
|
||||
abort_unless($service->available(), 404);
|
||||
|
||||
return DB::table('portal_tenders as t')->join('portal_tender_versions as v', fn ($q) => $q->on('v.id', '=', 't.published_version_id')->on('v.tender_id', '=', 't.id'))->whereNotNull('v.published_at');
|
||||
return $service->publicQuery();
|
||||
}
|
||||
|
||||
public function index(Request $request, Procurement $service): Response
|
||||
{
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'entity' => 'nullable|uuid', 'sector' => 'nullable|integer', 'territory' => 'nullable|uuid', 'modality' => 'nullable|string|max:200', 'financier' => 'nullable|string|max:200', 'state' => 'nullable|in:open,extended,deadline_ended,cancelled,results', 'deadline_before' => 'nullable|date_format:Y-m-d', 'regime' => 'nullable|in:state,external,private,other']);
|
||||
$filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
|
||||
$query = $this->query($service);
|
||||
if (! empty($filters['q'])) {
|
||||
$query->where(fn ($q) => $q->whereRaw("v.payload->>'title' ILIKE ?", ['%'.$filters['q'].'%'])->orWhereRaw("v.payload->>'object' ILIKE ?", ['%'.$filters['q'].'%'])->orWhereRaw("v.payload->>'reference' ILIKE ?", ['%'.$filters['q'].'%']));
|
||||
}
|
||||
foreach (['entity' => 'organization_id', 'sector' => 'sector_id', 'modality' => 'modality', 'financier' => 'financier', 'regime' => 'regime'] as $filter => $field) {
|
||||
if (! empty($filters[$filter])) {
|
||||
$query->whereRaw('v.payload->>? = ?', [$field, (string) $filters[$filter]]);
|
||||
}
|
||||
}
|
||||
if (! empty($filters['territory'])) {
|
||||
$query->whereRaw("v.payload->>'territory_id' IN (WITH RECURSIVE scope(id,depth) AS (SELECT id,0 FROM geo_locations WHERE id=? AND deleted_at IS NULL UNION ALL SELECT c.id,s.depth+1 FROM geo_locations c JOIN scope s ON c.parent_id=s.id WHERE c.deleted_at IS NULL AND s.depth<4) SELECT id::text FROM scope)", [$filters['territory']]);
|
||||
}
|
||||
if (! empty($filters['state'])) {
|
||||
$query->whereRaw(self::STATE_SQL.' = ?', [$filters['state']]);
|
||||
}
|
||||
if (! empty($filters['deadline_before'])) {
|
||||
$query->whereRaw("left(v.payload->>'deadline',10)<=?", [$filters['deadline_before']]);
|
||||
}
|
||||
$query = $service->publicQuery($filters);
|
||||
$rows = $query->select('t.id', 'v.id as vid')->orderByDesc('v.published_at')->paginate(20)->withQueryString();
|
||||
$rows->through(fn ($r) => ['id' => $r->id, ...$this->summary($service, $r->vid)]);
|
||||
$facets = $this->query($service)->get(['v.payload'])->map(fn ($r) => json_decode($r->payload, true));
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\ProductExperiments;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class ProductExperimentController extends Controller
|
||||
{
|
||||
public function index(Request $request, ProductExperiments $experiments): Response|JsonResponse
|
||||
{
|
||||
$data = $experiments->listing($request->user(), $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/experiments/index', $data);
|
||||
}
|
||||
|
||||
public function create(Request $request, ProductExperiments $experiments): Response|JsonResponse
|
||||
{
|
||||
return $this->show($request, $experiments);
|
||||
}
|
||||
|
||||
public function show(Request $request, ProductExperiments $experiments, ?string $id = null): Response|JsonResponse
|
||||
{
|
||||
$data = $experiments->view($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/experiments/edit', $data);
|
||||
}
|
||||
|
||||
public function store(Request $request, ProductExperiments $experiments): JsonResponse
|
||||
{
|
||||
return response()->json($experiments->save($request->user(), null, $request->all()), 201);
|
||||
}
|
||||
|
||||
public function revise(Request $request, ProductExperiments $experiments, string $id): JsonResponse
|
||||
{
|
||||
return response()->json($experiments->save($request->user(), $id, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\ProductUsageMetrics;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class ProductUsageMetricsController extends Controller
|
||||
{
|
||||
public function index(Request $request, ProductUsageMetrics $metrics): Response|JsonResponse
|
||||
{
|
||||
$data = ['report' => $metrics->report($request->user(), $request->all())];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/product-usage', $data);
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,14 @@ namespace App\Http\Controllers;
|
||||
use App\Http\Resources\PublicBusinessOpportunityResource;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Sector;
|
||||
use App\Services\BusinessProximitySearch;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\ExistingBusinessClassification;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\OpportunityClassification;
|
||||
use App\Services\PublicBusinessLocations;
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use App\Services\SectorOrganization;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -30,13 +33,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->whereExists(fn ($locations) => $locations->selectRaw('1')->from('existing_business_locations as matching_location')
|
||||
->whereColumn('matching_location.existing_business_id', 'existing_businesses.id')->where('matching_location.is_public', true)
|
||||
->where(function ($match) use ($territoryIds): void {
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id'] as $field) {
|
||||
$match->orWhereIn('matching_location.'.$field, $territoryIds);
|
||||
}
|
||||
}));
|
||||
$query->whereExists(app(PublicBusinessLocations::class)->matchingArea($territoryIds)->selectRaw('1')->whereColumn('l.existing_business_id', 'existing_businesses.id'));
|
||||
}
|
||||
if (! empty($filters['q'])) {
|
||||
$term = trim($filters['q']);
|
||||
@@ -52,12 +49,21 @@ class PublicBusinessOpportunityController extends Controller
|
||||
$query->where('existing_businesses.modality', $filters['modality']);
|
||||
}
|
||||
|
||||
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->appends($filters));
|
||||
$coverage = null;
|
||||
if (! empty($filters['near_business'])) {
|
||||
$proximity = app(BusinessProximitySearch::class);
|
||||
$coverage = $proximity->constrain($query, $proximity->origin($filters['near_business']), (float) $filters['radius_km']);
|
||||
} else {
|
||||
$query->orderByDesc('existing_businesses.published_at')->orderBy('existing_businesses.id');
|
||||
}
|
||||
$page = $query->paginate($filters['per_page'] ?? 12)->appends($filters);
|
||||
app(PublicSearchMetrics::class)->candidate($request, 'businesses', $page->total(), $filters);
|
||||
$results = PublicBusinessOpportunityResource::collection($page)->additional(['geographicCoverage' => $coverage]);
|
||||
if ($request->expectsJson()) {
|
||||
return $results->response();
|
||||
}
|
||||
|
||||
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path,
|
||||
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path, 'geographicCoverage' => $coverage,
|
||||
'classificationOptions' => app(OpportunityClassification::class)->options(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz'])]);
|
||||
}
|
||||
@@ -72,6 +78,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
|
||||
'sector' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
'near_business' => ['nullable', 'required_with:radius_km', 'uuid'], 'radius_km' => ['nullable', 'required_with:near_business', 'numeric', 'min:0.1', 'max:2000'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
|
||||
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
...app(ExistingBusinessClassification::class)->filterRules(),
|
||||
@@ -87,8 +94,18 @@ class PublicBusinessOpportunityController extends Controller
|
||||
}
|
||||
|
||||
$returnFilters = $this->filters($request);
|
||||
$similarProvince = $record->getAttribute('similar_province_id');
|
||||
if ($similarProvince !== null && ! app(InvestmentGeography::class)->publicReferences()->where('geo_locations.id', $similarProvince)->exists()) {
|
||||
$similarProvince = null;
|
||||
}
|
||||
|
||||
return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request),
|
||||
'similarRadiusAvailable' => app(BusinessProximitySearch::class)->available($record->id),
|
||||
'similarCatalogueUrl' => '/negocios?'.http_build_query(array_filter([
|
||||
'modality' => $record->modality,
|
||||
'sector' => $record->sector_id,
|
||||
'province_id' => $similarProvince,
|
||||
], fn ($value) => $value !== null && $value !== '')),
|
||||
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
|
||||
'interestUrl' => '/negocios/'.rawurlencode($slug).'/manifestar-interesse'.($returnFilters === [] ? '' : '?'.http_build_query($returnFilters))]);
|
||||
}
|
||||
@@ -110,14 +127,14 @@ class PublicBusinessOpportunityController extends Controller
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
private function publishedQuery(): Builder
|
||||
{
|
||||
$publicLocations = DB::table('existing_business_locations as locations')
|
||||
->leftJoin('geo_locations as province', 'province.id', '=', 'locations.province_id')
|
||||
->leftJoin('geo_locations as district', 'district.id', '=', 'locations.district_id')
|
||||
->leftJoin('geo_locations as locality', 'locality.id', '=', 'locations.locality_id')
|
||||
->where('locations.is_public', true)->where('locations.is_primary', true)
|
||||
$publicLocations = app(PublicBusinessLocations::class)->primary()
|
||||
->leftJoin('geo_locations as province', 'province.id', '=', 'l.province_id')
|
||||
->leftJoin('geo_locations as district', 'district.id', '=', 'l.district_id')
|
||||
->leftJoin('geo_locations as locality', 'locality.id', '=', 'l.locality_id')
|
||||
->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at')
|
||||
->select('locations.existing_business_id', 'province.name as province')
|
||||
->selectRaw("CASE WHEN locations.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
|
||||
->select('l.existing_business_id', 'l.updated_at as location_recorded_at', 'province.name as province', 'province.id as similar_province_id')
|
||||
->selectRaw(app(PublicBusinessLocations::class)->sourceProjection())
|
||||
->selectRaw("CASE WHEN l.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
|
||||
->selectRaw('NULL::text AS locality');
|
||||
|
||||
return ExistingBusiness::query()->published()->with('sector:id,name,slug')
|
||||
@@ -127,6 +144,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
|
||||
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
|
||||
'existing_businesses.owner_user_id', 'existing_businesses.organization_id', 'existing_businesses.version_no', 'existing_businesses.expires_at', 'existing_businesses.status', 'existing_businesses.modality',
|
||||
'public_location.province', 'public_location.district', 'public_location.locality']);
|
||||
'public_location.province', 'public_location.district', 'public_location.locality', 'public_location.similar_province_id',
|
||||
'public_location.location_recorded_at', 'public_location.location_source_reference', 'public_location.location_source_date']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Support\PublicSitemapXml;
|
||||
use Generator;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class PublicSitemapController extends Controller
|
||||
{
|
||||
private const PAGE_SIZE = 1000;
|
||||
|
||||
public function index(PublicSitemapXml $xml): StreamedResponse
|
||||
{
|
||||
$base = $this->base();
|
||||
$pages = (int) ceil(Opportunity::published()->count() / self::PAGE_SIZE);
|
||||
$locations = (static function () use ($base, $pages): Generator {
|
||||
yield $base.'/sitemap/pages.xml';
|
||||
for ($page = 1; $page <= $pages; $page++) {
|
||||
yield $base.'/sitemap/opportunities/'.$page.'.xml';
|
||||
}
|
||||
})();
|
||||
|
||||
return $this->response($xml, $locations, true);
|
||||
}
|
||||
|
||||
public function pages(PublicSitemapXml $xml): StreamedResponse
|
||||
{
|
||||
$base = $this->base();
|
||||
$paths = ['/', '/oportunidades', '/sectores', '/como-investir', '/documentos', '/apoio', '/simulador-fiscal', '/politica-de-privacidade', '/termos-de-uso'];
|
||||
|
||||
return $this->response($xml, array_map(fn ($path) => $base.$path, $paths));
|
||||
}
|
||||
|
||||
public function opportunities(string $page, PublicSitemapXml $xml): StreamedResponse
|
||||
{
|
||||
$number = filter_var($page, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000000]]);
|
||||
abort_if($number === false, 404);
|
||||
$base = $this->base();
|
||||
$records = Opportunity::published()->orderBy('id')->offset(($number - 1) * self::PAGE_SIZE)->limit(self::PAGE_SIZE)->get(['slug']);
|
||||
abort_if($records->isEmpty(), 404);
|
||||
|
||||
return $this->response($xml, $records->map(fn ($record) => $base.'/oportunidades/'.rawurlencode($record->slug)));
|
||||
}
|
||||
|
||||
private function base(): string
|
||||
{
|
||||
$url = rtrim((string) config('app.url'), '/');
|
||||
$parts = parse_url($url);
|
||||
abort_unless(filter_var($url, FILTER_VALIDATE_URL) && is_array($parts)
|
||||
&& in_array($parts['scheme'] ?? null, ['http', 'https'], true)
|
||||
&& ! isset($parts['query']) && ! isset($parts['fragment']) && ! isset($parts['user']) && ! isset($parts['pass']), 503);
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
/** @param iterable<string> $locations */
|
||||
private function response(PublicSitemapXml $xml, iterable $locations, bool $index = false): StreamedResponse
|
||||
{
|
||||
return response()->stream(static function () use ($xml, $locations, $index): void {
|
||||
foreach ($xml->chunks($locations, $index) as $chunk) {
|
||||
echo $chunk;
|
||||
}
|
||||
}, 200, ['Content-Type' => 'application/xml; charset=UTF-8', 'Cache-Control' => 'no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\OpportunityTechnicalSupport;
|
||||
use App\Services\TechnicalIncidentHandling;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class TechnicalSupportController extends Controller
|
||||
{
|
||||
public function index(Request $request, OpportunityTechnicalSupport $support): Response
|
||||
{
|
||||
$filters = $request->validate(['page' => ['nullable', 'integer', 'min:1'], 'status' => ['nullable', 'in:all,open,in_progress,resolved'], 'unread' => ['nullable', 'boolean']]);
|
||||
$status = $filters['status'] ?? 'all';
|
||||
$unread = $request->boolean('unread');
|
||||
$incidents = $support->queue($request->user(), $status, $unread);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return tap(Inertia::render('profiles/technical-support', ['actorId' => $request->user()->id, 'incidents' => $incidents, 'filters' => ['status' => $status, 'unread' => $unread]])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function show(Request $request, string $reference, TechnicalIncidentHandling $handling, OpportunityTechnicalSupport $support): Response
|
||||
{
|
||||
$filters = $request->validate(['history_page' => ['nullable', 'integer', 'min:1'], 'page' => ['nullable', 'integer', 'min:1'], 'status' => ['nullable', 'in:all,open,in_progress,resolved'], 'unread' => ['nullable', 'boolean']]);
|
||||
$data = $handling->detail($request->user(), $reference);
|
||||
Inertia::encryptHistory();
|
||||
|
||||
$query = array_filter(['page' => $request->integer('page') > 1 ? $request->integer('page') : null, 'status' => ($filters['status'] ?? 'all') !== 'all' ? $filters['status'] : null, 'unread' => $request->boolean('unread') ? 1 : null], fn ($v) => $v !== null);
|
||||
|
||||
return tap(Inertia::render('profiles/technical-incident', [...$data, 'notice' => $support->notice($request->user(), $reference), 'backUrl' => '/suporte-tecnico/incidentes'.($query !== [] ? '?'.http_build_query($query) : '')])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
|
||||
public function decide(Request $request, string $reference, TechnicalIncidentHandling $handling): JsonResponse
|
||||
{
|
||||
return response()->json($handling->decide($request->user(), $reference, $request->all()))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function consulted(Request $request, string $reference, OpportunityTechnicalSupport $support): JsonResponse
|
||||
{
|
||||
return response()->json($support->markConsulted($request->user(), $reference))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@ use App\Models\InvestmentSubmission;
|
||||
use App\Models\User;
|
||||
use App\Services\Ai\InvestorGuidance;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\DeskAttachments;
|
||||
use App\Services\DeskPaymentEvidence;
|
||||
use App\Services\DeskServiceAvailability;
|
||||
use App\Services\InstitutionalLinkMonitor;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestorContextConsumers;
|
||||
@@ -27,6 +30,7 @@ use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
class VirtualDeskController extends Controller
|
||||
{
|
||||
@@ -34,7 +38,7 @@ class VirtualDeskController extends Controller
|
||||
{
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:120', 'theme' => 'nullable|string|max:80', 'profile' => 'nullable|string|max:100']);
|
||||
$installed = $desk->installed();
|
||||
$services = $installed ? DB::table('desk_service_versions')->where('status', 'published')->orderBy('code')->orderByDesc('version')->get()->unique('code')->map(fn ($s) => ['id' => $s->id, 'version' => $s->version, 'definition' => json_decode($s->definition, true), 'source' => json_decode($s->source, true)])->values() : collect();
|
||||
$services = $installed ? app(DeskServiceAvailability::class)->current()->get()->map(fn ($s) => ['id' => $s->id, 'version' => $s->version, 'effective_from' => $s->effective_from ?? null, 'definition' => json_decode($s->definition, true), 'source' => json_decode($s->source, true)])->values() : collect();
|
||||
$services = $services->filter(fn ($s) => (! ($filters['q'] ?? '') || str_contains(mb_strtolower(json_encode($s['definition'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), mb_strtolower($filters['q'])))
|
||||
&& (! ($filters['theme'] ?? '') || $s['definition']['theme'] === $filters['theme']) && (! ($filters['profile'] ?? '') || $s['definition']['profile'] === $filters['profile']))->values();
|
||||
$page = max(1, (int) $request->query('page', 1));
|
||||
@@ -49,7 +53,7 @@ class VirtualDeskController extends Controller
|
||||
$actor = $request->user();
|
||||
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
|
||||
$cases = DB::table('desk_cases')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->orderByDesc('updated_at')->get(['id', 'title', 'version', 'updated_at']);
|
||||
$queue = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')->whereNotIn('r.status', ['draft', 'cancelled'])->when(! $actor->can('manage-portal'), fn ($q) => $q->where('r.analyst_id', $actor->id))
|
||||
$queue = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')->whereNull('c.closed_at')->whereNotIn('r.status', ['draft', 'cancelled', 'closed'])->when(! $actor->can('manage-portal'), fn ($q) => $q->where('r.analyst_id', $actor->id))
|
||||
->orderByRaw('r.due_at ASC NULLS LAST')->get(['r.id', 'r.protocol', 'r.status', 'r.version', 'r.analyst_id', 'r.due_at', 'c.title']);
|
||||
$data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(),
|
||||
'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']),
|
||||
@@ -74,6 +78,23 @@ class VirtualDeskController extends Controller
|
||||
}
|
||||
|
||||
public function showCase(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response
|
||||
{
|
||||
$data = $this->caseViewData($request, $id, $desk);
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/case', $data);
|
||||
}
|
||||
|
||||
public function preDossier(Request $request, string $id, VirtualDesk $desk): \Illuminate\Http\Response
|
||||
{
|
||||
return response()->view('desk.pre-dossier', $this->caseViewData($request, $id, $desk), 200, [
|
||||
'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
|
||||
/** Same authorised projection for the workspace and its preparation document.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function caseViewData(Request $request, string $id, VirtualDesk $desk): array
|
||||
{
|
||||
$case = $desk->case($request->user(), $id);
|
||||
$owner = $desk->owns($request->user(), $case, false);
|
||||
@@ -86,14 +107,15 @@ class VirtualDeskController extends Controller
|
||||
'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at')
|
||||
->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id))
|
||||
->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null,
|
||||
'owner' => $owner, 'canWrite' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'),
|
||||
'owner' => $owner, 'canWrite' => ! $case->closed_at && $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'),
|
||||
'canChangeState' => (int) $case->user_id === $request->user()->id && $desk->owns($request->user(), $case), 'activity' => $owner ? $desk->caseActivity($case) : null,
|
||||
'requests' => DB::table('desk_requests')->where('case_id', $id)->when(! $owner && ! $request->user()->can('manage-portal'), fn ($q) => $q->where('analyst_id', $request->user()->id))->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'service_version_id', 'version']),
|
||||
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'version', 'definition'])->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'version' => $s->version]),
|
||||
'services' => app(DeskServiceAvailability::class)->current()->get()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'version' => $s->version, 'effective_from' => $s->effective_from ?? null]),
|
||||
'documents' => $this->documents($id, $request->user()), 'events' => $this->events($id, $desk, $request->user()), 'stepStates' => config('virtual-desk.step_states'), 'states' => config('virtual-desk.request_states'),
|
||||
'links' => DB::table('desk_institutional_links')->get()->map(fn ($link) => [...(array) $link, 'monitor' => app(InstitutionalLinkMonitor::class)->status($link)]), 'source' => config('virtual-desk.source'), 'support' => config('portal.support'),
|
||||
'guidance' => app(InvestorGuidance::class)->installed() ? app(InvestorGuidance::class)->view($request->user(), $id) : null];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/case', $data);
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return Collection<int,\stdClass> */
|
||||
@@ -101,7 +123,46 @@ class VirtualDeskController extends Controller
|
||||
{
|
||||
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case)->whereNull('d.deleted_at')
|
||||
->when(! app(VirtualDesk::class)->owns($actor, app(VirtualDesk::class)->case($actor, $case), false) && ! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
|
||||
->get(['l.id', 'l.document_id', 'l.request_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.sha256']);
|
||||
->get(['l.id', 'l.document_id', 'l.request_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.sha256', 'd.media_type', 'd.size_bytes', 'd.version_no']);
|
||||
}
|
||||
|
||||
public function availableDocuments(Request $request, string $id, VirtualDesk $desk): JsonResponse
|
||||
{
|
||||
$case = $desk->case($request->user(), $id, true);
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado.');
|
||||
$data = $request->validate(['q' => 'nullable|string|max:120', 'offset' => 'nullable|integer|min:0']);
|
||||
$offset = (int) ($data['offset'] ?? 0);
|
||||
$actor = $request->user();
|
||||
// Match the existing reuse authority: this dossier, own personal dossiers, or own uploads.
|
||||
// A document's uploader does not inherit another dossier's reference or private context.
|
||||
$sources = DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')
|
||||
->where(fn ($q) => $q->where('c.id', $id)->orWhere(fn ($p) => $p->where('c.user_id', $actor->id)->whereNull('c.organization_id')))
|
||||
->select(['l.id', 'l.document_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'c.title as origin_label']);
|
||||
$query = DB::table('documents as d')->leftJoinSub($sources, 's', fn ($q) => $q->on('s.document_id', '=', 'd.id'))
|
||||
->whereNull('d.deleted_at')->where(fn ($q) => $q->where('d.uploaded_by', $actor->id)->orWhereNotNull('s.id'));
|
||||
$search = trim($data['q'] ?? '');
|
||||
if ($search !== '') {
|
||||
$like = '%'.addcslashes($search, '\\%_').'%';
|
||||
$query->where(fn ($q) => $q->where('d.file_name', 'ilike', $like)->orWhere('s.source_reference', 'ilike', $like)->orWhere('s.origin_label', 'ilike', $like));
|
||||
}
|
||||
$rows = $query->orderBy('d.file_name')->orderBy('d.id')->orderBy('s.id')->offset($offset)->limit(26)
|
||||
->get(['d.id as document_id', 'd.file_name', 'd.version_no', 'd.status', 'd.malware_scan_status', 'd.media_type', 'd.size_bytes', 'd.source_system', 's.id', 's.category', 's.stage', 's.source_reference', 's.valid_until', 's.origin_label']);
|
||||
$items = $rows->take(25)->filter(function ($document) {
|
||||
try {
|
||||
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment((object) [...(array) $document, 'id' => $document->document_id]);
|
||||
|
||||
return true;
|
||||
} catch (HttpExceptionInterface $exception) {
|
||||
if ($exception->getStatusCode() !== 403) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
})->map(fn ($document) => Arr::except((array) $document, ['source_system']))->values();
|
||||
$this->auditRead($request, 'desk_cases', $id);
|
||||
|
||||
return response()->json(['documents' => $items, 'next_offset' => $rows->count() > 25 ? $offset + 25 : null], 200, ['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
|
||||
/** @return Collection<int,array{id:mixed,request_id:mixed,action:mixed,version:mixed,created_at:mixed,name:mixed,payload:array<string,mixed>}> */
|
||||
@@ -112,6 +173,13 @@ class VirtualDeskController extends Controller
|
||||
->orderBy('e.event_order')->get(['e.id', 'e.request_id', 'e.action', 'e.payload', 'e.version', 'e.created_at', 'u.name'])->map(fn ($e) => ['id' => $e->id, 'request_id' => $e->request_id, 'action' => $e->action, 'version' => $e->version, 'created_at' => $e->created_at, 'name' => $e->name, 'payload' => $desk->decode($e->payload)]);
|
||||
}
|
||||
|
||||
public function caseState(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$result = $desk->changeCaseState($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json($result) : back()->with('success', $result['replayed'] ? 'Operação já registada; o estado actual do dossier é apresentado.' : ($result['closed_at'] ? 'Dossier encerrado pelo dono. Os registos continuam disponíveis para consulta.' : 'Dossier reaberto pelo dono. Mantêm-se os estados próprios dos pedidos e das tarefas.'));
|
||||
}
|
||||
|
||||
public function stage(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$case = $desk->stage($request->user(), $id, $request->all());
|
||||
@@ -147,17 +215,21 @@ class VirtualDeskController extends Controller
|
||||
}
|
||||
}
|
||||
$this->auditRead($request, 'desk_requests', $id);
|
||||
$caseDocuments = $this->documents($case->id, $request->user());
|
||||
$paymentEvidence = app(DeskPaymentEvidence::class)->forRequest($id);
|
||||
$data = ['boundContextRevision' => app(InvestorContextConsumers::class)->requestRevision($row), 'countries' => app(CountryCatalogue::class)->all(), 'toolPrefill' => $desk->requestToolPrefill($request->user(), $row), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
|
||||
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
|
||||
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
|
||||
'serviceEffectiveFrom' => DB::table('desk_service_versions')->where('id', $row->service_version_id)->selectRaw(app(DeskServiceAvailability::class)->dateProjection())->first()->effective_from,
|
||||
'owner' => $desk->owns($request->user(), $case), 'manager' => app(ScopedPortalAdministration::class)->deskDecision($request->user(), $row), 'analyst' => (int) $row->analyst_id === $request->user()->id,
|
||||
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
|
||||
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
||||
'operationsEditable' => ! $case->closed_at && ! in_array($row->status, ['closed', 'cancelled'], true), 'fieldsEditable' => ! $case->closed_at && in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => $case->closed_at ? [] : config('virtual-desk.transitions.'.$row->status, []), 'returnReasons' => config('product-metrics.return_reasons'),
|
||||
'findings' => $desk->findings($payload, $definition), 'ai' => config('virtual-desk.ai'), 'documents' => $caseDocuments->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
||||
'reusableDocuments' => $desk->owns($request->user(), $case) && ! $case->closed_at ? $caseDocuments->values() : [],
|
||||
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
|
||||
'kind' => $messageKinds[$m->id] ?? 'historical_unclassified']),
|
||||
'events' => $this->events($case->id, $desk, $request->user())->filter(fn ($e) => $e['request_id'] === $id)->values(),
|
||||
'revisions' => DB::table('desk_revisions')->where('request_id', $id)->orderByDesc('version')->get(['version', 'snapshot', 'created_at'])->map(fn ($r) => [...(array) $r, 'snapshot' => $desk->decode($r->snapshot)]),
|
||||
'payments' => DB::table('desk_payments')->where('request_id', $id)->get(),
|
||||
'payments' => DB::table('desk_payments')->where('request_id', $id)->get()->map(fn ($payment) => [...(array) $payment, 'document_evidence' => $paymentEvidence[$payment->id] ?? null]),
|
||||
'analysts' => $request->user()->can('manage-portal') ? User::orderBy('name')->get(['id', 'name']) : [],
|
||||
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type'])];
|
||||
|
||||
@@ -182,7 +254,9 @@ class VirtualDeskController extends Controller
|
||||
{
|
||||
abort_unless(app(ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||
// Triage projection deliberately excludes payloads, documents, investor identity and case titles.
|
||||
$data = ['requests' => DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled', 'closed'])->orderBy('created_at')->get(['id', 'protocol', 'status', 'version', 'analyst_id', 'due_at']),
|
||||
$data = ['requests' => DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled', 'closed'])
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('desk_cases')->whereColumn('desk_cases.id', 'desk_requests.case_id')->whereNull('desk_cases.closed_at'))
|
||||
->orderBy('created_at')->get(['id', 'protocol', 'status', 'version', 'analyst_id', 'due_at']),
|
||||
'analysts' => User::whereNotNull('email_verified_at')->orderBy('name')->get(['id', 'name'])];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/desk-assignments', $data);
|
||||
@@ -195,8 +269,9 @@ class VirtualDeskController extends Controller
|
||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||
$row = DB::table('desk_requests')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
$case = DB::table('desk_cases')->where('id', $row->case_id)->first();
|
||||
$case = DB::table('desk_cases')->where('id', $row->case_id)->lockForUpdate()->first();
|
||||
abort_unless($case !== null, 404);
|
||||
$desk->assertOpen($case);
|
||||
if ((int) $row->version !== (int) $data['version']) {
|
||||
throw ValidationException::withMessages(['version' => 'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
|
||||
}
|
||||
@@ -218,7 +293,8 @@ class VirtualDeskController extends Controller
|
||||
$data = $request->validate(['body' => 'required|string|min:1|max:10000', 'client_key' => 'required|uuid']);
|
||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, false, true);
|
||||
$case = $desk->case($request->user(), $row->case_id);
|
||||
$case = $desk->case($request->user(), $row->case_id, false, true);
|
||||
$desk->assertOpen($case);
|
||||
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409, 'Pedido encerrado.');
|
||||
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
|
||||
$existing = DB::table('desk_messages')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('client_key', $data['client_key'])->first();
|
||||
@@ -245,7 +321,10 @@ class VirtualDeskController extends Controller
|
||||
$this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded');
|
||||
|
||||
if ($format === 'html') {
|
||||
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $desk->definition($row)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
$definition = $desk->definition($row);
|
||||
|
||||
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $definition,
|
||||
'applicableFields' => $desk->applicableFields($snapshot['payload'] ?? [], $definition)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
return response()->streamDownload(function () use ($row, $snapshot) {
|
||||
@@ -257,49 +336,90 @@ class VirtualDeskController extends Controller
|
||||
public function attach(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer', 'file' => 'nullable|required_without:document_id|file|mimetypes:application/pdf,image/png,image/jpeg,text/plain|max:10240',
|
||||
'document_id' => 'nullable|required_without:file|uuid', 'category' => 'required|string|max:80', 'stage' => 'nullable|string|max:3', 'request_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'source_reference' => 'required|string|max:3000', 'consent' => 'accepted']);
|
||||
'document_id' => 'nullable|required_without:file|required_with:reuse_link_id|prohibits:file|uuid', 'reuse_link_id' => 'nullable|uuid|prohibits:file', 'category' => 'nullable|required_without:field_key|string|max:80', 'field_key' => 'nullable|string|max:64',
|
||||
'stage' => 'nullable|string|max:3', 'request_id' => 'nullable|required_with:field_key|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'source_reference' => 'nullable|required_without:document_id|string|max:3000', 'consent' => 'accepted']);
|
||||
$key = null;
|
||||
$newId = null;
|
||||
$linkId = null;
|
||||
$reusedLink = false;
|
||||
try {
|
||||
DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId) {
|
||||
DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId, &$linkId, &$reusedLink) {
|
||||
$row = ($data['request_id'] ?? null) ? $desk->request($request->user(), $data['request_id'], true, true) : null;
|
||||
$case = $desk->case($request->user(), $id, true, true);
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado.');
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409);
|
||||
if ($data['stage'] ?? null) {
|
||||
abort_unless(array_key_exists($data['stage'], config('virtual-desk.steps')), 422);
|
||||
}
|
||||
if ($data['request_id'] ?? null) {
|
||||
$row = $desk->request($request->user(), $data['request_id'], true, true);
|
||||
if ($row) {
|
||||
abort_unless($row->case_id === $id && in_array($row->status, ['draft', 'returned'], true), 409, 'Anexos de pedidos submetidos são imutáveis; use a devolução para corrigir.');
|
||||
}
|
||||
abort_if(DB::table('desk_documents')->where('case_id', $id)->count() >= 100, 422, 'Limite de anexos do dossier atingido.');
|
||||
if ($request->hasFile('file')) {
|
||||
$file = $request->file('file');
|
||||
$hash = hash_file('sha256', $file->getRealPath());
|
||||
$duplicate = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.sha256', $hash)->first();
|
||||
if ($duplicate) {
|
||||
return;
|
||||
$definition = $row ? $desk->definition($row) : [];
|
||||
$field = ($data['field_key'] ?? null) ? app(DeskAttachments::class)->field($definition, $data['field_key']) : null;
|
||||
if ($field) {
|
||||
if (isset($data['stage']) && $data['stage'] !== $definition['stage']) {
|
||||
throw ValidationException::withMessages(['stage' => 'A utilização nesta pergunta pertence à etapa do pedido; a origem do documento é conservada separadamente.']);
|
||||
}
|
||||
$newId = (string) Str::uuid();
|
||||
$key = $file->storeAs('virtual-desk/'.$id, $newId, 'local');
|
||||
abort_unless(is_string($key) && $key !== '', 500);
|
||||
DB::table('documents')->insert(['id' => $newId, 'source_system' => 'virtual-desk', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $key,
|
||||
'sha256' => $hash, 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id, 'status' => 'quarantined', 'data_classification' => 'confidential']);
|
||||
$documentId = $newId;
|
||||
} else {
|
||||
$documentId = $data['document_id'];
|
||||
$document = DB::table('documents')->where('id', $documentId)->whereNull('deleted_at')->first();
|
||||
abort_unless($document !== null, 404);
|
||||
$owned = (int) $document->uploaded_by === $request->user()->id || DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $documentId)->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')->exists();
|
||||
abort_unless($owned, 403, 'Não há autorização para reutilizar este documento.');
|
||||
if (DB::table('desk_documents')->where('case_id', $id)->where('document_id', $documentId)->exists()) {
|
||||
return;
|
||||
abort_unless(app(DeskAttachments::class)->scopedLinksInstalled(), 409, 'Instale a actualização dos vínculos documentais para este formulário.');
|
||||
if ($row->status === 'returned' && ! in_array($data['field_key'], json_decode($row->editable_fields ?? '[]', true), true)) {
|
||||
throw ValidationException::withMessages(['field_key' => 'Esta pergunta não está autorizada para correcção.']);
|
||||
}
|
||||
}
|
||||
DB::table('desk_documents')->insert(['id' => (string) Str::uuid(), 'case_id' => $id, 'document_id' => $documentId, 'request_id' => $data['request_id'] ?? null,
|
||||
'category' => $data['category'], 'stage' => $data['stage'] ?? null, 'valid_until' => $data['valid_until'] ?? null, 'source_reference' => $data['source_reference'], 'linked_by' => $request->user()->id]);
|
||||
$document = null;
|
||||
if ($request->hasFile('file')) {
|
||||
$file = $request->file('file');
|
||||
if ($field) {
|
||||
app(DeskAttachments::class)->checkMetadata((object) ['media_type' => $file->getMimeType(), 'size_bytes' => $file->getSize()], $field, 'file');
|
||||
}
|
||||
$hash = hash_file('sha256', $file->getRealPath());
|
||||
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->whereNull('d.deleted_at')->where('d.sha256', $hash)->first(['d.*']);
|
||||
if (! $document) {
|
||||
abort_if(DB::table('desk_documents')->where('case_id', $id)->distinct()->count('document_id') >= 100, 422, 'Limite de ficheiros distintos do dossier atingido.');
|
||||
$newId = (string) Str::uuid();
|
||||
$key = $file->storeAs('virtual-desk/'.$id, $newId, 'local');
|
||||
abort_unless(is_string($key) && $key !== '', 500);
|
||||
DB::table('documents')->insert(['id' => $newId, 'source_system' => 'virtual-desk', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $key,
|
||||
'sha256' => $hash, 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id, 'status' => 'quarantined', 'data_classification' => 'confidential']);
|
||||
$document = DB::table('documents')->where('id', $newId)->firstOrFail();
|
||||
}
|
||||
} else {
|
||||
$document = DB::table('documents')->where('id', $data['document_id'])->whereNull('deleted_at')->first();
|
||||
abort_unless($document !== null, 404);
|
||||
$owned = (int) $document->uploaded_by === $request->user()->id || DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists()
|
||||
|| DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $document->id)->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')->exists();
|
||||
abort_unless($owned, 403, 'Não há autorização para reutilizar este documento.');
|
||||
}
|
||||
if ($field) {
|
||||
app(DeskAttachments::class)->checkMetadata($document, $field, 'document_id', true);
|
||||
}
|
||||
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment($document);
|
||||
$existing = DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)
|
||||
->where(fn ($q) => ($data['request_id'] ?? null) ? $q->whereNull('request_id')->orWhere('request_id', $data['request_id']) : $q->whereNull('request_id'))->orderByRaw('request_id IS NULL DESC')->first();
|
||||
if ($existing) {
|
||||
$linkId = $existing->id;
|
||||
$reusedLink = true;
|
||||
|
||||
return;
|
||||
}
|
||||
if (! app(DeskAttachments::class)->scopedLinksInstalled() && DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists()) {
|
||||
throw ValidationException::withMessages(['document_id' => 'Instale a actualização dos vínculos para reutilizar o ficheiro noutro pedido, preservando o âmbito anterior.']);
|
||||
}
|
||||
$inCase = DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists();
|
||||
abort_if(! $inCase && DB::table('desk_documents')->where('case_id', $id)->distinct()->count('document_id') >= 100, 422, 'Limite de ficheiros distintos do dossier atingido.');
|
||||
$sourceLink = DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $document->id)
|
||||
->where(fn ($q) => $q->where('l.case_id', $id)->orWhere(fn ($p) => $p->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')))
|
||||
->when($data['reuse_link_id'] ?? null, fn ($q, $sourceId) => $q->where('l.id', $sourceId))->orderBy('l.created_at')->orderBy('l.id')->first(['l.*']);
|
||||
abort_if(($data['reuse_link_id'] ?? null) && ! $sourceLink, 403, 'Não há autorização para reutilizar esta referência documental.');
|
||||
$source = $data['source_reference'] ?? $sourceLink?->source_reference;
|
||||
if (! is_string($source) || trim($source) === '') {
|
||||
throw ValidationException::withMessages(['source_reference' => 'Indique a proveniência deste documento; não existe uma referência autorizada para reutilizar.']);
|
||||
}
|
||||
$linkId = (string) Str::uuid();
|
||||
DB::table('desk_documents')->insert(['id' => $linkId, 'case_id' => $id, 'document_id' => $document->id, 'request_id' => $data['request_id'] ?? null,
|
||||
'category' => $field ? Str::limit($field['label'], 80, '') : $data['category'], 'stage' => $data['stage'] ?? ($field ? $definition['stage'] : $sourceLink?->stage), 'valid_until' => array_key_exists('valid_until', $data) ? $data['valid_until'] : $sourceLink?->valid_until, 'source_reference' => $source, 'linked_by' => $request->user()->id]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event(DB::table('desk_cases')->where('id', $id)->first(), $request->user(), 'document_linked', ['document_id' => $documentId, 'source' => $data['source_reference'], 'consent' => true]);
|
||||
$desk->event(DB::table('desk_cases')->where('id', $id)->first(), $request->user(), 'document_linked', ['document_id' => $document->id, 'link_id' => $linkId, 'source' => $source, 'consent' => true, 'field_key' => $data['field_key'] ?? null, 'source_link_id' => $sourceLink?->id,
|
||||
'reused_source' => $sourceLink ? ['source_reference' => $sourceLink->source_reference, 'category' => $sourceLink->category, 'stage' => $sourceLink->stage, 'valid_until' => $sourceLink->valid_until, 'document_id' => $document->id, 'version_no' => $document->version_no, 'sha256' => trim($document->sha256)] : null], $row);
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
if ($key) {
|
||||
@@ -310,7 +430,10 @@ class VirtualDeskController extends Controller
|
||||
ScanDocumentForMalware::dispatch($newId)->afterCommit();
|
||||
}
|
||||
|
||||
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Documento privado associado; consulte o estado da análise.');
|
||||
$available = $this->documents($id, $request->user());
|
||||
|
||||
return $request->expectsJson() ? response()->json(['ok' => true, 'link_id' => $linkId, 'reused_link' => $reusedLink, 'case_version' => (int) DB::table('desk_cases')->where('id', $id)->value('version'),
|
||||
'documents' => $available->filter(fn ($d) => ! ($data['request_id'] ?? null) || ! $d->request_id || $d->request_id === $data['request_id'])->values(), 'reusable_documents' => $desk->owns($request->user(), $desk->case($request->user(), $id)) ? $available->values() : []]) : back()->with('success', $reusedLink ? 'Este documento já estava associado; conservou-se a referência registada.' : 'Documento privado associado; consulte o estado da análise.');
|
||||
}
|
||||
|
||||
public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse|\Illuminate\Http\Response
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\DeskServiceAvailability;
|
||||
use App\Services\DeskServiceEditor;
|
||||
use App\Services\VirtualDeskInstallation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
@@ -79,19 +81,22 @@ class VirtualDeskInstallationController extends Controller
|
||||
DB::select('select pg_advisory_xact_lock(261008, 2)');
|
||||
$definition = config('virtual-desk.services.'.$data['code']);
|
||||
$existing = DB::table('desk_service_versions')->where('code', $data['code'])->orderByDesc('version')->first();
|
||||
if ($existing && $existing->status === 'published' && json_decode($existing->definition, true) === $definition) {
|
||||
if ($existing && $existing->status === 'published' && app(DeskServiceEditor::class)->sameDefinition(json_decode($existing->definition, true, 512, JSON_THROW_ON_ERROR), $definition)) {
|
||||
return $existing;
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$effective = app(DeskServiceAvailability::class)->scheduled() ? now()->toDateString() : null;
|
||||
DB::table('desk_service_versions')->insert(['id' => $id, 'code' => $data['code'], 'version' => ($existing->version ?? 0) + 1, 'status' => 'published',
|
||||
...($effective ? ['effective_from' => $effective] : []),
|
||||
'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $request->user()->id,
|
||||
'published_by' => $request->user()->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $request->user()->id,
|
||||
'action' => 'internal_service_published', 'after_data' => json_encode(['code' => $data['code'], 'nature' => 'digital_preparation_not_official_form'])]);
|
||||
'action' => 'internal_service_published', 'after_data' => json_encode(['code' => $data['code'], 'nature' => 'digital_preparation_not_official_form', 'effective_from' => $effective])]);
|
||||
|
||||
return DB::table('desk_service_versions')->where('id', $id)->first();
|
||||
});
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $row->id], 201) : back()->with('success', 'Serviço de preparação interna publicado.');
|
||||
return $request->expectsJson() ? response()->json(['id' => $row->id, 'effective_from' => $row->effective_from ?? null], 201)
|
||||
: back()->with('success', 'Serviço de preparação interna publicado'.(($row->effective_from ?? null) ? ' com entrada em vigor em '.$row->effective_from : '').'.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\Ai\InvestorGuidanceEvidence;
|
||||
use App\Services\DeskPaymentEvidence;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Manual operations use the same requests, documents and encrypted audit history. */
|
||||
class VirtualDeskOperationsController extends Controller
|
||||
@@ -25,16 +27,19 @@ class VirtualDeskOperationsController extends Controller
|
||||
abort_unless(! $desk->owns($request->user(), $case, false) && ($request->user()->can('manage-portal') || ($row && (int) $row->analyst_id === $request->user()->id)), 403);
|
||||
}
|
||||
|
||||
private function cleanDocument(string $caseId, string $documentId, ?string $requestId): \stdClass
|
||||
private function cleanDocument(string $caseId, string $documentId, ?string $requestId, ?string $linkId = null): \stdClass
|
||||
{
|
||||
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.case_id', $caseId)->where('d.id', $documentId)->whereNull('d.deleted_at')
|
||||
->when($linkId, fn ($q) => $q->where('l.id', $linkId))
|
||||
->where(fn ($q) => $q->whereNull('l.request_id')->when($requestId, fn ($p) => $p->orWhere('l.request_id', $requestId)))
|
||||
->first(['d.*', 'l.id as link_id']);
|
||||
abort_unless($doc !== null && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento indisponível para conferência: verifique autorização, integridade e análise antimalware.');
|
||||
$path = realpath(Storage::disk('local')->path($doc->storage_key));
|
||||
$root = realpath(Storage::disk('local')->path(''));
|
||||
abort_unless($path && $root && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path) && is_string($hash = hash_file('sha256', $path)) && hash_equals(trim($doc->sha256), $hash), 422, 'O ficheiro original ou a sua integridade não pôde ser confirmado.');
|
||||
try {
|
||||
app(VerifiedDocumentBinary::class)->respond($doc);
|
||||
} catch (HttpExceptionInterface) {
|
||||
abort(422, 'O original, a sua autorização ou integridade não pôde ser confirmado.');
|
||||
}
|
||||
|
||||
return $doc;
|
||||
}
|
||||
@@ -43,15 +48,16 @@ class VirtualDeskOperationsController extends Controller
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'request_id' => 'nullable|uuid', 'outcome' => 'required|in:internal_verified,internal_issue,contradiction_identified', 'what_checked' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000', 'supports' => 'nullable|array|max:4', 'supports.*' => ['string', Rule::in(InvestorGuidanceEvidence::FIELDS)]]);
|
||||
DB::transaction(function () use ($request, $id, $document, $desk, $data) {
|
||||
$case = $desk->case($request->user(), $id, false, true);
|
||||
abort_unless(! $case->closed_at && (int) $case->version === (int) $data['version'], 409);
|
||||
$desk->case($request->user(), $id);
|
||||
$link = DB::table('desk_documents')->where('case_id', $id)->where('id', $document)->first();
|
||||
abort_unless($link !== null, 404);
|
||||
$requestId = $link->request_id ?: ($data['request_id'] ?? null);
|
||||
$row = $requestId ? $desk->request($request->user(), $requestId, false, true) : null;
|
||||
$case = $desk->case($request->user(), $id, false, true);
|
||||
abort_unless(! $case->closed_at && (int) $case->version === (int) $data['version'], 409);
|
||||
abort_if($row && $row->case_id !== $id, 422);
|
||||
$this->reviewer($request, $desk, $case, $row);
|
||||
$doc = $this->cleanDocument($id, $link->document_id, $requestId);
|
||||
$doc = $this->cleanDocument($id, $link->document_id, $requestId, $link->id);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event(DB::table('desk_cases')->where('id', $id)->firstOrFail(), $request->user(), 'document_reviewed', [
|
||||
...$data, 'document_id' => $doc->id, 'link_id' => $link->id, 'sha256' => trim($doc->sha256), 'document_version' => (int) $doc->version_no, 'reviewer_id' => $request->user()->id,
|
||||
@@ -64,26 +70,58 @@ class VirtualDeskOperationsController extends Controller
|
||||
|
||||
public function payment(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['reference' => 'required|string|max:255', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/', 'numeric', 'gt:0'], 'currency' => 'required|in:MZN,USD,EUR', 'source_reference' => 'required|string|min:3|max:3000', 'document_id' => 'nullable|uuid', 'consent' => 'accepted']);
|
||||
$data = $request->validate(['reference' => 'required|string|max:255', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/', 'numeric', 'gt:0'], 'currency' => 'required|in:MZN,USD,EUR', 'source_reference' => 'required|string|min:3|max:3000', 'document_id' => 'nullable|uuid', 'document_link_id' => 'nullable|uuid', 'consent' => 'accepted']);
|
||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, true, true);
|
||||
$case = $desk->case($request->user(), $row->case_id);
|
||||
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
if ($data['document_id'] ?? null) {
|
||||
abort_unless(DB::table('desk_documents')->where('case_id', $case->id)->where('document_id', $data['document_id'])->where(fn ($q) => $q->whereNull('request_id')->orWhere('request_id', $id))->exists(), 422);
|
||||
}
|
||||
$case = $desk->case($request->user(), $row->case_id, true, true);
|
||||
abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
$evidence = app(DeskPaymentEvidence::class)->snapshot($case->id, $id, $data);
|
||||
// References are supplied by the investor; no bank reference or fee is generated.
|
||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['virtual-desk-payment:'.$data['reference']]);
|
||||
$existing = DB::table('desk_payments')->where('reference', $data['reference'])->first();
|
||||
if ($existing) {
|
||||
$parts = explode('.', (string) $data['amount']);
|
||||
$amount = (ltrim($parts[0], '0') ?: '0').'.'.str_pad($parts[1] ?? '', 2, '0');
|
||||
abort_unless($existing->request_id === $id && (string) $existing->amount === $amount && $existing->currency === $data['currency'] && $existing->source_reference === $data['source_reference'] && $existing->document_id === ($data['document_id'] ?? null), 409);
|
||||
$saved = app(DeskPaymentEvidence::class)->forRequest($id)[$existing->id] ?? null;
|
||||
abort_unless($existing->request_id === $id && (string) $existing->amount === $amount && $existing->currency === $data['currency'] && $existing->source_reference === $data['source_reference'] && $existing->document_id === ($evidence['document_id'] ?? null)
|
||||
&& (! ($data['document_link_id'] ?? null) || ($saved['link_id'] ?? null) === $data['document_link_id']), 409);
|
||||
|
||||
return;
|
||||
}
|
||||
$payment = (string) Str::uuid();
|
||||
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $id, 'reference' => $data['reference'], 'amount' => $data['amount'], 'currency' => $data['currency'], 'source_reference' => $data['source_reference'], 'document_id' => $data['document_id'] ?? null, 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]);
|
||||
$desk->event($case, $request->user(), 'payment_declared', ['payment_id' => $payment, 'consent' => true, 'scope' => 'manual_declaration_no_bank_confirmation'], $row);
|
||||
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $id, 'reference' => $data['reference'], 'amount' => $data['amount'], 'currency' => $data['currency'], 'source_reference' => $data['source_reference'], 'document_id' => $evidence['document_id'] ?? null, 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]);
|
||||
$desk->event($case, $request->user(), 'payment_declared', ['payment_id' => $payment, 'payment_version' => 1, 'document_evidence' => $evidence, 'consent' => true, 'scope' => 'manual_declaration_no_bank_confirmation'], $row);
|
||||
});
|
||||
|
||||
return $this->result($request);
|
||||
}
|
||||
|
||||
public function paymentDocument(Request $request, string $id, string $payment, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'document_link_id' => 'required|uuid', 'reason' => 'required|string|min:3|max:3000', 'consent' => 'accepted', 'client_key' => 'required|uuid']);
|
||||
$data['version'] = (int) $data['version'];
|
||||
$data['consent'] = true;
|
||||
DB::transaction(function () use ($request, $id, $payment, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, true, true);
|
||||
$case = $desk->case($request->user(), $row->case_id, true, true);
|
||||
abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
$record = DB::table('desk_payments')->where('id', $payment)->where('request_id', $id)->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'payment_document_linked')->get(['payload']) as $event) {
|
||||
$saved = $desk->decode($event->payload);
|
||||
if (($saved['client_key'] ?? null) === $data['client_key']) {
|
||||
abort_unless(($saved['payment_id'] ?? null) === $payment && ($saved['operation'] ?? null) === $data, 409, 'A operação já foi utilizada com outros dados. Inicie uma nova associação.');
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
abort_unless((int) $record->version === (int) $data['version'] && in_array($record->status, ['pending', 'internal_issue'], true), 409, 'O registo mudou ou já está conferido. Actualize antes de associar outro comprovativo.');
|
||||
$evidence = app(DeskPaymentEvidence::class)->snapshot($case->id, $id, $data);
|
||||
abort_unless($evidence !== null, 422);
|
||||
$previous = app(DeskPaymentEvidence::class)->forRequest($id)[$payment] ?? null;
|
||||
DB::table('desk_payments')->where('id', $payment)->update(['document_id' => $evidence['document_id'], 'status' => 'pending', 'reason' => null, 'verified_by' => null, 'version' => $record->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($case, $request->user(), 'payment_document_linked', ['payment_id' => $payment, 'payment_version' => $record->version + 1, 'previous_document_id' => $record->document_id, 'previous_document_evidence' => $previous,
|
||||
'document_evidence' => $evidence, 'client_key' => $data['client_key'], 'operation' => $data, 'reason' => $data['reason'], 'consent' => true, 'scope' => 'documentary_correction_no_amount_change_or_payment_confirmation'], $row);
|
||||
});
|
||||
|
||||
return $this->result($request);
|
||||
@@ -94,19 +132,21 @@ class VirtualDeskOperationsController extends Controller
|
||||
$data = $request->validate(['version' => 'required|integer|min:1', 'status' => 'required|in:internal_verified,internal_issue', 'reason' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000']);
|
||||
DB::transaction(function () use ($request, $id, $payment, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, false, true);
|
||||
$case = $desk->case($request->user(), $row->case_id);
|
||||
$case = $desk->case($request->user(), $row->case_id, false, true);
|
||||
$this->reviewer($request, $desk, $case, $row);
|
||||
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
$record = DB::table('desk_payments')->where('request_id', $id)->where('id', $payment)->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
abort_unless((int) $record->version === (int) $data['version'], 409);
|
||||
$evidence = app(DeskPaymentEvidence::class)->forRequest($id)[$payment] ?? null;
|
||||
$doc = null;
|
||||
if ($data['status'] === 'internal_verified') {
|
||||
abort_unless($record->document_id, 422, 'A conferência exige um comprovativo autorizado.');
|
||||
$doc = $this->cleanDocument($case->id, $record->document_id, $id);
|
||||
$doc = $this->cleanDocument($case->id, $record->document_id, $id, $evidence['link_id'] ?? null);
|
||||
abort_if($evidence && ($evidence['document_id'] !== $doc->id || $evidence['document_version'] !== (int) $doc->version_no || ! hash_equals($evidence['sha256'], trim($doc->sha256))), 422, 'O original já não corresponde ao comprovativo associado. Registe a correcção antes de conferir.');
|
||||
}
|
||||
DB::table('desk_payments')->where('id', $payment)->update(['status' => $data['status'], 'reason' => $data['reason'], 'verified_by' => $request->user()->id, 'version' => $record->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($case, $request->user(), 'payment_reviewed', [...$data, 'payment_id' => $payment, 'document_id' => $doc?->id, 'sha256' => $doc ? trim($doc->sha256) : null, 'reviewer_id' => $request->user()->id, 'scope' => 'internal_proof_check_no_bank_confirmation'], $row);
|
||||
$desk->event($case, $request->user(), 'payment_reviewed', [...$data, 'payment_id' => $payment, 'payment_version' => $record->version + 1, 'document_id' => $record->document_id, 'document_evidence' => $evidence, 'sha256' => $doc ? trim($doc->sha256) : null, 'reviewer_id' => $request->user()->id, 'scope' => 'internal_proof_check_no_bank_confirmation'], $row);
|
||||
});
|
||||
|
||||
return $this->result($request);
|
||||
@@ -117,9 +157,9 @@ class VirtualDeskOperationsController extends Controller
|
||||
$data = $request->validate(['channel' => 'required|in:phone,email,sms,whatsapp,in_person', 'direction' => 'required|in:received,sent', 'occurred_at' => 'required|date|before_or_equal:now', 'summary' => 'required|string|min:3|max:5000', 'evidence' => 'required|string|min:3|max:3000', 'client_key' => 'required|uuid']);
|
||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||
$row = $desk->request($request->user(), $id, false, true);
|
||||
$case = $desk->case($request->user(), $row->case_id);
|
||||
$case = $desk->case($request->user(), $row->case_id, false, true);
|
||||
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
|
||||
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
|
||||
foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'manual_communication_recorded')->get(['payload']) as $event) {
|
||||
$saved = $desk->decode($event->payload);
|
||||
if (($saved['client_key'] ?? null) === $data['client_key']) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PublicSearchMetrics;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class CollectPublicSearchMetrics
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$response = $next($request);
|
||||
$candidate = $request->attributes->get(PublicSearchMetrics::ATTRIBUTE);
|
||||
$request->attributes->remove(PublicSearchMetrics::ATTRIBUTE);
|
||||
$prefetch = str_contains(strtolower($request->header('Purpose', '').' '.$request->header('Sec-Purpose', '')), 'prefetch') || $request->header('X-Inertia-Prefetch') === 'true';
|
||||
$privacySignal = $request->header('DNT') === '1' || $request->header('Sec-GPC') === '1';
|
||||
if ($request->isMethod('GET') && $response->getStatusCode() === 200 && ! $prefetch && ! $privacySignal && is_array($candidate) && isset($candidate['channel'], $candidate['empty']) && is_string($candidate['channel']) && is_bool($candidate['empty'])) {
|
||||
app(PublicSearchMetrics::class)->record($candidate['channel'], $candidate['empty']);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ final class EnsureScopedPortalAdministration
|
||||
'management/economic-references/lot-01', 'management/economic-references/lot-01/*',
|
||||
'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*',
|
||||
'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*',
|
||||
'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos',
|
||||
'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos', 'management/balcao/servicos/*',
|
||||
'management/balcao/fontes') || ($request->isMethod('GET') && $path === 'management/balcao-install');
|
||||
$fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*',
|
||||
'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*');
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Services\ContentManagement;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\OpportunityManagement;
|
||||
@@ -57,6 +58,7 @@ class HandleInertiaRequests extends Middleware
|
||||
...parent::share($request),
|
||||
'name' => config('app.name'),
|
||||
'procurementEnabled' => app(Procurement::class)->available(),
|
||||
'fundingEnabled' => app(FundingProgrammes::class)->installed(),
|
||||
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||
'contentManagementHref' => $contentManagementAccess !== [] ? '/gestao-conteudos' : null,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Services\ExistingBusinessClassification;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -24,6 +25,10 @@ class PublicBusinessOpportunityResource extends JsonResource
|
||||
'amount_max' => data_get($this->resource, 'amount_max'),
|
||||
'available_percentage' => data_get($this->resource, 'available_percentage'),
|
||||
'published_at' => data_get($this->resource, 'published_at'),
|
||||
'distance_km' => $this->resource->getAttribute('distance_km') !== null ? round((float) $this->resource->getAttribute('distance_km'), 1) : null,
|
||||
'location_recorded_at' => $this->resource->getAttribute('location_recorded_at') ? CarbonImmutable::parse($this->resource->getAttribute('location_recorded_at'))->toIso8601String() : null,
|
||||
'location_source_reference' => $this->resource->getAttribute('location_source_reference'),
|
||||
'location_source_date' => $this->resource->getAttribute('location_source_date'),
|
||||
'sector' => $this->whenLoaded('sector', fn () => data_get($this->resource, 'sector')?->only(['name', 'slug'])),
|
||||
'province' => $this->resource->getAttribute('province'),
|
||||
'district' => $this->resource->getAttribute('district'),
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Services\Malware\DocumentScanAttempts;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\OpportunityTechnicalIncidents;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
@@ -11,6 +13,7 @@ use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
@@ -25,7 +28,28 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
|
||||
public int $uniqueFor = 600;
|
||||
|
||||
public function __construct(public readonly string $documentId) {}
|
||||
public ?string $executionId = null;
|
||||
|
||||
/** @var array<string,mixed>|null */
|
||||
public ?array $opportunityContext = null;
|
||||
|
||||
/** @param array<string,mixed>|null $opportunityContext */
|
||||
public function __construct(public readonly string $documentId, ?array $opportunityContext = null)
|
||||
{
|
||||
$this->executionId = (string) Str::uuid();
|
||||
$this->opportunityContext = $opportunityContext;
|
||||
}
|
||||
|
||||
/** Queue UUID also supports payloads serialized before executionId existed. */
|
||||
public function runIdentifier(): string
|
||||
{
|
||||
if ($this->executionId !== null) {
|
||||
return $this->executionId;
|
||||
}
|
||||
$queued = $this->job?->uuid();
|
||||
|
||||
return is_string($queued) && Str::isUuid($queued) ? $queued : ($this->executionId = (string) Str::uuid());
|
||||
}
|
||||
|
||||
public function uniqueId(): string
|
||||
{
|
||||
@@ -51,11 +75,20 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
if ($row->malware_scan_status === 'infected') {
|
||||
return null;
|
||||
}
|
||||
$attempts = app(DocumentScanAttempts::class);
|
||||
if ($attempts->completed($row->id, $this->runIdentifier())) {
|
||||
return null;
|
||||
}
|
||||
if ($row->malware_scan_status === 'scanning' && $attempts->owns($row, $this->runIdentifier(), (int) $this->attempts())) {
|
||||
return null;
|
||||
}
|
||||
$attempt = $attempts->start($row, $this->runIdentifier(), (int) $this->attempts());
|
||||
|
||||
DB::table('documents')->where('id', $this->documentId)->update([
|
||||
'status' => 'quarantined', 'malware_scan_status' => 'scanning', 'malware_failure_reason' => null,
|
||||
'malware_scan_attempts' => DB::raw('malware_scan_attempts + 1'), 'updated_at' => now(),
|
||||
'malware_scan_attempts' => $attempt, 'updated_at' => now(),
|
||||
]);
|
||||
$row->malware_scan_attempts = $attempt;
|
||||
|
||||
return $row;
|
||||
});
|
||||
@@ -69,22 +102,32 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
$root = $disk->path('');
|
||||
$path = $disk->path($document->storage_key);
|
||||
$temporary = null;
|
||||
$operationFailed = false;
|
||||
try {
|
||||
if (($document->storage_encryption ?? null) === 'laravel') {
|
||||
$temporary = tempnam($root, 'scan-private-');
|
||||
if ($temporary === false) {
|
||||
throw new \RuntimeException('Private scan workspace unavailable');
|
||||
}
|
||||
chmod($temporary, 0600);
|
||||
file_put_contents($temporary, Crypt::decryptString($disk->get($document->storage_key)));
|
||||
if (! @chmod($temporary, 0600)) {
|
||||
throw new \RuntimeException('Private scan workspace permissions unavailable');
|
||||
}
|
||||
$plain = Crypt::decryptString($disk->get($document->storage_key));
|
||||
if (file_put_contents($temporary, $plain) !== strlen($plain)) {
|
||||
throw new \RuntimeException('Private scan workspace write incomplete');
|
||||
}
|
||||
unset($plain);
|
||||
$path = $temporary;
|
||||
}
|
||||
$beforeHash = $this->fileHash($path);
|
||||
if ($beforeHash === null || ! hash_equals(trim($document->sha256), $beforeHash)) {
|
||||
$this->record($document, [
|
||||
'result' => 'inconclusive', 'reason_code' => 'file_hash_mismatch', 'engine' => 'ClamAV',
|
||||
$applied = $this->record($document, [
|
||||
'result' => 'inconclusive', 'reason_code' => 'file_hash_mismatch', 'engine' => 'not_run',
|
||||
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => 0, 'detail' => null,
|
||||
], $startedAt, 'inconclusive');
|
||||
if ($applied) {
|
||||
$this->notify('scan_inconclusive');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -99,10 +142,29 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
}
|
||||
$result['file_sha256'] = $afterHash;
|
||||
|
||||
$this->record($document, $result, $startedAt, $result['result']);
|
||||
$applied = $this->record($document, $result, $startedAt, $result['result']);
|
||||
if (in_array($applied, ['inconclusive', 'failed'], true)) {
|
||||
$this->notify($applied === 'failed' ? 'scan_worker_failed' : 'scan_inconclusive');
|
||||
}
|
||||
} catch (Throwable $error) {
|
||||
$operationFailed = true;
|
||||
throw $error;
|
||||
} finally {
|
||||
if (is_string($temporary) && is_file($temporary)) {
|
||||
unlink($temporary);
|
||||
try {
|
||||
$removed = @unlink($temporary);
|
||||
} catch (Throwable) {
|
||||
$removed = false;
|
||||
}
|
||||
if (! $removed) {
|
||||
try {
|
||||
Log::warning('Private scan workspace cleanup requires verification.', ['reference' => $this->runIdentifier(), 'error_code' => 'scan_cleanup_unconfirmed']);
|
||||
} catch (Throwable) {
|
||||
}
|
||||
if (! $operationFailed) {
|
||||
$this->notify('scan_cleanup_unconfirmed');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,11 +175,38 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
if (! $document || $document->status === 'deleted' || $document->deleted_at !== null) {
|
||||
return;
|
||||
}
|
||||
if ($document->malware_scan_status === 'pending') {
|
||||
// A failure before claiming the row cannot overwrite another scan result.
|
||||
$this->notify('scan_worker_failed');
|
||||
|
||||
$this->record($document, [
|
||||
'result' => 'failed', 'reason_code' => 'scanner_unavailable_after_retries', 'engine' => 'ClamAV',
|
||||
return;
|
||||
}
|
||||
if ($document->malware_scan_status !== 'scanning' || ! app(DocumentScanAttempts::class)->owns($document, $this->runIdentifier(), (int) $this->attempts())) {
|
||||
return;
|
||||
}
|
||||
$descriptor = app(DocumentScanAttempts::class)->descriptor($document, $this->runIdentifier(), (int) $this->attempts());
|
||||
if ($descriptor === null) {
|
||||
$this->notify('scan_worker_failed');
|
||||
|
||||
return;
|
||||
}
|
||||
$document->sha256 = $descriptor['sha256'];
|
||||
$document->size_bytes = $descriptor['size_bytes'];
|
||||
|
||||
$applied = $this->record($document, [
|
||||
'result' => 'failed', 'reason_code' => 'scan_failed_after_retries', 'engine' => 'unknown',
|
||||
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => null, 'detail' => null,
|
||||
], now(), 'failed');
|
||||
if ($applied) {
|
||||
$this->notify('scan_worker_failed');
|
||||
}
|
||||
}
|
||||
|
||||
private function notify(string $errorCode): void
|
||||
{
|
||||
if ($this->opportunityContext !== null) {
|
||||
app(OpportunityTechnicalIncidents::class)->recordScan($this->opportunityContext, $this->runIdentifier(), $errorCode);
|
||||
}
|
||||
}
|
||||
|
||||
private function fileHash(string $path): ?string
|
||||
@@ -130,12 +219,17 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $result */
|
||||
private function record(\stdClass $document, array $result, \DateTimeInterface $startedAt, string $state): void
|
||||
private function record(\stdClass $document, array $result, \DateTimeInterface $startedAt, string $state): ?string
|
||||
{
|
||||
DB::transaction(function () use ($document, $result, $startedAt, $state): void {
|
||||
return DB::transaction(function () use ($document, $result, $startedAt, $state): ?string {
|
||||
$locked = DB::table('documents')->where('id', $this->documentId)->lockForUpdate()->first();
|
||||
if (! $locked || $locked->status === 'deleted' || $locked->deleted_at !== null) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if ($locked->malware_scan_status !== 'scanning' || ! app(DocumentScanAttempts::class)->owns($locked, $this->runIdentifier(), (int) $this->attempts(), (int) $document->malware_scan_attempts)) {
|
||||
app(DocumentScanAttempts::class)->discarded($locked, $this->runIdentifier(), (int) $this->attempts(), (int) $document->malware_scan_attempts);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$sameBytes = hash_equals(trim($document->sha256), trim((string) $locked->sha256));
|
||||
@@ -160,13 +254,16 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
|
||||
'updated_at' => $finishedAt,
|
||||
]);
|
||||
DB::table('document_malware_scans')->insert([
|
||||
'id' => $scanId, 'document_id' => $this->documentId, 'file_sha256' => trim($locked->sha256),
|
||||
'id' => $scanId, 'document_id' => $this->documentId, 'file_sha256' => trim($document->sha256),
|
||||
'result' => $finalState, 'reason_code' => $reason,
|
||||
'engine' => $result['engine'] ?? 'ClamAV', 'engine_version' => $result['engine_version'] ?? 'unknown',
|
||||
'signatures_at' => $result['signatures_at'] ?? null, 'started_at' => $startedAt,
|
||||
'finished_at' => $finishedAt, 'duration_ms' => $result['duration_ms'] ?? null,
|
||||
'file_size_bytes' => $locked->size_bytes ?? null, 'created_at' => $finishedAt, 'updated_at' => $finishedAt,
|
||||
'file_size_bytes' => $document->size_bytes ?? null, 'created_at' => $finishedAt, 'updated_at' => $finishedAt,
|
||||
]);
|
||||
app(DocumentScanAttempts::class)->finish($document, $this->runIdentifier(), (int) $this->attempts(), $scanId, $state === 'failed');
|
||||
|
||||
return $finalState;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Models;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* @property string|null $lead_id
|
||||
@@ -13,4 +15,23 @@ class CrmTask extends CrmRecord
|
||||
protected $table = 'tasks';
|
||||
|
||||
protected $casts = ['due_at' => 'immutable_datetime'];
|
||||
|
||||
/**
|
||||
* @param Builder<CrmTask> $query
|
||||
* @return Builder<CrmTask>
|
||||
*/
|
||||
public function scopeAvailableForWork(Builder $query): Builder
|
||||
{
|
||||
$query->whereNull('tasks.deleted_at')->whereIn('tasks.status', ['open', 'in_progress']);
|
||||
if (Schema::hasColumn('tasks', 'desk_case_id')) {
|
||||
if (Schema::hasColumn('desk_cases', 'closed_at')) {
|
||||
$query->where(fn ($q) => $q->whereNull('tasks.desk_case_id')->orWhereExists(fn ($desk) => $desk->selectRaw('1')->from('desk_cases')
|
||||
->whereColumn('desk_cases.id', 'tasks.desk_case_id')->whereNull('desk_cases.closed_at')));
|
||||
} else {
|
||||
$query->whereNull('tasks.desk_case_id');
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
Cache::forget('portal_home_v2_en');
|
||||
Cache::forget('portal_home_sector_organization_v1_pt');
|
||||
Cache::forget('portal_home_sector_organization_v1_en');
|
||||
Cache::forget('portal_home_territorial_v2_pt');
|
||||
Cache::forget('portal_home_territorial_v2_en');
|
||||
};
|
||||
$model::saved($invalidate);
|
||||
$model::deleted($invalidate);
|
||||
|
||||
@@ -69,7 +69,8 @@ final class AssistiveRules
|
||||
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereNull('owner_user_id')->orderBy('id')->limit(20)->get(['id']) as $lead) {
|
||||
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_owner', 'source_url' => '/management/crm/leads/'.$lead->id];
|
||||
}
|
||||
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['new', 'qualified'])->whereDoesntHave('tasks', fn ($q) => $q->whereIn('status', ['open', 'in_progress']))
|
||||
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['new', 'qualified'])
|
||||
->whereNotExists(CrmTask::availableForWork()->whereColumn('tasks.lead_id', 'leads.id')->selectRaw('1')->toBase())
|
||||
->orderBy('id')->limit(20)->get(['id']) as $lead) {
|
||||
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_next_action', 'source_url' => '/management/crm/leads/'.$lead->id];
|
||||
}
|
||||
@@ -91,7 +92,7 @@ final class AssistiveRules
|
||||
/** @return list<array<string, mixed>> */
|
||||
public function sla(): array
|
||||
{
|
||||
return array_values(CrmTask::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())->orderBy('due_at')->limit(50)
|
||||
return array_values(CrmTask::whereIn('data_classification', ['public', 'internal'])->availableForWork()->where('due_at', '<', now())->orderBy('due_at')->limit(50)
|
||||
->get()->map(fn ($task) => [
|
||||
'record_type' => 'task', 'record_id' => $task->id, 'rule' => 'overdue_open_task',
|
||||
'due_at' => $task->getAttribute('due_at')?->toIso8601String(), 'lead_id' => $task->lead_id,
|
||||
|
||||
@@ -4,8 +4,10 @@ namespace App\Services\Ai;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Lead;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Services\CrmNextAction;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Support\Arr;
|
||||
@@ -152,7 +154,7 @@ class InvestorGuidance
|
||||
->get(['t.id', 't.title', 't.status', 't.due_at', 't.version_no', 't.desk_request_id', 't.accepted_by', 't.accepted_at', 't.assignee_user_id', 'u.name as assignee_name', 't.external_sync_status']);
|
||||
|
||||
return ['version' => $case->version, 'rules_version' => InvestorGuidanceRules::VERSION, 'computed_at' => now()->toIso8601String(),
|
||||
...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => $this->desk->owns($actor, $case),
|
||||
...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => ! $case->closed_at && $this->desk->owns($actor, $case), 'can_update_tasks' => ! $case->closed_at,
|
||||
'external_ai' => ['status' => 'not_configured', 'model' => null, 'consulted' => []],
|
||||
'calculator_versions' => ['business_financial_plan' => hash_file('sha256', resource_path('js/lib/business-financial-plan.ts')), 'financial_calculators' => hash_file('sha256', resource_path('js/lib/financial-calculators.ts')), 'project_dossier' => hash_file('sha256', resource_path('js/lib/project-dossier.ts'))],
|
||||
'crm' => ['internal' => 'available', 'external' => 'out_of_scope', 'reason' => 'O acompanhamento usa o CRM interno existente. A sincronização externa está fora desta fase; nenhum contacto, mensagem ou documento é transmitido.']];
|
||||
@@ -235,10 +237,16 @@ class InvestorGuidance
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])],
|
||||
'reason' => 'required|string|min:3|max:3000', 'assignee_user_id' => 'nullable|integer|exists:users,id', 'due_at' => 'nullable|date|after:now'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $taskId, $data) {
|
||||
$case = $this->desk->case($actor, $id);
|
||||
$case = $this->desk->case($actor, $id, false, true);
|
||||
$this->desk->assertOpen($case);
|
||||
$candidate = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->firstOrFail();
|
||||
// Match CRM lock order, so two response channels cannot finish each other's only replacement.
|
||||
$lead = $candidate->lead_id === null ? null : Lead::withTrashed()->whereKey($candidate->lead_id)->lockForUpdate()->firstOrFail();
|
||||
$task = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->lockForUpdate()->firstOrFail();
|
||||
abort_unless($task->lead_id === $candidate->lead_id, 409, 'O acompanhamento associado mudou. Recupere a tarefa actual.');
|
||||
abort_unless($actor->can('manage-portal') || (int) $task->getAttribute('assignee_user_id') === $actor->id, 403);
|
||||
abort_unless((int) $task->getAttribute('version_no') === (int) $data['version'], 409);
|
||||
app(CrmNextAction::class)->assertMayFinish($lead, $task, $data['status']);
|
||||
$updates = ['status' => $data['status'], 'version_no' => $data['version'] + 1];
|
||||
if ($data['assignee_user_id'] ?? null) {
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
|
||||
@@ -15,7 +15,7 @@ final class BusinessFormSchema
|
||||
'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', '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],
|
||||
'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem do pedido (opcional)', 'en' => 'Country from which you submit 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],
|
||||
@@ -23,8 +23,8 @@ final class BusinessFormSchema
|
||||
'contact_preference' => ['step' => 1, 'pt' => 'Preferência de contacto', 'en' => 'Contact preference', 'type' => 'select', 'max' => 30, 'options' => ['through_portal' => 'Receber pedidos através da InvestMoz', 'approved_business_contact' => 'Mostrar contacto empresarial aprovado']],
|
||||
'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']],
|
||||
'declared_holder' => ['step' => 2, 'pt' => 'Entidade ou pessoa representada', 'en' => 'Entity or person represented', 'type' => 'text', 'max' => 200],
|
||||
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do documento de autorização', 'en' => 'Authorization document reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência interna do documento de autorização (não carregue aqui)', 'en' => 'Internal authorization document reference (do not upload here)', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_reference' => ['step' => 2, 'pt' => 'Número ou referência da autorização de representação', 'en' => 'Representation authorization number or reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência do comprovativo de representação no portal', 'en' => 'Reference of representation evidence in the portal', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'disclosure_scope' => ['step' => 2, 'pt' => 'Limites da autorização de divulgação', 'en' => 'Limits of disclosure authorization', 'type' => 'textarea', 'max' => 2000, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']],
|
||||
@@ -64,6 +64,7 @@ final class BusinessFormSchema
|
||||
'location_notes' => ['step' => 5, 'pt' => 'Endereço ou referência (interno)', 'en' => 'Address or reference (internal)', 'type' => 'textarea', 'max' => 2000],
|
||||
'location_unknown' => ['step' => 5, 'pt' => 'Não conheço a localização exacta', 'en' => 'I do not know the exact location', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim', 'no' => 'Não'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'disclosure_precision' => ['step' => 5, 'pt' => 'Precisão de divulgação', 'en' => 'Disclosure precision', 'type' => 'select', 'max' => 30, 'options' => ['exact' => 'Localização exacta (sujeita a aprovação)', 'approximate' => 'Localização aproximada', 'administrative' => 'Apenas território administrativo'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
...self::pointFields(),
|
||||
'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000],
|
||||
'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000],
|
||||
'source_provider' => ['step' => 7, 'pt' => 'Quem forneceu os dados?', 'en' => 'Who supplied the information?', 'type' => 'text', 'max' => 500],
|
||||
@@ -79,8 +80,27 @@ final class BusinessFormSchema
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, list<string|\Closure|In>> */
|
||||
public static function rules(): array
|
||||
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>,when?:array<string,list<string>>}> */
|
||||
private static function pointFields(): array
|
||||
{
|
||||
$when = ['geography_scope' => ['specific', 'multiple'], 'disclosure_precision' => ['exact'], 'location_unknown' => ['no']];
|
||||
$active = [...$when, 'location_point_enabled' => ['yes']];
|
||||
|
||||
return [
|
||||
'location_point_enabled' => ['step' => 5, 'pt' => 'Preparar um ponto exacto para publicação e pesquisa por raio?', 'en' => 'Prepare an exact point for publication and radius searches?', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim — o ponto substituirá a localização primária na publicação aprovada', 'no' => 'Não — conservar o cadastro de localizações existente'], 'when' => $when],
|
||||
'location_point_territory' => ['step' => 5, 'pt' => 'Localização já declarada a que pertence o ponto primário', 'en' => 'Previously declared location for the primary point', 'type' => 'point_territory', 'max' => 150, 'when' => [...$active, 'geography_scope' => ['multiple']]],
|
||||
'location_latitude' => ['step' => 5, 'pt' => 'Latitude WGS84 (graus decimais, -90 a 90)', 'en' => 'WGS84 latitude (decimal degrees, -90 to 90)', 'type' => 'decimal', 'max' => 16, 'when' => $active],
|
||||
'location_longitude' => ['step' => 5, 'pt' => 'Longitude WGS84 (graus decimais, -180 a 180)', 'en' => 'WGS84 longitude (decimal degrees, -180 to 180)', 'type' => 'decimal', 'max' => 16, 'when' => $active],
|
||||
'location_point_source_mode' => ['step' => 5, 'pt' => 'Fonte das coordenadas', 'en' => 'Coordinate source', 'type' => 'select', 'max' => 20, 'options' => ['listing' => 'Reutilizar referência e data da etapa Fontes, se também sustentam este ponto', 'custom' => 'Indicar uma fonte diferente para o ponto'], 'when' => $active],
|
||||
'location_point_source_reference' => ['step' => 5, 'pt' => 'Referência da fonte específica do ponto', 'en' => 'Point-specific source reference', 'type' => 'textarea', 'max' => 2000, 'when' => [...$active, 'location_point_source_mode' => ['custom']]],
|
||||
'location_point_source_date' => ['step' => 5, 'pt' => 'Data dessa fonte (deixe vazio se desconhecida)', 'en' => 'Source date (leave blank if unknown)', 'type' => 'date', 'max' => 10, 'when' => [...$active, 'location_point_source_mode' => ['custom']]],
|
||||
'location_point_share_source' => ['step' => 5, 'pt' => 'Divulgar também a referência da fonte do ponto?', 'en' => 'Also disclose the point source reference?', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim — referência sem contactos ou informação reservada, sujeita à publicação aprovada', 'no' => 'Não — manter a referência apenas no processo reservado'], 'when' => $active],
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return array<string, list<string|\Closure|In>> */
|
||||
public static function rules(array $payload = []): array
|
||||
{
|
||||
$rules = [];
|
||||
foreach (self::fields() as $key => $field) {
|
||||
@@ -99,6 +119,23 @@ final class BusinessFormSchema
|
||||
$rules['payload.investment_total'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.source_date'][] = 'date_format:Y-m-d';
|
||||
foreach (['location_latitude', 'location_longitude'] as $coordinate) {
|
||||
// Numeric rules make Laravel interpret max:16 as a numeric ceiling, not a text limit.
|
||||
$rules['payload.'.$coordinate] = ['nullable', 'string', function ($attribute, $value, $fail) {
|
||||
if (strlen((string) $value) > 16) {
|
||||
$fail('Indique a coordenada com até 16 caracteres.');
|
||||
}
|
||||
}];
|
||||
}
|
||||
if (app(BusinessPointPublication::class)->applicable($payload)) {
|
||||
if (($payload['location_point_source_mode'] ?? null) === 'custom') {
|
||||
$rules['payload.location_point_source_date'][] = 'date_format:Y-m-d';
|
||||
}
|
||||
$rules['payload.location_latitude'][] = 'numeric';
|
||||
$rules['payload.location_latitude'][] = 'between:-90,90';
|
||||
$rules['payload.location_longitude'][] = 'numeric';
|
||||
$rules['payload.location_longitude'][] = 'between:-180,180';
|
||||
}
|
||||
$rules['payload.official_source_url'][] = 'url';
|
||||
// The field limit is a text length, not an 8% ceiling.
|
||||
$rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Optional supplement of the approved listing; never grants publication authority. */
|
||||
final class BusinessPointPublication
|
||||
{
|
||||
public function available(): bool
|
||||
{
|
||||
return Schema::hasColumn('existing_business_locations', 'public_source_reference');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public function applicable(array $payload): bool
|
||||
{
|
||||
return ($payload['location_point_enabled'] ?? null) === 'yes'
|
||||
&& in_array($payload['geography_scope'] ?? null, ['specific', 'multiple'], true)
|
||||
&& ($payload['disclosure_precision'] ?? null) === 'exact'
|
||||
&& ($payload['location_unknown'] ?? null) === 'no';
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return list<array<string,mixed>> */
|
||||
public function paths(array $payload): array
|
||||
{
|
||||
if (($payload['geography_scope'] ?? null) === 'specific') {
|
||||
return [array_intersect_key($payload, InvestmentGeography::FIELDS)];
|
||||
}
|
||||
if (($payload['geography_scope'] ?? null) !== 'multiple') {
|
||||
return [];
|
||||
}
|
||||
$rows = json_decode((string) ($payload['locations_json'] ?? ''), true);
|
||||
|
||||
return is_array($rows) && array_is_list($rows) ? array_values(array_filter($rows, 'is_array')) : [];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $path */
|
||||
public function pathKey(array $path): string
|
||||
{
|
||||
return implode('|', array_map(fn ($field) => (string) ($path[$field] ?? ''), array_keys(InvestmentGeography::FIELDS)));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return array<string,mixed>|null */
|
||||
public function candidate(array $payload): ?array
|
||||
{
|
||||
if (! $this->applicable($payload)) {
|
||||
return null;
|
||||
}
|
||||
abort_unless($this->available(), 409, 'O suplemento de localização ainda não está instalado neste destino. O ponto não será publicado.');
|
||||
$rules = [
|
||||
'location_unknown' => ['required', 'in:no'],
|
||||
'location_latitude' => ['required', 'numeric', 'between:-90,90'],
|
||||
'location_longitude' => ['required', 'numeric', 'between:-180,180'],
|
||||
'location_point_source_mode' => ['required', 'in:listing,custom'],
|
||||
'location_point_share_source' => ['nullable', 'in:yes,no'],
|
||||
'location_point_source_reference' => ['required_if:location_point_source_mode,custom', 'nullable', 'string', 'max:2000'],
|
||||
'location_point_source_date' => ($payload['location_point_source_mode'] ?? null) === 'custom' ? ['nullable', 'date_format:Y-m-d'] : ['nullable'],
|
||||
'location_point_territory' => ['required_if:geography_scope,multiple', 'nullable', 'string', 'max:150'],
|
||||
];
|
||||
Validator::make($payload, $rules)->validate();
|
||||
$paths = $this->paths($payload);
|
||||
$path = ($payload['geography_scope'] ?? null) === 'specific' ? ($paths[0] ?? null)
|
||||
: collect($paths)->first(fn ($row) => $this->pathKey($row) === $payload['location_point_territory']);
|
||||
if (! $path || empty($path['province_id'])) {
|
||||
throw ValidationException::withMessages(['location_point_territory' => 'Seleccione uma das localizações já declaradas para o ponto primário. Não é atribuída uma localização por ordem ou por nome.']);
|
||||
}
|
||||
$nodes = app(InvestmentGeography::class)->selection($path);
|
||||
$listingSource = $payload['location_point_source_mode'] === 'listing';
|
||||
$source = $listingSource ? ($payload['source_reference'] ?? null) : ($payload['location_point_source_reference'] ?? null);
|
||||
$date = $listingSource ? ($payload['source_date'] ?? null) : ($payload['location_point_source_date'] ?? null);
|
||||
Validator::make(['location_point_source_reference' => $source, 'location_point_source_date' => $date], [
|
||||
'location_point_source_reference' => ['required', 'string', 'max:2000'], 'location_point_source_date' => ['nullable', 'date_format:Y-m-d'],
|
||||
])->validate();
|
||||
|
||||
return ['path' => array_combine(array_keys(InvestmentGeography::FIELDS), array_map(fn ($field) => ($path[$field] ?? null) ?: null, array_keys(InvestmentGeography::FIELDS))),
|
||||
'reference_snapshot' => array_map(fn ($node) => (array) $node, $nodes),
|
||||
'latitude' => (float) $payload['location_latitude'], 'longitude' => (float) $payload['location_longitude'],
|
||||
'source_reference' => $source, 'source_date' => $date ?: null,
|
||||
'public_source_reference' => ($payload['location_point_share_source'] ?? null) === 'yes' ? $source : null];
|
||||
}
|
||||
|
||||
/** Called only within the existing authorized, locked publication transaction.
|
||||
* @return array<string,mixed> */
|
||||
public function publish(ExistingBusiness $business): array
|
||||
{
|
||||
$point = $this->candidate($business->payload);
|
||||
if ($point === null) {
|
||||
return [];
|
||||
}
|
||||
$previous = DB::table('existing_business_locations')->where('existing_business_id', $business->id)->where('is_primary', true)
|
||||
->select('*')->selectRaw('ST_AsEWKT(geom) AS geometry_snapshot')->first();
|
||||
$geometry = DB::selectOne('SELECT ST_AsEWKT(ST_SetSRID(ST_MakePoint(?::float8, ?::float8),4326)) AS value', [$point['longitude'], $point['latitude']])->value;
|
||||
$values = [...$point['path'], 'precision_level' => 'exact', 'is_public' => true,
|
||||
'geom' => $geometry,
|
||||
'public_source_reference' => $point['public_source_reference'], 'source_date' => $point['source_date'],
|
||||
'source_system' => 'portal-business-form', 'source_payload_version' => $business->version_no + 1, 'updated_at' => now()];
|
||||
if ($previous) {
|
||||
DB::table('existing_business_locations')->where('id', $previous->id)->update($values);
|
||||
} else {
|
||||
DB::table('existing_business_locations')->insert([...$values, 'id' => (string) Str::uuid(), 'existing_business_id' => $business->id, 'is_primary' => true, 'created_at' => now()]);
|
||||
}
|
||||
|
||||
return ['point_publication' => ['previous' => $previous ? (array) $previous : null, 'used' => $point,
|
||||
'business_version' => $business->version_no + 1, 'source' => 'explicit_listing_point_supplement']];
|
||||
}
|
||||
|
||||
/** Private view, only after the listing's normal view authorization.
|
||||
* @return array<string,mixed>|null */
|
||||
public function registered(ExistingBusiness $business): ?array
|
||||
{
|
||||
$row = DB::table('existing_business_locations')->where('existing_business_id', $business->id)->where('is_primary', true)
|
||||
->select('id', 'precision_level', 'is_public', 'province_id', 'district_id', 'admin_post_id', 'locality_id')
|
||||
->selectRaw("geom IS NOT NULL AS has_geometry, CASE WHEN GeometryType(geom)='POINT' THEN ST_Y(geom) END AS latitude, CASE WHEN GeometryType(geom)='POINT' THEN ST_X(geom) END AS longitude")->first();
|
||||
|
||||
return $row ? (array) $row : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class BusinessProximitySearch
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function origin(string $id): array
|
||||
{
|
||||
$row = DB::query()->fromSub(app(PublicBusinessLocations::class)->points(), 'origin_point')
|
||||
->joinSub(ExistingBusiness::published()->select('id', 'public_title'), 'origin_business', 'origin_business.id', '=', 'origin_point.existing_business_id')
|
||||
->where('origin_point.existing_business_id', $id)->whereNotNull('origin_point.point')
|
||||
->select('origin_point.location_recorded_at', 'origin_point.location_source_reference', 'origin_point.location_source_date', 'origin_business.public_title')->selectRaw('ST_AsEWKT(origin_point.point) AS ewkt')->first();
|
||||
if (! $row) {
|
||||
throw ValidationException::withMessages(['near_business' => 'A ficha de referência não tem um ponto primário público exacto utilizável. Escolha outra referência ou pesquise por área.']);
|
||||
}
|
||||
|
||||
return ['id' => $id, 'title' => $row->public_title, 'ewkt' => $row->ewkt, 'source_reference' => $row->location_source_reference, 'source_date' => $row->location_source_date, 'location_recorded_at' => $row->location_recorded_at ? CarbonImmutable::parse($row->location_recorded_at)->toIso8601String() : null];
|
||||
}
|
||||
|
||||
public function available(string $id): bool
|
||||
{
|
||||
return DB::query()->fromSub(app(PublicBusinessLocations::class)->points(), 'point')
|
||||
->whereIn('existing_business_id', ExistingBusiness::published()->select('id'))
|
||||
->where('existing_business_id', $id)->whereNotNull('point')->exists();
|
||||
}
|
||||
|
||||
/** @param Builder<ExistingBusiness> $query
|
||||
* @param array<string,mixed> $origin
|
||||
* @return array<string,mixed> */
|
||||
public function constrain(Builder $query, array $origin, float $radius): array
|
||||
{
|
||||
$query->leftJoinSub(app(PublicBusinessLocations::class)->points(), 'public_point', 'public_point.existing_business_id', '=', 'existing_businesses.id');
|
||||
$withPoint = (clone $query)->whereNotNull('public_point.point')->count();
|
||||
$withoutPoint = (clone $query)->whereNull('public_point.point')->count();
|
||||
$query->whereNotNull('public_point.point')->whereRaw('ST_DWithin(public_point.point::geography, ST_GeomFromEWKT(?)::geography, ?)', [$origin['ewkt'], $radius * 1000])
|
||||
->addSelect('public_point.location_recorded_at')
|
||||
->selectRaw('ST_Distance(public_point.point::geography, ST_GeomFromEWKT(?)::geography) / 1000.0 AS distance_km', [$origin['ewkt']])
|
||||
->orderBy('distance_km')->orderBy('existing_businesses.id');
|
||||
|
||||
return ['origin_id' => $origin['id'], 'origin_title' => $origin['title'], 'radius_km' => $radius, 'origin_recorded_at' => $origin['location_recorded_at'],
|
||||
'origin_source_reference' => $origin['source_reference'], 'origin_source_date' => $origin['source_date'],
|
||||
'with_public_point' => $withPoint, 'without_public_point' => $withoutPoint,
|
||||
'source' => 'Localizações primárias públicas do cadastro de negócios do portal',
|
||||
'method' => 'Distância geodésica em linha recta entre pontos publicados; não é distância por estrada nem validação da localização real.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Informative comparison, stored in the existing encrypted dossier and event history. */
|
||||
final class CompanyComparison
|
||||
{
|
||||
public const EVENT = 'company_comparison_saved';
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function definition(): array
|
||||
{
|
||||
return config('company-comparison');
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $questions
|
||||
* @return list<string> */
|
||||
private function questionKeys(array $questions): array
|
||||
{
|
||||
$keys = [];
|
||||
foreach (array_keys($questions) as $key) {
|
||||
if (! is_string($key)) {
|
||||
throw new \LogicException('Comparison question identifiers must be strings.');
|
||||
}
|
||||
$keys[] = $key;
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,string> */
|
||||
public function answers(array $input): array
|
||||
{
|
||||
return $this->normalize($input, $this->definition()['questions']);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param array<array-key,mixed> $questions
|
||||
* @return array<string,string> */
|
||||
private function normalize(array $input, array $questions): array
|
||||
{
|
||||
$keys = $this->questionKeys($questions);
|
||||
$rules = ['answers' => ['sometimes', 'array:'.implode(',', $keys)]];
|
||||
foreach ($keys as $key) {
|
||||
$rules['answers.'.$key] = ['nullable', 'string', Rule::in(array_keys($questions[$key]['options']))];
|
||||
}
|
||||
$values = Validator::make($input, $rules)->validate()['answers'] ?? [];
|
||||
|
||||
$answers = [];
|
||||
foreach ($keys as $key) {
|
||||
$answers[$key] = is_string($values[$key] ?? null) ? $values[$key] : 'unknown';
|
||||
}
|
||||
|
||||
return $answers;
|
||||
}
|
||||
|
||||
/** @param array<string,string> $answers
|
||||
* @return list<string> */
|
||||
public function active(array $answers): array
|
||||
{
|
||||
return in_array($answers['purpose'], ['representation', 'cooperation'], true) ? ['purpose', 'regulated'] : $this->questionKeys($this->definition()['questions']);
|
||||
}
|
||||
|
||||
/** @param array<string,string> $answers
|
||||
* @return array<string,mixed> */
|
||||
public function evaluate(array $answers): array
|
||||
{
|
||||
$definition = $this->definition();
|
||||
$active = $this->active($answers);
|
||||
$pending = array_values(array_filter($active, fn ($key) => $key !== 'preferred' && $answers[$key] === 'unknown'));
|
||||
$tasks = ['Definir contribuições, gestão, direitos e obrigações no acto a preparar.', 'Conferir os actos e o registo aplicáveis à alternativa escolhida.'];
|
||||
if (in_array('capital', $active, true)) {
|
||||
$tasks[] = $answers['capital'] === 'defined' ? 'Conferir os valores e o modo de realização das contribuições definidas.' : 'Definir o capital e as contribuições ainda em falta.';
|
||||
if (in_array($answers['management'], ['participants', 'both'], true)) {
|
||||
$tasks[] = 'Definir poderes de gestão e regras de deliberação dos participantes.';
|
||||
}
|
||||
if (in_array($answers['management'], ['appointed', 'both'], true)) {
|
||||
$tasks[] = 'Definir a nomeação, o mandato e a prestação de contas da administração.';
|
||||
}
|
||||
if ($answers['responsibility'] !== 'unknown') {
|
||||
$tasks[] = 'Conferir no registo e no contrato o regime de responsabilidade e as excepções aplicáveis.';
|
||||
}
|
||||
if ($answers['listing'] === 'yes') {
|
||||
$tasks[] = 'Conferir os requisitos específicos da emissão e do mercado pretendido.';
|
||||
}
|
||||
}
|
||||
if ($answers['regulated'] !== 'no') {
|
||||
$tasks[] = 'Conferir as regras e habilitações específicas da actividade.';
|
||||
}
|
||||
$route = match ($answers['purpose']) {
|
||||
'representation' => 'Compare a representação da sociedade existente; não é uma nova forma societária (artigo 69).',
|
||||
'cooperation' => 'Prepare o acordo de cooperação; consórcio não é apresentado como uma forma societária autónoma.',
|
||||
default => 'Compare alternativas para discutir a constituição; não existe uma forma universalmente preferível.',
|
||||
};
|
||||
$forms = [];
|
||||
if (! in_array($answers['purpose'], ['representation', 'cooperation'], true)) {
|
||||
foreach ($definition['forms'] as $code => $form) {
|
||||
$constraints = [];
|
||||
$notes = [];
|
||||
if ($code === 'individual' && $answers['participants'] === 'several') {
|
||||
$constraints[] = 'A titularidade individual não corresponde a vários titulares (artigo 3).';
|
||||
}
|
||||
if ($code === 'collective' && $answers['participants'] === 'one') {
|
||||
$constraints[] = 'São necessários pelo menos dois sócios (artigo 264).';
|
||||
}
|
||||
if ($code === 'simplified' && $answers['listing'] === 'yes') {
|
||||
$constraints[] = 'As acções desta forma não podem ser negociadas em Bolsa (artigo 444).';
|
||||
}
|
||||
if ($answers['participants'] === 'one' && in_array($code, ['quotas', 'anonymous', 'simplified'], true)) {
|
||||
$notes[] = 'Comparar a modalidade unipessoal (artigo 257).';
|
||||
}
|
||||
if (($answers['participation'] === 'shares' && $code === 'quotas') || ($answers['participation'] === 'quotas' && in_array($code, ['anonymous', 'simplified'], true))) {
|
||||
$notes[] = 'A estrutura de participação difere da preferência indicada.';
|
||||
}
|
||||
if ($answers['participation'] === 'work') {
|
||||
$notes[] = $code === 'collective' ? 'Conferir a contribuição em trabalho (artigos 264–266).' : 'Conferir como realizar as contribuições pretendidas.';
|
||||
}
|
||||
$forms[] = ['code' => $code, ...$form, 'constraints' => $constraints, 'notes' => $notes,
|
||||
'selected' => $answers['preferred'] === $code, 'source_href' => $definition['source']['url'].'#page='.$form['page']];
|
||||
}
|
||||
}
|
||||
|
||||
return ['engine_version' => $definition['version'], 'source' => $definition['source'], 'questions' => $definition['questions'], 'active' => $active,
|
||||
'pending' => $pending, 'route' => $route, 'forms' => $forms, 'preparation' => $tasks,
|
||||
'scope' => 'Comparação informativa da edição indicada; a actividade, o contrato e as regras especiais continuam a exigir conferência própria.'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function view(User $actor, string $id, array $input): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
$saved = $this->desk->decode($case->payload)['company_comparison'] ?? null;
|
||||
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1'])->validate();
|
||||
if (! empty($v['revision'])) {
|
||||
if (array_key_exists('answers', $input)) {
|
||||
throw ValidationException::withMessages(['answers' => 'Abra a preparação actual para comparar outras respostas; a revisão histórica conserva os dados guardados.']);
|
||||
}
|
||||
$row = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
|
||||
abort_unless($row !== null, 404);
|
||||
$saved = $this->desk->decode($row->payload)['snapshot'];
|
||||
}
|
||||
$answers = array_key_exists('answers', $input) ? $this->answers($input) : ($saved['answers'] ?? $this->answers([]));
|
||||
$result = array_key_exists('answers', $input) || ! $saved ? $this->evaluate($answers) : $saved['result'];
|
||||
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
|
||||
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
|
||||
->orderByDesc('event_order')->limit(26)->get(['id', 'payload', 'event_order']);
|
||||
$history = $events->take(25)->map(function ($row) {
|
||||
$snapshot = $this->desk->decode($row->payload)['snapshot'];
|
||||
|
||||
return ['id' => $row->id, 'revision' => $snapshot['revision'], 'at' => $snapshot['at'], 'engine_version' => $snapshot['result']['engine_version']];
|
||||
})->all();
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
|
||||
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'answers' => $answers, 'result' => $result,
|
||||
'saved' => $saved, 'history' => $history, 'historyNext' => $events->count() > 25 ? $events[24]->event_order : null,
|
||||
'historical' => ! empty($v['revision']), 'workingCopy' => array_key_exists('answers', $input)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $id, array $input): array
|
||||
{
|
||||
$this->desk->case($actor, $id, true);
|
||||
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
|
||||
$v['version'] = (int) $v['version'];
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $v, $input) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->orderByDesc('event_order')->cursor() as $event) {
|
||||
$data = $this->desk->decode($event->payload);
|
||||
if ($data['operation_key'] === $v['operation_key']) {
|
||||
$answers = $this->normalize($input, $data['snapshot']['result']['questions']);
|
||||
$hash = hash('sha256', json_encode([$v['version'], $answers], JSON_THROW_ON_ERROR));
|
||||
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'Esta operação já guardou respostas diferentes. Reabra a comparação.');
|
||||
|
||||
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
|
||||
}
|
||||
}
|
||||
$answers = $this->answers($input);
|
||||
$hash = hash('sha256', json_encode([$v['version'], $answers], JSON_THROW_ON_ERROR));
|
||||
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Conserve as respostas e recupere a versão actual antes de guardar.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$result = $this->evaluate($answers);
|
||||
$previous = $payload['company_comparison'] ?? null;
|
||||
if ($previous !== null && $previous['answers'] === $answers && $previous['result'] === $result) {
|
||||
return ['saved' => true, 'replayed' => false, 'unchanged' => true, 'revision' => $previous['revision']];
|
||||
}
|
||||
$snapshot = ['revision' => (int) ($payload['company_comparison']['revision'] ?? 0) + 1, 'answers' => $answers,
|
||||
'result' => $result, 'at' => now()->toIso8601String(), 'actor_id' => $actor->id];
|
||||
$payload['company_comparison'] = $snapshot;
|
||||
$case->version++;
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
|
||||
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
|
||||
|
||||
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Factual preparation only. Actual contractual exemplars have not been supplied. */
|
||||
final class CompanyPreparation
|
||||
{
|
||||
public const EVENT = 'company_preparation_saved';
|
||||
|
||||
public const VERSION = 'company-preparation-1';
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function definition(): array
|
||||
{
|
||||
return ['version' => self::VERSION, 'forms' => config('company-comparison.forms'),
|
||||
'roles' => ['subscriber' => 'Titular, sócio ou accionista', 'administrator' => 'Administrador ou gerente', 'representative' => 'Representante', 'beneficial_owner' => 'Beneficiário efectivo declarado'],
|
||||
'source' => config('company-comparison.source'),
|
||||
'template_status' => 'source_pending', 'template_notice' => 'Os sete exemplares referidos no complemento ainda não foram fornecidos. Esta ficha prepara dados para revisão; não é uma minuta contratual, assinatura, registo ou licença.'];
|
||||
}
|
||||
|
||||
/** Reuse only the already-authorized, frozen dossier values, never a fresh master lookup.
|
||||
* @return array<string,array<string,mixed>> */
|
||||
private function sources(\stdClass $case): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$sources = [];
|
||||
if (! empty($payload['name'])) {
|
||||
$sources['case_proponent'] = ['name' => $payload['name'], 'kind' => 'person', 'reference' => $case->id,
|
||||
'version' => $payload['reuse_consent']['date'] ?? 'creation', 'origin' => 'Proponente conservado na criação do dossier'];
|
||||
}
|
||||
if ($case->company_id && ! empty($payload['company']['name'])) {
|
||||
$sources['case_company'] = ['name' => $payload['company']['name'], 'kind' => 'entity', 'reference' => $case->company_id,
|
||||
'version' => $payload['company_version'] ?? null, 'origin' => 'Declaração de empresa conservada no dossier'];
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param array<string,mixed>|null $definition
|
||||
* @return array<string,mixed> */
|
||||
public function facts(array $input, ?array $definition = null): array
|
||||
{
|
||||
$definition ??= $this->definition();
|
||||
$text = ['nullable', 'string', 'max:2000'];
|
||||
$number = ['nullable', 'string', 'regex:/^\d{1,18}(?:[.,]\d{1,6})?$/D'];
|
||||
$rules = ['facts' => ['present', 'array:form,proposed_name,seat,activities,regulated,currency,capital,nominal_value,management,binding,notes,parties'],
|
||||
'facts.form' => ['nullable', Rule::in(array_keys($definition['forms']))],
|
||||
'facts.proposed_name' => ['nullable', 'string', 'max:250'], 'facts.seat' => $text, 'facts.activities' => $text,
|
||||
'facts.regulated' => ['nullable', Rule::in(['unknown', 'yes', 'no'])],
|
||||
'facts.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/D'], 'facts.capital' => $number, 'facts.nominal_value' => $number,
|
||||
'facts.management' => $text, 'facts.binding' => $text, 'facts.notes' => $text,
|
||||
'facts.parties' => ['sometimes', 'array', 'list', 'max:100'],
|
||||
'facts.parties.*' => ['array:id,name,kind,source,roles,represented_id,cash,in_kind,paid,share_count,work,commitment'],
|
||||
'facts.parties.*.id' => ['required', 'uuid', 'distinct'], 'facts.parties.*.name' => ['nullable', 'string', 'max:250'],
|
||||
'facts.parties.*.kind' => ['required', Rule::in(['person', 'entity'])],
|
||||
'facts.parties.*.source' => ['nullable', Rule::in(['case_proponent', 'case_company'])],
|
||||
'facts.parties.*.roles' => ['present', 'array', 'list', 'max:4'],
|
||||
'facts.parties.*.roles.*' => ['string', Rule::in(array_keys($definition['roles']))],
|
||||
'facts.parties.*.represented_id' => ['nullable', 'uuid'],
|
||||
'facts.parties.*.cash' => $number, 'facts.parties.*.in_kind' => $number, 'facts.parties.*.paid' => $number,
|
||||
'facts.parties.*.share_count' => ['nullable', 'string', 'regex:/^\d{1,18}$/D'],
|
||||
'facts.parties.*.work' => $text, 'facts.parties.*.commitment' => $text];
|
||||
$v = Validator::make($input, $rules)->validate()['facts'];
|
||||
$facts = [];
|
||||
foreach (['form', 'proposed_name', 'seat', 'activities', 'currency', 'management', 'binding', 'notes'] as $key) {
|
||||
$facts[$key] = $v[$key] ?? null;
|
||||
}
|
||||
$facts['regulated'] = $v['regulated'] ?? 'unknown';
|
||||
foreach (['capital', 'nominal_value'] as $key) {
|
||||
$facts[$key] = $this->decimal($v[$key] ?? null);
|
||||
}
|
||||
$facts['parties'] = [];
|
||||
foreach ($v['parties'] ?? [] as $party) {
|
||||
$p = [];
|
||||
foreach (['id', 'name', 'kind', 'source', 'represented_id', 'work', 'commitment'] as $key) {
|
||||
$p[$key] = $party[$key] ?? null;
|
||||
}
|
||||
$p['roles'] = array_values(array_unique($party['roles']));
|
||||
sort($p['roles']);
|
||||
foreach (['cash', 'in_kind', 'paid', 'share_count'] as $key) {
|
||||
$p[$key] = $this->decimal($party[$key] ?? null);
|
||||
}
|
||||
$facts['parties'][] = $p;
|
||||
}
|
||||
|
||||
return $facts;
|
||||
}
|
||||
|
||||
private function decimal(?string $value): ?string
|
||||
{
|
||||
return $value === null ? null : (string) BigDecimal::of(str_replace(',', '.', $value))->strippedOfTrailingZeros();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $facts
|
||||
* @param array<string,array<string,mixed>> $sources
|
||||
* @param array<string,mixed>|null $previous
|
||||
* @return array<string,mixed> */
|
||||
private function resolve(array $facts, array $sources, ?array $previous): array
|
||||
{
|
||||
foreach ($facts['parties'] as &$party) {
|
||||
if ($party['source'] !== null) {
|
||||
$old = null;
|
||||
foreach ($previous['facts']['parties'] ?? [] as $candidate) {
|
||||
if ($candidate['id'] === $party['id'] && $candidate['source'] === $party['source']) {
|
||||
$old = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$source = $old['source_snapshot'] ?? $sources[$party['source']] ?? null;
|
||||
abort_unless($source !== null, 422, 'A origem seleccionada não existe neste dossier.');
|
||||
$party['name'] = $source['name'];
|
||||
$party['kind'] = $source['kind'];
|
||||
$party['source_snapshot'] = $source;
|
||||
}
|
||||
}
|
||||
|
||||
return $facts;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $facts
|
||||
* @return array<string,mixed> */
|
||||
public function review(array $facts): array
|
||||
{
|
||||
$issues = [];
|
||||
foreach (['form' => 'Definir a forma a preparar.', 'proposed_name' => 'Indicar a denominação proposta.', 'seat' => 'Indicar a sede proposta.', 'activities' => 'Descrever as actividades.', 'management' => 'Descrever a administração pretendida.', 'binding' => 'Indicar a forma de obrigar pretendida.'] as $key => $message) {
|
||||
if (! $facts[$key]) {
|
||||
$issues[] = $message;
|
||||
}
|
||||
}
|
||||
$subscribers = array_values(array_filter($facts['parties'], fn ($p) => in_array('subscriber', $p['roles'], true)));
|
||||
if ($subscribers === []) {
|
||||
$issues[] = 'Identificar os titulares, sócios ou accionistas.';
|
||||
}
|
||||
if ($facts['form'] === 'collective' && count($subscribers) < 2) {
|
||||
$issues[] = 'A forma colectiva exige pelo menos dois sócios (artigo 264).';
|
||||
}
|
||||
if ($facts['form'] === 'individual' && count($subscribers) > 1) {
|
||||
$issues[] = 'A titularidade individual não corresponde a vários titulares.';
|
||||
}
|
||||
$corporate = $facts['form'] !== null && $facts['form'] !== 'individual';
|
||||
$shares = in_array($facts['form'], ['anonymous', 'simplified'], true);
|
||||
$total = BigDecimal::zero();
|
||||
$paid = BigDecimal::zero();
|
||||
$units = BigDecimal::zero();
|
||||
$complete = $subscribers !== [];
|
||||
$paymentsComplete = $complete;
|
||||
$unitsComplete = $complete;
|
||||
$ids = array_column($facts['parties'], 'id');
|
||||
$usedSources = [];
|
||||
foreach ($facts['parties'] as $party) {
|
||||
if ($party['source'] && in_array($party['source'], $usedSources, true)) {
|
||||
$issues[] = 'A mesma origem foi seleccionada em mais de uma linha; conferir duplicação sem fundir pessoas por nome.';
|
||||
}
|
||||
$usedSources[] = $party['source'];
|
||||
if (! $party['name'] || $party['roles'] === []) {
|
||||
$issues[] = 'Completar o nome e os papéis de cada interveniente.';
|
||||
}
|
||||
if (in_array('representative', $party['roles'], true) && (! $party['represented_id'] || $party['represented_id'] === $party['id'] || ! in_array($party['represented_id'], $ids, true))) {
|
||||
$issues[] = 'Identificar quem cada representante representa, numa linha distinta.';
|
||||
}
|
||||
if (! in_array('subscriber', $party['roles'], true) || ! $corporate) {
|
||||
continue;
|
||||
}
|
||||
$complete = $complete && $party['cash'] !== null && $party['in_kind'] !== null;
|
||||
$subscription = BigDecimal::of($party['cash'] ?? '0')->plus($party['in_kind'] ?? '0');
|
||||
$total = $total->plus($subscription);
|
||||
$paymentsComplete = $paymentsComplete && $party['paid'] !== null;
|
||||
$paid = $paid->plus($party['paid'] ?? '0');
|
||||
if ($party['paid'] !== null && $party['cash'] !== null && $party['in_kind'] !== null && BigDecimal::of($party['paid'])->compareTo($subscription) > 0) {
|
||||
$issues[] = 'Uma realização declarada excede a subscrição desse participante.';
|
||||
}
|
||||
$unitsComplete = $unitsComplete && $party['share_count'] !== null;
|
||||
$units = $units->plus($party['share_count'] ?? '0');
|
||||
if ($shares && $party['share_count'] !== null && $facts['nominal_value'] !== null && $party['cash'] !== null && $party['in_kind'] !== null && BigDecimal::of($party['share_count'])->multipliedBy($facts['nominal_value'])->compareTo($subscription) !== 0) {
|
||||
$issues[] = 'O valor nominal das acções de um participante difere da sua subscrição.';
|
||||
}
|
||||
if ($party['work'] && $facts['form'] !== 'collective') {
|
||||
$issues[] = 'Conferir a admissibilidade da contribuição em trabalho para a forma escolhida.';
|
||||
}
|
||||
}
|
||||
$totals = null;
|
||||
if ($corporate) {
|
||||
if (! $facts['currency'] || $facts['capital'] === null || ! $complete) {
|
||||
$issues[] = 'Completar moeda, capital e entradas em dinheiro/espécie; valores desconhecidos não são zero.';
|
||||
}
|
||||
if ($complete && $facts['capital'] !== null && $total->compareTo($facts['capital']) !== 0) {
|
||||
$issues[] = 'A soma das subscrições difere do capital declarado.';
|
||||
}
|
||||
if (! $paymentsComplete) {
|
||||
$issues[] = 'Completar a realização declarada de cada subscrição; não equivale a prova de pagamento.';
|
||||
}
|
||||
if ($shares && ($facts['nominal_value'] === null || ! $unitsComplete)) {
|
||||
$issues[] = 'Completar o número de acções e o valor nominal para reconciliar as participações.';
|
||||
}
|
||||
$totals = ['currency' => $facts['currency'], 'subscribed' => $complete && $facts['currency'] ? (string) $total : null,
|
||||
'paid' => $paymentsComplete && $facts['currency'] ? (string) $paid : null,
|
||||
'unpaid' => $complete && $paymentsComplete && $facts['currency'] ? (string) $total->minus($paid) : null,
|
||||
'shares_nominal' => $shares && $unitsComplete && $facts['nominal_value'] !== null && $facts['currency'] ? (string) $units->multipliedBy($facts['nominal_value']) : null];
|
||||
}
|
||||
if ($facts['regulated'] !== 'no') {
|
||||
$issues[] = 'Conferir os requisitos sectoriais ou profissionais da actividade; o objecto não concede licença.';
|
||||
}
|
||||
|
||||
return ['issues' => array_values(array_unique($issues)), 'totals' => $totals, 'status' => 'preparation',
|
||||
'note' => $facts['form'] === 'collective' ? 'As contribuições em trabalho são conservadas separadamente e não integram o capital (artigo 266).' : 'Valores declarados para preparação; não comprovam entradas, poderes ou registo.'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function view(User $actor, string $id, array $input): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1'])->validate();
|
||||
$saved = $payload['company_preparation'] ?? null;
|
||||
if (! empty($v['revision'])) {
|
||||
$event = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
|
||||
abort_unless($event !== null, 404);
|
||||
$saved = $this->desk->decode($event->payload)['snapshot'];
|
||||
}
|
||||
$facts = $saved['facts'] ?? $this->facts(['facts' => []]);
|
||||
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
|
||||
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
|
||||
->orderByDesc('event_order')->limit(26)->get(['id', 'payload', 'event_order']);
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
|
||||
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'historical' => ! empty($v['revision']),
|
||||
'definition' => $saved['definition'] ?? $this->definition(), 'facts' => $facts, 'review' => $saved['review'] ?? $this->review($facts), 'saved' => $saved,
|
||||
'sources' => $this->sources($case), 'history' => $events->take(25)->map(function ($e) {
|
||||
$s = $this->desk->decode($e->payload)['snapshot'];
|
||||
|
||||
return ['id' => $e->id, 'revision' => $s['revision'], 'at' => $s['at']];
|
||||
})->all(), 'historyNext' => $events->count() > 25 ? $events[24]->event_order : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $id, array $input): array
|
||||
{
|
||||
$this->desk->case($actor, $id, true);
|
||||
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $v, $input) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->orderByDesc('event_order')->cursor() as $event) {
|
||||
$data = $this->desk->decode($event->payload);
|
||||
if ($data['operation_key'] === $v['operation_key']) {
|
||||
$facts = $this->facts($input, $data['snapshot']['definition']);
|
||||
$hash = hash('sha256', json_encode([(int) $v['version'], $facts], JSON_THROW_ON_ERROR));
|
||||
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'A operação já guardou outros dados.');
|
||||
|
||||
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
|
||||
}
|
||||
}
|
||||
$facts = $this->facts($input);
|
||||
$hash = hash('sha256', json_encode([(int) $v['version'], $facts], JSON_THROW_ON_ERROR));
|
||||
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Os dados continuam no formulário; recupere a versão antes de guardar.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$previous = $payload['company_preparation'] ?? null;
|
||||
$resolved = $this->resolve($facts, $this->sources($case), $previous);
|
||||
$definition = $this->definition();
|
||||
$review = $this->review($resolved);
|
||||
if ($previous && $previous['facts'] === $resolved && $previous['definition'] === $definition && $previous['review'] === $review) {
|
||||
return ['saved' => true, 'unchanged' => true, 'revision' => $previous['revision']];
|
||||
}
|
||||
$snapshot = ['revision' => (int) ($previous['revision'] ?? 0) + 1, 'at' => now()->toIso8601String(), 'actor_id' => $actor->id,
|
||||
'facts' => $resolved, 'definition' => $definition, 'review' => $review];
|
||||
$payload['company_preparation'] = $snapshot;
|
||||
$case->version++;
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
|
||||
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
|
||||
|
||||
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Lead;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class CrmNextAction
|
||||
{
|
||||
/** @return Builder<CrmTask> */
|
||||
public function future(Lead $lead, ?string $exceptTask = null): Builder
|
||||
{
|
||||
return CrmTask::availableForWork()->where('tasks.lead_id', $lead->id)->where('tasks.due_at', '>', now())
|
||||
->when($exceptTask !== null, fn ($query) => $query->where('tasks.id', '!=', $exceptTask));
|
||||
}
|
||||
|
||||
/** Both write paths lock the dossier (when linked), lead, then task before checking. */
|
||||
public function assertMayFinish(?Lead $lead, CrmTask $task, string $status): void
|
||||
{
|
||||
if ($lead !== null && ! $lead->trashed() && in_array($lead->status, ['new', 'qualified'], true)
|
||||
&& in_array($status, ['done', 'cancelled'], true) && ! $this->future($lead, $task->id)->exists()) {
|
||||
throw ValidationException::withMessages(['status' => 'Crie a próxima acção com prazo futuro antes de encerrar a última tarefa de um acompanhamento activo. Tarefas num dossier encerrado não estão disponíveis.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
final class CrmTaskCreation
|
||||
{
|
||||
private const SOURCE = 'portal-crm-task-creation';
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param array<int,int> $assignees
|
||||
* @return array{task_id:string,version:int,replayed:bool}
|
||||
*/
|
||||
public function create(User $actor, Lead $lead, array $input, array $assignees): array
|
||||
{
|
||||
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
|
||||
$data = Validator::make($input, ['client_key' => 'nullable|uuid', 'title' => 'required|string|max:200', 'due_at' => 'required|date', 'assignee_user_id' => 'required|integer'])->validate();
|
||||
$key = is_string($data['client_key'] ?? null) ? strtolower($data['client_key']) : null;
|
||||
$values = ['title' => trim($data['title']), 'due_at' => CarbonImmutable::parse($data['due_at'])->utc()->format('Y-m-d\TH:i:s.u\Z'), 'assignee_user_id' => (int) $data['assignee_user_id']];
|
||||
$hash = hash('sha256', json_encode($values, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $lead, $values, $key, $hash, $assignees) {
|
||||
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
|
||||
if ($key !== null) {
|
||||
$event = $this->query($actor, $lead)->whereRaw("after_data->'task_creation'->>'key' = ?", [$key])->selectRaw("entity_id,after_data->'task_creation'->>'hash' AS hash,after_data->'task_creation'->'version' AS version")->first();
|
||||
if ($event) {
|
||||
abort_unless($event->hash === $hash, 409, 'Esta tentativa já foi usada com outros dados. Compare as tarefas antes de continuar.');
|
||||
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
||||
abort_unless(is_string($event->entity_id) && Str::isUuid($event->entity_id) && is_int($version) && $version > 0, 409, 'A criação anterior não foi identificada com segurança.');
|
||||
|
||||
return ['task_id' => $event->entity_id, 'version' => $version, 'replayed' => true];
|
||||
}
|
||||
}
|
||||
Validator::make($values, ['title' => 'required|string|max:200', 'due_at' => 'required|date|after:now', 'assignee_user_id' => ['required', 'integer', Rule::in($assignees)]])->validate();
|
||||
$task = new CrmTask;
|
||||
PortalAudit::save($task, [...$values, 'lead_id' => $lead->id, 'status' => 'open'], $actor->id);
|
||||
if ($key !== null) {
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id, 'entity_type' => 'tasks', 'entity_id' => $task->id, 'action' => 'created', 'data_classification' => 'internal',
|
||||
'after_data' => json_encode(['task_creation' => ['lead_id' => $lead->id, 'key' => $key, 'hash' => $hash, 'version' => (int) $task->getAttribute('version_no')]], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
return ['task_id' => $task->id, 'version' => (int) $task->getAttribute('version_no'), 'replayed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{lead_id:string,actor_id:int,commands:list<array{key:string,task_id:string,version:int}>,preparation:array<string,mixed>} */
|
||||
public function context(User $actor, Lead $lead): array
|
||||
{
|
||||
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
|
||||
$commands = [];
|
||||
foreach ($this->query($actor, $lead)->orderBy('occurred_at')->selectRaw("entity_id,after_data->'task_creation'->>'key' AS key,after_data->'task_creation'->'version' AS version")->get() as $event) {
|
||||
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
||||
if (is_string($event->key) && Str::isUuid($event->key) && is_string($event->entity_id) && Str::isUuid($event->entity_id) && is_int($version) && $version > 0) {
|
||||
$commands[] = ['key' => $event->key, 'task_id' => $event->entity_id, 'version' => $version];
|
||||
}
|
||||
}
|
||||
|
||||
return ['lead_id' => $lead->id, 'actor_id' => $actor->id, 'commands' => $commands, 'preparation' => app(CrmTaskPreparations::class)->view($actor, $lead)];
|
||||
}
|
||||
|
||||
private function query(User $actor, Lead $lead): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', 'tasks')->where('action', 'created')
|
||||
->whereRaw("after_data->'task_creation'->>'lead_id' = ?", [$lead->id]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class CrmTaskPreparations
|
||||
{
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('crm_task_preparations');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function view(User $actor, Lead $lead): array
|
||||
{
|
||||
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
|
||||
$row = $this->installed() ? DB::table('crm_task_preparations')->where('actor_id', $actor->id)->where('lead_id', $lead->id)->first() : null;
|
||||
$snapshot = null;
|
||||
$unavailable = false;
|
||||
if ($row) {
|
||||
try {
|
||||
$decoded = json_decode(Crypt::decryptString($row->snapshot), true);
|
||||
$validator = Validator::make(['snapshot' => $decoded], $this->rules());
|
||||
if ($validator->fails()) {
|
||||
$unavailable = true;
|
||||
} else {
|
||||
$snapshot = $this->normalize($validator->validated()['snapshot']);
|
||||
}
|
||||
} catch (DecryptException) {
|
||||
$unavailable = true;
|
||||
}
|
||||
}
|
||||
|
||||
return ['installed' => $this->installed(), 'version' => (int) ($row->version ?? 0), 'snapshot' => $snapshot, 'operation_key' => $row->operation_key ?? null,
|
||||
'updated_at' => $row->updated_at ?? null, 'unavailable' => $unavailable];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, Lead $lead, array $input): array
|
||||
{
|
||||
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
|
||||
abort_unless($this->installed(), 409, 'A recuperação persistente ainda não está instalada. A criação manual continua disponível.');
|
||||
$data = Validator::make($input, [...$this->rules(), 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid'])->validate();
|
||||
$data['snapshot'] = $this->normalize($data['snapshot']);
|
||||
$key = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode(Arr::sortRecursive(['version' => (int) $data['version'], 'snapshot' => $data['snapshot']]), JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $lead, $data, $key, $hash): array {
|
||||
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
|
||||
$row = DB::table('crm_task_preparations')->where('actor_id', $actor->id)->where('lead_id', $lead->id)->lockForUpdate()->first();
|
||||
if ($row && $row->operation_key === $key) {
|
||||
abort_unless(hash_equals($row->operation_sha256, $hash), 409, 'Esta tentativa de guardar já foi usada com outros dados.');
|
||||
|
||||
return app(CrmTaskCreation::class)->context($actor, $lead);
|
||||
}
|
||||
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'A preparação mudou noutro separador. Compare antes de substituir.');
|
||||
if ($row) {
|
||||
abort_if($this->view($actor, $lead)['unavailable'], 409, 'A preparação guardada não pôde ser recuperada. Os dados anteriores foram preservados.');
|
||||
}
|
||||
$version = (int) ($row->version ?? 0) + 1;
|
||||
DB::table('crm_task_preparations')->updateOrInsert(['actor_id' => $actor->id, 'lead_id' => $lead->id], [
|
||||
'version' => $version, 'operation_key' => $key, 'operation_sha256' => $hash,
|
||||
'snapshot' => Crypt::encryptString(json_encode($data['snapshot'], JSON_THROW_ON_ERROR)),
|
||||
'created_at' => $row->created_at ?? now(), 'updated_at' => now(),
|
||||
]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-crm-task-preparation', 'entity_type' => 'crm_task_preparations', 'entity_id' => $lead->id,
|
||||
'actor_user_id' => $actor->id, 'action' => 'draft_checkpoint_saved', 'data_classification' => 'restricted', 'after_data' => json_encode(['version' => $version], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return app(CrmTaskCreation::class)->context($actor, $lead);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot
|
||||
* @return array<string,mixed> */
|
||||
private function normalize(array $snapshot): array
|
||||
{
|
||||
foreach (['title', 'due_at', 'assignee_user_id'] as $field) {
|
||||
$snapshot['generation'][$field] = (int) $snapshot['generation'][$field];
|
||||
if (is_array($snapshot['pending'])) {
|
||||
$snapshot['pending']['generation'][$field] = (int) $snapshot['pending']['generation'][$field];
|
||||
}
|
||||
}
|
||||
if (is_array($snapshot['pending'])) {
|
||||
$snapshot['pending']['values']['client_key'] = strtolower($snapshot['pending']['values']['client_key']);
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function rules(): array
|
||||
{
|
||||
$rules = ['snapshot' => 'required|array:values,generation,pending', 'snapshot.values' => 'required|array:title,due_at,assignee_user_id',
|
||||
'snapshot.generation' => 'required|array:title,due_at,assignee_user_id', 'snapshot.pending' => 'present|nullable|array:values,generation',
|
||||
'snapshot.pending.values' => 'required_with:snapshot.pending|array:title,due_at,assignee_user_id,client_key',
|
||||
'snapshot.pending.generation' => 'required_with:snapshot.pending|array:title,due_at,assignee_user_id',
|
||||
'snapshot.pending.values.client_key' => 'required_with:snapshot.pending|uuid'];
|
||||
foreach (['title' => 200, 'due_at' => 100, 'assignee_user_id' => 20] as $field => $limit) {
|
||||
$rules['snapshot.values.'.$field] = 'present|string|max:'.$limit;
|
||||
$rules['snapshot.generation.'.$field] = 'present|integer|min:0|max:1000000000';
|
||||
$rules['snapshot.pending.values.'.$field] = 'exclude_without:snapshot.pending|present|string|max:'.$limit;
|
||||
$rules['snapshot.pending.generation.'.$field] = 'exclude_without:snapshot.pending|present|integer|min:0|max:1000000000';
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** Personal follow-up only: assignment never grants authority beyond the destination. */
|
||||
final class DashboardWorkQueue
|
||||
{
|
||||
/**
|
||||
* @param array<string, int> $pages
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function forActor(User $actor, array $pages): ?array
|
||||
{
|
||||
$now = CarbonImmutable::now()->startOfSecond();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$manager = $actor->can('manage-portal') && ! $access->has($actor, 'auditor');
|
||||
$groups = [];
|
||||
if (app(ScopedPortalAdministration::class)->interestOperator($actor)) {
|
||||
$query = DB::table('interest_requests')->where('assigned_to', $actor->id)->whereNull('deleted_at')
|
||||
->whereNotIn('status', ['closed', 'cancelled', 'refused', 'converted'])
|
||||
->select(['id', 'reference', 'next_action as title', 'status', 'next_action_due_at as due_at']);
|
||||
$groups['interests'] = $this->group($query, 'interests', $pages, $now);
|
||||
}
|
||||
if (app(VirtualDesk::class)->installed()) {
|
||||
$assigned = DB::table('desk_requests')->where('analyst_id', $actor->id);
|
||||
// Direct request consultation already permits the assigned analyst, independently of decision authority.
|
||||
if ($manager || $assigned->exists()) {
|
||||
$query = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')
|
||||
->where('r.analyst_id', $actor->id)->whereNull('c.closed_at')
|
||||
->whereNotIn('r.status', ['draft', 'cancelled', 'closed'])
|
||||
->select(['r.id', 'r.protocol as reference', 'c.title', 'r.status', 'r.due_at']);
|
||||
$groups['desk'] = $this->group($query, 'desk', $pages, $now);
|
||||
}
|
||||
}
|
||||
if ($manager && Schema::hasTable('tasks') && Schema::hasTable('leads')) {
|
||||
$query = CrmTask::availableForWork()->join('leads as l', 'l.id', '=', 'tasks.lead_id')
|
||||
->where('tasks.assignee_user_id', $actor->id)->whereNull('l.deleted_at')
|
||||
->select(['tasks.id', 'tasks.title', 'tasks.status', 'tasks.due_at', 'l.id as parent_id', 'l.title as reference']);
|
||||
$groups['crm_tasks'] = $this->group($query->toBase(), 'crm_tasks', $pages, $now);
|
||||
}
|
||||
|
||||
return $groups === [] ? null : ['as_of' => $now->toISOString(), 'groups' => $groups, 'desk_states' => config('virtual-desk.request_states')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param 'interests'|'desk'|'crm_tasks' $kind
|
||||
* @param array<string, int> $pages
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function group(Builder $query, string $kind, array $pages, CarbonImmutable $now): array
|
||||
{
|
||||
[$deadline, $order, $idColumn] = match ($kind) {
|
||||
'interests' => ['next_action_due_at', 'next_action_due_at ASC NULLS LAST', 'id'],
|
||||
'desk' => ['r.due_at', 'r.due_at ASC NULLS LAST', 'r.id'],
|
||||
'crm_tasks' => ['tasks.due_at', 'tasks.due_at ASC NULLS LAST', 'tasks.id'],
|
||||
};
|
||||
$pageName = $kind.'_page';
|
||||
$page = $pages[$pageName] ?? 1;
|
||||
$total = (clone $query)->count();
|
||||
$overdue = (clone $query)->where($deadline, '<', $now)->count();
|
||||
$lastPage = max(1, (int) ceil($total / 5));
|
||||
// An assignment may disappear between visits. Recover to an existing page instead of trapping a stale URL.
|
||||
$page = min($page, $lastPage);
|
||||
$items = (clone $query)->orderByRaw($order)->orderBy($idColumn)
|
||||
->offset(($page - 1) * 5)->limit(5)->get()->map(function (\stdClass $row) use ($kind, $now): array {
|
||||
$due = $row->due_at === null ? null : CarbonImmutable::parse($row->due_at);
|
||||
|
||||
return ['id' => (string) $row->id, 'title' => $row->title ?: 'Acompanhar manifestação', 'reference' => $row->reference,
|
||||
'status' => $row->status, 'due_at' => $due?->toISOString(), 'overdue' => $due?->lessThan($now) ?? false,
|
||||
'href' => match ($kind) {
|
||||
'interests' => '/management/interests/'.$row->id,
|
||||
'desk' => '/balcao-virtual/pedidos/'.$row->id,
|
||||
'crm_tasks' => '/management/crm/leads/'.$row->parent_id.'#crm-task-'.$row->id,
|
||||
}];
|
||||
})->all();
|
||||
|
||||
return ['total' => $total, 'overdue' => $overdue, 'items' => $items, 'page' => $page, 'last_page' => $lastPage,
|
||||
'previous' => $page > 1 ? route('dashboard', [...$pages, $pageName => $page - 1], absolute: false) : null,
|
||||
'next' => $page < $lastPage ? route('dashboard', [...$pages, $pageName => $page + 1], absolute: false) : null];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
final class DemographicEvidence
|
||||
{
|
||||
public function territories(): Builder
|
||||
{
|
||||
$public = app(InvestmentGeography::class)->publicReferences();
|
||||
|
||||
return DB::table('geo_locations')->whereNull('deleted_at')->whereIn('location_type', ['province', 'district'])
|
||||
->where(function ($q) use ($public) {
|
||||
$q->whereIn('id', (clone $public)->select('id'));
|
||||
if ($this->installed() && str_ends_with(DB::connection()->getDatabaseName(), '_test')) {
|
||||
// Macate/Vanduzi: expressly authorised QA references, never active registry changes.
|
||||
$q->orWhere(fn ($qa) => $qa->where('source_system', 'ine-demography-qa')->where('data_classification', 'public')->whereIn('parent_id', (clone $public)->select('id')));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return (bool) config('demography.enabled', app()->environment('local', 'testing'))
|
||||
&& Schema::hasTable('demographic_imports') && Schema::hasTable('demographic_observations');
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
public static function sectors(): array
|
||||
{
|
||||
return ['commerce' => 'Comércio e serviços', 'industry' => 'Indústria', 'agriculture' => 'Agricultura e agro-indústria', 'education' => 'Educação', 'health' => 'Saúde', 'general' => 'Contexto geral'];
|
||||
}
|
||||
|
||||
/** @param list<string> $territories
|
||||
* @return array<string,mixed> */
|
||||
public function analyse(array $territories, int $start, int $end, string $sector = 'general', ?string $edition = null): array
|
||||
{
|
||||
$result = ['state' => 'unavailable', 'start_year' => $start, 'end_year' => $end, 'sector' => $sector, 'territories' => [], 'differences' => [], 'comparisons' => [],
|
||||
'limitations' => ['População residente não mede procura efectiva ou poder de compra.', 'Idade activa não demonstra disponibilidade ou qualificação de mão-de-obra.',
|
||||
'Sem extrapolação: anos sem série oficial permanecem sem dados.', 'A demografia não altera impostos, incentivos ou probabilidades de sucesso.']];
|
||||
if (! $this->installed() || $territories === []) {
|
||||
return $result;
|
||||
}
|
||||
$locations = $this->territories()->whereIn('id', $territories)->get(['id', 'name', 'location_type']);
|
||||
$records = DB::table('demographic_observations as o')->join('demographic_imports as b', 'b.id', '=', 'o.import_id')
|
||||
->where('b.status', 'approved')->whereIn('o.geo_location_id', $locations->pluck('id'))->whereBetween('o.year', [$start, $end])
|
||||
->where('o.sex', 'all')->when($edition, fn ($q) => $q->where('b.id', $edition))
|
||||
->orderBy('o.year')->orderBy('o.import_id')->orderBy('o.id')
|
||||
->get(['o.*', 'b.source', 'b.publication_version', 'b.sha256', 'b.file_name']);
|
||||
$issuesByImport = DB::table('demographic_imports')->whereIn('id', $records->pluck('import_id')->unique()->all())
|
||||
->get(['id', DB::raw("report->'issue_counts' AS issue_counts")])->keyBy('id');
|
||||
foreach ($locations as $location) {
|
||||
$series = [];
|
||||
foreach ($records->where('geo_location_id', $location->id)->groupBy('import_id') as $importId => $rows) {
|
||||
$first = $rows->first();
|
||||
$issueCounts = json_decode($issuesByImport->get($importId)->issue_counts ?? '{}', true, 512, JSON_THROW_ON_ERROR);
|
||||
$values = $rows->filter(function ($r) use ($sector) {
|
||||
if ($r->indicator !== 'population') {
|
||||
return in_array($sector, ['health', 'general'], true);
|
||||
}
|
||||
|
||||
return $r->age_group === 'all' || in_array($sector, ['education', 'health', 'industry', 'agriculture', 'general'], true);
|
||||
})->map(fn ($r) => ['year' => $r->year, 'indicator' => $r->indicator, 'age_group' => $r->age_group, 'residence' => $r->residence,
|
||||
'value' => $r->numeric_value, 'original_value' => $r->original_value, 'unit' => $r->unit, 'data_kind' => $r->data_kind,
|
||||
'sheet' => $r->sheet, 'cell' => $r->cell, 'validation_status' => $r->validation_status])->values()->all();
|
||||
$years = array_values(array_unique(array_column($values, 'year')));
|
||||
$series[] = ['import_id' => $importId, 'source' => $first->source, 'version' => $first->publication_version, 'sha256' => $first->sha256, 'file_name' => $first->file_name,
|
||||
'values' => $values, 'missing_years' => array_values(array_diff(range($start, $end), $years)), 'issue_counts' => $issueCounts];
|
||||
}
|
||||
$result['territories'][] = ['id' => $location->id, 'name' => $location->name, 'level' => $location->location_type, 'series' => $series,
|
||||
'factors_to_assess' => match ($sector) {
|
||||
'industry' => ['Estrutura etária e evolução da população; verificar qualificações, mobilidade e emprego.'],
|
||||
'agriculture' => ['População rural e mercados locais; relacionar com os clusters documentados.'],
|
||||
'education' => ['Grupos etários da população-alvo; verificar cobertura e capacidade dos serviços.'],
|
||||
'health' => ['Estrutura etária e estatísticas vitais com unidades conhecidas; verificar cobertura dos serviços.'],
|
||||
default => ['Dimensão e evolução da população; confrontar com rendimento, acesso e condições sectoriais.'],
|
||||
}];
|
||||
}
|
||||
// Identify concurrent values without summing editions or choosing a supposedly newer one.
|
||||
foreach ($result['territories'] as $territory) {
|
||||
$byDimension = [];
|
||||
foreach ($territory['series'] as $series) {
|
||||
foreach ($series['values'] as $row) {
|
||||
$key = implode('|', [$row['year'], $row['indicator'], $row['age_group'], $row['residence'], $row['unit']]);
|
||||
$byDimension[$key][] = ['import_id' => $series['import_id'], 'value' => $row['value'], 'data_kind' => $row['data_kind']];
|
||||
}
|
||||
}
|
||||
foreach ($byDimension as $key => $values) {
|
||||
if (count($values) > 1) {
|
||||
$result['differences'][] = ['territory_id' => $territory['id'], 'dimension' => $key, 'state' => count(array_unique(array_column($values, 'value'))) === 1 ? 'matching_values' : 'divergent_values', 'values' => $values];
|
||||
}
|
||||
}
|
||||
}
|
||||
$result['state'] = $records->isEmpty() ? 'no_data' : 'available';
|
||||
foreach ($result['territories'] as $i => $left) {
|
||||
foreach (array_slice($result['territories'], $i + 1) as $right) {
|
||||
foreach ($left['series'] as $a) {
|
||||
foreach ($right['series'] as $b) {
|
||||
foreach (array_unique([$start, $end]) as $year) {
|
||||
$isTotal = fn ($r) => $r['year'] === $year && $r['indicator'] === 'population' && $r['age_group'] === 'all' && $r['residence'] === 'all';
|
||||
$x = array_values(array_filter($a['values'], $isTotal))[0] ?? null;
|
||||
$y = array_values(array_filter($b['values'], $isTotal))[0] ?? null;
|
||||
if (! $x || ! $y) {
|
||||
continue;
|
||||
}
|
||||
$comparable = $left['level'] === $right['level'] && $x['unit'] === $y['unit'] && $x['data_kind'] === $y['data_kind'] && $a['version'] === $b['version'];
|
||||
$delta = $comparable ? DB::selectOne('SELECT (?::numeric - ?::numeric)::text AS value', [$x['value'], $y['value']])->value : null;
|
||||
$result['comparisons'][] = ['year' => $year, 'left' => $left['name'], 'right' => $right['name'], 'left_value' => $x['value'], 'right_value' => $y['value'],
|
||||
'left_import' => $a['import_id'], 'right_import' => $b['import_id'], 'difference' => $delta,
|
||||
'explanation' => $comparable ? 'Diferença dos totais de população no mesmo ano, nível, tipo de dado, unidade e identificação de edição. Não mede procura efectiva.' : 'Âmbitos ou metadados distintos; não se calculou uma diferença como se fossem equivalentes.'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context
|
||||
* @return array<string,mixed> */
|
||||
public function forContext(array $context): array
|
||||
{
|
||||
$fields = $context['fields'] ?? [];
|
||||
$id = ($fields['district_id'] ?? null) ?: ($fields['province_id'] ?? null);
|
||||
|
||||
// No inference from an influence area to a project's implantation territory.
|
||||
return $this->analyse($id ? [$id] : [], (int) date('Y'), (int) date('Y'), 'general');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Support\CheckedFile;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
final class DemographicImport
|
||||
{
|
||||
/**
|
||||
* CLI preparation is read-only input, never an import or approval.
|
||||
* @return array{preview:string,records:string,receipt:array<string,mixed>}|null
|
||||
*/
|
||||
public function preparedSource(string $sha, ?int $baselineYear, bool $verifyRecords = true): ?array
|
||||
{
|
||||
$root = config('demography.prepared_directory');
|
||||
if (! is_string($root) || $root === '') { return null; }
|
||||
abort_unless(preg_match('/^[a-f0-9]{64}$/', $sha) === 1, 422);
|
||||
$directory = $root.'/'.$sha;
|
||||
if (! is_file($directory.'/preparation.json')) { return null; }
|
||||
abort_unless(is_readable($directory.'/preparation.json'), 409, 'Recibo CLI indisponível.');
|
||||
try { $receipt = json_decode(CheckedFile::read($directory.'/preparation.json'), true, 512, JSON_THROW_ON_ERROR); }
|
||||
catch (\JsonException) { abort(409, 'Recibo CLI inválido.'); }
|
||||
abort_unless(is_array($receipt), 409, 'Recibo CLI inválido.');
|
||||
$preview = $directory.'/preview.json';
|
||||
$records = $directory.'/records.ndjson';
|
||||
abort_unless(($receipt['sha256'] ?? '') === $sha && array_key_exists('baseline_year', $receipt) && $receipt['baseline_year'] === $baselineYear
|
||||
&& ($receipt['parser_sha256'] ?? '') === CheckedFile::sha256(base_path('tools/demography_workbook.py'))
|
||||
&& is_file($preview) && CheckedFile::matches($preview, $receipt['preview_sha256'] ?? '') && is_file($records), 409, 'A preparação CLI mudou; conservar o original e preparar novamente fora do servidor web.');
|
||||
try { $report = json_decode(CheckedFile::read($preview), true, 512, JSON_THROW_ON_ERROR); }
|
||||
catch (\JsonException) { abort(409, 'Prévia CLI inválida.'); }
|
||||
abort_unless(is_array($report), 409, 'Prévia CLI inválida.');
|
||||
abort_unless(($report['sha256'] ?? '') === $sha && ($report['record_count'] ?? null) === ($receipt['record_count'] ?? null)
|
||||
&& ($report['records_file_sha256'] ?? '') === ($receipt['records_sha256'] ?? '')
|
||||
&& (! $verifyRecords || CheckedFile::matches($records, $receipt['records_sha256'] ?? '')), 409, 'Resultados da preparação CLI alterados.');
|
||||
|
||||
return ['preview' => $preview, 'records' => $records, 'receipt' => $receipt];
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $files */
|
||||
public function preparedSourcesReady(array $files): bool
|
||||
{
|
||||
try {
|
||||
foreach ($files as $name => $expected) {
|
||||
$source = $this->preparedSource($expected['sha256'], $name === 'Dados demograficos.xlsx' ? 2017 : null, false);
|
||||
if ($source === null || $source['receipt']['record_count'] !== $expected['records']) { return false; }
|
||||
}
|
||||
return $files !== [];
|
||||
} catch (\Throwable) { return false; }
|
||||
}
|
||||
|
||||
public function authorize(User $actor): void
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless(($actor->can('manage-portal') || $access->superuser($actor)) && ! $access->has($actor, 'auditor'), 403);
|
||||
abort_unless($actor->two_factor_confirmed_at && $actor->two_factor_secret, 403, 'Confirme MFA para gerir dados demográficos.');
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||
abort_unless(app(DemographicInstallation::class)->activeTarget() && app(DemographicEvidence::class)->installed(), 403, 'Destino demográfico não instalado ou não autorizado.');
|
||||
abort_unless(app(PortalProfileAccess::class)->mfa($actor), 403, 'Conclua MFA nesta sessão para gerir dados demográficos.');
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function prepare(User $actor, string $file, string $name, string $version, ?int $baselineYear): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
abort_unless(is_file($file) && filesize($file) <= 20_000_000 && strtolower(pathinfo($name, PATHINFO_EXTENSION)) === 'xlsx', 422);
|
||||
$sha = CheckedFile::sha256($file);
|
||||
$existing = DB::table('demographic_imports')->where('sha256', $sha)->first();
|
||||
if ($existing) {
|
||||
return $this->preview($actor, $existing->id);
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$directory = 'demography/'.$id;
|
||||
$disk = Storage::disk('local');
|
||||
$disk->makeDirectory($directory);
|
||||
$path = $disk->path($directory.'/original.xlsx');
|
||||
abort_unless(copy($file, $path) && CheckedFile::matches($path, $sha), 409);
|
||||
$scan = app(MalwareScanner::class)->scan($path, (int) filesize($path), $disk->path($directory));
|
||||
abort_unless($scan['result'] === 'clean', 423, 'Análise antimalware pendente ou não limpa; original privado conservado.');
|
||||
$output = $disk->path($directory.'/preview.json');
|
||||
$prepared = $this->preparedSource($sha, $baselineYear);
|
||||
if ($prepared !== null) {
|
||||
abort_unless(copy($prepared['preview'], $output) && CheckedFile::matches($output, $prepared['receipt']['preview_sha256'])
|
||||
&& copy($prepared['records'], $disk->path($directory.'/records.ndjson'))
|
||||
&& CheckedFile::matches($disk->path($directory.'/records.ndjson'), $prepared['receipt']['records_sha256']), 409, 'Preparação CLI alterada durante a cópia.');
|
||||
} else {
|
||||
abort_unless(function_exists('proc_open'), 503, 'Este servidor web não executa o preparador. Prepare este original pelo importador CLI e confira o respectivo recibo antes de continuar.');
|
||||
$command = [config('demography.python', 'python'), base_path('tools/demography_workbook.py'), $path, '--output', $output, '--records-output', $disk->path($directory.'/records.ndjson')];
|
||||
if ($baselineYear !== null) {
|
||||
array_push($command, '--baseline-year', (string) $baselineYear);
|
||||
}
|
||||
$process = new Process($command, base_path(), timeout: 120);
|
||||
$process->run();
|
||||
abort_unless($process->isSuccessful(), 422, 'Não foi possível reconhecer o Excel; confira a estrutura e o ano de referência.');
|
||||
}
|
||||
$report = json_decode(CheckedFile::read($output), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(hash_equals($sha, $report['sha256']) && CheckedFile::matches($path, $sha), 409);
|
||||
$summary = array_diff_key($report, ['records' => true]);
|
||||
$summary['scan'] = ['result' => $scan['result'], 'engine' => $scan['engine'], 'engine_version' => $scan['engine_version'], 'sha256' => $sha];
|
||||
// The supplied publication label is provenance metadata, never an invented edition/date.
|
||||
DB::table('demographic_imports')->insert(['id' => $id, 'sha256' => $sha, 'file_name' => basename($name),
|
||||
'source' => $report['source'], 'publication_version' => $version, 'status' => 'prepared',
|
||||
'report' => json_encode($summary, JSON_THROW_ON_ERROR), 'preview_sha256' => CheckedFile::sha256($output),
|
||||
'prepared_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->event($id, $actor, 'prepared', 'Pré-visualização do original; sem aprovação de utilização.', ['sha256' => $sha]);
|
||||
|
||||
return $this->preview($actor, $id);
|
||||
}
|
||||
|
||||
public static function key(string $province, string $territory, string $level): string
|
||||
{
|
||||
return $province.'|'.$territory.'|'.$level;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor, string $id): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
$batch = DB::table('demographic_imports')->where('id', $id)->first();
|
||||
abort_unless($batch !== null, 404);
|
||||
$report = json_decode($batch->report, true, 512, JSON_THROW_ON_ERROR);
|
||||
$locations = DB::table('geo_locations')->whereIn('location_type', ['province', 'district'])->whereNull('deleted_at')->get(['id', 'name', 'parent_id', 'location_type']);
|
||||
$matches = [];
|
||||
foreach ($report['territories'] as [$province, $territory, $level]) {
|
||||
$provinces = $locations->filter(fn ($g) => $g->location_type === 'province' && $this->normalize($g->name) === $this->normalize($province));
|
||||
$candidates = $level === 'province' ? $provinces : $locations->filter(fn ($g) => $g->location_type === 'district' && $provinces->contains('id', $g->parent_id) && $this->normalize($g->name) === $this->normalize($territory));
|
||||
$key = self::key($province, $territory, $level);
|
||||
if ($level === 'district') {
|
||||
$headers = $report['territory_headers'][$key] ?? [];
|
||||
if ($headers !== [] && $candidates->count() > 1 && array_all($headers, fn ($h) => preg_match('/^Distrito de /i', $h) === 1)) {
|
||||
$candidates = $candidates->filter(fn ($g) => ! preg_match('/^CIDADE /i', $g->name));
|
||||
}
|
||||
if ($headers !== [] && $candidates->count() > 1 && array_all($headers, fn ($h) => preg_match('/^Cidade (de|da) /i', $h) === 1)) {
|
||||
$candidates = $candidates->filter(fn ($g) => preg_match('/^CIDADE /i', $g->name) === 1);
|
||||
}
|
||||
$manifest = DemographicInstallation::remainingManifest();
|
||||
$hashes = array_column($manifest['files'], 'sha256');
|
||||
$alias = in_array($batch->sha256, $hashes, true) ? ($manifest['aliases'][$key] ?? null) : null;
|
||||
if ($alias !== null) {
|
||||
$candidates = $locations->filter(fn ($g) => $g->location_type === 'district' && $provinces->contains('id', $g->parent_id) && $this->literal($g->name) === $this->literal($alias));
|
||||
}
|
||||
}
|
||||
$matches[] = ['key' => self::key($province, $territory, $level), 'province' => $province, 'territory' => $territory, 'level' => $level,
|
||||
'geo_location_id' => $candidates->count() === 1 ? $candidates->first()->id : null, 'state' => $candidates->count() === 1 ? 'matched' : ($candidates->isEmpty() ? 'missing' : 'ambiguous')];
|
||||
}
|
||||
|
||||
return ['id' => $id, 'file_name' => $batch->file_name, 'sha256' => $batch->sha256, 'publication_version' => $batch->publication_version,
|
||||
'status' => $batch->status, 'report' => $report, 'matches' => $matches,
|
||||
'territory_options' => $locations->values()->all(), 'events' => DB::table('demographic_events')->where('import_id', $id)->orderBy('id')->get()];
|
||||
}
|
||||
|
||||
private function normalize(string $name): string
|
||||
{
|
||||
return preg_replace('/^(cidade|distrito) (de|da) /', '', $this->literal($name));
|
||||
}
|
||||
|
||||
private function literal(string $name): string
|
||||
{
|
||||
$name = str_replace(['`', '’', '‘', '´'], "'", Str::ascii($name));
|
||||
return preg_replace('/\s+/', ' ', trim(strtolower(str_replace(['-', '–'], ' ', $name))));
|
||||
}
|
||||
|
||||
/** @param array<string,string> $mapping
|
||||
* @return array<string,mixed> */
|
||||
public function confirm(User $actor, string $id, string $sha, array $mapping, string $reason): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $sha, $mapping, $reason) {
|
||||
$batch = DB::table('demographic_imports')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($batch && hash_equals($batch->sha256, $sha), 409);
|
||||
if ($batch->status !== 'prepared') {
|
||||
return ['id' => $id, 'status' => $batch->status, 'records' => DB::table('demographic_observations')->where('import_id', $id)->count(), 'repeated' => true];
|
||||
}
|
||||
$disk = Storage::disk('local');
|
||||
$file = $disk->path('demography/'.$id.'/preview.json');
|
||||
abort_unless(is_file($file) && CheckedFile::matches($file, $batch->preview_sha256) && CheckedFile::matches($disk->path('demography/'.$id.'/original.xlsx'), $sha), 409, 'Prévia ou original alterados.');
|
||||
$report = json_decode(CheckedFile::read($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$blocking = array_intersect(array_keys($report['issue_counts']), ['conflicting_value', 'duplicate_value', 'unsupported_sheet', 'unsupported_population_headers', 'reference_year_required', 'title_year_mismatch', 'invalid_numeric_or_formula']);
|
||||
abort_if($blocking !== [], 422, 'Corrija os erros estruturais antes de confirmar: '.implode(', ', $blocking));
|
||||
$plan = $this->preview($actor, $id);
|
||||
$resolved = [];
|
||||
foreach ($plan['matches'] as $match) {
|
||||
$locationId = $mapping[$match['key']] ?? $match['geo_location_id'];
|
||||
$location = DB::table('geo_locations')->where('id', $locationId)->whereNull('deleted_at')->first();
|
||||
abort_unless($location && $location->location_type === $match['level'], 422, 'Correspondência territorial por resolver.');
|
||||
if ($match['level'] === 'district') {
|
||||
$provinceKey = self::key($match['province'], $match['province'], 'province');
|
||||
$provinceMatch = array_values(array_filter($plan['matches'], fn ($m) => $m['key'] === $provinceKey))[0] ?? null;
|
||||
abort_unless($location->parent_id === ($mapping[$provinceKey] ?? $provinceMatch['geo_location_id'] ?? null), 422, 'Distrito fora da província indicada.');
|
||||
}
|
||||
abort_if(in_array($locationId, $resolved, true), 422, 'Duas designações não podem ser fundidas na mesma localização.');
|
||||
$resolved[$match['key']] = $locationId;
|
||||
}
|
||||
$chunk = [];
|
||||
$recordCount = 0;
|
||||
foreach ($this->recordRows($report, $disk->path('demography/'.$id.'/records.ndjson')) as $row) {
|
||||
$recordCount++;
|
||||
$chunk[] = ['import_id' => $id, 'geo_location_id' => $resolved[self::key($row['province'], $row['territory'], $row['level'])],
|
||||
...array_intersect_key($row, array_flip(['year', 'indicator', 'sex', 'residence', 'age_group', 'unit', 'data_kind', 'original_value', 'numeric_value', 'sheet', 'cell'])),
|
||||
'validation_status' => $report['issues'] === [] ? 'valid' : 'warning'];
|
||||
if (count($chunk) === 500) {
|
||||
DB::table('demographic_observations')->insert($chunk);
|
||||
$chunk = [];
|
||||
}
|
||||
}
|
||||
if ($chunk !== []) {
|
||||
DB::table('demographic_observations')->insert($chunk);
|
||||
}
|
||||
abort_unless($recordCount === $report['record_count'], 409, 'O número de observações difere da prévia.');
|
||||
DB::table('demographic_imports')->where('id', $id)->update(['status' => 'imported', 'updated_at' => now()]);
|
||||
$this->event($id, $actor, 'imported', $reason, ['mapping' => $resolved, 'records' => $recordCount, 'sha256' => $sha]);
|
||||
|
||||
return ['id' => $id, 'status' => 'imported', 'records' => $recordCount, 'repeated' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $report
|
||||
* @return iterable<array<string,mixed>> */
|
||||
private function recordRows(array $report, string $path): iterable
|
||||
{
|
||||
if (! isset($report['records_file_sha256'])) {
|
||||
yield from $report['records'];
|
||||
return;
|
||||
}
|
||||
abort_unless(is_file($path) && CheckedFile::matches($path, $report['records_file_sha256']), 409, 'As observações diferem da prévia conferida.');
|
||||
$stream = new \SplFileObject($path, 'r');
|
||||
while (! $stream->eof()) {
|
||||
$line = $stream->fgets();
|
||||
if (trim($line) === '') { continue; }
|
||||
yield json_decode($line, true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
public function transition(User $actor, string $id, string $action, string $reason): void
|
||||
{
|
||||
$this->authorize($actor);
|
||||
DB::transaction(function () use ($actor, $id, $action, $reason) {
|
||||
$batch = DB::table('demographic_imports')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($batch !== null, 404);
|
||||
abort_unless(in_array($action, ['approved', 'disabled'], true) && $batch->status !== 'prepared', 422);
|
||||
// No deletes, replacement of other editions, or automatic publication in production.
|
||||
DB::table('demographic_imports')->where('id', $id)->update(['status' => $action, 'updated_at' => now()]);
|
||||
$this->event($id, $actor, $action, $reason, ['previous_status' => $batch->status]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $details */
|
||||
private function event(string $id, User $actor, string $action, string $reason, array $details): void
|
||||
{
|
||||
DB::table('demographic_events')->insert(['import_id' => $id, 'actor_id' => $actor->id, 'action' => $action, 'reason' => $reason, 'details' => json_encode($details, JSON_THROW_ON_ERROR), 'created_at' => now()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Process\Exception\ExceptionInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/** Owner-authorised release; schema and data still require existing session MFA. */
|
||||
final class DemographicInstallation
|
||||
{
|
||||
public const MIGRATION = '2026_11_13_100000_create_demographic_series';
|
||||
|
||||
public const MANICA_SHA256 = '0c6d8feaefaed797fa57d61f923af5a86f37ac4b16f12d7d72ae1be8087ea698';
|
||||
|
||||
public const FILES = [
|
||||
'Manica.xlsx' => ['sha256' => self::MANICA_SHA256, 'records' => 71604],
|
||||
'Inhambane.xlsx' => ['sha256' => '51a9b91dfb6e32e5b49def115cb007f21faa97b3d0584b16ef911b22b89bd818', 'records' => 82620],
|
||||
'Dados demograficos.xlsx' => ['sha256' => '4763aaa7476f3ae24564e9750ac2ac8babb07dfbba67473a180fb9b1f47eb335', 'records' => 482],
|
||||
];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function remainingManifest(): array
|
||||
{
|
||||
return json_decode(CheckedFile::read(database_path('data/demography-remaining-20261113.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function zambeziaManifest(): array
|
||||
{
|
||||
return json_decode(CheckedFile::read(database_path('data/demography-zambezia-20261113.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function publicDistrictRefs(): array
|
||||
{
|
||||
$refs = [self::MANICA_SHA256.':Macate', self::MANICA_SHA256.':Vanduzi'];
|
||||
foreach ([self::remainingManifest(), self::zambeziaManifest()] as $manifest) {
|
||||
foreach ($manifest['new_districts'] as $province => $names) {
|
||||
$source = array_values(array_filter($manifest['files'], fn ($f) => $f['province'] === $province))[0]['sha256'];
|
||||
foreach ($names as $name) { $refs[] = $source.':'.$name; }
|
||||
}
|
||||
}
|
||||
return $refs;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function files(): array
|
||||
{
|
||||
return ['database/data/demography-zambezia-20261113.json', 'database/data/demography-remaining-20261113.json', 'app/Services/DemographicInstallation.php', 'app/Services/DemographicImport.php', 'app/Services/DemographicEvidence.php',
|
||||
'app/Services/InvestmentGeography.php', 'app/Services/InvestmentPreparationWorkspace.php', 'app/Http/Controllers/DemographyController.php',
|
||||
'database/migrations/'.self::MIGRATION.'.php', 'config/demography.php', 'routes/demography.php', 'routes/web.php', 'tools/demography_workbook.py',
|
||||
'resources/js/components/demographic-context.tsx', 'resources/js/components/demographic-evidence.tsx', 'resources/js/components/simulation-form.tsx',
|
||||
'resources/js/components/structure-geography.tsx', 'resources/js/pages/investment/demography.tsx', 'resources/js/pages/investment/catalogue.tsx',
|
||||
'resources/js/pages/investment/detail.tsx', 'resources/js/pages/management/demography.tsx', 'resources/js/pages/management/demography-install.tsx',
|
||||
'resources/js/pages/management/shared.tsx'];
|
||||
}
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files = [];
|
||||
foreach ($this->files() as $path) {
|
||||
$files[$path] = CheckedFile::sha256(base_path($path));
|
||||
}
|
||||
|
||||
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function activeTarget(): bool
|
||||
{
|
||||
$c = config('database.connections.pgsql');
|
||||
$homologation = config('app.url') === 'https://teste-investidor.tempo.co.mz'
|
||||
&& config('demography.enabled', false) && $c['database'] === 'teste_investidor';
|
||||
if (app()->environment('testing') || config('database.default') !== 'pgsql' || ! empty($c['url'])
|
||||
|| ! in_array($c['host'], ['127.0.0.1', 'localhost'], true) || (int) $c['port'] !== 5432
|
||||
|| ($c['database'] !== 'investemoz' && ! $homologation)) {
|
||||
return false;
|
||||
}
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
|
||||
return $target->database === $c['database'] && (int) $target->port === 5432;
|
||||
}
|
||||
|
||||
public function schemaAllowed(): bool
|
||||
{
|
||||
if (IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||
return true;
|
||||
}
|
||||
$actor = auth()->user();
|
||||
if (! config('demography.authenticated_installation', false) || ! $actor || ! $this->activeTarget()) {
|
||||
return false;
|
||||
}
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function authorize(User $actor, bool $write): void
|
||||
{
|
||||
app(PortalProfileInstallation::class)->authorize($actor, $write);
|
||||
abort_unless($this->activeTarget() || IsolatedQaDatabase::allowsSchemaChanges(), 403, 'Destino não autorizado para esta entrega.');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor, false);
|
||||
$proofFile = storage_path('app/private/demography-deployment/readiness.json');
|
||||
$proof = is_file($proofFile) ? json_decode(CheckedFile::read($proofFile), true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$code = $this->fingerprint();
|
||||
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$qa = IsolatedQaDatabase::allowsSchemaChanges();
|
||||
$ready = $qa || (($proof['code_sha256'] ?? '') === $code && ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
|
||||
&& ($proof['restore_verified'] ?? false) && ($proof['files_verified'] ?? false) && ($proof['target']['database'] ?? '') === $target['database']
|
||||
&& (int) ($proof['target']['port'] ?? 0) === (int) $target['port'] && ($proof['decision'] ?? '') !== ''
|
||||
&& strtotime($proof['verified_at'] ?? '') >= time() - 86400 && strtotime($proof['verified_at'] ?? '') <= time());
|
||||
if (! $qa) {
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
$file = $proof[$kind.'_path'] ?? '';
|
||||
$ready = $ready && is_file($file) && CheckedFile::matches($file, $proof[$kind.'_sha256'] ?? '');
|
||||
}
|
||||
$ready = $ready && CheckedFile::matches(base_path('.env'), $proof['environment_sha256'] ?? '')
|
||||
&& is_file(public_path('build/manifest.json')) && CheckedFile::matches(public_path('build/manifest.json'), $proof['release_manifest_sha256'] ?? '');
|
||||
foreach ($proof['release_files'] ?? [] as $relative => $sha) {
|
||||
$file = public_path('build/'.$relative);
|
||||
$ready = $ready && ! str_contains($relative, '..') && ! str_contains($relative, ':') && is_file($file) && CheckedFile::matches($file, $sha);
|
||||
}
|
||||
}
|
||||
$tables = array_map(fn ($t) => Schema::hasTable($t), ['demographic_imports', 'demographic_observations', 'demographic_events']);
|
||||
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
||||
$consistent = ($ledger && ! in_array(false, $tables, true)) || (! $ledger && ! in_array(true, $tables, true));
|
||||
$preparedFiles = self::FILES + self::remainingManifest()['files'] + self::zambeziaManifest()['files'];
|
||||
$runtimeReady = app(DemographicImport::class)->preparedSourcesReady($preparedFiles);
|
||||
try {
|
||||
if (! $runtimeReady && function_exists('proc_open')) {
|
||||
$runtime = new Process([config('demography.python', 'python'), '-c', 'import sys; assert sys.version_info >= (3, 9)'], base_path(), timeout: 15);
|
||||
$runtime->run();
|
||||
$runtimeReady = $runtime->isSuccessful();
|
||||
}
|
||||
} catch (ExceptionInterface) {
|
||||
$runtimeReady = false;
|
||||
}
|
||||
$mode = $ledger ? 'remaining' : 'initial';
|
||||
$manifest = self::remainingManifest();
|
||||
if ($ledger && DB::table('demographic_imports')->whereIn('sha256', array_column($manifest['files'], 'sha256'))->where('status', 'approved')->count() === count($manifest['files'])) { $mode = 'zambezia'; $manifest = self::zambeziaManifest(); }
|
||||
$files = $mode !== 'initial' ? $manifest['files'] : self::FILES;
|
||||
$already = $ledger ? DB::table('demographic_imports')->whereIn('sha256', array_column($files, 'sha256'))->where('status', 'approved')->pluck('sha256')->all() : [];
|
||||
$pending = array_filter($files, fn ($f) => ! in_array($f['sha256'], $already, true));
|
||||
$state = ['mode' => $mode, 'pending_count' => count($pending), 'aliases' => $mode !== 'initial' ? $manifest['aliases'] : [], 'alias_sources' => $mode !== 'initial' ? $manifest['sources'] : [], 'missing_province_source' => $manifest['missing_province_source'], 'target' => (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'),
|
||||
'migration' => self::MIGRATION, 'code_sha256' => $code, 'backup_verified' => $ready, 'consistent' => $consistent,
|
||||
'ready' => $ready && $consistent && $runtimeReady && count($pending) > 0, 'runtime_ready' => $runtimeReady, 'installed' => $ledger, 'files' => $files, 'new_districts' => $mode !== 'initial' ? array_merge(...array_values($manifest['new_districts'])) : ['Macate', 'Vanduzi'],
|
||||
'mfa_confirmed' => app(PortalProfileAccess::class)->mfa($actor),
|
||||
'notice' => ($runtimeReady ? '' : 'O interpretador do importador está indisponível; a execução permanece bloqueada. ').'Preservar seis advertências de Manica/2031, unidades ausentes e versões estatísticas. A instalação não corrige os originais nem concede permissões.'];
|
||||
|
||||
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||
}
|
||||
|
||||
/** @param list<string> $preservedHashes
|
||||
* @return array<string,array{count:int,sha256:string}> */
|
||||
private function protectedState(array $preservedHashes = []): array
|
||||
{
|
||||
$state = [];
|
||||
foreach (['desk_cases', 'simulation_form_drafts', 'funding_programmes', 'funding_programme_versions', 'funding_programme_interests',
|
||||
'labour_demands', 'training_capacities', 'opportunities', 'investment_dossiers', 'projects', 'economic_clusters'] as $table) {
|
||||
if (Schema::hasTable($table)) {
|
||||
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.$table.'" t ORDER BY row_to_json(t)::text');
|
||||
$state[$table] = ['count' => count($rows), 'sha256' => hash('sha256', implode("\n", array_map(fn ($r) => $r->row, $rows)))];
|
||||
}
|
||||
}
|
||||
|
||||
if (Schema::hasTable('demographic_imports')) {
|
||||
$ids = DB::table('demographic_imports')->whereIn('sha256', $preservedHashes ?: array_column(self::FILES, 'sha256'))->pluck('id');
|
||||
foreach (['demographic_imports' => 'id', 'demographic_observations' => 'import_id', 'demographic_events' => 'import_id'] as $table => $key) {
|
||||
$digest = hash_init('sha256');
|
||||
$count = 0;
|
||||
DB::table($table)->whereIn($key, $ids)->chunkById(500, function ($rows) use ($digest, &$count) {
|
||||
foreach ($rows as $row) {
|
||||
if ($count > 0) { hash_update($digest, "\n"); }
|
||||
hash_update($digest, json_encode($row, JSON_THROW_ON_ERROR));
|
||||
$count++;
|
||||
}
|
||||
});
|
||||
$state['accepted_'.$table] = ['count' => $count, 'sha256' => hash_final($digest)];
|
||||
}
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
|
||||
private function territories(User $actor): void
|
||||
{
|
||||
$province = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->whereRaw('lower(name)=?', ['manica'])->get(['id']);
|
||||
abort_unless($province->count() === 1, 422, 'Província de Manica ambígua ou indisponível.');
|
||||
foreach (['Macate', 'Vanduzi'] as $name) {
|
||||
$matches = DB::table('geo_locations')->where('parent_id', $province->first()->id)->where('location_type', 'district')->whereRaw('lower(trim(name))=?', [strtolower($name)])->get();
|
||||
if ($matches->isNotEmpty()) {
|
||||
abort_unless($matches->count() === 1 && $matches->first()->deleted_at === null, 409, 'Cadastro territorial divergente; não restaurar nem fundir automaticamente.');
|
||||
|
||||
continue;
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $province->first()->id, 'name' => $name, 'location_type' => 'district',
|
||||
'code' => 'INE-DEMOGRAPHY-'.strtoupper($name), 'source_system' => 'ine-demography', 'external_id' => self::MANICA_SHA256.':'.$name,
|
||||
'data_classification' => 'public', 'version_no' => 1, 'created_at' => now(), 'updated_at' => now()]);
|
||||
app(PortalProfileAccess::class)->audit($actor, 'demography_territory_created', ['territory_id' => $id, 'name' => $name,
|
||||
'source_sha256' => self::MANICA_SHA256, 'decision' => 'Autorização expressa do proprietário em 13/11/2026; destino conferido pelo instalador.',
|
||||
'scope' => 'Identificação territorial da série INE; sem limites geográficos ou direitos territoriais presumidos.']);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $manifest */
|
||||
private function remainingTerritories(User $actor, array $manifest): void
|
||||
{
|
||||
foreach ($manifest['new_districts'] as $province => $names) {
|
||||
$parents = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->whereRaw('lower(name)=?', [mb_strtolower($province)])->pluck('id');
|
||||
abort_unless($parents->count() === 1, 409);
|
||||
$source = array_values(array_filter($manifest['files'], fn ($f) => $f['province'] === $province))[0]['sha256'];
|
||||
foreach ($names as $name) {
|
||||
$existing = DB::table('geo_locations')->where('parent_id', $parents[0])->where('location_type', 'district')->whereRaw('lower(trim(name))=?', [mb_strtolower($name)])->get();
|
||||
if ($existing->isNotEmpty()) { abort_unless($existing->count() === 1 && $existing[0]->deleted_at === null, 409); continue; }
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parents[0], 'name' => $name, 'location_type' => 'district', 'code' => 'INE-DEMOGRAPHY-'.strtoupper($name), 'source_system' => 'ine-demography', 'external_id' => $source.':'.$name, 'data_classification' => 'public', 'version_no' => 1]);
|
||||
app(PortalProfileAccess::class)->audit($actor, 'demography_territory_created', ['territory_id' => $id, 'name' => $name, 'source_sha256' => $source, 'basis' => $manifest['authority']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true);
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'operation_key' => 'required|uuid',
|
||||
'mode' => 'nullable|in:initial,remaining,zambezia', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$mode = $data['mode'] ?? 'initial';
|
||||
$files = $mode === 'initial' ? self::FILES : ($mode === 'zambezia' ? self::zambeziaManifest()['files'] : self::remainingManifest()['files']);
|
||||
$preservedHashes = $mode === 'zambezia' ? array_column([...self::FILES, ...self::remainingManifest()['files']], 'sha256') : array_column(self::FILES, 'sha256');
|
||||
$action = $mode === 'zambezia' ? 'extend_zambezia' : ($mode === 'remaining' ? 'extend_provinces' : 'install_and_import');
|
||||
$payload = hash('sha256', json_encode($mode === 'initial' ? [$actor->id, $data['reason']] : [$actor->id, $data['reason'], $mode, $files], JSON_THROW_ON_ERROR));
|
||||
$existing = DB::table('audit_events')->where('source_system', 'demography-installation')->where('action', $action)->where('correlation_id', $data['operation_key'])->first();
|
||||
if ($existing) {
|
||||
$event = json_decode($existing->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless((int) $existing->actor_user_id === $actor->id && hash_equals($event['payload_sha256'], $payload), 409);
|
||||
|
||||
return [...$event['result'], 'repeated' => true];
|
||||
}
|
||||
$plan = $this->preview($actor);
|
||||
abort_unless($plan['ready'] && $plan['mode'] === $mode && hash_equals($plan['hash'], $data['hash']), 409, 'Consulte a prévia actual; código, destino ou provas mudaram.');
|
||||
set_time_limit(300);
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $payload, $mode, $files, $action, $preservedHashes) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(131126, 100000)');
|
||||
// Recheck after the lock as another request may have completed while we waited.
|
||||
$existing = DB::table('audit_events')->where('source_system', 'demography-installation')->where('action', $action)->where('correlation_id', $data['operation_key'])->first();
|
||||
if ($existing) {
|
||||
$event = json_decode($existing->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless((int) $existing->actor_user_id === $actor->id && hash_equals($event['payload_sha256'], $payload), 409);
|
||||
|
||||
return [...$event['result'], 'repeated' => true];
|
||||
}
|
||||
$before = $this->protectedState($preservedHashes);
|
||||
$previous = config('demography.authenticated_installation');
|
||||
config(['demography.authenticated_installation' => true]);
|
||||
try {
|
||||
if ($mode === 'initial') {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha ao instalar a estrutura demográfica.');
|
||||
} else { abort_unless(Schema::hasTable('demographic_observations'), 409); }
|
||||
} finally {
|
||||
config(['demography.authenticated_installation' => $previous]);
|
||||
}
|
||||
if ($mode === 'initial') { $this->territories($actor); } else { $this->remainingTerritories($actor, $mode === 'zambezia' ? self::zambeziaManifest() : self::remainingManifest()); }
|
||||
$receipts = [];
|
||||
$directory = config('demography.source_directory', 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo/portal do investidor/demografia/Provincias');
|
||||
$service = app(DemographicImport::class);
|
||||
foreach ($files as $name => $expected) {
|
||||
$old = DB::table('demographic_imports')->where('sha256', $expected['sha256'])->first();
|
||||
if ($old && $old->status === 'approved') {
|
||||
$count = DB::table('demographic_observations')->where('import_id', $old->id)->count();
|
||||
abort_unless($count === $expected['records'], 409);
|
||||
$receipts[] = ['file' => $name, 'sha256' => $expected['sha256'], 'id' => $old->id, 'records' => $count, 'preserved' => true];
|
||||
continue;
|
||||
}
|
||||
$file = $directory.'/'.$name;
|
||||
abort_unless(is_file($file) && CheckedFile::matches($file, $expected['sha256']), 409, 'O exemplar aprovado mudou: '.$name);
|
||||
$plan = $service->prepare($actor, $file, $name, 'Exemplar INE fornecido pela Tempo; edição não indicada; SHA256 identifica a versão', $name === 'Dados demograficos.xlsx' ? 2017 : null);
|
||||
$receipt = $service->confirm($actor, $plan['id'], $expected['sha256'], [], $data['reason']);
|
||||
abort_unless($receipt['records'] === $expected['records'], 409, 'Contagem divergente da homologação: '.$name);
|
||||
$service->transition($actor, $plan['id'], 'approved', $data['reason']);
|
||||
$receipts[] = ['file' => $name, 'sha256' => $expected['sha256'], 'id' => $plan['id'], 'records' => $receipt['records']];
|
||||
}
|
||||
abort_unless($before === ($mode === 'initial' ? array_filter($this->protectedState($preservedHashes), fn ($key) => ! str_starts_with($key, 'accepted_'), ARRAY_FILTER_USE_KEY) : $this->protectedState($preservedHashes)), 409, 'Estado protegido alterado; instalação revertida.');
|
||||
$result = ['installed' => true, 'target' => (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'),
|
||||
'imports' => $receipts, 'protected_state' => $before, 'record_count' => array_sum(array_column($receipts, 'records')), 'at' => now()->toIso8601String()];
|
||||
DB::table('audit_events')->insert(['source_system' => 'demography-installation', 'entity_type' => 'demographic_series',
|
||||
'actor_user_id' => $actor->id, 'action' => $action, 'correlation_id' => $data['operation_key'], 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['payload_sha256' => $payload, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
final class DeskAttachments
|
||||
{
|
||||
public const MIME_TYPES = ['application/pdf', 'image/png', 'image/jpeg', 'text/plain'];
|
||||
|
||||
public function scopedLinksInstalled(): bool
|
||||
{
|
||||
$indexes = DB::selectOne("SELECT to_regclass('public.desk_documents_scope_unique') AS scope, to_regclass('public.desk_documents_dossier_unique') AS dossier");
|
||||
|
||||
return $indexes->scope !== null && $indexes->dossier !== null;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $definition
|
||||
* @return array<string,mixed> */
|
||||
public function field(array $definition, string $key): array
|
||||
{
|
||||
$field = $definition['fields'][$key] ?? null;
|
||||
if (! $field || $field['type'] !== 'attachment') {
|
||||
throw ValidationException::withMessages(['field_key' => 'Seleccione uma pergunta de anexo da versão deste pedido.']);
|
||||
}
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $field */
|
||||
public function checkMetadata(\stdClass $document, array $field, string $path, bool $allowUnknown = false): void
|
||||
{
|
||||
$mime = strtolower(trim(explode(';', (string) ($document->media_type ?? ''), 2)[0]));
|
||||
if (($mime === '' && ! $allowUnknown) || ($mime !== '' && ! in_array($mime, $field['mime_types'], true)) || ($document->size_bytes === null && ! $allowUnknown) || ($document->size_bytes !== null && ($document->size_bytes === false || $document->size_bytes < 0 || $document->size_bytes > $field['max_size_kb'] * 1024))) {
|
||||
throw ValidationException::withMessages([$path => 'O ficheiro não corresponde aos formatos ou ao tamanho máximo desta pergunta. Escolha outro suporte; o original é conservado.']);
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate references through the existing case/request boundary; no parallel document store.
|
||||
* @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return array<string,mixed> */
|
||||
public function snapshot(\stdClass $request, array $payload, array $definition, bool $submitting): array
|
||||
{
|
||||
$applicable = app(VirtualDesk::class)->applicableFields($payload, $definition);
|
||||
$snapshot = [];
|
||||
$verified = [];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
if ($field['type'] !== 'attachment') {
|
||||
continue;
|
||||
}
|
||||
$files = [];
|
||||
$seen = [];
|
||||
foreach ($payload[$key] ?? [] as $linkId) {
|
||||
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.id', $linkId)->where('l.case_id', $request->case_id)->whereNull('d.deleted_at')
|
||||
->where(fn ($q) => $q->whereNull('l.request_id')->orWhere('l.request_id', $request->id))
|
||||
->first(['d.*', 'l.id as link_id', 'l.source_reference', 'l.category', 'l.valid_until as declared_valid_until', 'l.stage as linked_stage']);
|
||||
if (! $document) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione documentos associados a este dossier e disponíveis neste pedido.']);
|
||||
}
|
||||
if (isset($seen[$document->id])) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione cada ficheiro apenas uma vez nesta pergunta. Pode reutilizá-lo noutras perguntas aplicáveis.']);
|
||||
}
|
||||
$seen[$document->id] = true;
|
||||
$active = isset($applicable[$key]);
|
||||
// Hidden answers are preserved; they are not accepted as applicable evidence.
|
||||
if ($active) {
|
||||
$this->checkMetadata($document, $field, 'payload.'.$key, true);
|
||||
}
|
||||
$usable = $document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256));
|
||||
if ($submitting && $active) {
|
||||
if (! $usable) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'O suporte seleccionado ainda não está disponível com análise de segurança válida. Actualize o estado dos documentos antes de submeter.']);
|
||||
}
|
||||
if (! isset($verified[$document->id])) {
|
||||
try {
|
||||
$verificationDocument = clone $document;
|
||||
$verificationDocument->media_type = $verificationDocument->media_type ?: 'application/octet-stream';
|
||||
$response = app(VerifiedDocumentBinary::class)->respond($verificationDocument);
|
||||
if ($response instanceof BinaryFileResponse) {
|
||||
$verified[$document->id] = ['size_bytes' => $response->getFile()->getSize(), 'media_type' => (new \finfo(FILEINFO_MIME_TYPE))->file($response->getFile()->getPathname())];
|
||||
} else {
|
||||
$content = $response->getContent();
|
||||
if (! is_string($content)) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Não foi possível conferir o original deste suporte.']);
|
||||
}
|
||||
$verified[$document->id] = ['size_bytes' => strlen($content), 'media_type' => (new \finfo(FILEINFO_MIME_TYPE))->buffer($content)];
|
||||
}
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'O suporte não está disponível com a autorização e integridade exigidas. Recupere ou seleccione outro documento.']);
|
||||
}
|
||||
}
|
||||
$this->checkMetadata((object) $verified[$document->id], $field, 'payload.'.$key);
|
||||
$recordedMime = strtolower(trim(explode(';', (string) ($document->media_type ?? ''), 2)[0]));
|
||||
if (($document->size_bytes !== null && $verified[$document->id]['size_bytes'] !== (int) $document->size_bytes) || ($recordedMime !== '' && $verified[$document->id]['media_type'] !== $recordedMime)) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'O formato ou tamanho do original diverge dos dados registados. Recupere ou seleccione outro documento.']);
|
||||
}
|
||||
}
|
||||
$measured = $submitting && $active ? $verified[$document->id] : null;
|
||||
$files[] = ['link_id' => $document->link_id, 'document_id' => $document->id, 'file_name' => $document->file_name,
|
||||
'sha256' => trim($document->sha256), 'version_no' => $document->version_no, 'media_type' => $measured['media_type'] ?? $document->media_type,
|
||||
'size_bytes' => $measured['size_bytes'] ?? $document->size_bytes, 'recorded_media_type' => $document->media_type, 'recorded_size_bytes' => $document->size_bytes, 'metadata_measured' => $measured !== null, 'source_reference' => $document->source_reference,
|
||||
'valid_until' => $document->declared_valid_until, 'stage' => $document->linked_stage, 'status' => $document->status, 'malware_scan_status' => $document->malware_scan_status, 'usable_at_submission' => $submitting && $active && $usable];
|
||||
}
|
||||
$snapshot[$key] = ['label' => $field['label'], 'applicable' => isset($applicable[$key]), 'service_version_id' => $request->service_version_id,
|
||||
'limits' => ['mime_types' => $field['mime_types'], 'max_size_kb' => $field['max_size_kb'], 'max_files' => $field['max_files']], 'files' => $files];
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Payment facts stay in desk_payments; the existing encrypted events preserve documentary uses. */
|
||||
class DeskPaymentEvidence
|
||||
{
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function snapshot(string $caseId, string $requestId, array $input): ?array
|
||||
{
|
||||
if (! ($input['document_link_id'] ?? null) && ! ($input['document_id'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.case_id', $caseId)->whereNull('d.deleted_at')
|
||||
->where(fn ($q) => $q->whereNull('l.request_id')->orWhere('l.request_id', $requestId))
|
||||
->when($input['document_link_id'] ?? null, fn ($q, $id) => $q->where('l.id', $id))
|
||||
->when($input['document_id'] ?? null, fn ($q, $id) => $q->where('d.id', $id))
|
||||
->orderBy('l.created_at')->orderBy('l.id')->first(['d.*', 'l.id as link_id', 'l.source_reference', 'l.category', 'l.stage', 'l.valid_until as declared_valid_until']);
|
||||
abort_unless($document !== null, 422, 'Seleccione um comprovativo associado a este pedido ou ao seu dossier.');
|
||||
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment($document);
|
||||
|
||||
return ['link_id' => $document->link_id, 'document_id' => $document->id, 'file_name' => $document->file_name, 'document_version' => (int) $document->version_no,
|
||||
'sha256' => trim($document->sha256), 'source_reference' => $document->source_reference, 'category' => $document->category, 'stage' => $document->stage,
|
||||
'valid_until' => $document->declared_valid_until, 'status_at_association' => $document->status, 'scan_at_association' => $document->malware_scan_status,
|
||||
'scope' => 'registered_document_metadata_not_binary_or_payment_confirmation'];
|
||||
}
|
||||
|
||||
/** @return array<string,array<string,mixed>> */
|
||||
public function forRequest(string $requestId): array
|
||||
{
|
||||
$current = [];
|
||||
foreach (DB::table('desk_events')->where('request_id', $requestId)->whereIn('action', ['payment_declared', 'payment_document_linked'])->orderBy('event_order')->get(['payload']) as $event) {
|
||||
$payload = app(VirtualDesk::class)->decode($event->payload);
|
||||
if (is_string($payload['payment_id'] ?? null) && is_array($payload['document_evidence'] ?? null)) {
|
||||
$current[$payload['payment_id']] = $payload['document_evidence'];
|
||||
}
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
final class DeskRequestCheckpoints
|
||||
{
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('desk_request_checkpoints');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function show(User $actor, string $id): array
|
||||
{
|
||||
$desk = app(VirtualDesk::class);
|
||||
$request = $desk->request($actor, $id, true);
|
||||
$case = $desk->case($actor, $request->case_id, true);
|
||||
$row = $this->installed() ? DB::table('desk_request_checkpoints')->where('request_id', $id)->where('actor_id', $actor->id)->first() : null;
|
||||
|
||||
return ['installed' => $this->installed(), 'request' => ['id' => $id, 'version' => (int) $request->version, 'status' => $request->status,
|
||||
'protocol' => $request->protocol, 'analyst_id' => $request->analyst_id, 'due_at' => $request->due_at,
|
||||
'editable_fields' => json_decode($request->editable_fields ?? '[]', true), 'payload' => $desk->decode($request->payload),
|
||||
'can_edit' => ! $case->closed_at && in_array($request->status, ['draft', 'returned'], true)],
|
||||
'checkpoint' => $row ? ['version' => (int) $row->version, 'request_version' => (int) $row->request_version,
|
||||
'updated_at' => $row->updated_at, ...$desk->decode($row->snapshot)] : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $id, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 409, 'A gravação automática requer a actualização de rascunhos. A gravação manual continua disponível.');
|
||||
$data = Validator::make(['checkpoint' => $input], [
|
||||
'checkpoint' => 'required|array:version,request_version,operation_key,payload,edited_keys,reason',
|
||||
'checkpoint.version' => 'required|integer|min:0', 'checkpoint.request_version' => 'required|integer|min:1',
|
||||
'checkpoint.operation_key' => 'required|uuid', 'checkpoint.payload' => 'present|array',
|
||||
'checkpoint.edited_keys' => 'present|array|list|max:65', 'checkpoint.edited_keys.*' => 'required|string|distinct|max:100',
|
||||
'checkpoint.reason' => 'nullable|string|max:3000',
|
||||
])->validate()['checkpoint'];
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data): array {
|
||||
$desk = app(VirtualDesk::class);
|
||||
$request = $desk->request($actor, $id, true, true);
|
||||
$case = $desk->case($actor, $request->case_id, true, true);
|
||||
abort_unless(! $case->closed_at && in_array($request->status, ['draft', 'returned'], true), 409, 'Este pedido já não permite alterar o rascunho.');
|
||||
abort_unless((int) $request->version === (int) $data['request_version'], 409, 'O pedido mudou. Compare a versão actual antes de recuperar as suas alterações.');
|
||||
$payload = $desk->checkpointFields($data['payload'], $desk->definition($request));
|
||||
app(DeskAttachments::class)->snapshot($request, $payload, $desk->definition($request), false);
|
||||
$allowed = [...array_keys($desk->definition($request)['fields']), 'country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'];
|
||||
Validator::make($data, ['edited_keys.*' => [Rule::in($allowed)]])->validate();
|
||||
$base = $desk->decode($request->payload);
|
||||
$edited = array_values(array_unique([...$data['edited_keys'], ...array_filter(array_unique([...array_keys($base), ...array_keys($payload)]), fn ($key) => ($base[$key] ?? null) !== ($payload[$key] ?? null))]));
|
||||
if ($request->status === 'returned') {
|
||||
$editable = json_decode($request->editable_fields ?? '[]', true);
|
||||
foreach (array_unique([...array_keys($base), ...array_keys($payload), ...$data['edited_keys']]) as $key) {
|
||||
abort_if(! in_array($key, $editable, true) && ((($base[$key] ?? null) !== ($payload[$key] ?? null)) || in_array($key, $data['edited_keys'], true)), 422, 'O rascunho só pode corrigir os campos autorizados.');
|
||||
}
|
||||
}
|
||||
$operationHash = hash('sha256', json_encode(Arr::sortRecursive(['version' => (int) $data['version'], 'request_version' => (int) $data['request_version'],
|
||||
'operation_key' => $data['operation_key'], 'payload' => $payload, 'edited_keys' => $data['edited_keys'], 'reason' => $data['reason'] ?? '']), JSON_THROW_ON_ERROR));
|
||||
$row = DB::table('desk_request_checkpoints')->where('request_id', $id)->where('actor_id', $actor->id)->lockForUpdate()->first();
|
||||
if ($row && $row->operation_key === $data['operation_key']) {
|
||||
abort_unless(hash_equals($row->operation_sha256, $operationHash), 409, 'Esta tentativa já foi usada com outros dados.');
|
||||
|
||||
return $this->show($actor, $id);
|
||||
}
|
||||
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'O rascunho mudou noutro separador. Compare antes de substituir.');
|
||||
$version = (int) ($row->version ?? 0) + 1;
|
||||
DB::table('desk_request_checkpoints')->updateOrInsert(['request_id' => $id, 'actor_id' => $actor->id], [
|
||||
'version' => $version, 'request_version' => $request->version, 'operation_key' => $data['operation_key'], 'operation_sha256' => $operationHash,
|
||||
'snapshot' => $desk->encode(['payload' => $payload, 'base_payload' => $base, 'edited_keys' => $edited, 'reason' => $data['reason'] ?? '']),
|
||||
'created_at' => $row->created_at ?? now(), 'updated_at' => now(),
|
||||
]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_request_checkpoints', 'entity_id' => $id,
|
||||
'actor_user_id' => $actor->id, 'action' => 'draft_checkpoint_saved', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['version' => $version, 'request_version' => (int) $request->version], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->show($actor, $id);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** One applicable edition per service. Existing requests keep their immutable version FK. */
|
||||
final class DeskServiceAvailability
|
||||
{
|
||||
public function scheduled(): bool
|
||||
{
|
||||
return Schema::hasColumn('desk_service_versions', 'effective_from');
|
||||
}
|
||||
|
||||
public function current(): Builder
|
||||
{
|
||||
$query = DB::table('desk_service_versions')->where('status', 'published')
|
||||
->where(fn (Builder $date) => $date->whereNull('published_at')->orWhere('published_at', '<=', now()))
|
||||
->selectRaw('DISTINCT ON (code) *')->orderBy('code');
|
||||
if ($this->scheduled()) {
|
||||
$query->where(fn (Builder $date) => $date->whereNull('effective_from')->orWhere('effective_from', '<=', now()->toDateString()))
|
||||
->orderByRaw('effective_from DESC NULLS LAST');
|
||||
}
|
||||
|
||||
return $query->orderByDesc('version');
|
||||
}
|
||||
|
||||
public function upcoming(): Builder
|
||||
{
|
||||
$query = DB::table('desk_service_versions');
|
||||
if (! $this->scheduled()) {
|
||||
return $query->whereRaw('false')->select('code', 'version')->selectRaw('NULL::date AS effective_from');
|
||||
}
|
||||
|
||||
return $query->where('status', 'published')->where('effective_from', '>', now()->toDateString())
|
||||
->where(fn (Builder $date) => $date->whereNull('published_at')->orWhere('published_at', '<=', now()))
|
||||
->selectRaw('DISTINCT ON (code,effective_from) code,version,effective_from')->orderBy('code')->orderBy('effective_from')->orderByDesc('version');
|
||||
}
|
||||
|
||||
/** @return literal-string */
|
||||
public function dateProjection(): string
|
||||
{
|
||||
return $this->scheduled() ? 'effective_from' : 'NULL::date AS effective_from';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class DeskServiceEditor
|
||||
{
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function listing(): array
|
||||
{
|
||||
$availability = app(DeskServiceAvailability::class);
|
||||
$active = $availability->current()->get()->keyBy('code');
|
||||
$upcoming = $availability->upcoming()->get()->groupBy('code')->map(fn ($rows) => $rows->map(fn ($row) => ['version' => (int) $row->version, 'effective_from' => $row->effective_from])->all());
|
||||
$rows = DB::table('desk_service_versions')->selectRaw('DISTINCT ON (code) code, version, definition')
|
||||
->selectRaw($availability->dateProjection())
|
||||
->orderBy('code')->orderByDesc('version')->get()->keyBy('code');
|
||||
$services = [];
|
||||
foreach (config('virtual-desk.services') as $code => $initial) {
|
||||
$row = $rows->get($code);
|
||||
$services[] = ['code' => $code, 'version' => (int) ($row->version ?? 0), 'editable' => true,
|
||||
'effective_from' => $row->effective_from ?? null, 'activeVersion' => (int) ($active->get($code)->version ?? 0),
|
||||
'upcoming' => $upcoming->get($code, []),
|
||||
'fixedTypes' => array_map(fn (array $field) => $field['type'], $initial['fields']),
|
||||
'definition' => $row ? json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR) : $initial];
|
||||
}
|
||||
foreach ($rows as $code => $row) {
|
||||
if (! array_key_exists($code, config('virtual-desk.services'))) {
|
||||
$services[] = ['code' => $code, 'version' => (int) $row->version, 'editable' => false,
|
||||
'effective_from' => $row->effective_from ?? null, 'activeVersion' => (int) ($active->get($code)->version ?? 0),
|
||||
'upcoming' => $upcoming->get($code, []),
|
||||
'definition' => json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR)];
|
||||
}
|
||||
}
|
||||
|
||||
return $services;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function history(string $code, int $requestedPage): array
|
||||
{
|
||||
abort_unless(array_key_exists($code, config('virtual-desk.services')) || DB::table('desk_service_versions')->where('code', $code)->exists(), 404);
|
||||
$query = DB::table('desk_service_versions')->where('code', $code);
|
||||
$total = (clone $query)->count();
|
||||
$pages = max(1, (int) ceil($total / 10));
|
||||
$page = min(max(1, $requestedPage), $pages);
|
||||
$rows = $query->orderByDesc('version')->forPage($page, 10)->select(['id', 'version', 'status', 'author_id', 'published_by', 'published_at', 'definition', 'source'])
|
||||
->selectRaw(app(DeskServiceAvailability::class)->dateProjection())->get();
|
||||
$events = DB::table('audit_events')->where('source_system', 'virtual-desk')->where('entity_type', 'desk_service_versions')
|
||||
->where('action', 'service_definition_version_published')->whereIn('entity_id', $rows->pluck('id')->all())
|
||||
->get(['entity_id', 'after_data'])->keyBy('entity_id');
|
||||
|
||||
return ['page' => $page, 'pages' => $pages, 'total' => $total, 'data' => $rows->map(function ($row) use ($events): array {
|
||||
$event = $events->get($row->id);
|
||||
$audit = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
|
||||
return ['id' => $row->id, 'version' => (int) $row->version, 'status' => $row->status,
|
||||
'author_id' => $row->author_id, 'published_by' => $row->published_by, 'published_at' => $row->published_at,
|
||||
'definition' => json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR),
|
||||
'effective_from' => $row->effective_from,
|
||||
'source' => json_decode($row->source, true, 512, JSON_THROW_ON_ERROR), 'reason' => $audit['reason'] ?? null];
|
||||
})->all()];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function publish(User $actor, string $code, array $input): \stdClass
|
||||
{
|
||||
abort_unless(array_key_exists($code, config('virtual-desk.services')), 404);
|
||||
$data = Validator::make($input, [
|
||||
'base_version' => ['required', 'integer', 'min:0'], 'confirm' => ['accepted'],
|
||||
'effective_from' => ['nullable', 'date_format:Y-m-d'],
|
||||
'reason' => ['required', 'string', 'min:20', 'max:2000'],
|
||||
'definition' => ['required', 'array:title,theme,profile,stage,entity,result,fields'],
|
||||
'definition.title' => ['required', 'string', 'max:200'],
|
||||
'definition.theme' => ['required', 'string', 'max:150'],
|
||||
'definition.profile' => ['required', 'string', 'max:200'],
|
||||
'definition.stage' => ['required', 'string', 'max:20'],
|
||||
'definition.entity' => ['required', 'string', 'max:300'],
|
||||
'definition.result' => ['required', 'string', 'max:2000'],
|
||||
'definition.fields' => ['required', 'array', 'min:1', 'max:60'],
|
||||
'definition.fields.*' => ['required', 'array:label,type,required,min,options,when,statement,mime_types,max_size_kb,max_files'],
|
||||
'definition.fields.*.label' => ['required', 'string', 'max:300'],
|
||||
'definition.fields.*.type' => ['required', Rule::in(['text', 'textarea', 'email', 'tel', 'url', 'number', 'date', 'select', 'multiselect', 'consent', 'territory', 'attachment'])],
|
||||
'definition.fields.*.mime_types' => ['sometimes', 'array', 'list', 'min:1', 'max:4'],
|
||||
'definition.fields.*.mime_types.*' => ['required', 'string', Rule::in(DeskAttachments::MIME_TYPES)],
|
||||
'definition.fields.*.max_size_kb' => ['sometimes', 'integer', 'min:1', 'max:10240'],
|
||||
'definition.fields.*.max_files' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
'definition.fields.*.statement' => ['sometimes', 'string', 'min:3', 'max:5000'],
|
||||
'definition.fields.*.required' => ['required', 'boolean'],
|
||||
'definition.fields.*.min' => ['sometimes', 'numeric', 'min:0', 'max:999999999999'],
|
||||
'definition.fields.*.options' => ['sometimes', 'array', 'min:1', 'max:100'],
|
||||
'definition.fields.*.options.*' => ['required', 'string', 'max:300'],
|
||||
'definition.fields.*.when' => ['sometimes', 'array:field,equals,operator', 'required_array_keys:field,equals'],
|
||||
'definition.fields.*.when.operator' => ['sometimes', Rule::in(['equals', 'contains'])],
|
||||
'definition.fields.*.when.field' => ['required_with:definition.fields.*.when', 'string', 'max:64'],
|
||||
'definition.fields.*.when.equals' => ['required_with:definition.fields.*.when', 'string', 'max:1000'],
|
||||
])->validate();
|
||||
$this->checkFields($data['definition']['fields']);
|
||||
|
||||
return DB::transaction(function () use ($actor, $code, $data): \stdClass {
|
||||
DB::select('select pg_advisory_xact_lock(261008, 2)');
|
||||
$scheduled = app(DeskServiceAvailability::class)->scheduled();
|
||||
if (! $scheduled && ($data['effective_from'] ?? null) !== null) {
|
||||
throw ValidationException::withMessages(['effective_from' => 'Instale a actualização das datas de entrada em vigor antes de agendar uma versão.']);
|
||||
}
|
||||
$latest = DB::table('desk_service_versions')->where('code', $code)->orderByDesc('version')->first();
|
||||
$previous = $latest ? json_decode($latest->definition, true, 512, JSON_THROW_ON_ERROR) : config('virtual-desk.services.'.$code);
|
||||
if ($data['definition']['stage'] !== $previous['stage']) {
|
||||
throw ValidationException::withMessages(['definition.stage' => 'A etapa pertence ao percurso existente e não pode ser alterada neste editor.']);
|
||||
}
|
||||
foreach (config('virtual-desk.services.'.$code.'.fields') as $key => $canonical) {
|
||||
if (isset($data['definition']['fields'][$key]) && $data['definition']['fields'][$key]['type'] !== $canonical['type']) {
|
||||
throw ValidationException::withMessages(['definition.fields.'.$key.'.type' => 'Este identificador é interpretado pelo motor existente. Conserve o tipo ou acrescente um novo campo com outro identificador.']);
|
||||
}
|
||||
}
|
||||
// Retry of the same confirmed publication preserves the first version and authorship.
|
||||
if ($latest && (int) $latest->version === (int) $data['base_version'] + 1 && $latest->status === 'published'
|
||||
&& $this->sameEffectiveRequest($latest, $data, $scheduled)
|
||||
&& $this->definitionHash(json_decode($latest->definition, true, 512, JSON_THROW_ON_ERROR)) === $this->definitionHash($data['definition'])) {
|
||||
return $latest;
|
||||
}
|
||||
abort_unless((int) ($latest->version ?? 0) === (int) $data['base_version'], 409, 'O formulário foi alterado. Recarregue e compare a versão actual antes de publicar.');
|
||||
if (($data['effective_from'] ?? null) !== null && $data['effective_from'] < now()->toDateString()) {
|
||||
throw ValidationException::withMessages(['effective_from' => 'Uma nova publicação começa hoje ou numa data futura; não altera a vigência de pedidos anteriores.']);
|
||||
}
|
||||
$effective = ($data['effective_from'] ?? null) ?: now()->toDateString();
|
||||
if ($latest && $latest->status === 'published' && $this->definitionHash($previous) === $this->definitionHash($data['definition'])
|
||||
&& (! $scheduled || ($latest->effective_from ?? null) === $effective || (! ($data['effective_from'] ?? null) && (! ($latest->effective_from ?? null) || $latest->effective_from <= now()->toDateString())))) {
|
||||
throw ValidationException::withMessages(['definition' => 'Não há alterações na definição ou na data de início para publicar uma nova versão.']);
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('desk_service_versions')->insert([
|
||||
'id' => $id, 'code' => $code, 'version' => (int) $data['base_version'] + 1, 'status' => 'published',
|
||||
...($scheduled ? ['effective_from' => $effective] : []),
|
||||
'definition' => json_encode($data['definition'], JSON_THROW_ON_ERROR),
|
||||
'source' => $latest->source ?? json_encode(config('virtual-desk.source'), JSON_THROW_ON_ERROR),
|
||||
'author_id' => $actor->id, 'published_by' => $actor->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
DB::table('audit_events')->insert([
|
||||
'source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $actor->id,
|
||||
'action' => 'service_definition_version_published',
|
||||
'before_data' => json_encode(['id' => $latest?->id, 'version' => (int) $data['base_version']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['code' => $code, 'version' => (int) $data['base_version'] + 1, 'reason' => $data['reason'],
|
||||
'effect' => 'new_requests_only', 'effective_from' => $scheduled ? $effective : null,
|
||||
'effective_request_mode' => ($data['effective_from'] ?? null) ? 'dated' : 'immediate',
|
||||
'selection' => 'latest_started_effective_date_then_version; undated_legacy_fallback',
|
||||
'definition_sha256' => $this->definitionHash($data['definition'])], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
|
||||
return DB::table('desk_service_versions')->where('id', $id)->firstOrFail();
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $definition */
|
||||
private function definitionHash(array $definition): string
|
||||
{
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($definition), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/** PostgreSQL JSONB does not retain object-key order.
|
||||
* @param array<array-key,mixed> $left
|
||||
* @param array<array-key,mixed> $right */
|
||||
public function sameDefinition(array $left, array $right): bool
|
||||
{
|
||||
return $this->definitionHash($left) === $this->definitionHash($right);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function sameEffectiveRequest(\stdClass $latest, array $data, bool $scheduled): bool
|
||||
{
|
||||
if (! $scheduled || ($latest->effective_from ?? null) === null) {
|
||||
return ! ($data['effective_from'] ?? null);
|
||||
}
|
||||
if ($data['effective_from'] ?? null) {
|
||||
return $latest->effective_from === $data['effective_from'];
|
||||
}
|
||||
$event = DB::table('audit_events')->where('source_system', 'virtual-desk')->where('entity_type', 'desk_service_versions')
|
||||
->where('entity_id', $latest->id)->where('action', 'service_definition_version_published')->orderByDesc('id')->value('after_data');
|
||||
|
||||
return $event && (json_decode($event, true, 512, JSON_THROW_ON_ERROR)['effective_request_mode'] ?? null) === 'immediate';
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $fields */
|
||||
private function checkFields(array $fields): void
|
||||
{
|
||||
foreach ($fields as $key => $field) {
|
||||
$path = 'definition.fields.'.$key;
|
||||
if ($field['type'] === 'attachment') {
|
||||
if (count(array_unique($field['mime_types'] ?? [])) !== count($field['mime_types'] ?? [])) {
|
||||
throw ValidationException::withMessages([$path.'.mime_types' => 'Escolha cada formato apenas uma vez nesta pergunta.']);
|
||||
}
|
||||
if (! isset($field['mime_types'],$field['max_size_kb'],$field['max_files'])) {
|
||||
throw ValidationException::withMessages([$path => 'Defina os formatos, tamanho por ficheiro e quantidade máxima desta pergunta.']);
|
||||
}
|
||||
if (! app(DeskAttachments::class)->scopedLinksInstalled()) {
|
||||
throw ValidationException::withMessages([$path => 'Instale a actualização dos vínculos documentais antes de publicar perguntas de anexos. Os formulários existentes continuam disponíveis.']);
|
||||
}
|
||||
} elseif (array_intersect(['mime_types', 'max_size_kb', 'max_files'], array_keys($field))) {
|
||||
throw ValidationException::withMessages([$path => 'Os limites de ficheiros pertencem apenas a perguntas de anexos.']);
|
||||
}
|
||||
if (! preg_match('/^[a-z][a-z0-9_]{0,63}$/D', (string) $key) || in_array($key, ['country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'], true)) {
|
||||
throw ValidationException::withMessages(['definition.fields' => 'Use identificadores de campo distintos dos campos comuns de país e contexto, com letras minúsculas, números e sublinhado.']);
|
||||
}
|
||||
if (in_array($field['type'], ['select', 'multiselect'], true) && empty($field['options'])) {
|
||||
throw ValidationException::withMessages([$path.'.options' => 'Indique as opções deste campo.']);
|
||||
}
|
||||
if ((isset($field['min']) && $field['type'] !== 'number') || (isset($field['options']) && ! in_array($field['type'], ['select', 'multiselect'], true))) {
|
||||
throw ValidationException::withMessages([$path => 'O mínimo aplica-se apenas a números e as opções apenas a listas de respostas.']);
|
||||
}
|
||||
if (($field['type'] === 'consent' && trim($field['statement'] ?? '') === '') || (isset($field['statement']) && $field['type'] !== 'consent')) {
|
||||
throw ValidationException::withMessages([$path.'.statement' => 'Uma declaração de consentimento exige o texto exacto a apresentar; esse texto pertence apenas a campos de consentimento.']);
|
||||
}
|
||||
foreach (array_keys($field['options'] ?? []) as $option) {
|
||||
if (! preg_match('/^[a-zA-Z0-9_-]{1,80}$/D', (string) $option)) {
|
||||
throw ValidationException::withMessages([$path.'.options' => 'Use códigos de opção sem espaços ou pontuação especial.']);
|
||||
}
|
||||
}
|
||||
$visited = [$key];
|
||||
$node = $field;
|
||||
while (isset($node['when'])) {
|
||||
$parent = $node['when']['field'];
|
||||
if (! isset($fields[$parent]) || in_array($parent, $visited, true)) {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'A condição deve referir outro campo existente, sem dependências circulares.']);
|
||||
}
|
||||
if (in_array($fields[$parent]['type'], ['number', 'attachment'], true)) {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'Use uma resposta de texto, lista ou declaração como origem da condição; números e anexos não são respostas comparáveis por estas condições.']);
|
||||
}
|
||||
$operator = $node['when']['operator'] ?? 'equals';
|
||||
if (($fields[$parent]['type'] === 'multiselect') !== ($operator === 'contains')) {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'Use inclusão de uma opção para uma selecção múltipla e igualdade para respostas simples.']);
|
||||
}
|
||||
if (in_array($fields[$parent]['type'], ['select', 'multiselect'], true) && ! array_key_exists($node['when']['equals'], $fields[$parent]['options'] ?? [])) {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'O valor da condição deve corresponder a uma opção do campo escolhido.']);
|
||||
}
|
||||
if ($fields[$parent]['type'] === 'consent' && ! in_array($node['when']['equals'], ['accepted', 'declined'], true)) {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'Compare a declaração com accepted ou declined; uma resposta por preencher não é aceitação.']);
|
||||
}
|
||||
$visited[] = $parent;
|
||||
$node = $fields[$parent];
|
||||
}
|
||||
}
|
||||
if (isset($fields['territory_id'])) {
|
||||
if (! isset($fields['location_source'])) {
|
||||
throw ValidationException::withMessages(['definition.fields.location_source' => 'A localização exige a respectiva fonte. Mantenha o campo da fonte ou retire também a localização.']);
|
||||
}
|
||||
$locationConditions = $this->conditions('territory_id', $fields);
|
||||
$sourceConditions = $this->conditions('location_source', $fields);
|
||||
if (array_diff_assoc($sourceConditions, $locationConditions) !== []) {
|
||||
throw ValidationException::withMessages(['definition.fields.location_source.when' => 'A fonte tem de estar disponível sempre que a localização se aplica. Use as mesmas condições ou condições mais abrangentes.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Conditions have already been checked for valid references and cycles.
|
||||
* @param array<string,array<string,mixed>> $fields
|
||||
* @return array<string,string> */
|
||||
private function conditions(string $key, array $fields): array
|
||||
{
|
||||
$conditions = [];
|
||||
while (isset($fields[$key]['when'])) {
|
||||
$when = $fields[$key]['when'];
|
||||
$conditions[$when['field']] = ($when['operator'] ?? 'equals').':'.$when['equals'];
|
||||
$key = $when['field'];
|
||||
}
|
||||
|
||||
return $conditions;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,13 @@ use Illuminate\Support\Str;
|
||||
|
||||
class DocumentManagementAccess
|
||||
{
|
||||
/** Existing editorial publication authority; it does not grant financial decision powers. */
|
||||
public function catalogueEditor(?User $actor): bool
|
||||
{
|
||||
return $actor && $actor->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
||||
&& ($this->full($actor) || $this->editorial($actor));
|
||||
}
|
||||
|
||||
public function full(User $actor): bool
|
||||
{
|
||||
return Gate::forUser($actor)->allows('manage-portal');
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/** Existing internal administration; does not establish an institutional mandate. */
|
||||
final class EducationAccess
|
||||
{
|
||||
public function allows(User $actor): bool
|
||||
{
|
||||
return $actor->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
||||
&& ($actor->can('manage-portal') || app(ScopedPortalAdministration::class)->administrative($actor));
|
||||
}
|
||||
|
||||
public function authorize(User $actor): void
|
||||
{
|
||||
abort_unless(config('education.enabled'), 404);
|
||||
abort_unless($this->allows($actor), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
final class EducationDeclarationDrafts
|
||||
{
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('education_declaration_drafts');
|
||||
}
|
||||
|
||||
public function guard(User $actor, string $kind): void
|
||||
{
|
||||
abort_unless(config('education.enabled') && $this->installed() && in_array($kind, ['demands', 'capacities'], true), 404);
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function show(User $actor, string $kind, string $id): array
|
||||
{
|
||||
$this->guard($actor, $kind);
|
||||
$row = DB::table('education_declaration_drafts')->where('id', $id)->where('owner_user_id', $actor->id)->where('kind', $kind)->firstOrFail();
|
||||
|
||||
return ['id' => $id, 'kind' => $kind, 'version_no' => (int) $row->version_no, 'state' => $row->state,
|
||||
'payload' => $this->decode($row->payload),
|
||||
'references' => $row->reference_snapshot ? json_decode(Crypt::decryptString($row->reference_snapshot), true, 512, JSON_THROW_ON_ERROR) : null,
|
||||
'record_id' => $row->demand_id ?? $row->capacity_id, 'updated_at' => CarbonImmutable::parse($row->updated_at)->toIso8601String()];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $kind, ?string $id, array $input): array
|
||||
{
|
||||
$this->guard($actor, $kind);
|
||||
$data = Validator::make($input, ['version_no' => 'required|integer|min:0', 'client_key' => $id ? 'sometimes|uuid' : 'required|uuid', 'payload' => 'present|array'])->validate();
|
||||
$payload = $this->partial($kind, $data['payload']);
|
||||
|
||||
return DB::transaction(function () use ($actor, $kind, $id, $data, $payload): array {
|
||||
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
|
||||
$query = DB::table('education_declaration_drafts')->where('owner_user_id', $actor->id);
|
||||
$row = $id ? $query->where('id', $id)->where('kind', $kind)->lockForUpdate()->firstOrFail()
|
||||
: $query->where('client_key', $data['client_key'])->lockForUpdate()->first();
|
||||
abort_if($row && ($row->kind !== $kind || $row->state !== 'draft'), 409, 'Este rascunho já foi submetido ou pertence a outro tipo de declaração.');
|
||||
if ($row && Arr::sortRecursive($this->decode($row->payload)) === Arr::sortRecursive($payload)
|
||||
&& in_array((int) $data['version_no'], [(int) $row->version_no, (int) $row->version_no - 1], true)) {
|
||||
return $this->show($actor, $kind, $row->id);
|
||||
}
|
||||
abort_unless((int) ($row->version_no ?? 0) === (int) $data['version_no'], 409, 'O rascunho mudou. Recupere a versão actual antes de guardar.');
|
||||
$id = $row->id ?? (string) Str::uuid();
|
||||
DB::table('education_declaration_drafts')->updateOrInsert(['id' => $id], ['owner_user_id' => $actor->id, 'client_key' => $row->client_key ?? $data['client_key'],
|
||||
'kind' => $kind, 'version_no' => (int) ($row->version_no ?? 0) + 1, 'payload' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
|
||||
'state' => 'draft', 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
|
||||
$this->audit($actor, $id, 'draft_saved', (int) ($row->version_no ?? 0) + 1, $kind);
|
||||
|
||||
return $this->show($actor, $kind, $id);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function submit(User $actor, string $kind, string $id, array $input): array
|
||||
{
|
||||
$this->guard($actor, $kind);
|
||||
$data = Validator::make($input, ['version_no' => 'required|integer|min:1', 'payload' => 'present|array'])->validate();
|
||||
$payload = $this->partial($kind, $data['payload']);
|
||||
|
||||
return DB::transaction(function () use ($actor, $kind, $id, $data, $payload): array {
|
||||
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
|
||||
$row = DB::table('education_declaration_drafts')->where('id', $id)->where('owner_user_id', $actor->id)->where('kind', $kind)->lockForUpdate()->firstOrFail();
|
||||
if ($row->state === 'submitted') {
|
||||
abort_unless(in_array((int) $data['version_no'], [(int) $row->version_no, (int) $row->version_no - 1], true)
|
||||
&& Arr::sortRecursive($this->decode($row->payload)) === Arr::sortRecursive($payload), 409);
|
||||
|
||||
return $this->show($actor, $kind, $id);
|
||||
}
|
||||
abort_unless((int) $row->version_no === (int) $data['version_no'], 409, 'O rascunho mudou. Recupere a versão actual antes de submeter.');
|
||||
$validated = Validator::make($payload, EducationDeclarationRules::forKind($kind))->validate();
|
||||
$references = [];
|
||||
foreach (['occupation_id' => 'occupations', 'skill_id' => 'skills', $kind === 'demands' ? 'project_id' : 'course_id' => $kind === 'demands' ? 'projects' : 'courses'] as $field => $table) {
|
||||
$source = DB::table($table)->where('id', $validated[$field])->firstOrFail();
|
||||
$references[$field] = array_intersect_key((array) $source, array_flip(['id', 'name', 'title', 'code', 'provider_id', 'updated_at']));
|
||||
}
|
||||
$references['territory_path'] = array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($validated['geo_location_id'], true));
|
||||
$record = $kind === 'demands' ? new LabourDemand : new TrainingCapacity;
|
||||
PortalAudit::save($record, [...$validated, 'submitted_by' => $actor->id, 'status' => 'submitted'], $actor->id);
|
||||
DB::table('education_declaration_drafts')->where('id', $id)->update(['payload' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
|
||||
'reference_snapshot' => Crypt::encryptString(json_encode($references, JSON_THROW_ON_ERROR)),
|
||||
'state' => 'submitted', 'version_no' => (int) $row->version_no + 1, $kind === 'demands' ? 'demand_id' : 'capacity_id' => $record->id, 'updated_at' => now()]);
|
||||
$this->audit($actor, $id, 'draft_submitted', (int) $row->version_no + 1, $kind);
|
||||
|
||||
return $this->show($actor, $kind, $id);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return array<string,mixed> */
|
||||
private function partial(string $kind, array $payload): array
|
||||
{
|
||||
unset($payload[$kind === 'demands' ? 'course_id' : 'project_id']);
|
||||
if ($kind === 'capacities') {
|
||||
unset($payload['employer']);
|
||||
}
|
||||
$rules = ['occupation_id' => 'nullable|uuid', 'skill_id' => 'nullable|uuid', 'geo_location_id' => 'nullable|uuid',
|
||||
$kind === 'demands' ? 'project_id' : 'course_id' => 'nullable|uuid', 'qualification' => 'nullable|string|max:150',
|
||||
'quantity' => 'nullable|integer|min:0|max:10000000', 'period_start' => 'nullable|date_format:Y-m-d', 'period_end' => 'nullable|date_format:Y-m-d',
|
||||
'source' => 'nullable|string|max:5000', 'reference_date' => 'nullable|date_format:Y-m-d', 'valid_until' => 'nullable|date_format:Y-m-d'];
|
||||
if ($kind === 'demands') {
|
||||
$rules['employer'] = 'nullable|string|max:200';
|
||||
}
|
||||
Validator::make(['payload' => $payload], ['payload' => 'array:'.implode(',', array_keys($rules))])->validate();
|
||||
|
||||
return Validator::make($payload, $rules)->validate();
|
||||
}
|
||||
|
||||
private function audit(User $actor, string $id, string $action, int $version, string $kind): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'education-drafts', 'entity_type' => 'education_declaration_drafts', 'entity_id' => $id,
|
||||
'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'after_data' => json_encode(['version_no' => $version, 'kind' => $kind], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function decode(string $encrypted): array
|
||||
{
|
||||
$payload = json_decode(Crypt::decryptString($encrypted), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($payload)) {
|
||||
throw new \UnexpectedValueException('Invalid education draft payload.');
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\TrainingProvider;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
final class EducationDeclarationRules
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public static function forKind(string $kind): array
|
||||
{
|
||||
abort_unless(in_array($kind, ['demands', 'capacities'], true), 404);
|
||||
$demand = $kind === 'demands';
|
||||
|
||||
return [
|
||||
'occupation_id' => ['required', 'uuid', Rule::exists('occupations', 'id')->whereNull('deleted_at')],
|
||||
'skill_id' => ['required', 'uuid', Rule::exists('skills', 'id')->whereNull('deleted_at')],
|
||||
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])],
|
||||
$demand ? 'project_id' : 'course_id' => ['required', 'uuid', $demand ? Rule::exists('projects', 'id')->whereNull('deleted_at')
|
||||
: Rule::exists('courses', 'id')->whereNull('deleted_at')->whereNot('status', 'retired')->where(fn ($query) => $query->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id')))],
|
||||
'employer' => [$demand ? 'required' : 'exclude', 'string', 'max:200'],
|
||||
'qualification' => ['required', 'string', 'max:150'], 'quantity' => ['required', 'integer', 'min:1', 'max:10000000'],
|
||||
'period_start' => ['required', 'date_format:Y-m-d'], 'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
|
||||
'source' => ['required', 'string', 'min:10', 'max:5000'], 'reference_date' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'],
|
||||
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:reference_date'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use JsonException;
|
||||
|
||||
final class EducationReviews
|
||||
{
|
||||
private const SOURCE = 'portal-education-review';
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array{version:int,replayed:bool} */
|
||||
public function decide(User $actor, string $kind, string $id, array $input): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$data = Validator::make($input, ['client_key' => 'nullable|uuid', 'version_no' => 'required|integer|min:1', 'status' => 'required|in:reviewed,rejected', 'review_reason' => 'required|string|min:15|max:3000'])->validate();
|
||||
$key = is_string($data['client_key'] ?? null) ? strtolower($data['client_key']) : null;
|
||||
$hash = hash('sha256', json_encode(['version_no' => (int) $data['version_no'], 'status' => $data['status'], 'review_reason' => trim($data['review_reason'])], JSON_THROW_ON_ERROR));
|
||||
$model = match ($kind) {
|
||||
'demands' => LabourDemand::class,'capacities' => TrainingCapacity::class,default => abort(404)
|
||||
};
|
||||
|
||||
return DB::transaction(function () use ($actor, $model, $id, $data, $key, $hash) {
|
||||
$record = $model::lockForUpdate()->findOrFail($id);
|
||||
if ($key !== null) {
|
||||
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', $record->getTable())->where('entity_id', $id)->where('action', 'review_committed')
|
||||
->whereRaw("after_data->'education_review'->>'key' = ?", [$key])->selectRaw("after_data->'education_review'->>'hash' AS hash,after_data->'education_review'->'version' AS version")->first();
|
||||
if ($event) {
|
||||
abort_unless($event->hash === $hash, 409, 'Esta tentativa de revisão já foi usada com outros dados. Compare antes de continuar.');
|
||||
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
||||
abort_unless(is_int($version) && $version > 0, 409, 'A revisão anterior não pôde ser identificada com segurança.');
|
||||
|
||||
return ['version' => $version, 'replayed' => true];
|
||||
}
|
||||
}
|
||||
abort_if((int) $record->getAttribute('submitted_by') === $actor->id, 403, 'Outro gestor deve efectuar a revisão.');
|
||||
abort_if((int) $record->getAttribute('version_no') !== (int) $data['version_no'], 409, 'A versão foi alterada. Compare os dados actuais antes de decidir.');
|
||||
abort_if($record->getAttribute('valid_until') < now()->toDateString(), 422, 'A fonte expirou.');
|
||||
$version = (int) $data['version_no'] + 1;
|
||||
$before = ['version' => (int) $record->getAttribute('version_no'), 'status' => $record->getAttribute('status'), 'review_reason' => $record->getAttribute('review_reason'), 'reviewed_by' => $record->getAttribute('reviewed_by')];
|
||||
$subject = Arr::only($record->getAttributes(), ['id', 'project_id', 'course_id', 'occupation_id', 'skill_id', 'geo_location_id', 'employer', 'qualification', 'quantity', 'period_start', 'period_end', 'source', 'reference_date', 'valid_until', 'submitted_by']);
|
||||
PortalAudit::save($record, ['status' => $data['status'], 'review_reason' => trim($data['review_reason']), 'version_no' => $version, 'reviewed_by' => $actor->id], $actor->id);
|
||||
$snapshot = ['subject' => $subject, 'before' => $before, 'after' => ['version' => $version, 'status' => $data['status'], 'review_reason' => $record->getAttribute('review_reason'), 'reviewed_by' => $actor->id]];
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id, 'entity_type' => $record->getTable(), 'entity_id' => $id, 'action' => 'review_committed', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['education_review' => ['key' => $key, 'hash' => $key !== null ? $hash : null, 'version' => $version, 'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))]], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return ['version' => $version, 'replayed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** Private preparation only; never a decision or an authority grant.
|
||||
* @return array<string,mixed> */
|
||||
public function preparation(User $actor, LabourDemand|TrainingCapacity $record): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$event = $this->preparations($actor, $record)->orderByRaw("CASE WHEN (after_data->'education_preparation'->>'version') ~ '^[0-9]{1,10}$' THEN (after_data->'education_preparation'->>'version')::bigint END DESC NULLS LAST")->orderByDesc('occurred_at')->orderByDesc('id')->first(['after_data']);
|
||||
$value = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'] : null;
|
||||
$snapshot = null;
|
||||
$unavailable = false;
|
||||
if ($value) {
|
||||
try {
|
||||
$decoded = json_decode(Crypt::decryptString($value['snapshot']), true, 512, JSON_THROW_ON_ERROR);
|
||||
$snapshot = Validator::make(['snapshot' => $decoded], $this->preparationRules($decoded))->validate()['snapshot'];
|
||||
} catch (DecryptException|JsonException|ValidationException) {
|
||||
$unavailable = true;
|
||||
}
|
||||
}
|
||||
// Empty reference maps remain JSON objects in the browser, like the declaration props.
|
||||
if (is_array($snapshot)) {
|
||||
if ($snapshot['base']['references'] === []) {
|
||||
$snapshot['base']['references'] = (object) [];
|
||||
}
|
||||
if (is_array($snapshot['pending']) && $snapshot['pending']['base']['references'] === []) {
|
||||
$snapshot['pending']['base']['references'] = (object) [];
|
||||
}
|
||||
}
|
||||
|
||||
return ['actor_id' => $actor->id, 'kind' => $record instanceof LabourDemand ? 'demands' : 'capacities', 'record_id' => $record->id, 'version' => (int) ($value['version'] ?? 0), 'operation_key' => $value['operation_key'] ?? null,
|
||||
'snapshot' => $snapshot, 'unavailable' => $unavailable];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function savePreparation(User $actor, string $kind, string $id, array $input): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$model = match ($kind) {
|
||||
'demands' => LabourDemand::class, 'capacities' => TrainingCapacity::class, default => abort(404)
|
||||
};
|
||||
$data = Validator::make($input, [...$this->preparationRules($input['snapshot'] ?? null),
|
||||
'actor_id' => 'required|integer|min:1', 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid'])->validate();
|
||||
abort_unless((int) $data['actor_id'] === $actor->id, 409, 'A conta mudou. Actualize a entrada antes de guardar a preparação.');
|
||||
$key = strtolower($data['operation_key']);
|
||||
$snapshot = $data['snapshot'];
|
||||
foreach (['values', 'base'] as $field) {
|
||||
$snapshot[$field]['version_no'] = (int) $snapshot[$field]['version_no'];
|
||||
}
|
||||
$snapshot['base']['quantity'] = (int) $snapshot['base']['quantity'];
|
||||
foreach (['status', 'review_reason'] as $field) {
|
||||
$snapshot['generation'][$field] = (int) $snapshot['generation'][$field];
|
||||
}
|
||||
if ($snapshot['pending'] !== null) {
|
||||
$snapshot['pending']['values']['version_no'] = (int) $snapshot['pending']['values']['version_no'];
|
||||
$snapshot['pending']['base']['version_no'] = (int) $snapshot['pending']['base']['version_no'];
|
||||
$snapshot['pending']['base']['quantity'] = (int) $snapshot['pending']['base']['quantity'];
|
||||
$snapshot['pending']['values']['client_key'] = strtolower($snapshot['pending']['values']['client_key']);
|
||||
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
|
||||
$snapshot['pending'][$field] = (int) $snapshot['pending'][$field];
|
||||
}
|
||||
abort_unless($snapshot['pending']['values']['version_no'] === $snapshot['pending']['base']['version_no'], 422);
|
||||
abort_unless($snapshot['pending']['reasonGeneration'] <= $snapshot['generation']['review_reason'] && $snapshot['pending']['statusGeneration'] <= $snapshot['generation']['status'], 422);
|
||||
}
|
||||
abort_unless($snapshot['values']['version_no'] === $snapshot['base']['version_no'], 422);
|
||||
$hash = hash('sha256', json_encode(Arr::sortRecursive(['actor' => $actor->id, 'kind' => $kind, 'id' => $id,
|
||||
'version' => (int) $data['version'], 'snapshot' => $snapshot]), JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $model, $id, $data, $snapshot, $key, $hash): array {
|
||||
$record = $model::lockForUpdate()->findOrFail($id);
|
||||
$previous = $this->preparations($actor, $record)->whereRaw("after_data->'education_preparation'->>'operation_key' = ?", [$key])->first(['after_data']);
|
||||
if ($previous) {
|
||||
$receipt = json_decode($previous->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'];
|
||||
abort_unless(hash_equals($receipt['hash'], $hash), 409, 'Esta tentativa de guardar já foi usada com outros dados.');
|
||||
|
||||
return $this->preparation($actor, $record);
|
||||
}
|
||||
$current = $this->preparation($actor, $record);
|
||||
abort_unless($current['version'] === (int) $data['version'], 409, 'A preparação mudou noutra janela. Compare antes de substituir.');
|
||||
abort_if($current['unavailable'], 409, 'A preparação anterior não pôde ser recuperada e foi preservada.');
|
||||
abort_if($snapshot['base']['version_no'] > (int) $record->getAttribute('version_no'), 422, 'A versão analisada não existe nesta declaração.');
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id,
|
||||
'entity_type' => $record->getTable(), 'entity_id' => $id, 'action' => 'review_preparation_saved', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['education_preparation' => ['version' => $current['version'] + 1, 'operation_key' => $key, 'hash' => $hash,
|
||||
'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))]], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->preparation($actor, $record);
|
||||
});
|
||||
}
|
||||
|
||||
private function preparations(User $actor, LabourDemand|TrainingCapacity $record): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)
|
||||
->where('entity_type', $record->getTable())->where('entity_id', $record->id)->where('action', 'review_preparation_saved');
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function preparationRules(mixed $snapshot): array
|
||||
{
|
||||
$rules = ['snapshot' => 'required|array:values,generation,base,pending', 'snapshot.values' => 'required|array:version_no,status,review_reason',
|
||||
'snapshot.generation' => 'required|array:status,review_reason', 'snapshot.pending' => 'present|nullable|array:values,reasonGeneration,statusGeneration,base'];
|
||||
$roots = ['snapshot'];
|
||||
if (is_array($snapshot) && is_array($snapshot['pending'] ?? null)) {
|
||||
$roots[] = 'snapshot.pending';
|
||||
$rules['snapshot.pending.values'] = 'required|array:version_no,status,review_reason,client_key';
|
||||
$rules['snapshot.pending.values.client_key'] = 'required|uuid';
|
||||
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
|
||||
$rules['snapshot.pending.'.$field] = 'required|integer|min:0|max:1000000000';
|
||||
}
|
||||
}
|
||||
foreach (['status', 'review_reason'] as $field) {
|
||||
$rules['snapshot.generation.'.$field] = 'required|integer|min:0|max:1000000000';
|
||||
}
|
||||
foreach ($roots as $root) {
|
||||
$rules[$root.'.values.version_no'] = 'required|integer|min:1';
|
||||
$rules[$root.'.values.status'] = 'required|in:reviewed,rejected';
|
||||
$rules[$root.'.values.review_reason'] = 'present|string|max:3000';
|
||||
$rules[$root.'.base'] = 'required|array:version_no,qualification,quantity,status,period_start,period_end,valid_until,source,reference_date,employer,references';
|
||||
$rules[$root.'.base.version_no'] = 'required|integer|min:1';
|
||||
$rules[$root.'.base.quantity'] = 'required|integer|min:0';
|
||||
foreach (['qualification' => 250, 'status' => 40, 'period_start' => 40, 'period_end' => 40, 'valid_until' => 40, 'source' => 5000, 'reference_date' => 40, 'employer' => 1000] as $field => $max) {
|
||||
$rules[$root.'.base.'.$field] = 'present|string|max:'.$max;
|
||||
}
|
||||
$rules[$root.'.base.references'] = 'present|array:occupation,skill,project,course,location';
|
||||
$rules[$root.'.base.references.*'] = 'nullable|string|max:1000';
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @return array{actor_id:int,commands:list<array{key:string,version:int}>} */
|
||||
public function context(User $actor, LabourDemand|TrainingCapacity $record): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$commands = [];
|
||||
foreach (DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', $record->getTable())->where('entity_id', $record->id)->where('action', 'review_committed')
|
||||
->selectRaw("after_data->'education_review'->>'key' AS key,after_data->'education_review'->'version' AS version")->get() as $event) {
|
||||
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
|
||||
if (is_string($event->key) && is_int($version) && $version > 0) {
|
||||
$commands[] = ['key' => $event->key, 'version' => $version];
|
||||
}
|
||||
}
|
||||
|
||||
return ['actor_id' => $actor->id, 'commands' => $commands];
|
||||
}
|
||||
|
||||
/** Paginated private view data; no mutable paginator escapes the service.
|
||||
* @return array<string,mixed> */
|
||||
public function history(User $actor, LabourDemand|TrainingCapacity $record): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
|
||||
return DB::table('audit_events as event')->leftJoin('users', 'users.id', '=', 'event.actor_user_id')->where('event.source_system', self::SOURCE)
|
||||
->where('event.entity_type', $record->getTable())->where('event.entity_id', $record->id)->where('event.action', 'review_committed')
|
||||
->selectRaw("event.id,event.occurred_at,users.name AS actor,event.after_data->'education_review'->'version' AS version,event.after_data->'education_review'->>'snapshot' AS snapshot")
|
||||
->orderByRaw("CASE WHEN (event.after_data->'education_review'->>'version') ~ '^[0-9]{1,10}$' THEN (event.after_data->'education_review'->>'version')::bigint END DESC NULLS LAST")
|
||||
->orderByDesc('event.occurred_at')->orderByDesc('event.id')->paginate(10, ['*'], 'history_page')->withQueryString()->through(function ($event) {
|
||||
$version = is_string($event->version) ? json_decode($event->version, true) : $event->version;
|
||||
$content = null;
|
||||
try {
|
||||
if (is_string($event->snapshot)) {
|
||||
$content = json_decode(Crypt::decryptString($event->snapshot), true);
|
||||
}
|
||||
} catch (DecryptException) {/* Retain metadata and encrypted original; do not invent a past reason. */
|
||||
}
|
||||
$available = is_array($content) && isset($content['after']) && is_array($content['after']) && ($content['after']['version'] ?? null) === $version && is_string($content['after']['review_reason'] ?? null)
|
||||
&& in_array($content['after']['status'] ?? null, ['reviewed', 'rejected'], true);
|
||||
|
||||
return ['id' => $event->id, 'version' => is_int($version) && $version > 0 ? $version : null, 'actor' => $event->actor, 'occurred_at' => $event->occurred_at, 'available' => $available,
|
||||
'status' => $available ? $content['after']['status'] : null, 'reason' => $available ? $content['after']['review_reason'] : null,
|
||||
'previous_reason' => $available && is_string($content['before']['review_reason'] ?? null) ? $content['before']['review_reason'] : null];
|
||||
})->toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class EducationWorkQueue
|
||||
{
|
||||
/** @return array{actor_id:int,drafts:int|null,demands:array<string,int>,capacities:array<string,int>} */
|
||||
public function summary(User $actor): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
|
||||
return ['actor_id' => $actor->id, 'drafts' => app(EducationDeclarationDrafts::class)->installed() ? DB::table('education_declaration_drafts')->where('owner_user_id', $actor->id)->where('state', 'draft')->count() : null,
|
||||
'demands' => $this->counts('labour_demands', $actor), 'capacities' => $this->counts('training_capacities', $actor)];
|
||||
}
|
||||
|
||||
/** @return array<string,int> */
|
||||
private function counts(string $table, User $actor): array
|
||||
{
|
||||
$today = now()->toDateString();
|
||||
$id = $actor->id;
|
||||
$row = DB::table($table)->whereNull('deleted_at')->selectRaw("count(*) FILTER(WHERE submitted_by=?) AS total,
|
||||
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='submitted') AS submitted,
|
||||
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='reviewed') AS reviewed,
|
||||
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='rejected') AS rejected,
|
||||
count(*) FILTER(WHERE submitted_by=? AND valid_until<?) AS expired,
|
||||
count(*) FILTER(WHERE submitted_by<>? AND valid_until>=? AND status='submitted') AS to_review", [$id, $id, $today, $id, $today, $id, $today, $id, $today, $id, $today])->first();
|
||||
if ($row === null) {
|
||||
throw new \LogicException('Education aggregate result missing.');
|
||||
}
|
||||
$result = [];
|
||||
foreach (['total', 'submitted', 'reviewed', 'rejected', 'expired', 'to_review'] as $key) {
|
||||
$result[$key] = (int) $row->$key;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ final class ExistingBusinessDrafts
|
||||
'payload.declared_reason' => ['nullable', 'string', 'max:2000'],
|
||||
'payload.source_reference' => ['nullable', 'string', 'max:2000'],
|
||||
'payload.valid_until' => ['nullable', 'date_format:Y-m-d'],
|
||||
...BusinessFormSchema::rules(),
|
||||
...BusinessFormSchema::rules(is_array($input['payload'] ?? null) ? $input['payload'] : []),
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
@@ -95,6 +95,7 @@ final class ExistingBusinessDrafts
|
||||
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason, array $context = []): void
|
||||
{
|
||||
$snapshot = json_encode(['context' => $context, 'record' => $business->attributesToArray(), 'payload' => $business->payload,
|
||||
'locations' => DB::table('existing_business_locations')->where('existing_business_id', $business->id)->orderBy('id')->select('*')->selectRaw('ST_AsEWKT(geom) AS geometry_snapshot')->get()->map(fn ($row) => (array) $row)->all(),
|
||||
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
|
||||
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
|
||||
], JSON_THROW_ON_ERROR);
|
||||
|
||||
@@ -122,6 +122,7 @@ final class ExistingBusinessIntake
|
||||
$submissionRules['valid_until'][0] = 'required';
|
||||
}
|
||||
Validator::make([...$business->payload, 'consent' => $consent], $submissionRules)->validate();
|
||||
app(BusinessPointPublication::class)->candidate($business->payload);
|
||||
}
|
||||
if ($action === OpportunityStatus::Approved->value) {
|
||||
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
@@ -138,6 +139,7 @@ final class ExistingBusinessIntake
|
||||
abort_unless(! in_array((int) $actor->id, $approvalActors, true), 403,
|
||||
'A publicação deve ser executada por uma pessoa diferente dos aprovadores.');
|
||||
}
|
||||
$pointContext = $action === OpportunityStatus::Published->value ? app(BusinessPointPublication::class)->publish($business) : [];
|
||||
$fromStatus = $business->status;
|
||||
$business->status = $action;
|
||||
if ($action === OpportunityStatus::Published->value) {
|
||||
@@ -190,7 +192,7 @@ final class ExistingBusinessIntake
|
||||
DB::table('existing_business_reviews')->insert(['id' => (string) Str::uuid(), 'business_id' => $id, 'actor_id' => $actor->id,
|
||||
'version_no' => $business->version_no, 'action' => $action,
|
||||
'note' => Crypt::encryptString(json_encode(['note' => $note, 'review_consent' => $action === 'submitted' ? $consent : null], JSON_THROW_ON_ERROR))]);
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $action, $note);
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $action, $note, $pointContext);
|
||||
|
||||
return $business;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\QueryException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Combines independent, already-authorised sources without loading complete catalogues. */
|
||||
final class FederatedSearch
|
||||
{
|
||||
/** @param array<string, callable(): array{count:int, fetch:callable(int,int): iterable<array<string,mixed>>}> $factories
|
||||
* @return array{data:list<array<string,mixed>>,total:int,current_page:int,last_page:int,per_page:int,unavailable:list<string>}
|
||||
*/
|
||||
public function page(array $factories, int $requestedPage, int $size = 5, ?callable $score = null): array
|
||||
{
|
||||
$sources = [];
|
||||
$unavailable = [];
|
||||
foreach ($factories as $label => $factory) {
|
||||
try {
|
||||
$sources[$label] = $factory();
|
||||
} catch (QueryException|HttpException $exception) {
|
||||
if ($exception instanceof HttpException && ! in_array($exception->getStatusCode(), [404, 503], true)) {
|
||||
throw $exception;
|
||||
}
|
||||
report($exception);
|
||||
$unavailable[] = $label;
|
||||
}
|
||||
}
|
||||
|
||||
// If a source fails after its count, remove it and recompute the page offsets.
|
||||
do {
|
||||
$failed = false;
|
||||
$total = array_sum(array_column($sources, 'count'));
|
||||
$last = max(1, (int) ceil($total / $size));
|
||||
$page = min(max(1, $requestedPage), $last);
|
||||
$first = ($page - 1) * $size;
|
||||
$items = [];
|
||||
$positions = array_fill_keys(array_keys($sources), 0);
|
||||
$buffers = array_fill_keys(array_keys($sources), []);
|
||||
for ($position = 0; $position < min($total, $first + $size); $position++) {
|
||||
$best = null;
|
||||
$bestScore = PHP_INT_MIN;
|
||||
foreach ($sources as $label => $source) {
|
||||
if ($buffers[$label] === [] && $positions[$label] < $source['count']) {
|
||||
try {
|
||||
$batch = iterator_to_array((function () use ($source, $positions, $label, $size) {
|
||||
yield from ($source['fetch'])($positions[$label], $size);
|
||||
})(), false);
|
||||
$positions[$label] += count($batch);
|
||||
$buffers[$label] = $batch;
|
||||
if ($batch === []) {
|
||||
$positions[$label] = $source['count'];
|
||||
}
|
||||
} catch (QueryException|HttpException $exception) {
|
||||
if ($exception instanceof HttpException && ! in_array($exception->getStatusCode(), [404, 503], true)) {
|
||||
throw $exception;
|
||||
}
|
||||
report($exception);
|
||||
$unavailable[] = $label;
|
||||
unset($sources[$label]);
|
||||
$failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($buffers[$label] === []) {
|
||||
continue;
|
||||
}
|
||||
$candidateScore = $score ? $score($buffers[$label][0]) : 0;
|
||||
if ($best === null || $candidateScore > $bestScore) {
|
||||
$best = $label;
|
||||
$bestScore = $candidateScore;
|
||||
}
|
||||
}
|
||||
if ($failed || $best === null) {
|
||||
break;
|
||||
}
|
||||
$item = array_shift($buffers[$best]);
|
||||
if ($position >= $first) {
|
||||
$items[] = [...$item, 'category' => $best];
|
||||
}
|
||||
}
|
||||
} while ($failed);
|
||||
|
||||
return ['data' => $items, 'total' => $total, 'current_page' => $page, 'last_page' => $last,
|
||||
'per_page' => $size, 'unavailable' => $unavailable];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** A selected public funding reference in the existing encrypted investment dossier. */
|
||||
final class FundingDossierPreparation
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function context(User $actor, string $id, ?string $opportunity): array
|
||||
{
|
||||
$case = app(VirtualDesk::class)->case($actor, $id);
|
||||
abort_unless(app(VirtualDesk::class)->owns($actor, $case) || $actor->can('manage-portal'), 403);
|
||||
$state = app(InvestorContext::class)->state($case);
|
||||
$scope = app(InvestmentConsumerScope::class);
|
||||
$opportunity = $scope->key($state, $opportunity, true);
|
||||
$specific = $scope->context($state, $opportunity);
|
||||
$selections = app(VirtualDesk::class)->decode($case->payload)['investor_path']['funding_selections'] ?? [];
|
||||
|
||||
return ['id' => $id, 'version' => (int) $case->version, 'closed' => $case->closed_at !== null, 'opportunity' => $opportunity,
|
||||
'territory' => $specific['selection']['territory']['id'] ?? null,
|
||||
'selections' => array_values(array_filter($selections, fn ($row) => ($row['opportunity'] ?? null) === $opportunity)),
|
||||
'href' => '/investimentos/'.$id.($opportunity ? '?opportunity='.urlencode($opportunity) : '').'#financiamento'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $programme, array $input): array
|
||||
{
|
||||
$data = Validator::make($input, ['context' => 'required|uuid', 'opportunity' => 'nullable|string|max:150', 'version' => 'required|integer|min:1',
|
||||
'version_id' => 'required|uuid', 'product' => 'nullable|string|max:80', 'need' => ['required', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))],
|
||||
'territory' => 'nullable|uuid', 'location_id' => 'nullable|string|max:100', 'location_mode' => 'nullable|in:physical,coverage', 'operation_key' => 'required|uuid', 'consent' => 'accepted'])->validate();
|
||||
$intent = hash('sha256', json_encode(Arr::sortRecursive([...$data, 'actor' => $actor->id, 'programme' => $programme]), JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $programme, $data, $intent): array {
|
||||
$desk = app(VirtualDesk::class);
|
||||
$case = $desk->case($actor, $data['context'], true, true);
|
||||
abort_if($case->closed_at, 409, 'O dossier está encerrado.');
|
||||
$context = $this->context($actor, $case->id, $data['opportunity'] ?? null);
|
||||
$payload = $desk->decode($case->payload);
|
||||
$selections = $payload['investor_path']['funding_selections'] ?? [];
|
||||
foreach ($selections as $selection) {
|
||||
if ($selection['id'] === $data['operation_key']) {
|
||||
abort_unless(hash_equals($selection['intent'], $intent), 409, 'A intenção já tem outro conteúdo.');
|
||||
|
||||
return $context;
|
||||
}
|
||||
}
|
||||
foreach ($selections as $selection) {
|
||||
if (($selection['opportunity'] ?? null) === $context['opportunity'] && $selection['programme_id'] === $programme && $selection['version_id'] === $data['version_id'] && ($selection['product']['code'] ?? null) === ($data['product'] ?? null) && $selection['need'] === $data['need'] && ($selection['territory'] ?? null) === ($data['territory'] ?? null) && ($selection['location']['id'] ?? null) === ($data['location_id'] ?? null)) {
|
||||
return $context;
|
||||
}
|
||||
}
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409, 'O dossier mudou. Consulte-o antes de guardar esta escolha.');
|
||||
$catalogue = app(FundingProgrammes::class);
|
||||
$record = $catalogue->published($programme);
|
||||
abort_unless($record['version_id'] === $data['version_id'], 409, 'A ficha pública mudou. Confira a versão actual.');
|
||||
if (! empty($data['territory'])) {
|
||||
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $data['territory'])->exists(), 422);
|
||||
}
|
||||
$location = null;
|
||||
if (! empty($data['location_id'])) {
|
||||
foreach ($record['payload']['locations'] ?? [] as $candidate) {
|
||||
if (($candidate['id'] ?? null) === $data['location_id']) {
|
||||
$location = $candidate;
|
||||
}
|
||||
}
|
||||
abort_unless($location, 422, 'O local seleccionado não pertence à versão consultada da instituição.');
|
||||
}
|
||||
$product = null;
|
||||
if ($record['payload']['kind'] === 'institution') {
|
||||
foreach ($record['payload']['products'] as $candidate) {
|
||||
if (($candidate['code'] ?? null) === ($data['product'] ?? null)) {
|
||||
$product = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
abort_unless(($record['payload']['products'] === [] && empty($data['product']) && app(FundingInstitutionClassification::class)->permitsUnknownProduct($record['payload'], $data['need'])) || ($product && app(FundingInstitutionDetails::class)->match($product, $data)), 422, 'O serviço ou produto escolhido não corresponde à informação da ficha para esta necessidade/local. Confira as condições ou seleccione outra referência.');
|
||||
}
|
||||
abort_if(count($selections) >= 200, 422, 'O dossier atingiu o limite de referências de financiamento.');
|
||||
$selection = ['id' => $data['operation_key'], 'intent' => $intent, 'actor' => $actor->id, 'opportunity' => $context['opportunity'],
|
||||
'programme_id' => $programme, 'version_id' => $record['version_id'], 'version' => $record['version'], 'title' => $record['payload']['title'],
|
||||
'record' => $record['payload'], 'product' => $product, 'need' => $data['need'], 'territory' => $data['territory'] ?? null, 'location' => $location, 'location_mode' => $data['location_mode'] ?? 'coverage', 'categories' => $record['payload']['institution_categories'] ?? [], 'institution_types' => $record['payload']['institution_types'] ?? [], 'institution_key' => $record['payload']['institution_key'] ?? null, 'recorded_at' => now()->toIso8601String(),
|
||||
'notice' => 'Referência para preparação. Não é candidatura, contacto enviado, aprovação ou garantia de financiamento.'];
|
||||
$payload['investor_path']['funding_selections'][] = $selection;
|
||||
DB::table('desk_cases')->where('id', $case->id)->update(['payload' => $desk->encode($payload), 'version' => (int) $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($case, $actor, 'funding_preparation_saved', ['selection_id' => $selection['id'], 'programme_id' => $programme, 'version_id' => $record['version_id'], 'opportunity' => $context['opportunity']]);
|
||||
|
||||
return $this->context($actor, $case->id, $context['opportunity']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Documentary classification and physical presence; neither is lending eligibility. */
|
||||
final class FundingInstitutionClassification
|
||||
{
|
||||
public const CATEGORIES = ['banking' => 'Banca', 'credit' => 'Crédito e microfinanças', 'investment' => 'Gestão de investimento', 'pensions' => 'Fundos de pensões', 'insurance' => 'Seguros e resseguros', 'intermediation' => 'Mediação de seguros', 'exchange' => 'Câmbio', 'payments' => 'Pagamentos e serviços interbancários', 'supervision' => 'Supervisão', 'other' => 'Outras instituições'];
|
||||
|
||||
public const TYPES = ['commercial_bank' => 'Banco comercial', 'investment_bank' => 'Banco de investimento', 'bank' => 'Banco (tipo não especificado)', 'microbank' => 'Microbanco', 'cooperative' => 'Cooperativa de crédito', 'savings' => 'Organização de poupança e empréstimo', 'investment_manager' => 'Gestora de fundos de investimento', 'investment_company' => 'Sociedade de investimento', 'pension_manager' => 'Gestora de fundos de pensões', 'insurer' => 'Seguradora', 'reinsurer' => 'Resseguradora', 'microinsurer' => 'Micro-seguradora', 'broker' => 'Corretora de seguros', 'agent' => 'Agente de seguros', 'reinsurance_broker' => 'Corretor de resseguro', 'exchange_house' => 'Casa de câmbio', 'electronic_money' => 'Instituição de moeda electrónica', 'interbank' => 'Serviços interbancários', 'supervisor' => 'Supervisor', 'other' => 'Outro tipo documentado'];
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function normalize(array $input): array
|
||||
{
|
||||
return Validator::make($input, [
|
||||
'institution_categories' => 'array|max:10', 'institution_categories.*' => ['required', 'distinct', Rule::in(array_keys(self::CATEGORIES))],
|
||||
'institution_types' => 'array|max:10', 'institution_types.*' => ['required', 'distinct', Rule::in(array_keys(self::TYPES))],
|
||||
'institution_services' => 'array|max:12', 'institution_services.*' => ['required', 'distinct', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))],
|
||||
'institution_status' => 'nullable|in:reported,historical,merged,unknown', 'successor_key' => 'nullable|string|max:100',
|
||||
'register_reference' => 'nullable|string|max:2000', 'aliases' => 'array|max:100', 'aliases.*' => 'required|string|max:500',
|
||||
'source_rows' => 'array|max:250', 'source_rows.*' => 'required|array:id,section,text', 'source_rows.*.id' => 'required|string|max:100',
|
||||
'source_rows.*.section' => 'required|string|max:250', 'source_rows.*.text' => 'required|string|max:8000',
|
||||
])->validate();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
public function filter(Builder $query, array $filters): void
|
||||
{
|
||||
foreach (['category' => 'institution_categories', 'institution_type' => 'institution_types'] as $key => $field) {
|
||||
if (! empty($filters[$key])) {
|
||||
$query->whereRaw('v.payload->? @> ?::jsonb', [$field, json_encode([$filters[$key]], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
if (empty($filters['include_historical'])) {
|
||||
$query->whereRaw("COALESCE(v.payload->>'institution_status','reported') NOT IN ('historical','merged')");
|
||||
}
|
||||
if (($filters['location_mode'] ?? 'coverage') !== 'physical') {
|
||||
return;
|
||||
}
|
||||
$query->whereRaw("v.payload->>'kind'='institution'");
|
||||
if (empty($filters['territory'])) {
|
||||
return;
|
||||
}
|
||||
$unknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
$clauses = ["l->'territory_path' @> ?::jsonb"];
|
||||
$bindings = [json_encode([['id' => $filters['territory']]], JSON_THROW_ON_ERROR)];
|
||||
if ($unknown) {
|
||||
foreach ($path as $id) {
|
||||
$clauses[] = "l->>'territory_id' = ?";
|
||||
$bindings[] = $id;
|
||||
}
|
||||
}
|
||||
$status = $unknown ? '' : " AND COALESCE(l->>'evidence_status','reported') NOT IN ('to_confirm','historical','conflict','unlocated')";
|
||||
$query->where(function (Builder $q) use ($clauses, $bindings, $status, $unknown): void {
|
||||
$q->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) l WHERE (".implode(' OR ', $clauses).')'.$status.')', $bindings);
|
||||
if ($unknown) {
|
||||
$q->orWhereRaw("NOT EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) l WHERE NULLIF(l->>'territory_id','') IS NOT NULL)");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public function permitsUnknownProduct(array $payload, ?string $need): bool
|
||||
{
|
||||
return ! $need || ! isset($payload['institution_services']) || in_array($need, $payload['institution_services'], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Additional factual fields in the existing versioned funding catalogue. */
|
||||
final class FundingInstitutionDetails
|
||||
{
|
||||
public const NATURES = ['bank' => 'Banco', 'credit' => 'Instituição de crédito', 'microfinance' => 'Microfinanças', 'investment_fund' => 'Fundo de investimento', 'development' => 'Agência de desenvolvimento/financiamento', 'other' => 'Outra natureza documentada', 'unknown' => 'Natureza por confirmar'];
|
||||
|
||||
public const NEEDS = ['investment' => 'Investimento/equipamento', 'working_capital' => 'Fundo de maneio', 'equity' => 'Participação de capital', 'guarantee' => 'Garantia', 'technical_assistance' => 'Assistência técnica', 'insurance' => 'Seguros', 'foreign_exchange' => 'Câmbio', 'payments' => 'Pagamentos', 'pension' => 'Pensões', 'investment_management' => 'Gestão de investimento', 'other' => 'Outra necessidade documentada'];
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function normalize(array $input, bool $publishing): array
|
||||
{
|
||||
$required = $publishing ? 'required' : 'nullable';
|
||||
$rules = [
|
||||
'institution_key' => 'required|string|regex:/^[a-z0-9][a-z0-9.-]{0,99}$/D',
|
||||
'institution_nature' => ['required', Rule::in(array_keys(self::NATURES))],
|
||||
'contacts' => 'array|max:100', 'locations' => 'array|max:100', 'products' => 'array|max:40',
|
||||
'contacts.*' => 'array:id,kind,value,source_url,source_reference,checked_on,source_document_name,source_document_sha256,evidence_status,origin,source_refs',
|
||||
'contacts.*.kind' => 'required|in:website,email,phone,address', 'contacts.*.value' => "$required|string|max:1000",
|
||||
'locations.*' => 'array:id,role,label,address,territory_id,source_url,source_reference,checked_on,source_document_name,source_document_sha256,evidence_status,origin,source_refs,location_text,hours',
|
||||
'locations.*.role' => 'required|in:headquarters,branch,contact_point', 'locations.*.label' => "$required|string|max:250",
|
||||
'locations.*.address' => 'nullable|string|max:1500', 'locations.*.territory_id' => 'nullable|uuid',
|
||||
'products.*' => 'array:code,title,instrument,needs,coverage,coverage_text,territory_ids,conditions,amounts,availability,contact_url,source_url,source_reference,checked_on,source_document_name,source_document_sha256',
|
||||
'products.*.code' => 'required|string|regex:/^[a-z0-9][a-z0-9-]{0,79}$/D|distinct', 'products.*.title' => "$required|string|max:250",
|
||||
'products.*.instrument' => 'nullable|string|max:250', 'products.*.needs' => 'array|max:6',
|
||||
'products.*.needs.*' => ['required', 'distinct', Rule::in(array_keys(self::NEEDS))],
|
||||
'products.*.coverage' => 'required|in:national,territorial,unknown', 'products.*.coverage_text' => 'nullable|string|max:2000',
|
||||
'products.*.territory_ids' => 'array|max:30', 'products.*.territory_ids.*' => 'required|uuid|distinct',
|
||||
'products.*.conditions' => 'nullable|string|max:4000', 'products.*.amounts' => 'nullable|string|max:2000',
|
||||
'products.*.availability' => 'required|in:documented,unknown,closed', 'products.*.contact_url' => 'nullable|url:http,https|max:2000',
|
||||
];
|
||||
foreach (['contacts', 'locations', 'products'] as $prefix) {
|
||||
$rules[$prefix.'.*.source_url'] = 'nullable|url:http,https|max:2000';
|
||||
$rules[$prefix.'.*.source_document_name'] = 'nullable|string|max:250';
|
||||
$rules[$prefix.'.*.source_document_sha256'] = 'nullable|string|regex:/^[a-f0-9]{64}$/D';
|
||||
$rules[$prefix.'.*.source_reference'] = "$required|string|max:1500";
|
||||
$rules[$prefix.'.*.checked_on'] = "$required|date_format:Y-m-d|before_or_equal:today";
|
||||
}
|
||||
foreach (['contacts', 'locations'] as $prefix) {
|
||||
$rules[$prefix.'.*.id'] = 'nullable|string|max:100';
|
||||
$rules[$prefix.'.*.evidence_status'] = 'nullable|in:reported,to_confirm,historical,conflict,unlocated';
|
||||
$rules[$prefix.'.*.origin'] = 'nullable|string|max:500';
|
||||
$rules[$prefix.'.*.source_refs'] = 'array|max:100';
|
||||
$rules[$prefix.'.*.source_refs.*'] = 'required|string|max:100';
|
||||
}
|
||||
$rules['locations.*.location_text'] = 'nullable|string|max:1000';
|
||||
$rules['locations.*.hours'] = 'nullable|string|max:1000';
|
||||
$data = [...Validator::make($input, $rules)->validate(), ...app(FundingInstitutionClassification::class)->normalize($input)];
|
||||
if ($publishing) {
|
||||
foreach (['contacts', 'locations', 'products'] as $prefix) {
|
||||
foreach ($data[$prefix] ?? [] as $item) {
|
||||
Validator::make($item, ['source_url' => empty($item['source_document_sha256']) ? 'required|url:http,https' : 'nullable|url:http,https', 'source_document_name' => empty($item['source_url']) ? 'required|string' : 'nullable|string'])->validate();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['contacts', 'locations', 'products'] as $key) {
|
||||
$data[$key] ??= [];
|
||||
}
|
||||
foreach ($data['contacts'] as $contact) {
|
||||
Validator::make(['value' => $contact['value'] ?? null], ['value' => match ($contact['kind']) {
|
||||
'website' => "$required|url:http,https|max:1000",
|
||||
'email' => "$required|email|max:250",
|
||||
default => "$required|string|max:1000",
|
||||
}])->validate();
|
||||
}
|
||||
foreach ($data['locations'] as &$location) {
|
||||
if (! empty($location['territory_id'])) {
|
||||
$this->territory($location['territory_id']);
|
||||
if ($publishing) {
|
||||
$location['territory_path'] = $this->path($location['territory_id']);
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($location);
|
||||
foreach ($data['products'] as &$product) {
|
||||
$product['needs'] ??= [];
|
||||
$product['territory_ids'] ??= [];
|
||||
Validator::make($product, ['territory_ids' => $product['coverage'] === 'territorial' ? ($publishing ? 'required|array|min:1' : 'array') : 'array|size:0'])->validate();
|
||||
// Territorial drafts may be incomplete; other coverage modes never inherit the headquarters.
|
||||
foreach ($product['territory_ids'] as $id) {
|
||||
$this->territory($id);
|
||||
}
|
||||
if ($publishing) {
|
||||
$product['territory_paths'] = array_map($this->path(...), $product['territory_ids']);
|
||||
}
|
||||
}
|
||||
unset($product);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function territory(string $id): void
|
||||
{
|
||||
Validator::make(['territory' => $id], ['territory' => [Rule::in(app(InvestmentGeography::class)->publicReferences()->pluck('id')->all())]])->validate();
|
||||
}
|
||||
|
||||
/** @return list<array{id:string,name:string,type:string}> */
|
||||
private function path(string $id): array
|
||||
{
|
||||
return array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($id));
|
||||
}
|
||||
|
||||
/** Same product must satisfy both location and need; branch addresses never imply lending coverage.
|
||||
* @param array<string,mixed> $product
|
||||
* @param array<string,mixed> $filters */
|
||||
public function match(array $product, array $filters): bool
|
||||
{
|
||||
$unknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
|
||||
if ($product['availability'] === 'closed') {
|
||||
return false;
|
||||
}
|
||||
if (! $unknown && $product['availability'] === 'unknown') {
|
||||
return false;
|
||||
}
|
||||
if (! empty($filters['need']) && ! in_array($filters['need'], $product['needs'], true) && ! ($unknown && $product['needs'] === [])) {
|
||||
return false;
|
||||
}
|
||||
if (empty($filters['territory'])) {
|
||||
return true;
|
||||
}
|
||||
if ($product['coverage'] === 'national') {
|
||||
return true;
|
||||
}
|
||||
if ($product['coverage'] === 'unknown') {
|
||||
return $unknown;
|
||||
}
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
foreach ($product['territory_paths'] ?? [] as $covered) {
|
||||
$ids = array_column($covered, 'id');
|
||||
if (array_intersect($path, $product['territory_ids']) !== [] || in_array($filters['territory'], $ids, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
public function applyFilters(Builder $query, array $filters): void
|
||||
{
|
||||
app(FundingInstitutionClassification::class)->filter($query, $filters);
|
||||
if (empty($filters['need']) && (empty($filters['territory']) || ($filters['location_mode'] ?? '') === 'physical')) {
|
||||
return;
|
||||
}
|
||||
$unknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
|
||||
$conditions = ["p->>'availability' <> 'closed'"];
|
||||
$bindings = [];
|
||||
if (! $unknown) {
|
||||
$conditions[] = "p->>'availability' <> 'unknown'";
|
||||
}
|
||||
if (! empty($filters['need'])) {
|
||||
$conditions[] = "(p->'needs' @> ?::jsonb".($unknown ? " OR jsonb_array_length(p->'needs')=0" : '').')';
|
||||
$bindings[] = json_encode([$filters['need']], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
if (! empty($filters['territory']) && ($filters['location_mode'] ?? '') !== 'physical') {
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
$parts = ["p->>'coverage'='national'", "EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(p->'territory_paths','[]'::jsonb)) t WHERE t @> ?::jsonb)"];
|
||||
$bindings[] = json_encode([['id' => $filters['territory']]], JSON_THROW_ON_ERROR);
|
||||
foreach ($path as $id) {
|
||||
$parts[] = "p->'territory_ids' @> ?::jsonb";
|
||||
$bindings[] = json_encode([$id], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
if ($unknown) {
|
||||
$parts[] = "p->>'coverage'='unknown'";
|
||||
}
|
||||
$conditions[] = '('.implode(' OR ', $parts).')';
|
||||
}
|
||||
$sql = "EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) p WHERE ".implode(' AND ', $conditions).')';
|
||||
$query->where(function (Builder $q) use ($sql, $bindings, $unknown, $filters): void {
|
||||
$q->where(function (Builder $q) use ($unknown, $filters): void {
|
||||
$q->whereRaw("v.payload->>'kind' <> 'institution'");
|
||||
if (! empty($filters['need'])) {
|
||||
$q->where(function (Builder $q) use ($filters, $unknown): void {
|
||||
$q->whereRaw("v.payload->'funding_needs' @> ?::jsonb", [json_encode([$filters['need']], JSON_THROW_ON_ERROR)]);
|
||||
if ($unknown) {
|
||||
$q->orWhereRaw("jsonb_array_length(COALESCE(v.payload->'funding_needs','[]'::jsonb))=0");
|
||||
}
|
||||
});
|
||||
}
|
||||
})->orWhere(function (Builder $q) use ($sql, $bindings, $unknown, $filters): void {
|
||||
$q->whereRaw("v.payload->>'kind' = 'institution'")->where(function (Builder $q) use ($sql, $bindings, $unknown, $filters): void {
|
||||
$q->whereRaw($sql, $bindings);
|
||||
if ($unknown) {
|
||||
$q->orWhere(function (Builder $p) use ($filters): void {
|
||||
$p->whereRaw("jsonb_array_length(COALESCE(v.payload->'products','[]'::jsonb))=0");
|
||||
if (! empty($filters['need'])) {
|
||||
$p->where(fn ($z) => $z->whereRaw("v.payload->'institution_services' @> ?::jsonb", [json_encode([$filters['need']], JSON_THROW_ON_ERROR)])->orWhereRaw("NOT jsonb_exists(v.payload, 'institution_services')"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Packaged documentary references prepare private drafts through existing editorial authority. */
|
||||
final class FundingProgrammeReferences
|
||||
{
|
||||
/** @return array{references:array<string,mixed>,sha256:string} */
|
||||
private function package(): array
|
||||
{
|
||||
$references = [];
|
||||
$hashes = [];
|
||||
foreach (['funding-references.json', 'funding-institutions-nov2026.json'] as $file) {
|
||||
$bytes = CheckedFile::read(database_path('data/'.$file));
|
||||
$package = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless($package['format'] === 'investmoz-funding-references-v1', 503);
|
||||
$references = [...$references, ...$package['references']];
|
||||
$hashes[$file] = hash('sha256', $bytes);
|
||||
}
|
||||
|
||||
return ['references' => $references, 'sha256' => hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor, string $code): array
|
||||
{
|
||||
app(FundingProgrammes::class)->guard($actor);
|
||||
$package = $this->package();
|
||||
$reference = $package['references'][$code] ?? null;
|
||||
abort_unless(is_array($reference), 404);
|
||||
$unresolved = [];
|
||||
$resolve = function (string $name) use (&$unresolved): ?string {
|
||||
$matches = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->get(['id', 'name'])->filter(fn ($row) => Str::lower(Str::ascii($row->name)) === Str::lower(Str::ascii($name)));
|
||||
if ($matches->count() !== 1) {
|
||||
$unresolved[] = $name;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $matches->first()->id;
|
||||
};
|
||||
if (! empty($reference['territory_names'])) {
|
||||
$ids = array_values(array_filter(array_map($resolve, $reference['territory_names'])));
|
||||
if (count($ids) === count($reference['territory_names'])) {
|
||||
$reference['draft']['territory_ids'] = $ids;
|
||||
} else {
|
||||
$reference['draft']['coverage'] = 'unknown';
|
||||
$reference['draft']['territory_ids'] = [];
|
||||
$reference['draft']['coverage_text'] .= ' Correspondência ao cadastro territorial por confirmar.';
|
||||
}
|
||||
}
|
||||
foreach ($reference['location_territory_names'] ?? [] as $index => $name) {
|
||||
$reference['draft']['locations'][$index]['territory_id'] = $resolve($name);
|
||||
if (! $reference['draft']['locations'][$index]['territory_id']) {
|
||||
$reference['draft']['locations'][$index]['evidence_status'] = 'unlocated';
|
||||
}
|
||||
}
|
||||
$plan = ['unresolved_territories' => $unresolved, 'code' => $code, 'edition' => $reference['edition'], 'draft' => $reference['draft'], 'provenance' => $reference['provenance'],
|
||||
'package_sha256' => $package['sha256']];
|
||||
$plan['hash'] = hash_hmac('sha256', json_encode(Arr::sortRecursive($plan), JSON_THROW_ON_ERROR), config('app.key'));
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/** @return list<array{code:string,title:string}> */
|
||||
public function choices(User $actor): array
|
||||
{
|
||||
app(FundingProgrammes::class)->guard($actor);
|
||||
$package = $this->package();
|
||||
$choices = [];
|
||||
foreach ($package['references'] as $code => $reference) {
|
||||
$choices[] = ['code' => $code, 'title' => $reference['draft']['title']];
|
||||
}
|
||||
|
||||
return $choices;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function assisted(User $actor): array
|
||||
{
|
||||
app(FundingProgrammes::class)->guard($actor);
|
||||
$package = $this->package();
|
||||
$existing = DB::table('funding_programmes')->get(['id', 'code', 'version', 'published_version_id'])->keyBy('code');
|
||||
$items = [];
|
||||
foreach ($package['references'] as $code => $reference) {
|
||||
$draft = $reference['draft'];
|
||||
$row = $existing->get($code);
|
||||
$items[] = ['code' => $code, 'title' => $draft['title'], 'summary' => $draft['summary'], 'categories' => $draft['institution_categories'] ?? [],
|
||||
'types' => $draft['institution_types'] ?? [], 'status' => $draft['institution_status'] ?? 'reported', 'source_document' => $draft['source_document_name'] ?? null,
|
||||
'source_sha256' => $draft['source_document_sha256'] ?? null, 'locations' => $draft['locations'] ?? [], 'contacts' => $draft['contacts'] ?? [],
|
||||
'id' => $row?->id, 'published' => $row?->published_version_id !== null];
|
||||
}
|
||||
|
||||
return ['dataset_hash' => $package['sha256'], 'editor_id' => $actor->id, 'items' => $items];
|
||||
}
|
||||
|
||||
/** @return array{id:string,created:bool} */
|
||||
public function prepare(User $actor, string $code, string $hash): array
|
||||
{
|
||||
$plan = $this->preview($actor, $code);
|
||||
abort_unless(hash_equals($plan['hash'], $hash), 409, 'As referências mudaram. Recupere a prévia antes de preparar a ficha.');
|
||||
|
||||
return DB::transaction(function () use ($actor, $code, $plan): array {
|
||||
DB::select('select pg_advisory_xact_lock(261102, hashtext(?))', [$code]);
|
||||
$existing = DB::table('funding_programmes')->where('code', $code)->lockForUpdate()->first();
|
||||
if ($existing) {
|
||||
return ['id' => $existing->id, 'created' => false];
|
||||
}
|
||||
$id = app(FundingProgrammes::class)->save($actor, null, ['version' => 0, 'code' => $code,
|
||||
'reason' => 'Preparação de referência documental '.$plan['edition'].'; rascunho sem publicação automática.', 'draft' => $plan['draft']]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'funding-catalogue', 'entity_type' => 'funding_programmes', 'entity_id' => $id,
|
||||
'actor_user_id' => $actor->id, 'action' => 'reference_prepared', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['edition' => $plan['edition'], 'package_sha256' => $plan['package_sha256'], 'provenance' => $plan['provenance'], 'effect' => 'private_draft_only'], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return ['id' => $id, 'created' => true];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/** Informational funding catalogue, separate from applications, credit decisions and fiscal calculations. */
|
||||
final class FundingProgrammes
|
||||
{
|
||||
public const KINDS = ['institution' => 'Instituição financeira', 'fund' => 'Fundo', 'programme' => 'Programa de apoio', 'incentive' => 'Incentivo'];
|
||||
|
||||
public const WINDOWS = ['dated' => 'Datas documentadas', 'rolling' => 'Recepção contínua documentada', 'unknown' => 'Janela por confirmar', 'closed' => 'Encerrada segundo a fonte'];
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('funding_programme_interests') && Schema::hasTable('funding_programme_versions');
|
||||
}
|
||||
|
||||
public function access(?User $actor): bool
|
||||
{
|
||||
return app(DocumentManagementAccess::class)->catalogueEditor($actor);
|
||||
}
|
||||
|
||||
public function guard(?User $actor): void
|
||||
{
|
||||
abort_unless($this->installed(), 404);
|
||||
abort_unless($this->access($actor), 403);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $reference */
|
||||
public function matchesReference(User $actor, string $id, array $reference): bool
|
||||
{
|
||||
$this->guard($actor);
|
||||
$row = DB::table('funding_programmes')->where('id', $id)->firstOrFail();
|
||||
$expected = $this->normalize($actor, $reference, false);
|
||||
$actual = json_decode($row->draft, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(is_array($actual), 503);
|
||||
|
||||
return json_encode(Arr::sortRecursive($actual), JSON_THROW_ON_ERROR)
|
||||
=== json_encode(Arr::sortRecursive($expected), JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
public function publicQuery(): Builder
|
||||
{
|
||||
abort_unless($this->installed(), 404);
|
||||
|
||||
return DB::table('funding_programmes as p')->join('funding_programme_versions as v', fn ($join) => $join->on('v.id', '=', 'p.published_version_id')->on('v.programme_id', '=', 'p.id'))
|
||||
->where('v.published_at', '<=', now());
|
||||
}
|
||||
|
||||
public function readableVersions(): Builder
|
||||
{
|
||||
return DB::table('funding_programme_versions')->where('published_at', '<=', now())
|
||||
->whereIn('programme_id', $this->publicQuery()->select('p.id'));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
public function catalogueQuery(array $filters): Builder
|
||||
{
|
||||
$query = $this->publicQuery();
|
||||
app(FundingInstitutionDetails::class)->applyFilters($query, $filters);
|
||||
$includeUnknown = ($filters['certainty'] ?? 'include_unknown') === 'include_unknown';
|
||||
if (! empty($filters['sector'])) {
|
||||
$query->where(function (Builder $scope) use ($filters, $includeUnknown): void {
|
||||
$scope->whereRaw("v.payload->>'sectors_scope' = 'all'")
|
||||
->orWhereJsonContains('v.payload->sector_ids', (int) $filters['sector']);
|
||||
if ($includeUnknown) {
|
||||
$scope->orWhereRaw("v.payload->>'sectors_scope' = 'unknown'");
|
||||
}
|
||||
});
|
||||
}
|
||||
if (! empty($filters['territory']) && ($filters['location_mode'] ?? '') !== 'physical') {
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
$query->where(function (Builder $scope) use ($filters, $path, $includeUnknown): void {
|
||||
$scope->whereRaw("v.payload->>'kind' = 'institution'")->orWhereRaw("v.payload->>'coverage' = 'national'")
|
||||
->orWhereJsonContains('v.payload->territory_ancestor_ids', $filters['territory']);
|
||||
foreach ($path as $id) {
|
||||
$scope->orWhereJsonContains('v.payload->territory_ids', $id);
|
||||
}
|
||||
if ($includeUnknown) {
|
||||
$scope->orWhereRaw("v.payload->>'coverage' = 'unknown'");
|
||||
}
|
||||
});
|
||||
}
|
||||
if (! empty($filters['state'])) {
|
||||
$today = today()->toDateString();
|
||||
$state = $filters['state'];
|
||||
if ($state === 'unknown') {
|
||||
$query->whereRaw("(jsonb_array_length(v.payload->'windows') = 0 OR EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'unknown'))");
|
||||
} elseif ($state === 'closed') {
|
||||
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'closed' OR (w->>'mode' = 'dated' AND w->>'end_on' < ?))", [$today]);
|
||||
} elseif ($state === 'upcoming') {
|
||||
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' = 'dated' AND w->>'start_on' > ?)", [$today]);
|
||||
} else {
|
||||
$query->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(v.payload->'windows') w WHERE w->>'mode' IN ('dated','rolling') AND COALESCE(NULLIF(w->>'start_on',''),?) <= ? AND COALESCE(NULLIF(w->>'end_on',''),?) >= ?)", [$today, $today, $today, $today]);
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $record
|
||||
* @param array<string,mixed> $filters
|
||||
* @return array<string,string> */
|
||||
public function filterExplanation(array $record, array $filters): array
|
||||
{
|
||||
$payload = $record['payload'];
|
||||
if ($payload['kind'] === 'institution') {
|
||||
$products = array_values(array_filter($payload['products'] ?? [], fn ($p) => app(FundingInstitutionDetails::class)->match($p, $filters)));
|
||||
|
||||
if (($filters['location_mode'] ?? '') === 'physical') {
|
||||
return ['institution' => 'Pesquisa por presença física documentada, não por cobertura de financiamento. Confira a precisão do local e as indicações por confirmar na ficha.'];
|
||||
}
|
||||
|
||||
return ['institution' => $products === [] ? 'Instituição identificada; produtos, cobertura e disponibilidade por confirmar. Não é uma correspondência confirmada.' : 'Consulte os produtos correspondentes e as condições por confirmar. Sede e balcões não determinam a cobertura do financiamento.'];
|
||||
}
|
||||
$result = [];
|
||||
if (! empty($filters['sector'])) {
|
||||
$result['sector'] = $payload['sectors_scope'] === 'unknown'
|
||||
? 'Âmbito sectorial por confirmar; não é uma correspondência confirmada.'
|
||||
: 'O sector está abrangido pelo âmbito documentado do programa.';
|
||||
}
|
||||
if (! empty($filters['territory'])) {
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
$result['territory'] = $payload['coverage'] === 'unknown' ? 'Cobertura territorial por confirmar; não é uma correspondência confirmada.'
|
||||
: ($payload['coverage'] === 'national' || array_intersect($path, $payload['territory_ids']) !== []
|
||||
? 'O local está abrangido pela cobertura documentada do programa.'
|
||||
: 'O programa abrange uma parte da área seleccionada; confira os locais na ficha.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function published(string $id): array
|
||||
{
|
||||
$row = $this->publicQuery()->where('p.id', $id)->firstOrFail(['p.id', 'p.code', 'v.id as version_id', 'v.version', 'v.payload', 'v.published_at']);
|
||||
|
||||
return $this->present($row);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function present(\stdClass $row): array
|
||||
{
|
||||
$payload = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach ($payload['windows'] as &$window) {
|
||||
$window['state'] = $this->windowState($window);
|
||||
}
|
||||
unset($window);
|
||||
$payload['documents'] = array_map(fn ($document) => [...$document,
|
||||
'available' => app(Procurement::class)->publicDocuments()->where('r.id', $document['resource_id'])->where('d.id', $document['document_id'])
|
||||
->where('d.sha256', $document['sha256'])->where('d.version_no', $document['version'])->exists(),
|
||||
], $payload['document_snapshots'] ?? []);
|
||||
|
||||
return ['id' => $row->id, 'code' => $row->code, 'version_id' => $row->version_id, 'version' => (int) $row->version,
|
||||
'published_at' => $row->published_at, 'payload' => $payload];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $window */
|
||||
public function windowState(array $window): string
|
||||
{
|
||||
if ($window['mode'] === 'closed') {
|
||||
return 'closed';
|
||||
}
|
||||
if ($window['mode'] === 'unknown') {
|
||||
return 'unknown';
|
||||
}
|
||||
if (! empty($window['end_on']) && $window['end_on'] < today()->toDateString()) {
|
||||
return 'closed';
|
||||
}
|
||||
if (! empty($window['start_on']) && $window['start_on'] > today()->toDateString()) {
|
||||
return 'upcoming';
|
||||
}
|
||||
|
||||
return 'open';
|
||||
}
|
||||
|
||||
/** Resolve only the exact library binary incorporated in the current public version. */
|
||||
public function download(string $id, string $version, int $resource): Response|BinaryFileResponse
|
||||
{
|
||||
$record = $this->published($id);
|
||||
abort_unless($record['version_id'] === $version, 404);
|
||||
$snapshot = null;
|
||||
foreach ($record['payload']['document_snapshots'] ?? [] as $candidate) {
|
||||
if ($candidate['resource_id'] === $resource) {
|
||||
$snapshot = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
abort_unless($snapshot !== null, 404);
|
||||
$document = app(Procurement::class)->publicDocuments()->where('r.id', $resource)
|
||||
->where('d.id', $snapshot['document_id'])->where('d.version_no', $snapshot['version'])
|
||||
->where('d.sha256', $snapshot['sha256'])->first(['d.*']);
|
||||
abort_unless($document !== null, 404);
|
||||
|
||||
return app(VerifiedDocumentBinary::class)->respond($document);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, ?string $id, array $input): string
|
||||
{
|
||||
$this->guard($actor);
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:0', 'code' => 'required|string|regex:/^[a-z0-9][a-z0-9-]{0,79}$/D',
|
||||
'reason' => 'required|string|min:20|max:2000', 'draft' => 'required|array'])->validate();
|
||||
$draft = $this->normalize($actor, $data['draft'], false);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $draft): string {
|
||||
DB::select('select pg_advisory_xact_lock(261102, hashtext(?))', [$data['code']]);
|
||||
$row = $id ? DB::table('funding_programmes')->where('id', $id)->lockForUpdate()->firstOrFail() : null;
|
||||
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'A ficha foi alterada. Recupere a versão actual antes de guardar.');
|
||||
abort_if($row && $row->code !== $data['code'], 422, 'O identificador da ficha é estável.');
|
||||
if (! $row && DB::table('funding_programmes')->where('code', $data['code'])->exists()) {
|
||||
throw ValidationException::withMessages(['code' => 'Este identificador já pertence a uma ficha. Abra-a para actualizar ou acrescentar uma janela.']);
|
||||
}
|
||||
if ($draft['kind'] === 'institution') {
|
||||
DB::select('select pg_advisory_xact_lock(261102, hashtext(?))', ['institution:'.$draft['institution_key']]);
|
||||
$duplicate = DB::table('funding_programmes')->whereRaw("draft->>'kind' = 'institution'")->whereRaw("draft->>'institution_key' = ?", [$draft['institution_key']])->when($id, fn ($q) => $q->where('id', '<>', $id))->exists();
|
||||
if ($duplicate) {
|
||||
throw ValidationException::withMessages(['institution_key' => 'A instituição já tem ficha. Reutilize a identidade existente; não substitua as suas edições.']);
|
||||
}
|
||||
}
|
||||
$id ??= (string) Str::uuid();
|
||||
DB::table('funding_programmes')->updateOrInsert(['id' => $id], ['code' => $data['code'], 'version' => (int) $data['version'] + 1,
|
||||
'draft' => json_encode($draft, JSON_THROW_ON_ERROR), 'created_by' => $row->created_by ?? $actor->id,
|
||||
'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
|
||||
$this->audit($actor, $id, 'draft_saved', ['version' => (int) $data['version'] + 1, 'reason' => $data['reason']]);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
private function normalize(User $actor, array $input, bool $publishing): array
|
||||
{
|
||||
$required = $publishing ? 'required' : 'nullable';
|
||||
$rules = [
|
||||
'title' => "$required|string|max:250", 'kind' => ['required', Rule::in(array_keys(self::KINDS))], 'summary' => "$required|string|max:4000",
|
||||
'manager_name' => 'nullable|string|max:250', 'manager_organization_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
|
||||
'source_url' => 'nullable|url:http,https|max:2000', 'source_document_name' => 'nullable|string|max:250', 'source_document_sha256' => 'nullable|string|regex:/^[a-f0-9]{64}$/D', 'source_reference' => "$required|string|max:1500", 'source_checked_on' => "$required|date_format:Y-m-d|before_or_equal:today",
|
||||
'source_published_on' => 'nullable|date_format:Y-m-d', 'source_status' => 'required|in:identified,unknown,example',
|
||||
'coverage' => 'required|in:national,territorial,unknown', 'coverage_text' => 'nullable|string|max:2000',
|
||||
'territory_ids' => 'array|max:30', 'territory_ids.*' => 'required|uuid|distinct',
|
||||
'sectors_scope' => 'required|in:all,selected,unknown', 'sectors_text' => 'nullable|string|max:2000', 'sector_ids' => 'array|max:40',
|
||||
'sector_ids.*' => ['required', 'integer', 'distinct', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())],
|
||||
'resource_ids' => 'array|max:30', 'resource_ids.*' => 'required|integer|distinct|exists:portal_resources,id',
|
||||
'funding_needs' => 'array|max:6', 'funding_needs.*' => ['required', 'distinct', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))],
|
||||
'criteria' => 'array|max:30', 'windows' => 'array|max:20',
|
||||
'windows.*' => 'required|array:code,title,mode,start_on,end_on,coverage,coverage_text,territory_ids,source_url,source_reference,checked_on,application_url,criteria',
|
||||
'windows.*.code' => 'required|string|regex:/^[a-z0-9][a-z0-9-]{0,79}$/D|distinct', 'windows.*.title' => "$required|string|max:250",
|
||||
'windows.*.mode' => ['required', Rule::in(array_keys(self::WINDOWS))], 'windows.*.start_on' => 'nullable|date_format:Y-m-d', 'windows.*.end_on' => 'nullable|date_format:Y-m-d',
|
||||
'windows.*.coverage' => 'required|in:programme,national,territorial,unknown', 'windows.*.coverage_text' => 'nullable|string|max:2000',
|
||||
'windows.*.territory_ids' => 'array|max:30', 'windows.*.territory_ids.*' => 'required|uuid|distinct',
|
||||
'windows.*.source_url' => "$required|url:http,https|max:2000", 'windows.*.source_reference' => "$required|string|max:1500",
|
||||
'windows.*.checked_on' => "$required|date_format:Y-m-d|before_or_equal:today", 'windows.*.application_url' => 'nullable|url:http,https|max:2000', 'windows.*.criteria' => 'array|max:30',
|
||||
];
|
||||
foreach (['criteria', 'windows.*.criteria'] as $prefix) {
|
||||
$rules[$prefix.'.*'] = 'required|array:code,question,applies_to,expected,source_reference,explanation';
|
||||
$rules[$prefix.'.*.code'] = 'required|string|regex:/^[a-z0-9][a-z0-9-]{0,79}$/D';
|
||||
$rules[$prefix.'.*.question'] = "$required|string|max:500";
|
||||
$rules[$prefix.'.*.applies_to'] = 'required|in:all,individual,entity';
|
||||
$rules[$prefix.'.*.expected'] = 'required|in:yes,no';
|
||||
$rules[$prefix.'.*.source_reference'] = "$required|string|max:1500";
|
||||
$rules[$prefix.'.*.explanation'] = "$required|string|max:2000";
|
||||
}
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
if ($publishing && empty($data['source_url'])) {
|
||||
Validator::make($data, ['source_document_name' => 'required|string', 'source_document_sha256' => 'required|string|size:64'])->validate();
|
||||
}
|
||||
if ($data['kind'] === 'institution') {
|
||||
$data = [...$data, ...app(FundingInstitutionDetails::class)->normalize($input, $publishing)];
|
||||
}
|
||||
$data = [...$data, 'territory_ids' => $data['territory_ids'] ?? [], 'sector_ids' => $data['sector_ids'] ?? [], 'resource_ids' => $data['resource_ids'] ?? [],
|
||||
'criteria' => $data['criteria'] ?? [], 'windows' => $data['windows'] ?? []];
|
||||
if ($data['coverage'] !== 'territorial' && $data['territory_ids'] !== []) {
|
||||
throw ValidationException::withMessages(['territory_ids' => 'Seleccione cobertura territorial para associar locais específicos.']);
|
||||
}
|
||||
if ($data['sectors_scope'] !== 'selected' && $data['sector_ids'] !== []) {
|
||||
throw ValidationException::withMessages(['sector_ids' => 'Seleccione o âmbito por sectores para associar sectores específicos.']);
|
||||
}
|
||||
if ($publishing && $data['coverage'] === 'territorial' && $data['territory_ids'] === []) {
|
||||
throw ValidationException::withMessages(['territory_ids' => 'Seleccione os locais documentados ou assinale a cobertura como por determinar.']);
|
||||
}
|
||||
if ($data['manager_organization_id'] ?? null) {
|
||||
$data['manager_name'] = DB::table('organizations')->where('id', $data['manager_organization_id'])->value('name');
|
||||
}
|
||||
if ($publishing && empty($data['manager_name'])) {
|
||||
throw ValidationException::withMessages(['manager_name' => 'Seleccione a entidade do cadastro ou identifique o gestor indicado pela fonte.']);
|
||||
}
|
||||
if ($publishing && $data['source_status'] !== 'identified') {
|
||||
throw ValidationException::withMessages(['source_status' => 'Identifique a fonte efectiva. Conteúdo de exemplo ou origem por identificar não confirma um programa real.']);
|
||||
}
|
||||
if ($publishing && $data['sectors_scope'] === 'selected' && $data['sector_ids'] === []) {
|
||||
throw ValidationException::withMessages(['sector_ids' => 'Seleccione os sectores documentados ou assinale o âmbito como por determinar.']);
|
||||
}
|
||||
$territories = $data['territory_ids'];
|
||||
$codes = [];
|
||||
foreach (array_merge([$data['criteria']], array_column($data['windows'], 'criteria')) as $criteria) {
|
||||
foreach ($criteria as $criterion) {
|
||||
if (in_array($criterion['code'], $codes, true)) {
|
||||
throw ValidationException::withMessages(['criteria' => 'Cada critério deve ter um identificador único na ficha, sem repetir perguntas comuns por janela.']);
|
||||
}
|
||||
$codes[] = $criterion['code'];
|
||||
}
|
||||
}
|
||||
foreach ($data['windows'] as $index => &$window) {
|
||||
$window['criteria'] ??= [];
|
||||
$window['territory_ids'] ??= [];
|
||||
if ($window['coverage'] !== 'territorial' && $window['territory_ids'] !== []) {
|
||||
throw ValidationException::withMessages(['windows.'.$index.'.territory_ids' => 'Associe locais apenas numa janela de cobertura territorial.']);
|
||||
}
|
||||
if ($publishing && $window['coverage'] === 'territorial' && $window['territory_ids'] === []) {
|
||||
throw ValidationException::withMessages(['windows.'.$index.'.territory_ids' => 'Seleccione os locais documentados ou assinale a cobertura como por determinar.']);
|
||||
}
|
||||
$territories = array_merge($territories, $window['territory_ids']);
|
||||
if ($publishing && $window['mode'] === 'dated' && empty($window['end_on'])) {
|
||||
throw ValidationException::withMessages(['windows.'.$index.'.end_on' => 'Uma janela com datas documentadas precisa da data-limite.']);
|
||||
}
|
||||
if (! empty($window['start_on']) && ! empty($window['end_on']) && $window['start_on'] > $window['end_on']) {
|
||||
throw ValidationException::withMessages(['windows.'.$index.'.end_on' => 'A data-limite não pode anteceder a abertura.']);
|
||||
}
|
||||
if (in_array($window['mode'], ['rolling', 'unknown'], true) && (! empty($window['start_on']) || ! empty($window['end_on']))) {
|
||||
throw ValidationException::withMessages(['windows.'.$index.'.mode' => 'Conserve datas documentadas ou escolha uma janela sem datas; não misture as duas indicações.']);
|
||||
}
|
||||
}
|
||||
unset($window);
|
||||
foreach (array_unique($territories) as $territory) {
|
||||
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $territory)->exists()) {
|
||||
throw ValidationException::withMessages(['territory_ids' => 'Seleccione referências do cadastro territorial público.']);
|
||||
}
|
||||
}
|
||||
if ($publishing) {
|
||||
$data['territory_paths'] = array_map(fn ($id) => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($id)), $data['territory_ids']);
|
||||
$data['territory_ancestor_ids'] = array_values(array_unique(array_merge([], ...array_map(fn ($path) => array_column($path, 'id'), $data['territory_paths']))));
|
||||
$data['sector_snapshots'] = Sector::choices()->whereIn('id', $data['sector_ids'])->get(['id', 'name'])->toArray();
|
||||
foreach ($data['windows'] as &$window) {
|
||||
$window['territory_paths'] = array_map(fn ($id) => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($id)), $window['territory_ids']);
|
||||
}
|
||||
unset($window);
|
||||
}
|
||||
foreach ($data['resource_ids'] as $resource) {
|
||||
$public = app(Procurement::class)->publicDocuments()->where('r.id', $resource)->first(['r.title', 'd.id', 'd.version_no', 'd.sha256']);
|
||||
$document = DB::table('portal_resources')->where('id', $resource)->value('document_id');
|
||||
if (! $public && ($publishing || ! app(DocumentManagementAccess::class)->documents($actor)->where('id', $document)->exists())) {
|
||||
throw ValidationException::withMessages(['resource_ids' => 'Um documento publicado exige acesso público, direitos e análise de segurança válidos na biblioteca.']);
|
||||
}
|
||||
if ($publishing) {
|
||||
$data['document_snapshots'][] = ['resource_id' => $resource, 'document_id' => $public->id, 'version' => (int) $public->version_no,
|
||||
'sha256' => trim($public->sha256), 'title' => $public->title];
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor, string $id): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
$row = DB::table('funding_programmes')->where('id', $id)->firstOrFail();
|
||||
$payload = $this->normalize($actor, json_decode($row->draft, true, 512, JSON_THROW_ON_ERROR), true);
|
||||
unset($payload['manager_organization_id']);
|
||||
$plan = ['id' => $id, 'code' => $row->code, 'version' => (int) $row->version, 'payload' => $payload];
|
||||
$plan['hash'] = hash_hmac('sha256', json_encode(Arr::sortRecursive($plan), JSON_THROW_ON_ERROR), config('app.key'));
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function publish(User $actor, string $id, array $input): string
|
||||
{
|
||||
$this->guard($actor);
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'hash' => 'required|string|size:64',
|
||||
'reason' => 'required|string|min:20|max:2000', 'confirm' => 'accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data): string {
|
||||
$row = DB::table('funding_programmes')->where('id', $id)->lockForUpdate()->firstOrFail();
|
||||
$plan = $this->preview($actor, $id);
|
||||
abort_unless((int) $row->version === (int) $data['version'] && hash_equals($plan['hash'], $data['hash']), 409, 'A prévia mudou. Confira novamente antes de publicar.');
|
||||
if ($row->published_version_id) {
|
||||
$previous = DB::table('funding_programme_versions')->where('id', $row->published_version_id)->firstOrFail();
|
||||
if (json_decode($previous->payload, false, 512, JSON_THROW_ON_ERROR) == json_decode(json_encode($plan['payload'], JSON_THROW_ON_ERROR), false, 512, JSON_THROW_ON_ERROR)) {
|
||||
return $previous->id;
|
||||
}
|
||||
}
|
||||
$version = (string) Str::uuid();
|
||||
$publicationNumber = max((int) $row->version, (int) DB::table('funding_programme_versions')->where('programme_id', $id)->max('version') + 1);
|
||||
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => $publicationNumber,
|
||||
'payload' => json_encode($plan['payload'], JSON_THROW_ON_ERROR), 'reason' => $data['reason'], 'actor_id' => $actor->id, 'published_at' => now()]);
|
||||
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version, 'updated_at' => now()]);
|
||||
$this->audit($actor, $id, 'published', ['version_id' => $version, 'version' => $publicationNumber, 'draft_version' => (int) $row->version, 'reason' => $data['reason'], 'effect' => 'new_public_version_only']);
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
public function withdraw(User $actor, string $id, int $version, string $reason): void
|
||||
{
|
||||
$this->guard($actor);
|
||||
Validator::make(['reason' => $reason], ['reason' => 'required|string|min:20|max:2000'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $version, $reason): void {
|
||||
$row = DB::table('funding_programmes')->where('id', $id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless((int) $row->version === $version, 409);
|
||||
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => null, 'version' => $version + 1, 'updated_at' => now()]);
|
||||
$this->audit($actor, $id, 'withdrawn', ['previous_version_id' => $row->published_version_id, 'reason' => $reason]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function assess(string $id, array $input): array
|
||||
{
|
||||
$record = $this->published($id);
|
||||
$data = Validator::make($input, ['version_id' => 'required|uuid', 'applicant_kind' => 'required|in:individual,entity,unknown',
|
||||
'window_code' => 'nullable|string|max:80', 'answers' => 'present|array|max:60', 'answers.*' => 'required|in:yes,no,unknown'])->validate();
|
||||
abort_unless($data['version_id'] === $record['version_id'], 409, 'A versão pública mudou. Recupere os critérios actuais antes de conferir.');
|
||||
$window = null;
|
||||
foreach ($record['payload']['windows'] as $candidate) {
|
||||
if ($candidate['code'] === ($data['window_code'] ?? null)) {
|
||||
$window = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
abort_if(! empty($data['window_code']) && ! $window, 422);
|
||||
$criteria = array_merge($record['payload']['criteria'], $window['criteria'] ?? []);
|
||||
abort_if(array_diff(array_keys($data['answers']), array_column($criteria, 'code')) !== [], 422, 'A resposta deve pertencer aos critérios desta versão e janela.');
|
||||
$results = [];
|
||||
foreach ($criteria as $criterion) {
|
||||
$status = 'unknown';
|
||||
if ($criterion['applies_to'] !== 'all' && $data['applicant_kind'] !== 'unknown' && $criterion['applies_to'] !== $data['applicant_kind']) {
|
||||
$status = 'not_applicable';
|
||||
} elseif (($criterion['applies_to'] === 'all' || $criterion['applies_to'] === $data['applicant_kind']) && ($data['answers'][$criterion['code']] ?? 'unknown') !== 'unknown') {
|
||||
$status = $data['answers'][$criterion['code']] === $criterion['expected'] ? 'matches' : 'does_not_match';
|
||||
}
|
||||
$results[] = [...$criterion, 'status' => $status];
|
||||
}
|
||||
|
||||
return ['version_id' => $record['version_id'], 'window_code' => $window['code'] ?? null, 'window_state' => $window ? $this->windowState($window) : 'unknown',
|
||||
'criteria' => $results, 'counts' => array_count_values(array_column($results, 'status')),
|
||||
'notice' => 'Correspondência preliminar das respostas declaradas com os critérios citados. Não é aprovação, candidatura enviada, concessão de financiamento ou benefício fiscal.'];
|
||||
}
|
||||
|
||||
public function saveInterest(User $actor, string $id, string $version, bool $consent): void
|
||||
{
|
||||
abort_unless($consent, 422, 'Confirme que pretende guardar este programa na sua área privada.');
|
||||
DB::transaction(function () use ($actor, $id, $version): void {
|
||||
// Serialize this person's bookmarks without blocking audit FK KEY SHARE locks.
|
||||
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
|
||||
DB::table('funding_programmes')->where('id', $id)->lockForUpdate()->firstOrFail();
|
||||
$record = $this->published($id);
|
||||
abort_unless($record['version_id'] === $version, 409, 'A versão pública mudou. Recupere a ficha antes de guardar.');
|
||||
$saved = DB::table('funding_programme_interests')->where('user_id', $actor->id)->where('programme_id', $id)->first();
|
||||
if ($saved && $saved->removed_at === null) {
|
||||
return;
|
||||
}
|
||||
DB::table('funding_programme_interests')->updateOrInsert(['user_id' => $actor->id, 'programme_id' => $id], [
|
||||
'version_id' => $version, 'saved_at' => now(), 'removed_at' => null,
|
||||
]);
|
||||
$this->audit($actor, $id, 'interest_saved', ['version_id' => $version, 'scope' => 'private_bookmark_not_application']);
|
||||
});
|
||||
}
|
||||
|
||||
public function removeInterest(User $actor, string $id): void
|
||||
{
|
||||
DB::transaction(function () use ($actor, $id): void {
|
||||
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
|
||||
if (DB::table('funding_programme_interests')->where('user_id', $actor->id)->where('programme_id', $id)->whereNull('removed_at')->update(['removed_at' => now()])) {
|
||||
$this->audit($actor, $id, 'interest_removed', ['scope' => 'private_bookmark']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function audit(User $actor, string $id, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'funding-catalogue', 'entity_type' => 'funding_programmes', 'entity_id' => $id,
|
||||
'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'after_data' => json_encode($data, JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
@@ -135,19 +135,7 @@ class InvestmentCatalogue
|
||||
}
|
||||
}
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.$filters['q'].'%';
|
||||
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('description', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
|
||||
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term))
|
||||
->orWhereExists(fn ($g) => $g->selectRaw('1')->from('geo_locations as search_location')->whereNull('search_location.deleted_at')->where('search_location.data_classification', 'public')
|
||||
->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
|
||||
->where(fn ($direct) => $direct->whereColumn('search_location.id', 'opportunities.primary_territory_id')
|
||||
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations as search_link')->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereColumn('search_link.geo_location_id', 'search_location.id'))))
|
||||
->orWhereExists(fn ($d) => $d->selectRaw('1')->from('investment_dossiers as searchable_dossier')
|
||||
->whereNull('searchable_dossier.deleted_at')->where('searchable_dossier.publication_status', 'published')
|
||||
->where(fn ($text) => $text->where('searchable_dossier.title', 'ilike', $term)->orWhereRaw('searchable_dossier.content::text ILIKE ?', [$term]))
|
||||
->where(fn ($relation) => $relation
|
||||
->whereExists(fn ($p) => $p->selectRaw('1')->from('opportunity_projects as search_project')->whereColumn('search_project.opportunity_id', 'opportunities.id')->whereColumn('search_project.project_id', 'searchable_dossier.project_id'))
|
||||
->orWhereExists(fn ($c) => $c->selectRaw('1')->from('opportunity_clusters as search_cluster')->whereColumn('search_cluster.opportunity_id', 'opportunities.id')->whereColumn('search_cluster.cluster_id', 'searchable_dossier.cluster_id')))));
|
||||
app(OpportunityTextSearch::class)->constrain($query, $filters['q']);
|
||||
}
|
||||
if (! empty($filters['sector'])) {
|
||||
SectorOrganization::constrain($query, $filters['sector']);
|
||||
@@ -272,26 +260,41 @@ class InvestmentCatalogue
|
||||
|
||||
/** Public result presentation only; no editorial or territorial data is saved. */
|
||||
public function presentLocation(Opportunity $record): Opportunity
|
||||
{
|
||||
$record->setAttribute('territorial_summary', $this->locationPresentation($record)['summary']);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @return array{summary: string, provinces: list<string>} */
|
||||
public function locationPresentation(Opportunity $record): array
|
||||
{
|
||||
$geo = app(InvestmentGeography::class);
|
||||
$paths = [];
|
||||
$provinceNames = [];
|
||||
$ids = array_filter([$record->primary_territory_id, ...$record->additionalTerritories()->pluck('geo_locations.id')->all()]);
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$path = $geo->path($id);
|
||||
if ($path) {
|
||||
$paths[] = implode(' / ', array_column($path, 'name'));
|
||||
foreach ($path as $node) {
|
||||
if ($node->location_type === 'province') {
|
||||
$provinceNames[] = (string) $node->name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($paths) {
|
||||
$label = implode('; ', array_unique($paths));
|
||||
} elseif ($provinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record)) {
|
||||
$label = implode(' / ', array_column($provinces, 'name')).' — contexto provincial do corredor; distrito e posto administrativo não indicados';
|
||||
$provinceNames = array_map(fn ($province) => (string) $province->name, $provinces);
|
||||
$label = implode(' / ', $provinceNames).' — contexto provincial do corredor; distrito e posto administrativo não indicados';
|
||||
} else {
|
||||
$label = implode(' / ', array_filter([$record->province, $record->district])) ?: 'Localização não indicada';
|
||||
$provinceNames = $record->province ? [(string) $record->province] : [];
|
||||
}
|
||||
$record->setAttribute('territorial_summary', $label);
|
||||
|
||||
return $record;
|
||||
return ['summary' => $label, 'provinces' => array_values(array_unique($provinceNames))];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $territoryFilters
|
||||
@@ -519,11 +522,11 @@ class InvestmentCatalogue
|
||||
->whereIn('t.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign))
|
||||
->get(['l.opportunity_id', 't.name'])->groupBy('opportunity_id');
|
||||
}
|
||||
$features = $missing = [];
|
||||
$features = $missing = $thematic = [];
|
||||
$areas = (clone $spatial)->whereIn('shape.geometry_type', ['polygon', 'multipolygon'])->orderBy('shape.id')
|
||||
->get(['o.id', 'o.title', 'o.slug', 'g.name', 'shape.source_system', 'shape.properties', DB::raw('ST_AsGeoJSON(shape.geom) as geometry'),
|
||||
DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'território declarado da oportunidade' ELSE 'contexto do projeto associado; implantação da oportunidade por confirmar' END AS basis")])
|
||||
->map(fn ($area) => ['geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')',
|
||||
->map(fn ($area) => ['opportunity_id' => (int) $area->id, 'geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')',
|
||||
'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null,
|
||||
'url' => '/oportunidades/'.$area->slug.($filters === [] ? '' : '?'.http_build_query($filters))])->all();
|
||||
$located = 0;
|
||||
@@ -533,6 +536,15 @@ class InvestmentCatalogue
|
||||
foreach ($relations as $relation => $groups) {
|
||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||
}
|
||||
$public = app(ProactiveInvestment::class)->publicData($record);
|
||||
$evidence = array_values(array_filter(StructuredData::collectionItems($public['evidence'] ?? []),
|
||||
fn ($proof) => in_array($proof['category'] ?? null, ['resource', 'infrastructure', 'workforce', 'activity', 'supply', 'demand'], true) && ($proof['purpose'] ?? null) === 'local'));
|
||||
if ($evidence !== []) {
|
||||
$thematic[] = ['id' => $record->id, 'title' => $record->title, 'url' => $properties['url'], 'location' => $properties['location'],
|
||||
'state' => $public['state'] ?? 'hypothesis', 'limitations' => $public['limitations'] ?? null,
|
||||
'evidence' => array_map(fn ($proof) => [...array_intersect_key($proof, array_flip(['id', 'statement', 'source', 'locator', 'period', 'scope', 'coverage', 'verified_on'])),
|
||||
'source_category' => $proof['category'], 'category' => in_array($proof['category'], ['activity', 'supply', 'demand'], true) ? 'economic_potential' : $proof['category']], $evidence)];
|
||||
}
|
||||
$sites = collect($points->get($record->id) ?? []);
|
||||
if ($sites->isNotEmpty()) {
|
||||
$located++;
|
||||
@@ -549,6 +561,6 @@ class InvestmentCatalogue
|
||||
|
||||
return ['type' => 'FeatureCollection', 'limit' => 1000, 'matched_count' => $total, 'truncated' => $total > $records->count(),
|
||||
'georeferenced_count' => $located, 'marker_count' => count($features), 'unlocated' => $missing, 'features' => $features,
|
||||
'areas' => $areas, 'complete' => $total === $located];
|
||||
'thematic_records' => $thematic, 'areas' => $areas, 'complete' => $total === $located];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,10 +53,10 @@ final class InvestmentConsumerScope
|
||||
public function context(array $context, ?string $key): array
|
||||
{
|
||||
$choices = $context['opportunity_choices'] ?? [];
|
||||
$key = $this->key($context, $key);
|
||||
if (! $choices) {
|
||||
return $context;
|
||||
}
|
||||
$key = $key ?: (count($choices) === 1 ? $choices[0]['opportunity']['key'] : null);
|
||||
$choice = $key ? collect(StructuredData::collectionItems($choices))->firstWhere('opportunity.key', $key) : null;
|
||||
abort_if($key && ! $choice, 422, 'Escolha uma oportunidade deste dossier.');
|
||||
$specific = ['project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'special_zone_id', 'investment_regime'];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -12,6 +13,52 @@ final class InvestmentGeography
|
||||
{
|
||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||
|
||||
/** Public declared coverage; a territory join never multiplies the opportunity total.
|
||||
*
|
||||
* @return array{opportunities: int, provinces: int}
|
||||
*/
|
||||
public function opportunityStatistics(): array
|
||||
{
|
||||
$opportunities = Opportunity::published()->select(['id', 'primary_territory_id', 'province', 'geography_scope'])->toBase();
|
||||
$references = $this->publicReferences()->select(['id', 'parent_id', 'name', 'location_type']);
|
||||
$result = DB::selectOne('WITH RECURSIVE
|
||||
published_opportunities AS ('.$opportunities->toSql().'),
|
||||
public_references AS ('.$references->toSql().'),
|
||||
declared_locations AS (
|
||||
SELECT id AS opportunity_id, primary_territory_id AS location_id
|
||||
FROM published_opportunities WHERE primary_territory_id IS NOT NULL
|
||||
UNION
|
||||
SELECT l.opportunity_id, l.geo_location_id FROM opportunity_locations l
|
||||
JOIN published_opportunities o ON o.id=l.opportunity_id
|
||||
),
|
||||
territory_paths AS (
|
||||
SELECT d.opportunity_id, d.location_id, g.id, g.parent_id, g.name, g.location_type,
|
||||
ARRAY[g.id] AS visited, 1 AS depth
|
||||
FROM declared_locations d JOIN public_references g ON g.id=d.location_id
|
||||
UNION ALL
|
||||
SELECT t.opportunity_id, t.location_id, g.id, g.parent_id, g.name, g.location_type,
|
||||
t.visited||g.id, t.depth+1
|
||||
FROM territory_paths t JOIN public_references g ON g.id=t.parent_id
|
||||
WHERE t.depth<5 AND NOT g.id=ANY(t.visited)
|
||||
),
|
||||
covered_provinces AS (
|
||||
SELECT t.name FROM territory_paths t WHERE t.location_type=\'province\'
|
||||
AND EXISTS (SELECT 1 FROM territory_paths root
|
||||
WHERE root.opportunity_id=t.opportunity_id AND root.location_id=t.location_id AND root.parent_id IS NULL)
|
||||
UNION
|
||||
SELECT g.name FROM public_references g JOIN published_opportunities o
|
||||
ON lower(btrim(o.province))=lower(btrim(g.name))
|
||||
WHERE g.location_type=\'province\' AND o.primary_territory_id IS NULL
|
||||
AND COALESCE(o.geography_scope, \'unspecified\')<>\'national\'
|
||||
AND NOT EXISTS (SELECT 1 FROM opportunity_locations l WHERE l.opportunity_id=o.id)
|
||||
)
|
||||
SELECT (SELECT count(DISTINCT id) FROM published_opportunities) AS opportunities,
|
||||
(SELECT count(DISTINCT lower(btrim(name))) FROM covered_provinces) AS provinces',
|
||||
[...$opportunities->getBindings(), ...$references->getBindings()]);
|
||||
|
||||
return ['opportunities' => (int) $result->opportunities, 'provinces' => (int) $result->provinces];
|
||||
}
|
||||
|
||||
/** Resolve an old province-name search only when the public register has exactly one match.
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @return array<array-key, mixed>
|
||||
@@ -91,6 +138,10 @@ final class InvestmentGeography
|
||||
$query->where(function ($workbook) {
|
||||
$workbook->where('source_system', 'cartografia-workbook')
|
||||
->where('external_id', 'like', '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:%');
|
||||
})->orWhere(function ($demography) {
|
||||
// Owner, 13/11/2026: only these source-backed additions are authorised.
|
||||
$demography->where('source_system', 'ine-demography')->where('location_type', 'district')
|
||||
->whereIn('external_id', DemographicInstallation::publicDistrictRefs());
|
||||
})->orWhereIn('id', app(TerritorialRegistry::class)->published()->select('g.id'));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Source-versioned references, stored in the existing dossier, not a financing workflow. */
|
||||
final class InvestmentGuides
|
||||
{
|
||||
public const EVENT = 'investment_guide_saved';
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function guide(string $slug): array
|
||||
{
|
||||
$guide = config('investment-guides.'.$slug);
|
||||
abort_unless(is_array($guide), 404);
|
||||
|
||||
return [...$guide, 'sha256' => hash('sha256', json_encode($guide, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** Only coded choices pass through public/authentication URLs.
|
||||
* @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function selection(array $input): array
|
||||
{
|
||||
$v = Validator::make($input, ['slug' => ['required', 'string', Rule::in(array_keys(config('investment-guides')))], 'sha256' => 'required|string|size:64'])->validate();
|
||||
$guide = $this->guide($v['slug']);
|
||||
abort_unless(hash_equals($guide['sha256'], $v['sha256']), 409, 'O guia mudou desde a consulta. Abra a edição actual antes de preparar uma nova referência.');
|
||||
|
||||
return ['slug' => $v['slug'], 'sha256' => $v['sha256'], 'instruments' => $this->choices($input, $guide)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param array<string,mixed> $guide
|
||||
* @return list<string> */
|
||||
private function choices(array $input, array $guide): array
|
||||
{
|
||||
$v = Validator::make($input, ['instruments' => ['sometimes', 'array', 'list', 'max:20'], 'instruments.*' => ['string', Rule::in(array_keys($guide['instruments']))]])->validate();
|
||||
$values = array_values(array_unique($v['instruments'] ?? []));
|
||||
sort($values);
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function publicView(string $slug, array $input): array
|
||||
{
|
||||
$guide = $this->guide($slug);
|
||||
|
||||
return ['guide' => $guide, 'instruments' => $this->choices($input, $guide), 'note' => '', 'case' => null, 'saved' => null,
|
||||
'canWrite' => false, 'historical' => false, 'olderEdition' => false, 'currentAvailable' => true, 'workingCopy' => false, 'history' => [], 'historyNext' => null, 'contextChanged' => false, 'unavailableInstruments' => []];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function view(User $actor, string $id, string $slug, array $input): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
$current = is_array(config('investment-guides.'.$slug)) ? $this->guide($slug) : null;
|
||||
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1', 'current' => 'nullable|boolean', 'selection' => 'nullable|boolean'])->validate();
|
||||
$saved = $this->desk->decode($case->payload)['investment_guides'][$slug] ?? null;
|
||||
if (! empty($v['revision'])) {
|
||||
abort_if(isset($input['instruments']) || ! empty($v['current']) || ! empty($v['selection']), 422, 'A revisão histórica conserva a referência original.');
|
||||
$row = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
|
||||
abort_unless($row !== null, 404);
|
||||
$saved = $this->desk->decode($row->payload)['snapshot'];
|
||||
abort_unless($saved['guide']['slug'] === $slug, 404);
|
||||
}
|
||||
$working = array_key_exists('instruments', $input) || ! empty($v['current']) || ! empty($v['selection']);
|
||||
abort_unless($current !== null || $saved !== null, 404);
|
||||
abort_if($working && $current === null, 409, 'O guia foi retirado da consulta actual; as referências guardadas continuam disponíveis.');
|
||||
if ($working && isset($input['sha256'])) {
|
||||
$this->selection([...$input, 'slug' => $slug]);
|
||||
}
|
||||
$guide = $working || ! $saved ? $current : $saved['guide'];
|
||||
$selected = array_key_exists('instruments', $input) || ! empty($v['selection']) ? $this->choices($input, $guide)
|
||||
: ($working ? array_values(array_intersect($saved['instruments'] ?? [], array_keys($guide['instruments']))) : ($saved['instruments'] ?? []));
|
||||
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
|
||||
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
|
||||
->orderByDesc('event_order')->cursor();
|
||||
$history = [];
|
||||
foreach ($events as $event) {
|
||||
$snapshot = $this->desk->decode($event->payload)['snapshot'];
|
||||
if ($snapshot['guide']['slug'] !== $slug) {
|
||||
continue;
|
||||
}
|
||||
$history[] = ['id' => $event->id, 'revision' => $snapshot['revision'], 'at' => $snapshot['at'], 'edition' => $snapshot['guide']['version'], 'order' => $event->event_order];
|
||||
if (count($history) === 26) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$unavailable = [];
|
||||
if ($working && $saved) {
|
||||
foreach ($saved['instruments'] as $code) {
|
||||
if (! isset($guide['instruments'][$code])) {
|
||||
$unavailable[] = $saved['guide']['instruments'][$code]['title'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['guide' => $guide, 'instruments' => $selected, 'note' => $saved['note'] ?? '', 'saved' => $saved,
|
||||
'case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
|
||||
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'historical' => ! empty($v['revision']),
|
||||
'olderEdition' => $current === null || $guide['sha256'] !== $current['sha256'], 'currentAvailable' => $current !== null, 'workingCopy' => $working,
|
||||
'contextChanged' => $saved && ($saved['context']['revision'] !== $context['revision'] || $saved['context']['dependency_hash'] !== ($context['dependency_hash'] ?? null)),
|
||||
'unavailableInstruments' => $unavailable,
|
||||
'history' => array_slice($history, 0, 25), 'historyNext' => count($history) > 25 ? $history[24]['order'] : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @param array<string,mixed> $guide
|
||||
* @return array<string,mixed> */
|
||||
private function reference(array $input, array $guide): array
|
||||
{
|
||||
$v = Validator::make($input, ['sha256' => ['required', Rule::in([$guide['sha256']])], 'note' => 'nullable|string|max:3000'])->validate();
|
||||
|
||||
return ['sha256' => $v['sha256'], 'note' => $v['note'] ?? '', 'instruments' => $this->choices($input, $guide)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, string $id, string $slug, array $input): array
|
||||
{
|
||||
$this->desk->case($actor, $id, true);
|
||||
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $slug, $input, $v) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->orderByDesc('event_order')->cursor() as $event) {
|
||||
$data = $this->desk->decode($event->payload);
|
||||
if ($data['operation_key'] === $v['operation_key']) {
|
||||
abort_unless($data['snapshot']['guide']['slug'] === $slug, 409);
|
||||
$reference = $this->reference($input, $data['snapshot']['guide']);
|
||||
$hash = hash('sha256', json_encode([(int) $v['version'], $slug, $reference], JSON_THROW_ON_ERROR));
|
||||
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'Esta operação já guardou uma referência diferente.');
|
||||
|
||||
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
|
||||
}
|
||||
}
|
||||
$guide = $this->guide($slug);
|
||||
abort_unless(($input['sha256'] ?? null) === $guide['sha256'], 409, 'O guia mudou. Conserve a nota e abra a edição actual para uma nova referência.');
|
||||
$reference = $this->reference($input, $guide);
|
||||
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Os dados continuam nesta página; confira a edição guardada antes de tentar novamente.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$previous = $payload['investment_guides'][$slug] ?? null;
|
||||
$state = app(InvestorContext::class)->state($case);
|
||||
$context = ['revision' => $state['revision'], 'dependency_hash' => $state['dependency_hash'] ?? null];
|
||||
if ($previous && $previous['guide'] === $guide && $previous['instruments'] === $reference['instruments'] && $previous['note'] === $reference['note'] && $previous['context'] === $context) {
|
||||
return ['saved' => true, 'unchanged' => true, 'revision' => $previous['revision']];
|
||||
}
|
||||
$snapshot = ['revision' => (int) ($previous['revision'] ?? 0) + 1, 'guide' => $guide, 'instruments' => $reference['instruments'], 'note' => $reference['note'],
|
||||
'context' => $context, 'scope' => 'dossier_reference', 'at' => now()->toIso8601String(), 'actor_id' => $actor->id];
|
||||
$payload['investment_guides'][$slug] = $snapshot;
|
||||
$case->version++;
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
|
||||
$hash = hash('sha256', json_encode([(int) $v['version'], $slug, $reference], JSON_THROW_ON_ERROR));
|
||||
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
|
||||
|
||||
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentZone;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Public park observations remain individual source records, never regional estimates. */
|
||||
final class InvestmentMapIndicators
|
||||
{
|
||||
public const INDICATORS = ['employment', 'investment', 'production', 'exports', 'local_procurement'];
|
||||
|
||||
/** @param Collection<int, InvestmentZone> $zones
|
||||
* @return array<string,mixed> */
|
||||
public function forZones(Collection $zones, bool $zoneLimitReached = false): array
|
||||
{
|
||||
$zoneLimitReached = $zoneLimitReached || $zones->count() > 30;
|
||||
$zones = $zones->take(30)->values();
|
||||
$details = app(InvestmentZoneOperationalDetails::class);
|
||||
$result = ['state' => $details->installed() ? 'available' : 'unavailable', 'records' => [],
|
||||
'zones_consulted' => $zones->count(), 'zone_limit' => 30, 'record_limit' => 200, 'truncated' => $zoneLimitReached];
|
||||
if ($result['state'] === 'unavailable') {
|
||||
return $result;
|
||||
}
|
||||
foreach ($zones as $zone) {
|
||||
// This is the already selected public envelope; never decrypt the private preparation.
|
||||
$public = $details->publicData($zone);
|
||||
$observations = StructuredData::collectionItems($public['integral']['observations'] ?? []);
|
||||
$values = [];
|
||||
if ($observations !== []) {
|
||||
// Extract decimal text from this exact loaded snapshot, not a newer database version or a PHP float.
|
||||
foreach (DB::select("SELECT item->>'id' AS id, item->>'value' AS value FROM jsonb_array_elements((?::jsonb)->'public'->'integral'->'observations') AS item", [$zone->getRawOriginal('operational_details')]) as $number) {
|
||||
$values[$number->id] = $number->value;
|
||||
}
|
||||
}
|
||||
foreach ($observations as $row) {
|
||||
if (! in_array($row['indicator'] ?? null, self::INDICATORS, true)) {
|
||||
continue;
|
||||
}
|
||||
if (count($result['records']) === 200) {
|
||||
$result['truncated'] = true;
|
||||
|
||||
return $result;
|
||||
}
|
||||
$knowledge = $row['knowledge'] ?? 'unknown';
|
||||
$rawValue = $values[$row['id'] ?? ''] ?? null;
|
||||
$value = $knowledge !== 'unknown' && is_numeric($rawValue) ? $rawValue : null;
|
||||
$missing = [];
|
||||
foreach (['unit', 'period_start', 'period_end', 'scope', 'population', 'methodology', 'source_reference', 'source_date'] as $field) {
|
||||
if (trim((string) ($row[$field] ?? '')) === '') {
|
||||
$missing[] = $field;
|
||||
}
|
||||
}
|
||||
$result['records'][] = [
|
||||
...array_intersect_key($row, array_flip(['id', 'label', 'description', 'indicator', 'unit', 'period_start', 'period_end', 'scope', 'population', 'methodology', 'source_reference', 'source_date', 'phase_id', 'plot_id'])),
|
||||
'zone_id' => $zone->id, 'zone_name' => $zone->name, 'zone_version' => (int) $zone->version_no, 'url' => '/zonas/'.$zone->id,
|
||||
'theme' => $row['indicator'] === 'employment' ? 'workforce' : 'economic_potential',
|
||||
'value' => $value, 'knowledge' => $knowledge, 'missing_metadata' => $missing,
|
||||
'measure_kind' => in_array($row['measure_kind'] ?? null, ['observed', 'planned', 'projected'], true) ? $row['measure_kind'] : 'unknown',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class InvestmentOpportunityAlerts
|
||||
{
|
||||
public const FREQUENCIES = ['as_available' => 'Na próxima verificação', 'daily' => 'De 24 em 24 horas', 'weekly' => 'De 7 em 7 dias'];
|
||||
|
||||
public function fundingAvailable(): bool
|
||||
{
|
||||
return Schema::hasTable('investment_funding_alert_seen') && Schema::hasColumn('investment_notifications', 'funding_version_id')
|
||||
&& app(FundingProgrammes::class)->installed();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $criteria
|
||||
* @return array<string,mixed> */
|
||||
private function fundingFilters(array $criteria): array
|
||||
{
|
||||
return array_filter(['sector' => isset($criteria['sector']) ? Sector::choices()->where('slug', $criteria['sector'])->value('id') : null,
|
||||
'territory' => $criteria['province_id'] ?? null, 'certainty' => $criteria['funding_certainty'] ?? 'documented',
|
||||
'state' => $criteria['funding_state'] ?? null], fn ($value) => $value !== null);
|
||||
}
|
||||
|
||||
public function tendersInstalled(): bool
|
||||
{
|
||||
return Schema::hasTable('investment_tender_alert_seen') && Schema::hasColumn('investment_alert_preferences', 'sources')
|
||||
&& Schema::hasColumn('investment_notifications', 'tender_version_id');
|
||||
}
|
||||
|
||||
public function tendersAvailable(): bool
|
||||
{
|
||||
return $this->tendersInstalled() && app(Procurement::class)->available();
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('investment_alert_seen') && Schema::hasTable('investment_alert_preferences') && Schema::hasColumn('investment_notifications', 'opportunity_id');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preferences(int $user): array
|
||||
{
|
||||
$row = DB::table('investment_alert_preferences')->where('user_id', $user)->first();
|
||||
|
||||
$criteria = $row ? json_decode(Crypt::decryptString($row->criteria), true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$sources = isset($row->sources) ? json_decode($row->sources, true, 512, JSON_THROW_ON_ERROR) : ['opportunities'];
|
||||
$statuses = [];
|
||||
foreach ($sources as $source) {
|
||||
$statuses[$source] = $this->criteriaAvailable($criteria, $source) && ($source !== 'tenders' || $this->tendersAvailable())
|
||||
&& ($source !== 'funding' || $this->fundingAvailable());
|
||||
}
|
||||
|
||||
return ['version' => (int) ($row->version ?? 0), 'enabled' => (bool) ($row->enabled ?? false),
|
||||
'frequency' => $row->frequency ?? 'as_available', 'channel' => 'in_app', 'next_run_at' => $row->next_run_at ?? null,
|
||||
'criteria' => $criteria, 'sources' => $sources, 'source_statuses' => $statuses, 'criteria_available' => ! in_array(false, $statuses, true)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $criteria */
|
||||
private function criteriaAvailable(array $criteria, string $source): bool
|
||||
{
|
||||
return (! isset($criteria['sector']) || Sector::choices()->whereNotNull('published_at')->where('slug', $criteria['sector'])->exists())
|
||||
&& (! isset($criteria['province_id']) || app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->where('id', $criteria['province_id'])->exists())
|
||||
&& ($source !== 'opportunities' || ! isset($criteria['category']) || in_array($criteria['category'], OpportunityManagement::CATEGORIES, true))
|
||||
&& ($source !== 'tenders' || ! isset($criteria['tender_regime']) || array_key_exists($criteria['tender_regime'], config('procurement.regimes')))
|
||||
&& ($source !== 'funding' || ((! isset($criteria['funding_certainty']) || in_array($criteria['funding_certainty'], ['documented', 'include_unknown'], true))
|
||||
&& (! isset($criteria['funding_state']) || in_array($criteria['funding_state'], ['open', 'closed', 'upcoming', 'unknown'], true))));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function save(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 503);
|
||||
$enabling = in_array($input['enabled'] ?? null, [true, 1, '1'], true);
|
||||
// Cancelling only needs the actor and version; retired form choices must not prevent it.
|
||||
$validatedInput = $enabling ? $input : ['version' => $input['version'] ?? null, 'enabled' => $input['enabled'] ?? null];
|
||||
if ($enabling) {
|
||||
$validatedInput['sources'] ??= ['opportunities'];
|
||||
if (is_array($validatedInput['sources']) && is_array($validatedInput['criteria'] ?? null)) {
|
||||
if (! in_array('opportunities', $validatedInput['sources'], true)) {
|
||||
unset($validatedInput['criteria']['category']);
|
||||
}
|
||||
if (! in_array('tenders', $validatedInput['sources'], true)) {
|
||||
unset($validatedInput['criteria']['tender_regime']);
|
||||
}
|
||||
if (! in_array('funding', $validatedInput['sources'], true)) {
|
||||
unset($validatedInput['criteria']['funding_certainty'], $validatedInput['criteria']['funding_state']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$data = Validator::make($validatedInput, [
|
||||
'version' => ['required', 'integer', 'min:0'], 'enabled' => ['required', 'boolean'],
|
||||
'frequency' => [$enabling ? 'required' : 'sometimes', Rule::in(array_keys(self::FREQUENCIES))], 'channel' => [$enabling ? 'required' : 'sometimes', 'in:in_app'],
|
||||
'consent' => $enabling ? ['accepted'] : ['nullable', 'boolean'],
|
||||
'sources' => [$enabling ? 'required' : 'sometimes', 'array', 'min:1', 'max:3'],
|
||||
'sources.*' => ['required', 'string', 'distinct', Rule::in(['opportunities', 'tenders', 'funding'])],
|
||||
'criteria' => [$enabling ? 'present' : 'sometimes', 'array:sector,province_id,category,tender_regime,funding_certainty,funding_state'],
|
||||
'criteria.sector' => ['nullable', 'string', 'max:80', ...($enabling ? [Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('slug')->all())] : [])],
|
||||
'criteria.province_id' => ['nullable', 'uuid'], 'criteria.category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)],
|
||||
'criteria.tender_regime' => ['nullable', Rule::in(array_keys(config('procurement.regimes')))],
|
||||
'criteria.funding_certainty' => ['nullable', 'in:documented,include_unknown'], 'criteria.funding_state' => ['nullable', 'in:open,closed,upcoming,unknown'],
|
||||
])->validate();
|
||||
$sources = $data['sources'] ?? ['opportunities'];
|
||||
sort($sources);
|
||||
if ($enabling && in_array('funding', $sources, true) && ! $this->fundingAvailable()) {
|
||||
throw ValidationException::withMessages(['sources' => 'O catálogo de fundos não está disponível. Pode manter as outras fontes ou cancelar.']);
|
||||
}
|
||||
if ($enabling && in_array('tenders', $sources, true) && ! $this->tendersAvailable()) {
|
||||
throw ValidationException::withMessages(['sources' => 'O catálogo de concursos não está disponível. Pode manter o acompanhamento de oportunidades ou cancelar.']);
|
||||
}
|
||||
$criteria = array_filter($data['criteria'] ?? [], fn ($value) => $value !== null && $value !== '');
|
||||
ksort($criteria);
|
||||
if ($enabling && isset($criteria['province_id']) && ! app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->where('id', $criteria['province_id'])->exists()) {
|
||||
throw ValidationException::withMessages(['criteria.province_id' => 'Seleccione uma província do cadastro público.']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $criteria, $sources): array {
|
||||
// Keep preference writes serialized without blocking notification/audit FK readers.
|
||||
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
|
||||
$row = DB::table('investment_alert_preferences')->where('user_id', $actor->id)->lockForUpdate()->first();
|
||||
$before = $this->preferences($actor->id);
|
||||
if (! $data['enabled']) {
|
||||
$data['frequency'] = $before['frequency'];
|
||||
$criteria = $before['criteria'];
|
||||
$sources = $before['sources'];
|
||||
}
|
||||
$same = $row && $before['enabled'] === (bool) $data['enabled'] && $before['frequency'] === $data['frequency'] && $before['criteria'] === $criteria && $before['sources'] === $sources;
|
||||
if ($same && in_array((int) $data['version'], [$before['version'], $before['version'] - 1], true)) {
|
||||
return $before;
|
||||
}
|
||||
abort_unless((int) $data['version'] === $before['version'], 409, 'As preferências foram alteradas. Recarregue antes de guardar.');
|
||||
if ($data['enabled'] && (! $before['enabled'] || $criteria !== $before['criteria'] || $sources !== $before['sources'])) {
|
||||
// Existing public identities establish the baseline; no timestamps or backdated publications are guessed.
|
||||
if (in_array('opportunities', $sources, true)) {
|
||||
Opportunity::published()->select('id')->chunkById(500, function ($records) use ($actor): void {
|
||||
DB::table('investment_alert_seen')->insertOrIgnore($records->map(fn ($record) => [
|
||||
'user_id' => $actor->id, 'opportunity_id' => $record->id, 'observed_at' => now(),
|
||||
])->all());
|
||||
});
|
||||
}
|
||||
if (in_array('tenders', $sources, true)) {
|
||||
app(Procurement::class)->publicQuery()->select('v.id as version_id')->chunkById(500, function ($records) use ($actor): void {
|
||||
DB::table('investment_tender_alert_seen')->insertOrIgnore($records->map(fn ($record) => [
|
||||
'user_id' => $actor->id, 'tender_version_id' => $record->version_id, 'observed_at' => now(),
|
||||
])->all());
|
||||
}, 'v.id', 'version_id');
|
||||
}
|
||||
if (in_array('funding', $sources, true)) {
|
||||
app(FundingProgrammes::class)->publicQuery()->select('v.id as version_id')->chunkById(500, function ($records) use ($actor): void {
|
||||
DB::table('investment_funding_alert_seen')->insertOrIgnore($records->map(fn ($record) => [
|
||||
'user_id' => $actor->id, 'funding_version_id' => $record->version_id, 'observed_at' => now(),
|
||||
])->all());
|
||||
}, 'v.id', 'version_id');
|
||||
}
|
||||
}
|
||||
$next = ! $data['enabled'] ? null : (($same || ($row && $before['enabled'] && $before['frequency'] === $data['frequency'])) ? $row->next_run_at : $this->nextRun($data['frequency']));
|
||||
$id = $row->id ?? (string) Str::uuid();
|
||||
DB::table('investment_alert_preferences')->updateOrInsert(['user_id' => $actor->id], [
|
||||
'id' => $id,
|
||||
'version' => $before['version'] + 1, 'enabled' => (bool) $data['enabled'], 'frequency' => $data['frequency'], 'channel' => 'in_app',
|
||||
'criteria' => Crypt::encryptString(json_encode($criteria, JSON_THROW_ON_ERROR)),
|
||||
'consented_at' => $data['enabled'] ? now() : ($row->consented_at ?? null), 'next_run_at' => $next,
|
||||
'created_at' => $row->created_at ?? now(), 'updated_at' => now(),
|
||||
...(Schema::hasColumn('investment_alert_preferences', 'sources') ? ['sources' => json_encode($sources, JSON_THROW_ON_ERROR)] : []),
|
||||
]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'investment-alerts', 'entity_type' => 'investment_alert_preferences',
|
||||
'entity_id' => $id, 'actor_user_id' => $actor->id, 'action' => $data['enabled'] ? 'preferences_saved' : 'preferences_cancelled',
|
||||
'data_classification' => 'restricted', 'before_data' => json_encode(['version' => $before['version'], 'enabled' => $before['enabled']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['version' => $before['version'] + 1, 'enabled' => (bool) $data['enabled'], 'frequency' => $data['frequency'],
|
||||
'channel' => 'in_app', 'sources' => $sources, 'criteria_sha256' => hash('sha256', json_encode($criteria, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->preferences($actor->id);
|
||||
});
|
||||
}
|
||||
|
||||
private function nextRun(string $frequency): CarbonImmutable
|
||||
{
|
||||
return match ($frequency) {
|
||||
'daily' => now()->addDay(), 'weekly' => now()->addWeek(), default => now(),
|
||||
};
|
||||
}
|
||||
|
||||
public function dispatchDue(): int
|
||||
{
|
||||
if (! $this->installed()) {
|
||||
return 0;
|
||||
}
|
||||
$count = 0;
|
||||
DB::table('investment_alert_preferences')->where('enabled', true)->where('next_run_at', '<=', now())
|
||||
->whereIn('user_id', DB::table('users')->whereNotNull('email_verified_at')->select('id'))
|
||||
->orderBy('user_id')->chunkById(100, function ($preferences) use (&$count): void {
|
||||
foreach ($preferences as $preference) {
|
||||
$count += DB::transaction(function () use ($preference): int {
|
||||
$row = DB::table('investment_alert_preferences')->where('user_id', $preference->user_id)->lockForUpdate()->first();
|
||||
if (! $row || ! $row->enabled || ! $row->next_run_at || CarbonImmutable::parse($row->next_run_at)->isFuture()) {
|
||||
return 0;
|
||||
}
|
||||
$criteria = json_decode(Crypt::decryptString($row->criteria), true, 512, JSON_THROW_ON_ERROR);
|
||||
$sources = isset($row->sources) ? json_decode($row->sources, true, 512, JSON_THROW_ON_ERROR) : ['opportunities'];
|
||||
$delivered = 0;
|
||||
$more = false;
|
||||
if (in_array('opportunities', $sources, true) && $this->criteriaAvailable($criteria, 'opportunities')) {
|
||||
$records = app(InvestmentCatalogue::class)->query(Arr::except($criteria, ['tender_regime', 'funding_certainty', 'funding_state']))->whereNotExists(fn ($seen) => $seen->selectRaw('1')
|
||||
->from('investment_alert_seen')->where('user_id', $row->user_id)->whereColumn('opportunity_id', 'opportunities.id'))
|
||||
->orderBy('opportunities.id')->limit(201)->get();
|
||||
foreach ($records->take(200) as $record) {
|
||||
$notification = app(InvestmentWorkspace::class)->notifyOpportunity((int) $row->user_id, $record, (int) $row->version, $criteria);
|
||||
DB::table('investment_alert_seen')->insert(['user_id' => $row->user_id, 'opportunity_id' => $record->id, 'notification_id' => $notification, 'observed_at' => now()]);
|
||||
}
|
||||
$delivered += min(200, $records->count());
|
||||
$more = $records->count() > 200;
|
||||
}
|
||||
if (in_array('tenders', $sources, true) && $this->tendersAvailable() && $this->criteriaAvailable($criteria, 'tenders')) {
|
||||
$filters = array_filter(['territory' => $criteria['province_id'] ?? null, 'regime' => $criteria['tender_regime'] ?? null], fn ($value) => $value !== null);
|
||||
if (isset($criteria['sector'])) {
|
||||
$filters['sector_ids'] = Sector::whereIn('slug', SectorOrganization::slugs($criteria['sector']))->pluck('id')->all();
|
||||
}
|
||||
$records = app(Procurement::class)->publicQuery($filters)->whereNotExists(fn ($seen) => $seen->selectRaw('1')
|
||||
->from('investment_tender_alert_seen')->where('user_id', $row->user_id)->whereColumn('tender_version_id', 'v.id'))
|
||||
->select('t.id as tender_id', 'v.id as version_id', 'v.version', 'v.act', 'v.payload', 'v.published_at')->orderBy('v.id')->limit(201)->get();
|
||||
foreach ($records->take(200) as $record) {
|
||||
$notification = app(InvestmentWorkspace::class)->notifyTender((int) $row->user_id, $record, (int) $row->version, $criteria);
|
||||
DB::table('investment_tender_alert_seen')->insert(['user_id' => $row->user_id, 'tender_version_id' => $record->version_id, 'notification_id' => $notification, 'observed_at' => now()]);
|
||||
}
|
||||
$delivered += min(200, $records->count());
|
||||
$more = $more || $records->count() > 200;
|
||||
}
|
||||
if (in_array('funding', $sources, true) && $this->fundingAvailable() && $this->criteriaAvailable($criteria, 'funding')) {
|
||||
$filters = $this->fundingFilters($criteria);
|
||||
$records = app(FundingProgrammes::class)->catalogueQuery($filters)->whereNotExists(fn ($seen) => $seen->selectRaw('1')
|
||||
->from('investment_funding_alert_seen')->where('user_id', $row->user_id)->whereColumn('funding_version_id', 'v.id'))
|
||||
->select('p.id as programme_id', 'v.id as version_id', 'v.version', 'v.payload', 'v.published_at')->orderBy('v.id')->limit(201)->get();
|
||||
foreach ($records->take(200) as $record) {
|
||||
$notification = app(InvestmentWorkspace::class)->notifyFunding((int) $row->user_id, $record, (int) $row->version, $criteria, $filters);
|
||||
DB::table('investment_funding_alert_seen')->insert(['user_id' => $row->user_id, 'funding_version_id' => $record->version_id, 'notification_id' => $notification, 'observed_at' => now()]);
|
||||
}
|
||||
$delivered += min(200, $records->count());
|
||||
$more = $more || $records->count() > 200;
|
||||
}
|
||||
$next = $more ? now() : ($row->frequency === 'as_available' ? now()->addMinutes(5) : $this->nextRun($row->frequency));
|
||||
DB::table('investment_alert_preferences')->where('user_id', $row->user_id)->update(['next_run_at' => $next]);
|
||||
|
||||
return $delivered;
|
||||
});
|
||||
}
|
||||
}, 'user_id');
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Continuation of the existing private dossier, its documentary assessment and proactive evidence. */
|
||||
final class InvestmentPreparationWorkspace
|
||||
{
|
||||
private const SOURCE = 'investor-preparation';
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/** @return list<array<array-key,mixed>> */
|
||||
private function rows(mixed $value): array
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
throw new \LogicException('Dossier list is not recoverable; original retained.');
|
||||
}
|
||||
$rows = [];
|
||||
foreach ($value as $row) {
|
||||
if (! is_array($row)) {
|
||||
throw new \LogicException('Dossier row is not recoverable; original retained.');
|
||||
} $rows[] = $row;
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $data */
|
||||
private function hash(array $data): string
|
||||
{
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($data), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
private function events(string $id, ?string $opportunity): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'desk_cases')->where('entity_id', $id)
|
||||
->where('after_data->scope', $opportunity ?? 'dossier');
|
||||
}
|
||||
|
||||
/** @return array<array-key,mixed> */
|
||||
private function decode(?\stdClass $event): array
|
||||
{
|
||||
return $event ? json_decode(Crypt::decryptString(json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['snapshot']), true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['version' => 0, 'apiex' => ['additional_documents' => [], 'note' => '', 'review' => null, 'exports' => [], 'external' => []],
|
||||
'swot' => ['object_key' => '', 'scope' => '', 'rows' => [], 'source_fingerprint' => '', 'review' => null, 'actions' => []]];
|
||||
}
|
||||
|
||||
/** @return array<array-key,mixed> */
|
||||
private function current(string $id, ?string $opportunity): array
|
||||
{
|
||||
return $this->decode($this->events($id, $opportunity)->orderByRaw("(after_data->>'version')::integer DESC")->first());
|
||||
}
|
||||
|
||||
/** @return array{0: \stdClass, 1: array<array-key,mixed>, 2: ?string, 3: array<array-key,mixed>, 4: bool} */
|
||||
private function context(User $actor, string $id, ?string $opportunity, bool $initialScope = false): array
|
||||
{
|
||||
abort_unless(app(InvestorPath::class)->available() && app(PrivateInvestmentPreparation::class)->available(), 404);
|
||||
$case = $this->desk->case($actor, $id);
|
||||
abort_unless($this->desk->owns($actor, $case, false) || $actor->can('manage-portal'), 403);
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$scope = app(InvestmentConsumerScope::class);
|
||||
$historical = false;
|
||||
abort_if($initialScope && ! $this->events($id, null)->exists(), 404);
|
||||
$choices = array_column(array_column($context['opportunity_choices'] ?? [], 'opportunity'), 'key');
|
||||
if ((($opportunity && ! in_array($opportunity, $choices, true)) || ($initialScope && $choices)) && $this->events($id, $opportunity)->exists()) {
|
||||
$saved = $this->current($id, $opportunity);
|
||||
$last = $saved['apiex']['exports'] ? $saved['apiex']['exports'][array_key_last($saved['apiex']['exports'])] : null;
|
||||
$oldContext = $saved['context_snapshot'] ?? $last['prepared']['context'] ?? $saved['swot']['sources_snapshot']['context'] ?? null;
|
||||
abort_unless(is_array($oldContext), 409, 'Contexto histórico conservado; snapshot de consulta indisponível.');
|
||||
$context = $oldContext;
|
||||
$historical = true;
|
||||
} else {
|
||||
$opportunity = $scope->key($context, $opportunity, true);
|
||||
$context = $scope->context($context, $opportunity);
|
||||
}
|
||||
|
||||
$documents = app(InvestorContext::class)->preparationDocuments($id);
|
||||
// Reuse request-level document authorization, including for a dossier team member.
|
||||
$documents = array_values(array_filter($documents, function ($document) use ($actor, $id) {
|
||||
$link = DB::table('desk_documents')->where('id', $document['id'])->where('case_id', $id)->first();
|
||||
if ($link?->request_id) {
|
||||
try {
|
||||
$this->desk->request($actor, $link->request_id);
|
||||
} catch (HttpException $e) {
|
||||
if (in_array($e->getStatusCode(), [403, 404], true)) {
|
||||
return false;
|
||||
} throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}));
|
||||
foreach ($documents as &$document) {
|
||||
$record = DB::table('documents')->where('id', $document['document_id'])->first();
|
||||
$document['available'] = $record && $record->status === 'active' && $record->malware_scan_status === 'clean'
|
||||
&& hash_equals(trim($record->sha256), trim((string) $record->malware_scanned_sha256));
|
||||
}
|
||||
unset($document);
|
||||
|
||||
$unique = [];
|
||||
foreach ($documents as $document) {
|
||||
$unique[$document['document_id']] = $document;
|
||||
}
|
||||
|
||||
return [$case, $context, $opportunity, array_values($unique), $historical];
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $context
|
||||
* @return array<array-key,mixed> */
|
||||
private function sources(User $actor, \stdClass $case, array $context, string $object): array
|
||||
{
|
||||
$objects = [['key' => 'investment:'.$case->id, 'label' => $case->title, 'kind' => 'investment']];
|
||||
$evidence = [];
|
||||
$demography = app(DemographicEvidence::class)->forContext($context);
|
||||
if ($demography['state'] === 'available') {
|
||||
$evidence['demography'] = ['key' => 'demography', 'label' => 'Contexto demográfico INE', 'current' => $demography,
|
||||
'notice' => 'Evidência para análise SWOT; não produz conclusões automáticas. Consulte ano, edição e limitações.'];
|
||||
}
|
||||
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'];
|
||||
}
|
||||
foreach ($refs as $ref) {
|
||||
if (! is_array($ref) || empty($ref['key'])) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$live = app(InvestorContext::class)->reference($ref['key']);
|
||||
} catch (ModelNotFoundException|HttpException $e) {
|
||||
$live = ['key' => $ref['key'], 'unavailable' => true];
|
||||
}
|
||||
$evidence[$ref['key']] = ['key' => $ref['key'], 'label' => $ref['title'] ?? $ref['key'], 'consulted' => $ref, 'current' => $live];
|
||||
if (in_array($ref['kind'] ?? '', ['territory', 'sector'], true)) {
|
||||
$objects[] = ['key' => $ref['key'], 'label' => $ref['title'], 'kind' => $ref['kind']];
|
||||
}
|
||||
if (($ref['kind'] ?? '') === 'portfolio') {
|
||||
$portfolio = InvestmentPortfolioController::visible()->whereKey($ref['id'])->first();
|
||||
if ($portfolio?->cluster_id) {
|
||||
$cluster = EconomicCluster::find($portfolio->cluster_id);
|
||||
if ($cluster) {
|
||||
$objects[] = ['key' => 'cluster:'.$cluster->id, 'label' => $cluster->getAttribute('name'), 'kind' => 'cluster'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sector/territory may have been deliberately entered rather than selected as a source.
|
||||
foreach ([['sector', 'sector_id'], ['territory', 'province_id'], ['territory', 'district_id'], ['territory', 'admin_post_id'], ['territory', 'locality_id']] as [$kind, $field]) {
|
||||
if (! empty($context['fields'][$field])) {
|
||||
$key = $kind.':'.$context['fields'][$field];
|
||||
try {
|
||||
$ref = app(InvestorContext::class)->reference($key);
|
||||
$objects[] = ['key' => $key, 'label' => $ref['title'], 'kind' => $kind];
|
||||
$evidence[$key] = ['key' => $key, 'label' => $ref['title'], 'consulted' => $ref, 'current' => $ref];
|
||||
} catch (ModelNotFoundException|HttpException $e) { /* Keep the declared context; do not invent evidence. */
|
||||
}
|
||||
}
|
||||
}
|
||||
// A manually chosen cluster must already be a public, visible portfolio association.
|
||||
if (str_starts_with($object, 'cluster:')) {
|
||||
$clusterId = substr($object, 8);
|
||||
$visible = InvestmentPortfolioController::visible()->where('cluster_id', $clusterId)->exists();
|
||||
$cluster = $visible ? EconomicCluster::find($clusterId) : null;
|
||||
$objects[] = ['key' => $object, 'label' => $cluster ? $cluster->getAttribute('name') : 'Cluster da análise guardada — fonte actual indisponível', 'kind' => 'cluster'];
|
||||
}
|
||||
foreach ($objects as $item) {
|
||||
if ($item['kind'] === 'cluster') {
|
||||
$evidence[$item['key']] = ['key' => $item['key'], 'label' => 'Competitividade — '.$item['label'],
|
||||
'current' => InvestmentPortfolioController::visible()->where('cluster_id', substr($item['key'], 8))->exists() ? app(ClusterCompetitiveness::class)->publicData(substr($item['key'], 8)) : null, 'notice' => 'Versão pública aprovada; ausência de análise não prova ausência de oferta/concorrência.'];
|
||||
}
|
||||
}
|
||||
|
||||
$unique = [];
|
||||
foreach ($objects as $item) {
|
||||
$unique[$item['key']] = $item;
|
||||
}
|
||||
|
||||
return [array_values($unique), array_values($evidence)];
|
||||
}
|
||||
|
||||
/** @return array<array-key,mixed> */
|
||||
public function view(User $actor, string $id, ?string $opportunity = null, ?int $historyBefore = null, bool $initialScope = false): array
|
||||
{
|
||||
[$case, $context, $opportunity, $documents, $historical] = $this->context($actor, $id, $opportunity, $initialScope);
|
||||
$state = $this->current($id, $opportunity);
|
||||
[$objects, $sources] = $this->sources($actor, $case, $context, $state['swot']['object_key']);
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$reused = ['investor' => Arr::only($payload, ['name', 'email']), 'profile' => Arr::only($payload['profile'] ?? [], ['phone', 'nuit', 'address', 'country_code', 'nationality', 'residence_country_code']), 'company' => Arr::only($payload['company'] ?? [], ['id', 'name', 'nuit', 'registration', 'address', 'type']), 'company_version' => $payload['company_version'] ?? null, 'notice' => 'Valores autorizados conservados no dossier; não foram substituídos por dados recentes de outra origem.'];
|
||||
if ($historical && isset($state['reused_snapshot'])) {
|
||||
$reused = $state['reused_snapshot'];
|
||||
}
|
||||
foreach ($documents as $document) {
|
||||
$sources[] = ['key' => 'document:'.$document['document_id'], 'label' => $document['file_name'], 'current' => $document, 'notice' => 'Documento privado do dossier; disponibilidade não certifica o conteúdo.'];
|
||||
}
|
||||
$assessment = app(PrivateInvestmentPreparation::class)->assess($context, $documents);
|
||||
$issues = $assessment['missing_labels'];
|
||||
if (! $assessment['enabled'] || ! $assessment['period_covered'] || ! $assessment['scope_covered'] || $assessment['mode'] === 'indeterminate') {
|
||||
$issues[] = 'Completar o enquadramento da preparação existente.';
|
||||
}
|
||||
foreach ($assessment['requirements'] as &$requirement) {
|
||||
$document = collect($this->rows($documents))->firstWhere('document_id', $requirement['document_id']);
|
||||
$requirement['available'] = $document['available'] ?? false;
|
||||
if ($requirement['state'] === 'indeterminate' || ($requirement['required'] && ! $requirement['available'])) {
|
||||
$issues[] = $requirement['label'];
|
||||
}
|
||||
}
|
||||
unset($requirement);
|
||||
$selected = array_values(array_unique([...collect($this->rows($assessment['requirements']))->where('required', true)->pluck('document_id')->filter()->all(), ...$state['apiex']['additional_documents']]));
|
||||
foreach ($selected as $doc) {
|
||||
if (! (collect($this->rows($documents))->firstWhere('document_id', $doc)['available'] ?? false)) {
|
||||
$issues[] = 'Anexo indisponível: '.$doc;
|
||||
}
|
||||
}
|
||||
$documentary = array_values(array_filter($documents, fn ($d) => in_array($d['document_id'], $selected, true)));
|
||||
$fingerprint = $this->hash(['context' => $context, 'reused' => $reused, 'assessment' => $assessment, 'documents' => $documentary, 'note' => $state['apiex']['note']]);
|
||||
$swotFingerprint = $this->hash($this->sourceSnapshot($context, $reused, $sources, $state['swot']['object_key'], $state['swot']['rows']));
|
||||
$external = collect($this->rows($state['apiex']['external']));
|
||||
$apiState = $external->contains('kind', 'decision') ? 'decision_received' : ($external->contains('kind', 'delivery') ? 'delivery_recorded' : (! $issues && ($state['apiex']['review']['fingerprint'] ?? null) === $fingerprint ? 'ready' : 'preparing'));
|
||||
$query = $opportunity ? '?opportunity='.urlencode($opportunity) : '';
|
||||
$editQuery = $historical ? '' : $query;
|
||||
|
||||
$savedScopes = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'desk_cases')->where('entity_id', $id)->selectRaw("DISTINCT after_data->>'scope' as scope")->get()->map(fn ($row) => ['key' => $row->scope, 'label' => $row->scope === 'dossier' ? 'Contexto inicial do dossier' : $row->scope, 'href' => '/investimentos/'.$id.'/preparacao?'.($row->scope === 'dossier' ? 'history_scope=dossier' : 'opportunity='.urlencode($row->scope))])->all();
|
||||
$historyRows = $this->events($id, $opportunity)->when($historyBefore !== null, fn ($q) => $q->whereRaw("(after_data->>'version')::integer < ?", [$historyBefore]))->orderByRaw("(after_data->>'version')::integer DESC")->limit(26)->get();
|
||||
$history = $historyRows->take(25)->map(fn ($e) => ['version' => json_decode($e->after_data, true)['version'], 'action' => $e->action, 'at' => $e->occurred_at, 'actor' => $e->actor_user_id, 'operation_key' => $e->correlation_id])->values()->all();
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'closed' => $case->closed_at !== null], 'opportunity' => $opportunity, 'opportunity_label' => $context['selection']['opportunity']['title'] ?? null,
|
||||
'historical' => $historical, 'initial_scope' => $initialScope, 'saved_scopes' => $savedScopes, 'version' => $state['version'], 'apiex' => $state['apiex'], 'swot' => $state['swot'], 'assessment' => $assessment, 'context' => $context, 'reused' => $reused,
|
||||
'documents' => $documents, 'selected_documents' => $documentary, 'api_issues' => array_values(array_unique($issues)), 'api_state' => $apiState,
|
||||
'api_fingerprint' => $fingerprint, 'swot_fingerprint' => $swotFingerprint,
|
||||
'swot_review_required' => $state['swot']['source_fingerprint'] !== $swotFingerprint || ($state['swot']['review']['fingerprint'] ?? null) !== $swotFingerprint,
|
||||
'objects' => $objects, 'sources' => $sources, 'can_write' => ! $historical && ! $case->closed_at && $this->desk->owns($actor, $case),
|
||||
'can_review' => ! $historical && ! $case->closed_at && ($this->desk->owns($actor, $case) || $actor->can('manage-portal')),
|
||||
'links' => ['dossier' => '/investimentos/'.$id.$editQuery, 'context' => '/investimentos/'.$id.'/contexto/editar'.$editQuery,
|
||||
'documents' => '/balcao-virtual/dossiers/'.$id.$query, 'partners' => '/parcerias/painel?context='.$id.($opportunity ? '&opportunity='.urlencode($opportunity) : ''),
|
||||
'library' => '/documentos?context='.$id.($opportunity ? '&opportunity='.urlencode($opportunity) : ''),
|
||||
'editorial' => '/acesso-gestao', 'idea' => '/investimentos/'.$id.'/contexto/editar'.$query.'#project-summary', 'opportunity' => '/investimentos/'.$id.'/contexto/editar'.$query.'#project-summary', 'risk' => '/investimentos/'.$id.$query.'#tarefas'],
|
||||
'history' => $history, 'history_next' => $historyRows->count() > 25 ? ($history[count($history) - 1]['version'] ?? null) : null];
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $context
|
||||
* @param array<array-key,mixed> $reused
|
||||
* @param array<array-key,mixed> $sources
|
||||
* @param array<array-key,mixed> $rows
|
||||
* @return array<array-key,mixed> */
|
||||
private function sourceSnapshot(array $context, array $reused, array $sources, string $object, array $rows): array
|
||||
{
|
||||
$used = array_column($rows, 'source_key');
|
||||
$tracked = array_values(array_filter($sources, fn ($source) => ! str_starts_with($source['key'], 'document:') || in_array($source['key'], $used, true)));
|
||||
|
||||
return ['context' => $context, 'reused' => $reused, 'sources' => $tracked, 'object' => $object];
|
||||
}
|
||||
|
||||
/** @return array<array-key,mixed>|null */
|
||||
public function continuation(User $actor, string $id, ?string $opportunity, mixed $actionId): ?array
|
||||
{
|
||||
if (! is_string($actionId) || ! Str::isUuid($actionId)) {
|
||||
return null;
|
||||
}
|
||||
[, , $scope] = $this->context($actor, $id, $opportunity);
|
||||
|
||||
return collect($this->rows($this->current($id, $scope)['swot']['actions']))->firstWhere('id', $actionId);
|
||||
}
|
||||
|
||||
/** Reuses the authorised workspace and its preserved exports; never creates an export or a review.
|
||||
* @return array<string,mixed> */
|
||||
public function reportSummary(User $actor, string $id, ?string $opportunity): array
|
||||
{
|
||||
$view = $this->view($actor, $id, $opportunity);
|
||||
$query = $view['opportunity'] ? '?opportunity='.urlencode($view['opportunity']) : '';
|
||||
$base = '/investimentos/'.$id.'/preparacao';
|
||||
|
||||
return ['case_id' => $id, 'opportunity' => $view['opportunity'], 'version' => $view['version'],
|
||||
'context_revision' => $view['context']['revision'], 'href' => $base.$query, 'api_state' => $view['api_state'],
|
||||
'api_issues' => $view['api_issues'], 'external' => $view['apiex']['external'],
|
||||
'exports' => array_map(fn ($export) => ['id' => $export['id'], 'at' => $export['at'],
|
||||
'context_revision' => $export['context_revision'], 'fingerprint' => $export['fingerprint'],
|
||||
'historical' => $export['fingerprint'] !== $view['api_fingerprint'],
|
||||
'href' => $base.'/exportar/'.$export['id'].$query], $this->rows($view['apiex']['exports'])),
|
||||
'swot' => $view['swot'], 'swot_review_required' => $view['swot_review_required']];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function taskKeys(User $actor, string $id, string $opportunity): array
|
||||
{
|
||||
[, , $scope] = $this->context($actor, $id, $opportunity);
|
||||
|
||||
return array_values(array_map(fn ($action) => 'swot:'.$action['id'], $this->current($id, $scope)['swot']['actions']));
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $input
|
||||
* @param array<array-key,mixed> $view
|
||||
* @return array<array-key,mixed> */
|
||||
private function draft(array $input, array $view): array
|
||||
{
|
||||
$data = Validator::make($input, ['object_key' => ['required', Rule::in(array_column($view['objects'], 'key'))], 'scope' => 'present|nullable|string|max:4000',
|
||||
'source_fingerprint' => 'present|string|size:64', 'rows' => 'present|array|list|max:80', 'rows.*' => 'array:id,dimension,text,reference,source_key,date,classification',
|
||||
'rows.*.id' => 'required|uuid|distinct', 'rows.*.dimension' => 'required|in:strength,weakness,opportunity,threat',
|
||||
'rows.*.classification' => 'required|in:documented_fact,hypothesis,unconfirmed', 'rows.*.text' => 'present|nullable|string|max:4000',
|
||||
'rows.*.reference' => 'present|nullable|string|max:4000', 'rows.*.source_key' => ['nullable', Rule::in(array_column($view['sources'], 'key'))], 'rows.*.date' => 'nullable|date_format:Y-m-d'])->validate();
|
||||
|
||||
$snapshot = $this->sourceSnapshot($view['context'], $view['reused'], $view['sources'], $data['object_key'], $data['rows']);
|
||||
|
||||
return [...$data, 'sources_snapshot' => $snapshot, 'snapshot_fingerprint' => $this->hash($snapshot), 'review' => null, 'actions' => $view['swot']['actions']];
|
||||
}
|
||||
|
||||
/** @param array<array-key,mixed> $input
|
||||
* @return array<array-key,mixed> */
|
||||
public function change(User $actor, string $id, array $input): array
|
||||
{
|
||||
$control = Validator::make($input, ['opportunity' => 'nullable|string|max:150', 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid',
|
||||
'action' => 'required|in:apiex_save,apiex_review,apiex_export,external,swot_save,swot_review,swot_action,swot_restore', 'reason' => 'required|string|min:3|max:4000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $input, $control) {
|
||||
$case = $this->desk->case($actor, $id, false, true);
|
||||
$this->desk->assertOpen($case);
|
||||
$view = $this->view($actor, $id, $control['opportunity'] ?? null);
|
||||
$review = in_array($control['action'], ['apiex_review', 'swot_review'], true);
|
||||
abort_unless($review ? $view['can_review'] : $view['can_write'], 403);
|
||||
$requestHash = $this->hash([...$input, 'actor' => $actor->id]);
|
||||
$prior = $this->events($id, $view['opportunity'])->where('correlation_id', $control['operation_key'])->first();
|
||||
if ($prior) {
|
||||
abort_unless(hash_equals(json_decode($prior->after_data, true)['request_hash'], $requestHash), 409, 'A tentativa já tem outro conteúdo.');
|
||||
|
||||
return [...$this->view($actor, $id, $view['opportunity']), 'replayed' => true];
|
||||
}
|
||||
abort_unless((int) $control['version'] === $view['version'], 409, 'Existe outra versão. Os seus campos foram preservados; consulte e compare antes de substituir.');
|
||||
$state = Arr::only($view, ['version', 'apiex', 'swot']);
|
||||
$receipt = ['actor' => $actor->id, 'at' => now()->toISOString(), 'reason' => $control['reason']];
|
||||
switch ($control['action']) {
|
||||
case 'apiex_save':
|
||||
$data = Validator::make($input, ['note' => 'present|nullable|string|max:6000', 'additional_documents' => 'present|array|list|max:60', 'additional_documents.*' => ['required', 'distinct', Rule::in(array_column($view['documents'], 'document_id'))]])->validate();
|
||||
$state['apiex'] = [...$state['apiex'], ...$data, 'review' => null];
|
||||
break;
|
||||
case 'apiex_review':
|
||||
abort_if($view['api_issues'], 422, 'Complete os requisitos e documentos aplicáveis.');
|
||||
abort_unless(($input['fingerprint'] ?? '') === $view['api_fingerprint'], 409, 'O dossier/documentos mudaram; reveja a versão actual.');
|
||||
foreach ($view['selected_documents'] as $document) {
|
||||
$record = DB::table('documents')->where('id', $document['document_id'])->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
app(VerifiedDocumentBinary::class)->respond($record);
|
||||
}
|
||||
$state['apiex']['review'] = [...$receipt, 'fingerprint' => $view['api_fingerprint']];
|
||||
break;
|
||||
case 'apiex_export':
|
||||
abort_if($view['api_issues'] || ($state['apiex']['review']['fingerprint'] ?? '') !== $view['api_fingerprint'], 409, 'Reveja a preparação actual antes de exportar.');
|
||||
$prepared = Arr::only($view, ['case', 'opportunity', 'context', 'reused', 'assessment', 'selected_documents']);
|
||||
$prepared['apiex'] = Arr::only($state['apiex'], ['note', 'review']);
|
||||
$state['apiex']['exports'][] = [...$receipt, 'id' => $control['operation_key'], 'fingerprint' => $view['api_fingerprint'], 'context_revision' => $view['context']['revision'], 'documents' => $view['selected_documents'], 'prepared' => $prepared];
|
||||
break;
|
||||
case 'external':
|
||||
$data = Validator::make($input, ['kind' => 'required|in:delivery,clarification,response,decision', 'date' => 'required|date_format:Y-m-d|before_or_equal:today', 'reference' => 'required|string|max:2000',
|
||||
'proof_document' => ['required', Rule::in(collect($this->rows($view['documents']))->where('available', true)->pluck('document_id')->all())], 'export_id' => 'required|uuid', 'related_id' => 'nullable|uuid', 'outcome' => 'nullable|in:approved,refused,conditional,other'])->validate();
|
||||
abort_unless(collect($this->rows($state['apiex']['exports']))->contains('id', $data['export_id']), 422, 'Escolha a versão exportada deste dossier/oportunidade.');
|
||||
$same = collect($this->rows($state['apiex']['external']))->where('export_id', $data['export_id']);
|
||||
if ($data['kind'] !== 'delivery') {
|
||||
abort_unless($same->contains('kind', 'delivery'), 422, 'Registe a entrega externa desta versão.');
|
||||
}
|
||||
if ($data['kind'] === 'response') {
|
||||
abort_unless($same->where('kind', 'clarification')->contains('id', $data['related_id'] ?? ''), 422, 'Identifique o pedido de esclarecimento a que responde.');
|
||||
}
|
||||
if ($data['kind'] === 'decision') {
|
||||
abort_unless(! empty($data['outcome']), 422, 'Identifique a decisão efectivamente recebida.');
|
||||
}
|
||||
$record = DB::table('documents')->where('id', $data['proof_document'])->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
app(VerifiedDocumentBinary::class)->respond($record);
|
||||
$state['apiex']['external'][] = [...$data, ...$receipt, 'id' => $control['operation_key'], 'proof_snapshot' => collect($this->rows($view['documents']))->firstWhere('document_id', $data['proof_document'])];
|
||||
break;
|
||||
case 'swot_save':
|
||||
$state['swot'] = $this->draft($input['draft'] ?? [], $view);
|
||||
break;
|
||||
case 'swot_review':
|
||||
$swot = $state['swot'];
|
||||
abort_unless(($input['fingerprint'] ?? '') === $view['swot_fingerprint'], 409, 'As fontes mudaram; compare antes de rever.');
|
||||
abort_unless(trim($swot['scope'] ?? '') !== '' && in_array($swot['object_key'], array_column($view['objects'], 'key'), true), 422, 'Identifique objecto e âmbito.');
|
||||
foreach (['strength', 'weakness', 'opportunity', 'threat'] as $dimension) {
|
||||
abort_unless(collect($this->rows($swot['rows']))->contains('dimension', $dimension), 422, 'Trate as quatro dimensões; incerteza deve ficar classificada.');
|
||||
}
|
||||
foreach ($swot['rows'] as $row) {
|
||||
abort_unless(trim($row['text'] ?? '') !== '' && trim($row['reference'] ?? '') !== '' && ! empty($row['date']), 422, 'Cada conclusão exige fonte, data e classificação; desconhecido não é ausência.');
|
||||
}
|
||||
$state['swot']['source_fingerprint'] = $view['swot_fingerprint'];
|
||||
$state['swot']['sources_snapshot'] = $this->sourceSnapshot($view['context'], $view['reused'], $view['sources'], $state['swot']['object_key'], $state['swot']['rows']);
|
||||
$state['swot']['snapshot_fingerprint'] = $view['swot_fingerprint'];
|
||||
$state['swot']['review'] = [...$receipt, 'fingerprint' => $view['swot_fingerprint'], 'version' => $state['version'] + 1];
|
||||
break;
|
||||
case 'swot_action':
|
||||
abort_if($view['swot_review_required'], 409, 'Reveja a análise e as fontes antes de ligar uma acção.');
|
||||
$data = Validator::make($input, ['conclusion_id' => ['required', Rule::in(array_column($state['swot']['rows'], 'id'))], 'kind' => 'required|in:idea,opportunity,partners,risk', 'title' => 'required|string|min:3|max:200'])->validate();
|
||||
$href = $view['links'][$data['kind']];
|
||||
if ($data['kind'] === 'risk') {
|
||||
$href = str_replace('#tarefas', (str_contains($href, '?') ? '&' : '?').'swot_action='.$control['operation_key'].'#tarefas', $href);
|
||||
}
|
||||
$state['swot']['actions'][] = [...$data, ...$receipt, 'id' => $control['operation_key'], 'case_id' => $id, 'opportunity' => $view['opportunity'], 'review_version' => $state['swot']['review']['version'], 'href' => $href];
|
||||
break;
|
||||
case 'swot_restore':
|
||||
$data = Validator::make($input, ['revision' => 'required|integer|min:1'])->validate();
|
||||
$event = $this->events($id, $view['opportunity'])->where('after_data->version', $data['revision'])->first();
|
||||
abort_unless($event !== null, 404);
|
||||
$old = $this->decode($event)['swot'];
|
||||
$state['swot'] = [...$old, 'review' => null, 'actions' => $state['swot']['actions']];
|
||||
break;
|
||||
}
|
||||
$state['context_snapshot'] = $view['context'];
|
||||
$state['reused_snapshot'] = $view['reused'];
|
||||
$state['version']++;
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'desk_cases', 'entity_id' => $id, 'external_id' => $id.':'.hash('sha256', $view['opportunity'] ?? 'dossier').':'.$state['version'],
|
||||
'correlation_id' => $control['operation_key'], 'actor_user_id' => $actor->id, 'action' => $control['action'], 'data_classification' => 'restricted',
|
||||
'before_data' => json_encode(['version' => $view['version']], JSON_THROW_ON_ERROR), 'after_data' => json_encode(['version' => $state['version'], 'scope' => $view['opportunity'] ?? 'dossier', 'request_hash' => $requestHash, 'snapshot' => Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return [...$this->view($actor, $id, $view['opportunity']), 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** Export uses the existing verified binary reader, never a browser-supplied path.
|
||||
* @return array{bytes:string,export_id:string} */
|
||||
public function bundle(User $actor, string $id, ?string $opportunity, string $exportId, bool $initialScope = false): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $id, $opportunity, $exportId, $initialScope) {
|
||||
$this->desk->case($actor, $id, false, true);
|
||||
if ($opportunity === null && ! $initialScope) {
|
||||
$scopes = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'desk_cases')->where('entity_id', $id)->where('correlation_id', $exportId)->where('action', 'apiex_export')->selectRaw("DISTINCT after_data->>'scope' as scope")->get();
|
||||
abort_unless($scopes->count() === 1, 422, 'Identifique o âmbito da exportação preservada.');
|
||||
$scope = $scopes->first()->scope;
|
||||
$initialScope = $scope === 'dossier';
|
||||
$opportunity = $initialScope ? null : $scope;
|
||||
}
|
||||
$view = $this->view($actor, $id, $opportunity, null, $initialScope);
|
||||
$export = collect($this->rows($view['apiex']['exports']))->firstWhere('id', $exportId);
|
||||
abort_unless($export !== null, 404);
|
||||
$records = [];
|
||||
foreach ($export['documents'] as $document) {
|
||||
abort_unless(collect($this->rows($view['documents']))->contains('document_id', $document['document_id']), 403);
|
||||
$record = DB::table('documents')->where('id', $document['document_id'])->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($record !== null && $record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($document['sha256']), trim($record->sha256)) && hash_equals(trim($record->sha256), trim((string) $record->malware_scanned_sha256)), 404, 'Documento da versão preparada indisponível para descarga; o histórico foi preservado.');
|
||||
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment($record);
|
||||
$records[$document['document_id']] = $record;
|
||||
}
|
||||
$disk = Storage::disk('local');
|
||||
$key = 'investor-preparations/'.$id.'/'.hash('sha256', $view['opportunity'] ?? 'dossier').'/'.$exportId.'.zip.enc';
|
||||
if ($disk->exists($key)) {
|
||||
try {
|
||||
$sealed = json_decode(Crypt::decryptString($disk->get($key)), true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (DecryptException|\JsonException $e) {
|
||||
abort(404, 'Pacote preservado indisponível; não foi substituído.');
|
||||
}
|
||||
abort_unless(($sealed['case_id'] ?? '') === $id && ($sealed['opportunity'] ?? null) === $view['opportunity'] && ($sealed['export_id'] ?? '') === $exportId && ($sealed['fingerprint'] ?? '') === $export['fingerprint'], 404);
|
||||
$bytes = base64_decode($sealed['binary'] ?? '', true);
|
||||
abort_unless(is_string($bytes) && hash_equals($sealed['sha256'] ?? '', hash('sha256', $bytes)), 404);
|
||||
|
||||
return ['bytes' => $bytes, 'export_id' => $exportId];
|
||||
}
|
||||
$prepared = $export['prepared'];
|
||||
abort_unless(is_array($prepared), 409, 'Snapshot de exportação indisponível; original conservado.');
|
||||
$file = tempnam(sys_get_temp_dir(), 'investmoz-apiex-');
|
||||
abort_unless(is_string($file), 503);
|
||||
$zip = new \ZipArchive;
|
||||
$open = false;
|
||||
try {
|
||||
abort_unless($zip->open($file, \ZipArchive::OVERWRITE) === true, 503);
|
||||
$open = true;
|
||||
$manifest = ['format' => 'investmoz-apiex-preparation/1', 'case_id' => $id, 'opportunity' => $view['opportunity'], 'export' => $export, 'context' => $prepared['context'], 'reused' => $prepared['reused'], 'assessment' => $prepared['assessment'], 'notice' => 'Preparação para entrega externa. Não é formulário oficial, submissão electrónica ou aprovação.'];
|
||||
$index = view('investments.preparation-index', ['workspace' => $prepared, 'manifest' => $manifest])->render();
|
||||
abort_unless($zip->addFromString('indice.html', $index), 503);
|
||||
abort_unless($zip->addFromString('manifesto.json', json_encode($manifest, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)), 503);
|
||||
foreach ($export['documents'] as $n => $document) {
|
||||
$record = $records[$document['document_id']];
|
||||
$response = app(VerifiedDocumentBinary::class)->respond($record);
|
||||
$bytes = $response instanceof BinaryFileResponse ? file_get_contents($response->getFile()->getPathname()) : $response->getContent();
|
||||
abort_unless(is_string($bytes), 503);
|
||||
abort_unless($zip->addFromString('anexos/'.sprintf('%02d-', $n + 1).preg_replace('/[^\pL\pN._-]+/u', '-', basename($document['file_name'])), $bytes), 503);
|
||||
}
|
||||
abort_unless($zip->close(), 503);
|
||||
$open = false;
|
||||
|
||||
$bytes = file_get_contents($file);
|
||||
abort_unless(is_string($bytes), 503);
|
||||
$sealed = ['case_id' => $id, 'opportunity' => $view['opportunity'], 'export_id' => $exportId, 'fingerprint' => $export['fingerprint'], 'sha256' => hash('sha256', $bytes), 'binary' => base64_encode($bytes)];
|
||||
$temporary = $key.'.'.Str::uuid().'.tmp';
|
||||
try {
|
||||
abort_unless($disk->put($temporary, Crypt::encryptString(json_encode($sealed, JSON_THROW_ON_ERROR))) && $disk->move($temporary, $key), 503, 'Não foi possível preservar o pacote; repita a mesma exportação.');
|
||||
} finally {
|
||||
$disk->delete($temporary);
|
||||
}
|
||||
|
||||
return ['bytes' => $bytes, 'export_id' => $exportId];
|
||||
} finally {
|
||||
if ($open) {
|
||||
$zip->close();
|
||||
}
|
||||
if (is_file($file)) {
|
||||
unlink($file);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Idempotent self-service commands, serialized by the caller's existing user row lock. */
|
||||
final class InvestmentProfileCommands
|
||||
{
|
||||
private const SOURCE = 'investment-workspace-command';
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $command
|
||||
* @return array{version:int,id?:string,country?:string}|null
|
||||
*/
|
||||
public function replay(User $actor, ?string $key, array $command): ?array
|
||||
{
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('correlation_id', strtolower($key))->first();
|
||||
if (! $event) {
|
||||
return null;
|
||||
}
|
||||
$data = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(is_array($data) && is_string($data['command_encrypted'] ?? null) && hash_equals(Crypt::decryptString($data['command_encrypted']), $this->canonical($command)), 409,
|
||||
'Este pedido já foi utilizado com outros dados. Consulte o registo guardado antes de preparar outro pedido.');
|
||||
$result = is_string($data['result_encrypted'] ?? null) ? json_decode(Crypt::decryptString($data['result_encrypted']), true, 512, JSON_THROW_ON_ERROR) : ($data['result'] ?? null);
|
||||
if (! is_array($result) || ! is_int($result['version'] ?? null) || $result['version'] < 1
|
||||
|| (array_key_exists('id', $result) && (! is_string($result['id']) || ! Str::isUuid($result['id'])))
|
||||
|| (array_key_exists('country', $result) && (! is_string($result['country']) || preg_match('/^[A-Z]{2}$/D', $result['country']) !== 1))) {
|
||||
throw new \LogicException('Stored workspace command result unavailable.');
|
||||
}
|
||||
|
||||
$receipt = isset($result['id']) ? ['id' => $result['id'], 'version' => $result['version']] : ['version' => $result['version']];
|
||||
if (isset($result['country'])) {
|
||||
$receipt['country'] = $result['country'];
|
||||
}
|
||||
|
||||
return $receipt;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $command
|
||||
* @param array{version:int,id?:string,country?:string} $result */
|
||||
public function record(User $actor, ?string $key, array $command, array $result): void
|
||||
{
|
||||
if ($key === null) {
|
||||
return;
|
||||
}
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'actor_user_id' => $actor->id,
|
||||
'entity_type' => 'investment-profile-command', 'entity_id' => $result['id'] ?? null, 'action' => 'command_applied', 'correlation_id' => strtolower($key), 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['command_encrypted' => Crypt::encryptString($this->canonical($command)), ...(array_key_exists('country', $result) ? ['result_encrypted' => Crypt::encryptString(json_encode($result, JSON_THROW_ON_ERROR))] : ['result' => $result])], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $command */
|
||||
private function canonical(array $command): string
|
||||
{
|
||||
if (is_array($command['payload'] ?? null)) {
|
||||
ksort($command['payload']);
|
||||
}
|
||||
ksort($command);
|
||||
|
||||
return json_encode($command, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,68 @@ namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentSpecificNeed;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InvestmentWorkspace
|
||||
{
|
||||
/** @param array<string,mixed> $criteria
|
||||
* @param array<string,mixed> $filters */
|
||||
public function notifyFunding(int $userId, \stdClass $record, int $version, array $criteria, array $filters): string
|
||||
{
|
||||
$public = json_decode($record->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
$event = 'public-funding-version:'.$record->version_id;
|
||||
$id = (string) Str::uuid();
|
||||
$windows = [];
|
||||
foreach ($public['windows'] as $window) {
|
||||
$windows[] = ['title' => $window['title'], 'state' => app(FundingProgrammes::class)->windowState($window), 'end_on' => $window['end_on'] ?? null];
|
||||
}
|
||||
DB::table('investment_notifications')->insertOrIgnore(['id' => $id, 'user_id' => $userId, 'submission_id' => null,
|
||||
'funding_version_id' => $record->version_id, 'kind' => 'funding_match', 'event_key' => $event,
|
||||
'payload' => Crypt::encryptString(json_encode(['title' => $public['title'], 'programme_id' => $record->programme_id,
|
||||
'publication_version' => (int) $record->version, 'source' => 'Catálogo público de fundos e apoios do InvesteMoz',
|
||||
'published_at' => CarbonImmutable::parse($record->published_at)->toIso8601String(), 'source_url' => $public['source_url'],
|
||||
'source_reference' => $public['source_reference'], 'source_checked_on' => $public['source_checked_on'], 'window_states' => $windows,
|
||||
'scope_explanation' => app(FundingProgrammes::class)->filterExplanation(['payload' => $public], $filters),
|
||||
'preference_version' => $version, 'criteria' => $criteria], JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
||||
|
||||
return DB::table('investment_notifications')->where('user_id', $userId)->where('event_key', $event)->value('id');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $criteria */
|
||||
public function notifyTender(int $userId, \stdClass $record, int $version, array $criteria): string
|
||||
{
|
||||
$public = json_decode($record->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
$event = 'public-tender-version:'.$record->version_id;
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('investment_notifications')->insertOrIgnore(['id' => $id, 'user_id' => $userId, 'submission_id' => null,
|
||||
'tender_version_id' => $record->version_id, 'kind' => 'tender_match', 'event_key' => $event,
|
||||
'payload' => Crypt::encryptString(json_encode(['title' => $public['title'], 'reference' => $public['reference'],
|
||||
'tender_id' => $record->tender_id, 'publication_version' => (int) $record->version, 'act' => $record->act,
|
||||
'source' => 'Catálogo público de concursos do InvesteMoz', 'published_at' => CarbonImmutable::parse($record->published_at)->toIso8601String(),
|
||||
'origin_published_at' => $public['origin_published_at'] ?? null, 'preference_version' => $version,
|
||||
'criteria' => $criteria], JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
||||
|
||||
return DB::table('investment_notifications')->where('user_id', $userId)->where('event_key', $event)->value('id');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $criteria */
|
||||
public function notifyOpportunity(int $userId, Opportunity $opportunity, int $version, array $criteria): string
|
||||
{
|
||||
$event = 'public-opportunity:'.$opportunity->id;
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('investment_notifications')->insertOrIgnore(['id' => $id, 'user_id' => $userId, 'submission_id' => null,
|
||||
'opportunity_id' => $opportunity->id, 'kind' => 'opportunity_match', 'event_key' => $event,
|
||||
'payload' => Crypt::encryptString(json_encode(['title' => $opportunity->title, 'slug' => $opportunity->slug,
|
||||
'source' => 'Catálogo público do InvesteMoz', 'published_at' => $opportunity->published_at?->toIso8601String(),
|
||||
'preference_version' => $version, 'criteria' => $criteria], JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
||||
|
||||
return DB::table('investment_notifications')->where('user_id', $userId)->where('event_key', $event)->value('id');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public function notify(int $userId, InvestmentSubmission $submission, string $kind, string $eventKey, array $payload = []): void
|
||||
{
|
||||
|
||||
@@ -18,7 +18,7 @@ class InvestmentZoneIntegralDetails
|
||||
'phases' => ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
|
||||
'plots' => ['code', 'phase_id', 'area', 'area_unit', 'status', 'geometry_id'],
|
||||
'occupants' => ['organization_id', 'documentary_name', 'phase_id', 'plot_id', 'status', 'valid_from', 'valid_until'],
|
||||
'observations' => ['indicator', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
|
||||
'observations' => ['indicator', 'measure_kind', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
|
||||
'chains' => ['kind', 'organization_id', 'documentary_name', 'zone_link_id', 'phase_id', 'plot_id'],
|
||||
];
|
||||
|
||||
@@ -59,6 +59,7 @@ class InvestmentZoneIntegralDetails
|
||||
$rules['titles.*.kind'] = 'nullable|in:creation,land_use,licence,special_regime,other';
|
||||
$rules['chains.*.kind'] = 'nullable|in:anchor,supplier,unmet_need,other';
|
||||
$rules['observations.*.indicator'] = 'required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
|
||||
$rules['observations.*.measure_kind'] = 'nullable|in:unknown,observed,planned,projected';
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
$result = $before;
|
||||
foreach (self::GROUPS as $group) {
|
||||
@@ -148,7 +149,7 @@ class InvestmentZoneIntegralDetails
|
||||
foreach ($result['observations'] as $item) {
|
||||
if (! isset($item['period_start'],$item['period_end'])) {
|
||||
continue;
|
||||
}$key = implode('|', [$item['indicator'], $item['period_start'], $item['period_end'], $item['scope'] ?? '', $item['population'] ?? '', $item['unit'] ?? '', $item['methodology'] ?? '', $item['source_reference'] ?? '', $item['source_date'] ?? '', $item['phase_id'] ?? '', $item['plot_id'] ?? '']);
|
||||
}$key = implode('|', [$item['indicator'], $item['measure_kind'] ?? 'unknown', $item['period_start'], $item['period_end'], $item['scope'] ?? '', $item['population'] ?? '', $item['unit'] ?? '', $item['methodology'] ?? '', $item['source_reference'] ?? '', $item['source_date'] ?? '', $item['phase_id'] ?? '', $item['plot_id'] ?? '']);
|
||||
abort_if(in_array($key, $keys, true), 422, 'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');
|
||||
$keys[] = $key;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -160,7 +161,9 @@ final class InvestorPath
|
||||
$next = ['code' => 'S06', 'title' => $preparation['next'], 'action' => 'Preparar', 'href' => '/investimentos/'.$id.'/contexto/editar#preparation-questions'];
|
||||
}
|
||||
|
||||
return ['private_investment' => $preparation, 'case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
$preparationTaskKeys = $opportunity !== null && ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(InvestmentPreparationWorkspace::class)->taskKeys($actor, $id, $opportunity) : null;
|
||||
|
||||
return ['funding_selections' => ($owner || $manager) ? array_values(array_filter($path['funding_selections'] ?? [], fn ($row) => ($row['opportunity'] ?? null) === $opportunity)) : [], 'preparation_action' => ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(InvestmentPreparationWorkspace::class)->continuation($actor, $id, $opportunity, request()->query('swot_action')) : null, 'private_investment' => $preparation, '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' => $factReasons,
|
||||
'context_opportunity' => $opportunity, 'opportunity_options' => $allChoices,
|
||||
@@ -169,16 +172,30 @@ final class InvestorPath
|
||||
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => $next['href'] ?? '#'.$next['code']] : null,
|
||||
'investment_context' => ($owner || $manager) ? [...$context, 'opportunity_choices' => $opportunity ? $context['opportunity_choices'] : $allChoices] : null,
|
||||
'results' => $results, 'requests' => $requests, 'documents' => $documents,
|
||||
'fiscal_reports' => (int) $case->user_id === $actor->id && (count($allChoices) < 2 || $opportunity !== null)
|
||||
? app(SimulationFormDrafts::class)->dossierReportSources($actor, $id, $opportunity) : [],
|
||||
'land_report' => $landCase ? ['id' => $landCase->id, 'version' => $landCase->version, 'updated_at' => $landCase->updated_at?->toIso8601String(),
|
||||
'href' => '/investidor/terra-duat/'.$landCase->id.'/imprimir'] : null,
|
||||
'preparation_report' => ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() && (count($allChoices) < 2 || $opportunity !== null)
|
||||
? app(InvestmentPreparationWorkspace::class)->reportSummary($actor, $id, $opportunity) : null,
|
||||
'company_reports' => ($owner || $manager) ? array_filter([
|
||||
'comparison' => isset($payload['company_comparison']) ? Arr::only($payload['company_comparison'], ['revision', 'at']) : null,
|
||||
'preparation' => isset($payload['company_preparation']) ? Arr::only($payload['company_preparation'], ['revision', 'at']) : null,
|
||||
'guides' => array_map(fn ($guide) => ['revision' => $guide['revision'], 'at' => $guide['at'], 'slug' => $guide['guide']['slug'], 'title' => $guide['guide']['title'] ?? $guide['guide']['slug']], $payload['investment_guides'] ?? []),
|
||||
]) : [],
|
||||
'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')
|
||||
->when($preparationTaskKeys !== null, fn ($q) => $q->where(fn ($p) => $p->whereNull('guidance_key')->orWhere('guidance_key', 'not like', 'swot:%')->orWhereIn('guidance_key', $preparationTaskKeys ?? [])))
|
||||
->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 : '').($opportunity ? '&opportunity='.urlencode($opportunity) : '') : null,
|
||||
'services' => app(DeskServiceAvailability::class)->current()->get()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'effective_from' => $s->effective_from ?? null]),
|
||||
'tools' => ['funding' => ($owner || $manager) && app(FundingProgrammes::class)->installed() ? '/fundos?kind=institution&location_mode=physical&context='.$id.($opportunity ? '&opportunity='.urlencode($opportunity) : '') : null, 'simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '').($opportunity ? '&opportunity='.urlencode($opportunity) : '') : null,
|
||||
'preparation' => ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? '/investimentos/'.$id.'/preparacao'.($opportunity ? '?opportunity='.urlencode($opportunity) : '') : null,
|
||||
'company' => '/investimentos/'.$id.'/forma-juridica',
|
||||
'desk' => '/balcao-virtual/dossiers/'.$id.($opportunity ? '?opportunity='.urlencode($opportunity) : ''), 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
|
||||
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id,
|
||||
'land' => ($facts['land_needed'] ?? 'unknown') !== 'no' && (int) $case->user_id === $actor->id ? ($landCase ? '/investidor/terra-duat/'.$landCase->id : '/investidor/terra-duat/novo?context='.$id.($opportunity ? '&opportunity='.urlencode($opportunity) : '')) : null]];
|
||||
@@ -337,12 +354,16 @@ final class InvestorPath
|
||||
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)))],
|
||||
'preparation_action' => 'nullable|uuid', 'opportunity' => 'nullable|string|max:150',
|
||||
'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'];
|
||||
if (!empty($data['preparation_action'])) { app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), $data['opportunity'] ?? null, true); }
|
||||
$origin = !empty($data['preparation_action']) ? app(InvestmentPreparationWorkspace::class)->continuation($actor, $id, $data['opportunity'] ?? null, $data['preparation_action']) : null;
|
||||
abort_if(!empty($data['preparation_action']) && (!$origin || $origin['kind'] !== 'risk'), 422, 'A acção SWOT não pertence a este dossier/oportunidade ou não é uma acção de risco.');
|
||||
$key = $origin ? 'swot:'.$origin['id'] : '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
|
||||
@@ -351,12 +372,12 @@ final class InvestorPath
|
||||
return $existing->id;
|
||||
}
|
||||
$this->writable($actor, $id, $data['version']);
|
||||
$step = $this->findStep($this->view($actor, $id), $data['code']);
|
||||
$step = $this->findStep($this->view($actor, $id, $origin['opportunity'] ?? null), $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']);
|
||||
$this->desk->event($case, $actor, 'path_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'scope' => 'internal_crm', 'preparation_action' => $origin['id'] ?? null, 'opportunity' => $origin['opportunity'] ?? null, 'swot_review_version' => $origin['review_version'] ?? null]);
|
||||
|
||||
return $task->id;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use stdClass;
|
||||
|
||||
/** Attempt ownership in the existing audit ledger; callers hold the document row lock. */
|
||||
final class DocumentScanAttempts
|
||||
{
|
||||
private const SOURCE = 'document-malware-worker';
|
||||
|
||||
public function owns(stdClass $document, string $run, int $delivery, ?int $expectedAttempt = null): bool
|
||||
{
|
||||
$attempt = (int) $document->malware_scan_attempts;
|
||||
if ($expectedAttempt !== null && $attempt !== $expectedAttempt) {
|
||||
return false;
|
||||
}
|
||||
$events = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $document->id)
|
||||
->where('action', 'scan_started')->whereRaw("after_data->>'attempt' = ?", [(string) $attempt])->get(['after_data']);
|
||||
if ($events->count() !== 1) {
|
||||
return false;
|
||||
}
|
||||
$lease = json_decode($events->first()->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return is_array($lease) && ($lease['run_id'] ?? null) === $run && ($lease['delivery_attempt'] ?? null) === $delivery && ($lease['attempt'] ?? null) === $attempt;
|
||||
}
|
||||
|
||||
public function start(stdClass $document, string $run, int $delivery): int
|
||||
{
|
||||
$attempt = (int) $document->malware_scan_attempts + 1;
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_started', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => $attempt, 'file_sha256' => trim($document->sha256), 'file_size_bytes' => $document->size_bytes ?? null], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $attempt;
|
||||
}
|
||||
|
||||
/** @return array{sha256:string,size_bytes:int|null}|null */
|
||||
public function descriptor(stdClass $document, string $run, int $delivery): ?array
|
||||
{
|
||||
if (! $this->owns($document, $run, $delivery)) {
|
||||
return null;
|
||||
}
|
||||
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $document->id)
|
||||
->where('action', 'scan_started')->whereRaw("after_data->>'attempt' = ?", [(string) $document->malware_scan_attempts])->first(['after_data']);
|
||||
$data = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR) : null;
|
||||
if (! is_array($data) || ! is_string($data['file_sha256'] ?? null) || preg_match('/^[a-f0-9]{64}$/D', $data['file_sha256']) !== 1
|
||||
|| ! array_key_exists('file_size_bytes', $data) || ($data['file_size_bytes'] !== null && ! is_int($data['file_size_bytes']))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['sha256' => $data['file_sha256'], 'size_bytes' => $data['file_size_bytes']];
|
||||
}
|
||||
|
||||
public function completed(string $documentId, string $run): bool
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('entity_type', 'document-scan')->where('entity_id', $documentId)
|
||||
->where('action', 'scan_result_recorded')->where('correlation_id', $run)->whereRaw("after_data->>'retryable_failure' = 'false'")->exists();
|
||||
}
|
||||
|
||||
public function finish(stdClass $document, string $run, int $delivery, string $scanId, bool $retryableFailure): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_result_recorded', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => (int) $document->malware_scan_attempts, 'scan_id' => $scanId, 'retryable_failure' => $retryableFailure], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
public function discarded(stdClass $document, string $run, int $delivery, int $expectedAttempt): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE, 'entity_type' => 'document-scan', 'entity_id' => $document->id,
|
||||
'actor_user_id' => null, 'action' => 'scan_result_discarded', 'correlation_id' => $run, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['run_id' => $run, 'delivery_attempt' => $delivery, 'attempt' => $expectedAttempt, 'current_attempt' => (int) $document->malware_scan_attempts], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user