commit16
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\OpportunityTextSearch;
|
||||
use App\Services\SectorOrganization;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -41,16 +42,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'])) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
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()];
|
||||
|
||||
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], 201)
|
||||
: back()->with('success', 'Nova versão publicada para pedidos futuros. 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)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Services\DocumentManagementAccess;
|
||||
use App\Services\FundingProgrammeReferences;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\Procurement;
|
||||
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
|
||||
{
|
||||
return tap(Inertia::render('funding/reference', ['reference' => $references->preview($request->user(), $code)])->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
|
||||
{
|
||||
$data = $request->validate(['hash' => 'required|string|size:64']);
|
||||
$result = $references->prepare($request->user(), $code, $data['hash']);
|
||||
|
||||
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 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])->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']),
|
||||
'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
|
||||
{
|
||||
$service->publish($request->user(), $id, $request->all());
|
||||
|
||||
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:fund,programme,incentive',
|
||||
'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 !== '');
|
||||
$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]));
|
||||
}
|
||||
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, 'kinds' => FundingProgrammes::KINDS,
|
||||
'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
|
||||
{
|
||||
$record = $service->published($id);
|
||||
$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])
|
||||
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('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,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.');
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Services\InvestmentComplements;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\OpportunityCorridorExplorer;
|
||||
use App\Services\OpportunityTextSearch;
|
||||
use App\Services\SectorInvestment;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -29,12 +30,20 @@ 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)),
|
||||
];
|
||||
|
||||
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)]);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,17 @@
|
||||
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\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;
|
||||
@@ -119,14 +126,38 @@ class InvestmentWorkspaceController extends Controller
|
||||
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 +166,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();
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -87,8 +87,17 @@ 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),
|
||||
'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))]);
|
||||
}
|
||||
@@ -116,7 +125,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
->leftJoin('geo_locations as locality', 'locality.id', '=', 'locations.locality_id')
|
||||
->where('locations.is_public', true)->where('locations.is_primary', true)
|
||||
->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at')
|
||||
->select('locations.existing_business_id', 'province.name as province')
|
||||
->select('locations.existing_business_id', 'province.name as province', 'province.id as similar_province_id')
|
||||
->selectRaw("CASE WHEN locations.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
|
||||
->selectRaw('NULL::text AS locality');
|
||||
|
||||
@@ -127,6 +136,6 @@ 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']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ class VirtualDeskController extends Controller
|
||||
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
|
||||
'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(),
|
||||
'findings' => $desk->findings($payload, $definition), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
||||
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
|
||||
'kind' => $messageKinds[$m->id] ?? 'historical_unclassified']),
|
||||
'events' => $this->events($case->id, $desk, $request->user())->filter(fn ($e) => $e['request_id'] === $id)->values(),
|
||||
@@ -245,7 +245,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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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']],
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
<?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
|
||||
{
|
||||
$rows = DB::table('desk_service_versions')->selectRaw('DISTINCT ON (code) code, version, definition')
|
||||
->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,
|
||||
'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,
|
||||
'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)->get(['id', 'version', 'status', 'author_id', 'published_by', 'published_at', 'definition', 'source']);
|
||||
$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),
|
||||
'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'],
|
||||
'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'],
|
||||
'definition.fields.*.label' => ['required', 'string', 'max:300'],
|
||||
'definition.fields.*.type' => ['required', Rule::in(['text', 'textarea', 'email', 'tel', 'url', 'number', 'date', 'select', 'territory'])],
|
||||
'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', 'required_array_keys:field,equals'],
|
||||
'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)');
|
||||
$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->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 ($latest && $latest->status === 'published' && $this->definitionHash($previous) === $this->definitionHash($data['definition'])) {
|
||||
throw ValidationException::withMessages(['definition' => 'Não há alterações na definição 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',
|
||||
'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', '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));
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $fields */
|
||||
private function checkFields(array $fields): void
|
||||
{
|
||||
foreach ($fields as $key => $field) {
|
||||
$path = 'definition.fields.'.$key;
|
||||
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 ($field['type'] === 'select' && empty($field['options'])) {
|
||||
throw ValidationException::withMessages([$path.'.options' => 'Indique as opções deste campo.']);
|
||||
}
|
||||
if ((isset($field['min']) && $field['type'] !== 'number') || (isset($field['options']) && $field['type'] !== 'select')) {
|
||||
throw ValidationException::withMessages([$path => 'O mínimo aplica-se apenas a números e as opções apenas a listas de respostas.']);
|
||||
}
|
||||
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 ($fields[$parent]['type'] === 'number') {
|
||||
throw ValidationException::withMessages([$path.'.when' => 'As condições actuais comparam respostas exactas. Use uma lista de opções como origem da condição numérica.']);
|
||||
}
|
||||
if ($fields[$parent]['type'] === 'select' && ! 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.']);
|
||||
}
|
||||
$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['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,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Packaged official references prepare private drafts through existing editorial authority. */
|
||||
final class FundingProgrammeReferences
|
||||
{
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor, string $code): array
|
||||
{
|
||||
app(FundingProgrammes::class)->guard($actor);
|
||||
$bytes = CheckedFile::read(database_path('data/funding-references.json'));
|
||||
$package = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
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'],
|
||||
'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 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 oficial '.$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,453 @@
|
||||
<?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 = ['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);
|
||||
}
|
||||
|
||||
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();
|
||||
$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'])) {
|
||||
$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'")
|
||||
->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'];
|
||||
$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.']);
|
||||
}
|
||||
$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' => "$required|url:http,https|max:2000", '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',
|
||||
'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();
|
||||
$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']);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Public keyword search: every meaningful term is required, with explicit narrow writing variants. */
|
||||
final class OpportunityTextSearch
|
||||
{
|
||||
private const STOP_WORDS = ['a', 'as', 'o', 'os', 'de', 'da', 'das', 'do', 'dos', 'e', 'em', 'no', 'nos', 'na', 'nas', 'para', 'por', 'com', 'um', 'uma', 'uns', 'umas'];
|
||||
|
||||
private const CULTIVATION = ['plantio', 'plantacao', 'plantacoes', 'cultivo', 'cultivar', 'cultivacao', 'semeadura', 'semeio'];
|
||||
|
||||
/** @return list<string> */
|
||||
public function terms(string $text): array
|
||||
{
|
||||
$parts = preg_split('/[\s,;]+/u', Str::lower(Str::ascii(trim($text)))) ?: [];
|
||||
|
||||
return array_values(array_unique(array_filter(array_map(fn ($part) => trim($part, "\"'"), $parts),
|
||||
fn ($part) => $part !== '' && ! in_array($part, self::STOP_WORDS, true))));
|
||||
}
|
||||
|
||||
/** A secondary query keeps the subject/location; it never relabels processing as cultivation. */
|
||||
public function relatedQuery(string $text): ?string
|
||||
{
|
||||
$terms = $this->terms($text);
|
||||
$subject = array_values(array_diff($terms, self::CULTIVATION));
|
||||
|
||||
return $subject !== [] && count($subject) < count($terms) ? implode(' ', $subject) : null;
|
||||
}
|
||||
|
||||
/** @param literal-string $column
|
||||
* @return literal-string */
|
||||
private function normalized(string $column): string
|
||||
{
|
||||
return "translate(lower(COALESCE($column, '')), 'áàâãäåéèêëíìîïóòôõöúùûüçñýÿ', 'aaaaaaeeeeiiiiooooouuuucnyy')";
|
||||
}
|
||||
|
||||
/** @param Builder<Opportunity> $query */
|
||||
public function constrain(Builder $query, string $text): void
|
||||
{
|
||||
$terms = $this->terms($text);
|
||||
if ($terms === []) {
|
||||
$query->whereRaw('false');
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($terms as $term) {
|
||||
$variants = in_array($term, self::CULTIVATION, true) ? ['plantio', 'plantacao', 'plantacoes', 'cultiv', 'semead', 'semeio'] : [$term];
|
||||
$patterns = array_map(fn ($value) => '%'.addcslashes($value, '%_\\').'%', $variants);
|
||||
$geography = app(InvestmentGeography::class);
|
||||
$locations = $geography->publicReferences()->where(function ($names) use ($patterns): void {
|
||||
foreach ($patterns as $pattern) {
|
||||
$names->orWhereRaw($this->normalized('name').' LIKE ?', [$pattern]);
|
||||
}
|
||||
})->pluck('id');
|
||||
$territories = [];
|
||||
foreach ($locations as $location) {
|
||||
$territories = array_merge($territories, $geography->descendants((string) $location));
|
||||
}
|
||||
$territories = array_values(array_unique($territories));
|
||||
$query->where(function ($matches) use ($patterns, $territories): void {
|
||||
foreach ($patterns as $pattern) {
|
||||
foreach (['opportunities.title', 'opportunities.description', 'opportunities.summary', 'opportunities.reference', 'opportunities.province', 'opportunities.district'] as $column) {
|
||||
$matches->orWhereRaw($this->normalized($column).' LIKE ?', [$pattern]);
|
||||
}
|
||||
$matches->orWhereHas('sector', fn ($sector) => $sector->whereRaw($this->normalized('name').' LIKE ?', [$pattern])
|
||||
->orWhereRaw($this->normalized('slug').' LIKE ?', [$pattern]));
|
||||
$matches->orWhereExists(fn ($dossier) => $dossier->selectRaw('1')->from('investment_dossiers as searchable_dossier')
|
||||
->whereIn('searchable_dossier.id', InvestmentPortfolioController::visible()->reorder()->select('investment_dossiers.id'))
|
||||
->where(fn ($value) => $value->whereRaw($this->normalized('searchable_dossier.title').' LIKE ?', [$pattern])
|
||||
->orWhereRaw($this->normalized('searchable_dossier.content::text').' LIKE ?', [$pattern]))
|
||||
->where(fn ($relation) => $relation
|
||||
->whereExists(fn ($project) => $project->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 ($cluster) => $cluster->selectRaw('1')->from('opportunity_clusters as search_cluster')->whereColumn('search_cluster.opportunity_id', 'opportunities.id')->whereColumn('search_cluster.cluster_id', 'searchable_dossier.cluster_id'))));
|
||||
}
|
||||
if ($territories !== []) {
|
||||
$matches->orWhereIn('opportunities.primary_territory_id', $territories)
|
||||
->orWhereExists(fn ($linked) => $linked->selectRaw('1')->from('opportunity_locations as search_link')
|
||||
->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereIn('search_link.geo_location_id', $territories));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,43 @@ use Illuminate\Validation\ValidationException;
|
||||
/** Publication of notices; never receives bids or changes the linked investment. */
|
||||
final class Procurement
|
||||
{
|
||||
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";
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
public function publicQuery(array $filters = []): Builder
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$query = 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');
|
||||
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 (isset($filters['sector_ids'])) {
|
||||
$query->whereIn(DB::raw("v.payload->>'sector_id'"), array_map('strval', $filters['sector_ids']));
|
||||
}
|
||||
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']]);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** Published historical acts remain readable while their tender remains public. */
|
||||
public function readableVersions(): Builder
|
||||
{
|
||||
return DB::table('portal_tender_versions')->whereNotNull('published_at')->whereIn('tender_id', $this->publicQuery()->select('t.id'));
|
||||
}
|
||||
|
||||
public const TEXT = ['title', 'reference', 'responsible_unit', 'modality', 'object', 'object_kind', 'quantities', 'financier', 'instrument', 'edition', 'rule_source', 'financing_agreement', 'eligibility', 'requirements', 'proposal_validity', 'guarantee_status', 'guarantees', 'delivery_channel', 'delivery_address', 'delivery_url', 'public_contact', 'dissemination', 'origin_url', 'origin_published_at', 'clarifications_at', 'deadline', 'opening_at', 'timezone', 'minimum_source', 'minimum_edition', 'minimum_modality', 'minimum_day_basis', 'result', 'internal_notes', 'public_reason', 'minimum_working_days', 'minimum_holidays', 'minimum_calendar_source'];
|
||||
|
||||
public function available(): bool
|
||||
@@ -25,12 +62,7 @@ final class Procurement
|
||||
|
||||
public function access(?User $actor): bool
|
||||
{
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
$docs = app(DocumentManagementAccess::class);
|
||||
|
||||
return ! app(PortalProfileAccess::class)->has($actor, 'auditor') && ($docs->full($actor) || $docs->editorial($actor));
|
||||
return app(DocumentManagementAccess::class)->catalogueEditor($actor);
|
||||
}
|
||||
|
||||
public function guard(?User $actor): void
|
||||
|
||||
@@ -187,8 +187,12 @@ class VirtualDesk
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
$base = $this->decode($case->payload);
|
||||
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
|
||||
if (config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
$payload = Arr::only(['title' => $case->title, 'description' => $base['investment']['objective'] ?? ''], array_keys($serviceFields));
|
||||
if (isset($serviceFields['regime']['options']['unknown'])) {
|
||||
$payload['regime'] = 'unknown';
|
||||
}
|
||||
if (isset($serviceFields['description']) && config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
|
||||
$draftRequest = Request::create('/');
|
||||
$draftRequest->setUserResolver(fn () => $actor);
|
||||
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
|
||||
@@ -197,7 +201,7 @@ class VirtualDesk
|
||||
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
|
||||
}
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
if (count($context['opportunity_choices'] ?? []) > 1 && ! $opportunity) {
|
||||
if (isset($serviceFields['description']) && count($context['opportunity_choices'] ?? []) > 1 && ! $opportunity) {
|
||||
$payload['description'] = '';
|
||||
}
|
||||
$mapped = app(InvestorContext::class)->prefill($context, $opportunity)['desk'];
|
||||
@@ -205,9 +209,9 @@ class VirtualDesk
|
||||
$payload['context_opportunity'] = $opportunity;
|
||||
}
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $caseId, $payload);
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
foreach (['territory_id' => 'territory_id', 'location_source' => 'location_source', 'title' => 'title', 'description' => 'description', 'sector' => 'sector', 'province_id' => 'province_id', 'district_id' => 'district_id', 'admin_post_id' => 'admin_post_id', 'locality_id' => 'locality_id'] as $field => $source) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)
|
||||
&& Validator::make(['value' => $mapped[$source]], ['value' => $this->fieldRules($serviceFields[$field], false)])->passes()) {
|
||||
$payload[$field] = $mapped[$source];
|
||||
}
|
||||
}
|
||||
@@ -272,25 +276,22 @@ class VirtualDesk
|
||||
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
|
||||
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()]];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
$active = ! isset($field['when']) || ($payload[$field['when']['field']] ?? null) === $field['when']['equals'];
|
||||
$active = $this->fieldApplies((string) $key, $definition['fields'], $payload);
|
||||
$required = $submitting && ($field['required'] ?? false) && $active;
|
||||
$rule = [$required ? 'required' : 'nullable'];
|
||||
$rule = [...$rule, ...match ($field['type']) {
|
||||
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
|
||||
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
|
||||
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
|
||||
}];
|
||||
$rules['payload.'.$key] = $rule;
|
||||
$rules['payload.'.$key] = $this->fieldRules($field, $required);
|
||||
}
|
||||
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
if ($field['type'] === 'select' && isset($validated[$key])) {
|
||||
$validated[$key] = (string) $validated[$key];
|
||||
}
|
||||
if ($field['type'] === 'territory' && ! empty($validated[$key])) {
|
||||
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $validated[$key])->exists()) {
|
||||
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione uma localização disponível no cadastro territorial.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($validated['territory_id'] ?? null) {
|
||||
if (($validated['territory_id'] ?? null) && $this->fieldApplies('territory_id', $definition['fields'], $validated)) {
|
||||
if ($submitting && trim($validated['location_source'] ?? '') === '') {
|
||||
throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
|
||||
}
|
||||
@@ -299,11 +300,56 @@ class VirtualDesk
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $field
|
||||
* @return list<mixed> */
|
||||
private function fieldRules(array $field, bool $required): array
|
||||
{
|
||||
return [$required ? 'required' : 'nullable', ...match ($field['type']) {
|
||||
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
|
||||
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
|
||||
'email' => ['string', 'email', 'max:1000'], 'url' => ['string', 'url:http,https', 'max:1000'],
|
||||
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
|
||||
}];
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $fields
|
||||
* @param array<string,mixed> $payload
|
||||
* @param array<string,bool> $ancestors */
|
||||
private function fieldApplies(string $key, array $fields, array $payload, array $ancestors = []): bool
|
||||
{
|
||||
$field = $fields[$key] ?? null;
|
||||
if (! $field || isset($ancestors[$key])) {
|
||||
return false;
|
||||
}
|
||||
if (! isset($field['when'])) {
|
||||
return true;
|
||||
}
|
||||
$parent = $field['when']['field'];
|
||||
$answer = $payload[$parent] ?? null;
|
||||
if (! is_scalar($answer) || (string) $answer !== $field['when']['equals']) {
|
||||
return false;
|
||||
}
|
||||
$ancestors[$key] = true;
|
||||
|
||||
return $this->fieldApplies($parent, $fields, $payload, $ancestors);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return array<string,array<string,mixed>> */
|
||||
public function applicableFields(array $payload, array $definition): array
|
||||
{
|
||||
return array_filter($definition['fields'], fn ($key) => $this->fieldApplies((string) $key, $definition['fields'], $payload), ARRAY_FILTER_USE_KEY);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @param array<string,mixed> $definition
|
||||
* @return list<array<string,mixed>> */
|
||||
public function findings(array $payload): array
|
||||
public function findings(array $payload, array $definition): array
|
||||
{
|
||||
$findings = [];
|
||||
$fields = $this->applicableFields($payload, $definition);
|
||||
$financeApplies = isset($fields['investment_amount'], $fields['own_finance'], $fields['other_finance']);
|
||||
$amounts = array_map(function ($key) use ($payload) {
|
||||
$value = (string) ($payload[$key] ?? '');
|
||||
if (! preg_match('/^\d{1,12}(?:\.\d{1,2})?$/', $value)) {
|
||||
@@ -313,13 +359,13 @@ class VirtualDesk
|
||||
|
||||
return (int) $whole * 100 + (int) str_pad($fraction, 2, '0');
|
||||
}, ['investment_amount', 'own_finance', 'other_finance']);
|
||||
if (! in_array(null, $amounts, true) && $amounts[0] !== $amounts[1] + $amounts[2]) {
|
||||
if ($financeApplies && ! in_array(null, $amounts, true) && $amounts[0] !== $amounts[1] + $amounts[2]) {
|
||||
$findings[] = ['code' => 'finance_difference', 'severity' => 'error', 'field' => 'investment_amount', 'explanation' => 'A soma do financiamento difere do valor do investimento.', 'recommendation' => 'Confirme valores e moeda.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
if (in_array(null, $amounts, true)) {
|
||||
if ($financeApplies && in_array(null, $amounts, true)) {
|
||||
$findings[] = ['code' => 'finance_unknown', 'severity' => 'warning', 'field' => 'investment_amount', 'explanation' => 'A coerência do financiamento permanece indeterminada sem os três valores válidos na mesma moeda.', 'recommendation' => 'Complete as fontes de financiamento; valores ausentes não são zero.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
if (! ($payload['territory_id'] ?? null)) {
|
||||
if (isset($fields['territory_id']) && ! ($payload['territory_id'] ?? null)) {
|
||||
$findings[] = ['code' => 'location_unknown', 'severity' => 'warning', 'field' => 'territory_id', 'explanation' => 'Localização ainda não documentada.', 'recommendation' => 'Complete quando houver fonte.', 'method' => 'deterministic', 'confidence' => null];
|
||||
}
|
||||
$findings[] = ['code' => 'official_form_pending', 'severity' => 'warning', 'field' => null, 'explanation' => 'Adaptação digital do plano; não foi identificada uma versão oficial homologada do formulário APIEX no acervo.', 'recommendation' => 'A preparação e análise interna continuam disponíveis; confirme a versão exigida pela entidade para o ato oficial.', 'method' => 'documentary', 'confidence' => null];
|
||||
@@ -364,7 +410,7 @@ class VirtualDesk
|
||||
}
|
||||
abort_if($submit && trim($data['reason'] ?? '') === '', 422, 'Justifique a correção.');
|
||||
}
|
||||
$findings = $this->findings($payload);
|
||||
$findings = $this->findings($payload, $this->definition($request));
|
||||
if ($submit && array_filter($findings, fn ($f) => $f['severity'] === 'error')) {
|
||||
throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user