Prepare supplied financial directory with product coverage and native dossier continuity
This commit is contained in:
@@ -4,10 +4,15 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use App\Services\FundingDossierPreparation;
|
||||
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;
|
||||
@@ -43,7 +48,7 @@ final class FundingProgrammeController extends Controller
|
||||
$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])->toResponse($request),
|
||||
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'));
|
||||
}
|
||||
|
||||
@@ -63,6 +68,7 @@ final class FundingProgrammeController extends Controller
|
||||
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']),
|
||||
'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'));
|
||||
@@ -118,11 +124,17 @@ final class FundingProgrammeController extends Controller
|
||||
|
||||
public function index(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'kind' => 'nullable|in:fund,programme,incentive',
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'kind' => 'nullable|in:institution,fund,programme,incentive',
|
||||
'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']).'%';
|
||||
@@ -138,7 +150,7 @@ final class FundingProgrammeController extends Controller
|
||||
return [...$record, 'filter_explanation' => $service->filterExplanation($record, $filters)];
|
||||
});
|
||||
|
||||
return tap(Inertia::render('funding/index', ['items' => $items, 'filters' => $filters, 'kinds' => FundingProgrammes::KINDS,
|
||||
return tap(Inertia::render('funding/index', ['items' => $items, 'filters' => $filters, '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'));
|
||||
@@ -146,14 +158,38 @@ final class FundingProgrammeController extends Controller
|
||||
|
||||
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']);
|
||||
$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])
|
||||
return tap(Inertia::render('funding/show', ['record' => $record, 'saved' => $saved, 'authenticated' => $request->user() !== null, 'dossier' => $dossier, 'selection' => [...$request->only(['need', 'territory', 'context', 'opportunity']), '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');
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?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' => 'required|uuid', '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'] === $data['territory']) {
|
||||
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.');
|
||||
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $data['territory'])->exists(), 422);
|
||||
$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'])) || ($product && app(FundingInstitutionDetails::class)->match($product, $data)), 422, 'Seleccione um produto correspondente ao local e necessidade, incluindo as condições por confirmar.');
|
||||
}
|
||||
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'], '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,178 @@
|
||||
<?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', '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:20', 'locations' => 'array|max:50', 'products' => 'array|max:40',
|
||||
'contacts.*' => 'array:kind,value,source_url,source_reference,checked_on',
|
||||
'contacts.*.kind' => 'required|in:website,email,phone,address', 'contacts.*.value' => "$required|string|max:1000",
|
||||
'locations.*' => 'array:role,label,address,territory_id,source_url,source_reference,checked_on',
|
||||
'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',
|
||||
'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'] = "$required|url:http,https|max:2000";
|
||||
$rules[$prefix.'.*.source_reference'] = "$required|string|max:1500";
|
||||
$rules[$prefix.'.*.checked_on'] = "$required|date_format:Y-m-d|before_or_equal:today";
|
||||
}
|
||||
$data = Validator::make($input, $rules)->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
|
||||
{
|
||||
if (empty($filters['need']) && empty($filters['territory'])) {
|
||||
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'])) {
|
||||
$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): void {
|
||||
$q->whereRaw("v.payload->>'kind' = 'institution'")->where(function (Builder $q) use ($sql, $bindings, $unknown): void {
|
||||
$q->whereRaw($sql, $bindings);
|
||||
if ($unknown) {
|
||||
$q->orWhereRaw("jsonb_array_length(COALESCE(v.payload->'products','[]'::jsonb))=0");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,9 @@ use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Packaged official references prepare private drafts through existing editorial authority. */
|
||||
/** Packaged documentary references prepare private drafts through existing editorial authority. */
|
||||
final class FundingProgrammeReferences
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
@@ -19,13 +20,50 @@ final class FundingProgrammeReferences
|
||||
abort_unless($package['format'] === 'investmoz-funding-references-v1', 503);
|
||||
$reference = $package['references'][$code] ?? null;
|
||||
abort_unless(is_array($reference), 404);
|
||||
$plan = ['code' => $code, 'edition' => $reference['edition'], 'draft' => $reference['draft'], 'provenance' => $reference['provenance'],
|
||||
$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);
|
||||
}
|
||||
$plan = ['unresolved_territories' => $unresolved, 'code' => $code, 'edition' => $reference['edition'], 'draft' => $reference['draft'], 'provenance' => $reference['provenance'],
|
||||
'package_sha256' => hash('sha256', $bytes)];
|
||||
$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 = json_decode(CheckedFile::read(database_path('data/funding-references.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
$choices = [];
|
||||
foreach ($package['references'] as $code => $reference) {
|
||||
$choices[] = ['code' => $code, 'title' => $reference['draft']['title']];
|
||||
}
|
||||
|
||||
return $choices;
|
||||
}
|
||||
|
||||
/** @return array{id:string,created:bool} */
|
||||
public function prepare(User $actor, string $code, string $hash): array
|
||||
{
|
||||
@@ -39,7 +77,7 @@ final class FundingProgrammeReferences
|
||||
return ['id' => $existing->id, 'created' => false];
|
||||
}
|
||||
$id = app(FundingProgrammes::class)->save($actor, null, ['version' => 0, 'code' => $code,
|
||||
'reason' => 'Preparação de referência oficial '.$plan['edition'].'; rascunho sem publicação automática.', 'draft' => $plan['draft']]);
|
||||
'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)]);
|
||||
|
||||
@@ -18,7 +18,7 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
/** Informational funding catalogue, separate from applications, credit decisions and fiscal calculations. */
|
||||
final class FundingProgrammes
|
||||
{
|
||||
public const KINDS = ['fund' => 'Fundo', 'programme' => 'Programa de apoio', 'incentive' => 'Incentivo'];
|
||||
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'];
|
||||
|
||||
@@ -56,6 +56,7 @@ final class FundingProgrammes
|
||||
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 {
|
||||
@@ -69,7 +70,7 @@ final class FundingProgrammes
|
||||
if (! empty($filters['territory'])) {
|
||||
$path = array_column(app(InvestmentGeography::class)->path($filters['territory']), 'id');
|
||||
$query->where(function (Builder $scope) use ($filters, $path, $includeUnknown): void {
|
||||
$scope->whereRaw("v.payload->>'coverage' = 'national'")
|
||||
$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);
|
||||
@@ -102,6 +103,11 @@ final class FundingProgrammes
|
||||
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)));
|
||||
|
||||
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'
|
||||
@@ -200,6 +206,13 @@ final class FundingProgrammes
|
||||
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,
|
||||
@@ -225,6 +238,7 @@ final class FundingProgrammes
|
||||
'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",
|
||||
@@ -244,6 +258,9 @@ final class FundingProgrammes
|
||||
$rules[$prefix.'.*.explanation'] = "$required|string|max:2000";
|
||||
}
|
||||
$data = Validator::make($input, $rules)->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'] !== []) {
|
||||
|
||||
@@ -162,7 +162,7 @@ final class InvestorPath
|
||||
|
||||
$preparationTaskKeys = $opportunity !== null && ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(InvestmentPreparationWorkspace::class)->taskKeys($actor, $id, $opportunity) : null;
|
||||
|
||||
return ['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],
|
||||
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,
|
||||
@@ -180,7 +180,7 @@ final class InvestorPath
|
||||
->when(! $owner && ! $manager, fn ($q) => $q->where('assignee_user_id', $actor->id))
|
||||
->get(['id', 'title', 'status', 'version_no', 'due_at', 'assignee_user_id']),
|
||||
'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' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '').($opportunity ? '&opportunity='.urlencode($opportunity) : '') : null,
|
||||
'tools' => ['funding' => ($owner || $manager) && app(FundingProgrammes::class)->installed() ? '/fundos?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',
|
||||
|
||||
Reference in New Issue
Block a user